Annotation of imach/src/imach.c, revision 1.136

1.136   ! brouard     1: /* $Id: imach.c,v 1.135 2009/10/29 15:33:14 brouard Exp $
1.126     brouard     2:   $State: Exp $
                      3:   $Log: imach.c,v $
1.136   ! brouard     4:   Revision 1.135  2009/10/29 15:33:14  brouard
        !             5:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
        !             6: 
1.135     brouard     7:   Revision 1.134  2009/10/29 13:18:53  brouard
                      8:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                      9: 
1.134     brouard    10:   Revision 1.133  2009/07/06 10:21:25  brouard
                     11:   just nforces
                     12: 
1.133     brouard    13:   Revision 1.132  2009/07/06 08:22:05  brouard
                     14:   Many tings
                     15: 
1.132     brouard    16:   Revision 1.131  2009/06/20 16:22:47  brouard
                     17:   Some dimensions resccaled
                     18: 
1.131     brouard    19:   Revision 1.130  2009/05/26 06:44:34  brouard
                     20:   (Module): Max Covariate is now set to 20 instead of 8. A
                     21:   lot of cleaning with variables initialized to 0. Trying to make
                     22:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                     23: 
1.130     brouard    24:   Revision 1.129  2007/08/31 13:49:27  lievre
                     25:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                     26: 
1.129     lievre     27:   Revision 1.128  2006/06/30 13:02:05  brouard
                     28:   (Module): Clarifications on computing e.j
                     29: 
1.128     brouard    30:   Revision 1.127  2006/04/28 18:11:50  brouard
                     31:   (Module): Yes the sum of survivors was wrong since
                     32:   imach-114 because nhstepm was no more computed in the age
                     33:   loop. Now we define nhstepma in the age loop.
                     34:   (Module): In order to speed up (in case of numerous covariates) we
                     35:   compute health expectancies (without variances) in a first step
                     36:   and then all the health expectancies with variances or standard
                     37:   deviation (needs data from the Hessian matrices) which slows the
                     38:   computation.
                     39:   In the future we should be able to stop the program is only health
                     40:   expectancies and graph are needed without standard deviations.
                     41: 
1.127     brouard    42:   Revision 1.126  2006/04/28 17:23:28  brouard
                     43:   (Module): Yes the sum of survivors was wrong since
                     44:   imach-114 because nhstepm was no more computed in the age
                     45:   loop. Now we define nhstepma in the age loop.
                     46:   Version 0.98h
                     47: 
1.126     brouard    48:   Revision 1.125  2006/04/04 15:20:31  lievre
                     49:   Errors in calculation of health expectancies. Age was not initialized.
                     50:   Forecasting file added.
                     51: 
                     52:   Revision 1.124  2006/03/22 17:13:53  lievre
                     53:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                     54:   The log-likelihood is printed in the log file
                     55: 
                     56:   Revision 1.123  2006/03/20 10:52:43  brouard
                     57:   * imach.c (Module): <title> changed, corresponds to .htm file
                     58:   name. <head> headers where missing.
                     59: 
                     60:   * imach.c (Module): Weights can have a decimal point as for
                     61:   English (a comma might work with a correct LC_NUMERIC environment,
                     62:   otherwise the weight is truncated).
                     63:   Modification of warning when the covariates values are not 0 or
                     64:   1.
                     65:   Version 0.98g
                     66: 
                     67:   Revision 1.122  2006/03/20 09:45:41  brouard
                     68:   (Module): Weights can have a decimal point as for
                     69:   English (a comma might work with a correct LC_NUMERIC environment,
                     70:   otherwise the weight is truncated).
                     71:   Modification of warning when the covariates values are not 0 or
                     72:   1.
                     73:   Version 0.98g
                     74: 
                     75:   Revision 1.121  2006/03/16 17:45:01  lievre
                     76:   * imach.c (Module): Comments concerning covariates added
                     77: 
                     78:   * imach.c (Module): refinements in the computation of lli if
                     79:   status=-2 in order to have more reliable computation if stepm is
                     80:   not 1 month. Version 0.98f
                     81: 
                     82:   Revision 1.120  2006/03/16 15:10:38  lievre
                     83:   (Module): refinements in the computation of lli if
                     84:   status=-2 in order to have more reliable computation if stepm is
                     85:   not 1 month. Version 0.98f
                     86: 
                     87:   Revision 1.119  2006/03/15 17:42:26  brouard
                     88:   (Module): Bug if status = -2, the loglikelihood was
                     89:   computed as likelihood omitting the logarithm. Version O.98e
                     90: 
                     91:   Revision 1.118  2006/03/14 18:20:07  brouard
                     92:   (Module): varevsij Comments added explaining the second
                     93:   table of variances if popbased=1 .
                     94:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                     95:   (Module): Function pstamp added
                     96:   (Module): Version 0.98d
                     97: 
                     98:   Revision 1.117  2006/03/14 17:16:22  brouard
                     99:   (Module): varevsij Comments added explaining the second
                    100:   table of variances if popbased=1 .
                    101:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    102:   (Module): Function pstamp added
                    103:   (Module): Version 0.98d
                    104: 
                    105:   Revision 1.116  2006/03/06 10:29:27  brouard
                    106:   (Module): Variance-covariance wrong links and
                    107:   varian-covariance of ej. is needed (Saito).
                    108: 
                    109:   Revision 1.115  2006/02/27 12:17:45  brouard
                    110:   (Module): One freematrix added in mlikeli! 0.98c
                    111: 
                    112:   Revision 1.114  2006/02/26 12:57:58  brouard
                    113:   (Module): Some improvements in processing parameter
                    114:   filename with strsep.
                    115: 
                    116:   Revision 1.113  2006/02/24 14:20:24  brouard
                    117:   (Module): Memory leaks checks with valgrind and:
                    118:   datafile was not closed, some imatrix were not freed and on matrix
                    119:   allocation too.
                    120: 
                    121:   Revision 1.112  2006/01/30 09:55:26  brouard
                    122:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    123: 
                    124:   Revision 1.111  2006/01/25 20:38:18  brouard
                    125:   (Module): Lots of cleaning and bugs added (Gompertz)
                    126:   (Module): Comments can be added in data file. Missing date values
                    127:   can be a simple dot '.'.
                    128: 
                    129:   Revision 1.110  2006/01/25 00:51:50  brouard
                    130:   (Module): Lots of cleaning and bugs added (Gompertz)
                    131: 
                    132:   Revision 1.109  2006/01/24 19:37:15  brouard
                    133:   (Module): Comments (lines starting with a #) are allowed in data.
                    134: 
                    135:   Revision 1.108  2006/01/19 18:05:42  lievre
                    136:   Gnuplot problem appeared...
                    137:   To be fixed
                    138: 
                    139:   Revision 1.107  2006/01/19 16:20:37  brouard
                    140:   Test existence of gnuplot in imach path
                    141: 
                    142:   Revision 1.106  2006/01/19 13:24:36  brouard
                    143:   Some cleaning and links added in html output
                    144: 
                    145:   Revision 1.105  2006/01/05 20:23:19  lievre
                    146:   *** empty log message ***
                    147: 
                    148:   Revision 1.104  2005/09/30 16:11:43  lievre
                    149:   (Module): sump fixed, loop imx fixed, and simplifications.
                    150:   (Module): If the status is missing at the last wave but we know
                    151:   that the person is alive, then we can code his/her status as -2
                    152:   (instead of missing=-1 in earlier versions) and his/her
                    153:   contributions to the likelihood is 1 - Prob of dying from last
                    154:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    155:   the healthy state at last known wave). Version is 0.98
                    156: 
                    157:   Revision 1.103  2005/09/30 15:54:49  lievre
                    158:   (Module): sump fixed, loop imx fixed, and simplifications.
                    159: 
                    160:   Revision 1.102  2004/09/15 17:31:30  brouard
                    161:   Add the possibility to read data file including tab characters.
                    162: 
                    163:   Revision 1.101  2004/09/15 10:38:38  brouard
                    164:   Fix on curr_time
                    165: 
                    166:   Revision 1.100  2004/07/12 18:29:06  brouard
                    167:   Add version for Mac OS X. Just define UNIX in Makefile
                    168: 
                    169:   Revision 1.99  2004/06/05 08:57:40  brouard
                    170:   *** empty log message ***
                    171: 
                    172:   Revision 1.98  2004/05/16 15:05:56  brouard
                    173:   New version 0.97 . First attempt to estimate force of mortality
                    174:   directly from the data i.e. without the need of knowing the health
                    175:   state at each age, but using a Gompertz model: log u =a + b*age .
                    176:   This is the basic analysis of mortality and should be done before any
                    177:   other analysis, in order to test if the mortality estimated from the
                    178:   cross-longitudinal survey is different from the mortality estimated
                    179:   from other sources like vital statistic data.
                    180: 
                    181:   The same imach parameter file can be used but the option for mle should be -3.
                    182: 
1.133     brouard   183:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   184:   former routines in order to include the new code within the former code.
                    185: 
                    186:   The output is very simple: only an estimate of the intercept and of
                    187:   the slope with 95% confident intervals.
                    188: 
                    189:   Current limitations:
                    190:   A) Even if you enter covariates, i.e. with the
                    191:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    192:   B) There is no computation of Life Expectancy nor Life Table.
                    193: 
                    194:   Revision 1.97  2004/02/20 13:25:42  lievre
                    195:   Version 0.96d. Population forecasting command line is (temporarily)
                    196:   suppressed.
                    197: 
                    198:   Revision 1.96  2003/07/15 15:38:55  brouard
                    199:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    200:   rewritten within the same printf. Workaround: many printfs.
                    201: 
                    202:   Revision 1.95  2003/07/08 07:54:34  brouard
                    203:   * imach.c (Repository):
                    204:   (Repository): Using imachwizard code to output a more meaningful covariance
                    205:   matrix (cov(a12,c31) instead of numbers.
                    206: 
                    207:   Revision 1.94  2003/06/27 13:00:02  brouard
                    208:   Just cleaning
                    209: 
                    210:   Revision 1.93  2003/06/25 16:33:55  brouard
                    211:   (Module): On windows (cygwin) function asctime_r doesn't
                    212:   exist so I changed back to asctime which exists.
                    213:   (Module): Version 0.96b
                    214: 
                    215:   Revision 1.92  2003/06/25 16:30:45  brouard
                    216:   (Module): On windows (cygwin) function asctime_r doesn't
                    217:   exist so I changed back to asctime which exists.
                    218: 
                    219:   Revision 1.91  2003/06/25 15:30:29  brouard
                    220:   * imach.c (Repository): Duplicated warning errors corrected.
                    221:   (Repository): Elapsed time after each iteration is now output. It
                    222:   helps to forecast when convergence will be reached. Elapsed time
                    223:   is stamped in powell.  We created a new html file for the graphs
                    224:   concerning matrix of covariance. It has extension -cov.htm.
                    225: 
                    226:   Revision 1.90  2003/06/24 12:34:15  brouard
                    227:   (Module): Some bugs corrected for windows. Also, when
                    228:   mle=-1 a template is output in file "or"mypar.txt with the design
                    229:   of the covariance matrix to be input.
                    230: 
                    231:   Revision 1.89  2003/06/24 12:30:52  brouard
                    232:   (Module): Some bugs corrected for windows. Also, when
                    233:   mle=-1 a template is output in file "or"mypar.txt with the design
                    234:   of the covariance matrix to be input.
                    235: 
                    236:   Revision 1.88  2003/06/23 17:54:56  brouard
                    237:   * 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.
                    238: 
                    239:   Revision 1.87  2003/06/18 12:26:01  brouard
                    240:   Version 0.96
                    241: 
                    242:   Revision 1.86  2003/06/17 20:04:08  brouard
                    243:   (Module): Change position of html and gnuplot routines and added
                    244:   routine fileappend.
                    245: 
                    246:   Revision 1.85  2003/06/17 13:12:43  brouard
                    247:   * imach.c (Repository): Check when date of death was earlier that
                    248:   current date of interview. It may happen when the death was just
                    249:   prior to the death. In this case, dh was negative and likelihood
                    250:   was wrong (infinity). We still send an "Error" but patch by
                    251:   assuming that the date of death was just one stepm after the
                    252:   interview.
                    253:   (Repository): Because some people have very long ID (first column)
                    254:   we changed int to long in num[] and we added a new lvector for
                    255:   memory allocation. But we also truncated to 8 characters (left
                    256:   truncation)
                    257:   (Repository): No more line truncation errors.
                    258: 
                    259:   Revision 1.84  2003/06/13 21:44:43  brouard
                    260:   * imach.c (Repository): Replace "freqsummary" at a correct
                    261:   place. It differs from routine "prevalence" which may be called
                    262:   many times. Probs is memory consuming and must be used with
                    263:   parcimony.
                    264:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    265: 
                    266:   Revision 1.83  2003/06/10 13:39:11  lievre
                    267:   *** empty log message ***
                    268: 
                    269:   Revision 1.82  2003/06/05 15:57:20  brouard
                    270:   Add log in  imach.c and  fullversion number is now printed.
                    271: 
                    272: */
                    273: /*
                    274:    Interpolated Markov Chain
                    275: 
                    276:   Short summary of the programme:
                    277:   
                    278:   This program computes Healthy Life Expectancies from
                    279:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    280:   first survey ("cross") where individuals from different ages are
                    281:   interviewed on their health status or degree of disability (in the
                    282:   case of a health survey which is our main interest) -2- at least a
                    283:   second wave of interviews ("longitudinal") which measure each change
                    284:   (if any) in individual health status.  Health expectancies are
                    285:   computed from the time spent in each health state according to a
                    286:   model. More health states you consider, more time is necessary to reach the
                    287:   Maximum Likelihood of the parameters involved in the model.  The
                    288:   simplest model is the multinomial logistic model where pij is the
                    289:   probability to be observed in state j at the second wave
                    290:   conditional to be observed in state i at the first wave. Therefore
                    291:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    292:   'age' is age and 'sex' is a covariate. If you want to have a more
                    293:   complex model than "constant and age", you should modify the program
                    294:   where the markup *Covariates have to be included here again* invites
                    295:   you to do it.  More covariates you add, slower the
                    296:   convergence.
                    297: 
                    298:   The advantage of this computer programme, compared to a simple
                    299:   multinomial logistic model, is clear when the delay between waves is not
                    300:   identical for each individual. Also, if a individual missed an
                    301:   intermediate interview, the information is lost, but taken into
                    302:   account using an interpolation or extrapolation.  
                    303: 
                    304:   hPijx is the probability to be observed in state i at age x+h
                    305:   conditional to the observed state i at age x. The delay 'h' can be
                    306:   split into an exact number (nh*stepm) of unobserved intermediate
                    307:   states. This elementary transition (by month, quarter,
                    308:   semester or year) is modelled as a multinomial logistic.  The hPx
                    309:   matrix is simply the matrix product of nh*stepm elementary matrices
                    310:   and the contribution of each individual to the likelihood is simply
                    311:   hPijx.
                    312: 
                    313:   Also this programme outputs the covariance matrix of the parameters but also
                    314:   of the life expectancies. It also computes the period (stable) prevalence. 
                    315:   
1.133     brouard   316:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    317:            Institut national d'études démographiques, Paris.
1.126     brouard   318:   This software have been partly granted by Euro-REVES, a concerted action
                    319:   from the European Union.
                    320:   It is copyrighted identically to a GNU software product, ie programme and
                    321:   software can be distributed freely for non commercial use. Latest version
                    322:   can be accessed at http://euroreves.ined.fr/imach .
                    323: 
                    324:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    325:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    326:   
                    327:   **********************************************************************/
                    328: /*
                    329:   main
                    330:   read parameterfile
                    331:   read datafile
                    332:   concatwav
                    333:   freqsummary
                    334:   if (mle >= 1)
                    335:     mlikeli
                    336:   print results files
                    337:   if mle==1 
                    338:      computes hessian
                    339:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    340:       begin-prev-date,...
                    341:   open gnuplot file
                    342:   open html file
                    343:   period (stable) prevalence
                    344:    for age prevalim()
                    345:   h Pij x
                    346:   variance of p varprob
                    347:   forecasting if prevfcast==1 prevforecast call prevalence()
                    348:   health expectancies
                    349:   Variance-covariance of DFLE
                    350:   prevalence()
                    351:    movingaverage()
                    352:   varevsij() 
                    353:   if popbased==1 varevsij(,popbased)
                    354:   total life expectancies
                    355:   Variance of period (stable) prevalence
                    356:  end
                    357: */
                    358: 
                    359: 
                    360: 
                    361:  
                    362: #include <math.h>
                    363: #include <stdio.h>
                    364: #include <stdlib.h>
                    365: #include <string.h>
                    366: #include <unistd.h>
                    367: 
                    368: #include <limits.h>
                    369: #include <sys/types.h>
                    370: #include <sys/stat.h>
                    371: #include <errno.h>
                    372: extern int errno;
                    373: 
                    374: /* #include <sys/time.h> */
                    375: #include <time.h>
                    376: #include "timeval.h"
                    377: 
1.136   ! brouard   378: #ifdef GSL
        !           379: #include <gsl/gsl_errno.h>
        !           380: #include <gsl/gsl_multimin.h>
        !           381: #endif
        !           382: 
1.126     brouard   383: /* #include <libintl.h> */
                    384: /* #define _(String) gettext (String) */
                    385: 
                    386: #define MAXLINE 256
                    387: 
                    388: #define GNUPLOTPROGRAM "gnuplot"
                    389: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    390: #define FILENAMELENGTH 132
                    391: 
                    392: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    393: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    394: 
1.131     brouard   395: #define MAXPARM 128 /* Maximum number of parameters for the optimization */
1.126     brouard   396: #define NPARMAX 64 /* (nlstate+ndeath-1)*nlstate*ncovmodel */
                    397: 
                    398: #define NINTERVMAX 8
                    399: #define NLSTATEMAX 8 /* Maximum number of live states (for func) */
                    400: #define NDEATHMAX 8 /* Maximum number of dead states (for func) */
1.130     brouard   401: #define NCOVMAX 20 /* Maximum number of covariates */
1.126     brouard   402: #define MAXN 20000
                    403: #define YEARM 12. /* Number of months per year */
                    404: #define AGESUP 130
                    405: #define AGEBASE 40
                    406: #define AGEGOMP 10. /* Minimal age for Gompertz adjustment */
                    407: #ifdef UNIX
                    408: #define DIRSEPARATOR '/'
                    409: #define CHARSEPARATOR "/"
                    410: #define ODIRSEPARATOR '\\'
                    411: #else
                    412: #define DIRSEPARATOR '\\'
                    413: #define CHARSEPARATOR "\\"
                    414: #define ODIRSEPARATOR '/'
                    415: #endif
                    416: 
1.136   ! brouard   417: /* $Id: imach.c,v 1.135 2009/10/29 15:33:14 brouard Exp $ */
1.126     brouard   418: /* $State: Exp $ */
                    419: 
1.136   ! brouard   420: char version[]="Imach version 0.98m, April 2010, INED-EUROREVES-Institut de longevite ";
        !           421: char fullversion[]="$Revision: 1.135 $ $Date: 2009/10/29 15:33:14 $"; 
1.126     brouard   422: char strstart[80];
                    423: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   424: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.133     brouard   425: int nvar=0, nforce=0; /* Number of variables, number of forces */
1.130     brouard   426: int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov=0; /* Number of covariates, of covariates with '*age' */
1.126     brouard   427: int npar=NPARMAX;
                    428: int nlstate=2; /* Number of live states */
                    429: int ndeath=1; /* Number of dead states */
1.130     brouard   430: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   431: int popbased=0;
                    432: 
                    433: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   434: int maxwav=0; /* Maxim number of waves */
                    435: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    436: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    437: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   438:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   439: int mle=1, weightopt=0;
1.126     brouard   440: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    441: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    442: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    443:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.130     brouard   444: double jmean=1; /* Mean space between 2 waves */
1.126     brouard   445: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    446: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136   ! brouard   447: /*FILE *fic ; */ /* Used in readdata only */
        !           448: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   449: FILE *ficlog, *ficrespow;
1.130     brouard   450: int globpr=0; /* Global variable for printing or not */
1.126     brouard   451: double fretone; /* Only one call to likelihood */
1.130     brouard   452: long ipmx=0; /* Number of contributions */
1.126     brouard   453: double sw; /* Sum of weights */
                    454: char filerespow[FILENAMELENGTH];
                    455: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    456: FILE *ficresilk;
                    457: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    458: FILE *ficresprobmorprev;
                    459: FILE *fichtm, *fichtmcov; /* Html File */
                    460: FILE *ficreseij;
                    461: char filerese[FILENAMELENGTH];
                    462: FILE *ficresstdeij;
                    463: char fileresstde[FILENAMELENGTH];
                    464: FILE *ficrescveij;
                    465: char filerescve[FILENAMELENGTH];
                    466: FILE  *ficresvij;
                    467: char fileresv[FILENAMELENGTH];
                    468: FILE  *ficresvpl;
                    469: char fileresvpl[FILENAMELENGTH];
                    470: char title[MAXLINE];
                    471: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    472: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    473: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    474: char command[FILENAMELENGTH];
                    475: int  outcmd=0;
                    476: 
                    477: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
                    478: 
                    479: char filelog[FILENAMELENGTH]; /* Log file */
                    480: char filerest[FILENAMELENGTH];
                    481: char fileregp[FILENAMELENGTH];
                    482: char popfile[FILENAMELENGTH];
                    483: 
                    484: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    485: 
                    486: struct timeval start_time, end_time, curr_time, last_time, forecast_time;
                    487: struct timezone tzp;
                    488: extern int gettimeofday();
                    489: struct tm tmg, tm, tmf, *gmtime(), *localtime();
                    490: long time_value;
                    491: extern long time();
                    492: char strcurr[80], strfor[80];
                    493: 
                    494: char *endptr;
                    495: long lval;
                    496: double dval;
                    497: 
                    498: #define NR_END 1
                    499: #define FREE_ARG char*
                    500: #define FTOL 1.0e-10
                    501: 
                    502: #define NRANSI 
                    503: #define ITMAX 200 
                    504: 
                    505: #define TOL 2.0e-4 
                    506: 
                    507: #define CGOLD 0.3819660 
                    508: #define ZEPS 1.0e-10 
                    509: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    510: 
                    511: #define GOLD 1.618034 
                    512: #define GLIMIT 100.0 
                    513: #define TINY 1.0e-20 
                    514: 
                    515: static double maxarg1,maxarg2;
                    516: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    517: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    518:   
                    519: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    520: #define rint(a) floor(a+0.5)
                    521: 
                    522: static double sqrarg;
                    523: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    524: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    525: int agegomp= AGEGOMP;
                    526: 
                    527: int imx; 
                    528: int stepm=1;
                    529: /* Stepm, step in month: minimum step interpolation*/
                    530: 
                    531: int estepm;
                    532: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    533: 
                    534: int m,nb;
                    535: long *num;
                    536: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
                    537: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    538: double **pmmij, ***probs;
                    539: double *ageexmed,*agecens;
                    540: double dateintmean=0;
                    541: 
                    542: double *weight;
                    543: int **s; /* Status */
                    544: double *agedc, **covar, idx;
1.131     brouard   545: int **nbcode, *Tvar, **codtab, **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   546: double *lsurv, *lpop, *tpop;
                    547: 
                    548: double ftol=FTOL; /* Tolerance for computing Max Likelihood */
                    549: double ftolhess; /* Tolerance for computing hessian */
                    550: 
                    551: /**************** split *************************/
                    552: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    553: {
                    554:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    555:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    556:   */ 
                    557:   char *ss;                            /* pointer */
                    558:   int  l1, l2;                         /* length counters */
                    559: 
                    560:   l1 = strlen(path );                  /* length of path */
                    561:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    562:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    563:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    564:     strcpy( name, path );              /* we got the fullname name because no directory */
                    565:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    566:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    567:     /* get current working directory */
                    568:     /*    extern  char* getcwd ( char *buf , int len);*/
                    569:     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    570:       return( GLOCK_ERROR_GETCWD );
                    571:     }
                    572:     /* got dirc from getcwd*/
                    573:     printf(" DIRC = %s \n",dirc);
                    574:   } else {                             /* strip direcotry from path */
                    575:     ss++;                              /* after this, the filename */
                    576:     l2 = strlen( ss );                 /* length of filename */
                    577:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    578:     strcpy( name, ss );                /* save file name */
                    579:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
                    580:     dirc[l1-l2] = 0;                   /* add zero */
                    581:     printf(" DIRC2 = %s \n",dirc);
                    582:   }
                    583:   /* We add a separator at the end of dirc if not exists */
                    584:   l1 = strlen( dirc );                 /* length of directory */
                    585:   if( dirc[l1-1] != DIRSEPARATOR ){
                    586:     dirc[l1] =  DIRSEPARATOR;
                    587:     dirc[l1+1] = 0; 
                    588:     printf(" DIRC3 = %s \n",dirc);
                    589:   }
                    590:   ss = strrchr( name, '.' );           /* find last / */
                    591:   if (ss >0){
                    592:     ss++;
                    593:     strcpy(ext,ss);                    /* save extension */
                    594:     l1= strlen( name);
                    595:     l2= strlen(ss)+1;
                    596:     strncpy( finame, name, l1-l2);
                    597:     finame[l1-l2]= 0;
                    598:   }
                    599: 
                    600:   return( 0 );                         /* we're done */
                    601: }
                    602: 
                    603: 
                    604: /******************************************/
                    605: 
                    606: void replace_back_to_slash(char *s, char*t)
                    607: {
                    608:   int i;
                    609:   int lg=0;
                    610:   i=0;
                    611:   lg=strlen(t);
                    612:   for(i=0; i<= lg; i++) {
                    613:     (s[i] = t[i]);
                    614:     if (t[i]== '\\') s[i]='/';
                    615:   }
                    616: }
                    617: 
1.132     brouard   618: char *trimbb(char *out, char *in)
                    619: { /* Trim multiple blanks in line */
                    620:   char *s;
                    621:   s=out;
                    622:   while (*in != '\0'){
                    623:     while( *in == ' ' && *(in+1) == ' ' && *(in+1) != '\0'){
                    624:       in++;
                    625:     }
                    626:     *out++ = *in++;
                    627:   }
                    628:   *out='\0';
                    629:   return s;
                    630: }
                    631: 
1.126     brouard   632: int nbocc(char *s, char occ)
                    633: {
                    634:   int i,j=0;
                    635:   int lg=20;
                    636:   i=0;
                    637:   lg=strlen(s);
                    638:   for(i=0; i<= lg; i++) {
                    639:   if  (s[i] == occ ) j++;
                    640:   }
                    641:   return j;
                    642: }
                    643: 
                    644: void cutv(char *u,char *v, char*t, char occ)
                    645: {
                    646:   /* cuts string t into u and v where u ends before first occurence of char 'occ' 
                    647:      and v starts after first occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2')
                    648:      gives u="abcedf" and v="ghi2j" */
                    649:   int i,lg,j,p=0;
                    650:   i=0;
                    651:   for(j=0; j<=strlen(t)-1; j++) {
                    652:     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1;
                    653:   }
                    654: 
                    655:   lg=strlen(t);
                    656:   for(j=0; j<p; j++) {
                    657:     (u[j] = t[j]);
                    658:   }
                    659:      u[p]='\0';
                    660: 
                    661:    for(j=0; j<= lg; j++) {
                    662:     if (j>=(p+1))(v[j-p-1] = t[j]);
                    663:   }
                    664: }
                    665: 
                    666: /********************** nrerror ********************/
                    667: 
                    668: void nrerror(char error_text[])
                    669: {
                    670:   fprintf(stderr,"ERREUR ...\n");
                    671:   fprintf(stderr,"%s\n",error_text);
                    672:   exit(EXIT_FAILURE);
                    673: }
                    674: /*********************** vector *******************/
                    675: double *vector(int nl, int nh)
                    676: {
                    677:   double *v;
                    678:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                    679:   if (!v) nrerror("allocation failure in vector");
                    680:   return v-nl+NR_END;
                    681: }
                    682: 
                    683: /************************ free vector ******************/
                    684: void free_vector(double*v, int nl, int nh)
                    685: {
                    686:   free((FREE_ARG)(v+nl-NR_END));
                    687: }
                    688: 
                    689: /************************ivector *******************************/
                    690: int *ivector(long nl,long nh)
                    691: {
                    692:   int *v;
                    693:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                    694:   if (!v) nrerror("allocation failure in ivector");
                    695:   return v-nl+NR_END;
                    696: }
                    697: 
                    698: /******************free ivector **************************/
                    699: void free_ivector(int *v, long nl, long nh)
                    700: {
                    701:   free((FREE_ARG)(v+nl-NR_END));
                    702: }
                    703: 
                    704: /************************lvector *******************************/
                    705: long *lvector(long nl,long nh)
                    706: {
                    707:   long *v;
                    708:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                    709:   if (!v) nrerror("allocation failure in ivector");
                    710:   return v-nl+NR_END;
                    711: }
                    712: 
                    713: /******************free lvector **************************/
                    714: void free_lvector(long *v, long nl, long nh)
                    715: {
                    716:   free((FREE_ARG)(v+nl-NR_END));
                    717: }
                    718: 
                    719: /******************* imatrix *******************************/
                    720: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                    721:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                    722: { 
                    723:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                    724:   int **m; 
                    725:   
                    726:   /* allocate pointers to rows */ 
                    727:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                    728:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                    729:   m += NR_END; 
                    730:   m -= nrl; 
                    731:   
                    732:   
                    733:   /* allocate rows and set pointers to them */ 
                    734:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                    735:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                    736:   m[nrl] += NR_END; 
                    737:   m[nrl] -= ncl; 
                    738:   
                    739:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                    740:   
                    741:   /* return pointer to array of pointers to rows */ 
                    742:   return m; 
                    743: } 
                    744: 
                    745: /****************** free_imatrix *************************/
                    746: void free_imatrix(m,nrl,nrh,ncl,nch)
                    747:       int **m;
                    748:       long nch,ncl,nrh,nrl; 
                    749:      /* free an int matrix allocated by imatrix() */ 
                    750: { 
                    751:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                    752:   free((FREE_ARG) (m+nrl-NR_END)); 
                    753: } 
                    754: 
                    755: /******************* matrix *******************************/
                    756: double **matrix(long nrl, long nrh, long ncl, long nch)
                    757: {
                    758:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                    759:   double **m;
                    760: 
                    761:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                    762:   if (!m) nrerror("allocation failure 1 in matrix()");
                    763:   m += NR_END;
                    764:   m -= nrl;
                    765: 
                    766:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                    767:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                    768:   m[nrl] += NR_END;
                    769:   m[nrl] -= ncl;
                    770: 
                    771:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                    772:   return m;
                    773:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) 
                    774:    */
                    775: }
                    776: 
                    777: /*************************free matrix ************************/
                    778: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                    779: {
                    780:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                    781:   free((FREE_ARG)(m+nrl-NR_END));
                    782: }
                    783: 
                    784: /******************* ma3x *******************************/
                    785: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                    786: {
                    787:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                    788:   double ***m;
                    789: 
                    790:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                    791:   if (!m) nrerror("allocation failure 1 in matrix()");
                    792:   m += NR_END;
                    793:   m -= nrl;
                    794: 
                    795:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                    796:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                    797:   m[nrl] += NR_END;
                    798:   m[nrl] -= ncl;
                    799: 
                    800:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                    801: 
                    802:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                    803:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                    804:   m[nrl][ncl] += NR_END;
                    805:   m[nrl][ncl] -= nll;
                    806:   for (j=ncl+1; j<=nch; j++) 
                    807:     m[nrl][j]=m[nrl][j-1]+nlay;
                    808:   
                    809:   for (i=nrl+1; i<=nrh; i++) {
                    810:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                    811:     for (j=ncl+1; j<=nch; j++) 
                    812:       m[i][j]=m[i][j-1]+nlay;
                    813:   }
                    814:   return m; 
                    815:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                    816:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                    817:   */
                    818: }
                    819: 
                    820: /*************************free ma3x ************************/
                    821: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                    822: {
                    823:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                    824:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                    825:   free((FREE_ARG)(m+nrl-NR_END));
                    826: }
                    827: 
                    828: /*************** function subdirf ***********/
                    829: char *subdirf(char fileres[])
                    830: {
                    831:   /* Caution optionfilefiname is hidden */
                    832:   strcpy(tmpout,optionfilefiname);
                    833:   strcat(tmpout,"/"); /* Add to the right */
                    834:   strcat(tmpout,fileres);
                    835:   return tmpout;
                    836: }
                    837: 
                    838: /*************** function subdirf2 ***********/
                    839: char *subdirf2(char fileres[], char *preop)
                    840: {
                    841:   
                    842:   /* Caution optionfilefiname is hidden */
                    843:   strcpy(tmpout,optionfilefiname);
                    844:   strcat(tmpout,"/");
                    845:   strcat(tmpout,preop);
                    846:   strcat(tmpout,fileres);
                    847:   return tmpout;
                    848: }
                    849: 
                    850: /*************** function subdirf3 ***********/
                    851: char *subdirf3(char fileres[], char *preop, char *preop2)
                    852: {
                    853:   
                    854:   /* Caution optionfilefiname is hidden */
                    855:   strcpy(tmpout,optionfilefiname);
                    856:   strcat(tmpout,"/");
                    857:   strcat(tmpout,preop);
                    858:   strcat(tmpout,preop2);
                    859:   strcat(tmpout,fileres);
                    860:   return tmpout;
                    861: }
                    862: 
                    863: /***************** f1dim *************************/
                    864: extern int ncom; 
                    865: extern double *pcom,*xicom;
                    866: extern double (*nrfunc)(double []); 
                    867:  
                    868: double f1dim(double x) 
                    869: { 
                    870:   int j; 
                    871:   double f;
                    872:   double *xt; 
                    873:  
                    874:   xt=vector(1,ncom); 
                    875:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                    876:   f=(*nrfunc)(xt); 
                    877:   free_vector(xt,1,ncom); 
                    878:   return f; 
                    879: } 
                    880: 
                    881: /*****************brent *************************/
                    882: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
                    883: { 
                    884:   int iter; 
                    885:   double a,b,d,etemp;
                    886:   double fu,fv,fw,fx;
                    887:   double ftemp;
                    888:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                    889:   double e=0.0; 
                    890:  
                    891:   a=(ax < cx ? ax : cx); 
                    892:   b=(ax > cx ? ax : cx); 
                    893:   x=w=v=bx; 
                    894:   fw=fv=fx=(*f)(x); 
                    895:   for (iter=1;iter<=ITMAX;iter++) { 
                    896:     xm=0.5*(a+b); 
                    897:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                    898:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                    899:     printf(".");fflush(stdout);
                    900:     fprintf(ficlog,".");fflush(ficlog);
                    901: #ifdef DEBUG
                    902:     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);
                    903:     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);
                    904:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                    905: #endif
                    906:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                    907:       *xmin=x; 
                    908:       return fx; 
                    909:     } 
                    910:     ftemp=fu;
                    911:     if (fabs(e) > tol1) { 
                    912:       r=(x-w)*(fx-fv); 
                    913:       q=(x-v)*(fx-fw); 
                    914:       p=(x-v)*q-(x-w)*r; 
                    915:       q=2.0*(q-r); 
                    916:       if (q > 0.0) p = -p; 
                    917:       q=fabs(q); 
                    918:       etemp=e; 
                    919:       e=d; 
                    920:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                    921:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                    922:       else { 
                    923:        d=p/q; 
                    924:        u=x+d; 
                    925:        if (u-a < tol2 || b-u < tol2) 
                    926:          d=SIGN(tol1,xm-x); 
                    927:       } 
                    928:     } else { 
                    929:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                    930:     } 
                    931:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                    932:     fu=(*f)(u); 
                    933:     if (fu <= fx) { 
                    934:       if (u >= x) a=x; else b=x; 
                    935:       SHFT(v,w,x,u) 
                    936:        SHFT(fv,fw,fx,fu) 
                    937:        } else { 
                    938:          if (u < x) a=u; else b=u; 
                    939:          if (fu <= fw || w == x) { 
                    940:            v=w; 
                    941:            w=u; 
                    942:            fv=fw; 
                    943:            fw=fu; 
                    944:          } else if (fu <= fv || v == x || v == w) { 
                    945:            v=u; 
                    946:            fv=fu; 
                    947:          } 
                    948:        } 
                    949:   } 
                    950:   nrerror("Too many iterations in brent"); 
                    951:   *xmin=x; 
                    952:   return fx; 
                    953: } 
                    954: 
                    955: /****************** mnbrak ***********************/
                    956: 
                    957: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                    958:            double (*func)(double)) 
                    959: { 
                    960:   double ulim,u,r,q, dum;
                    961:   double fu; 
                    962:  
                    963:   *fa=(*func)(*ax); 
                    964:   *fb=(*func)(*bx); 
                    965:   if (*fb > *fa) { 
                    966:     SHFT(dum,*ax,*bx,dum) 
                    967:       SHFT(dum,*fb,*fa,dum) 
                    968:       } 
                    969:   *cx=(*bx)+GOLD*(*bx-*ax); 
                    970:   *fc=(*func)(*cx); 
                    971:   while (*fb > *fc) { 
                    972:     r=(*bx-*ax)*(*fb-*fc); 
                    973:     q=(*bx-*cx)*(*fb-*fa); 
                    974:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
                    975:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); 
                    976:     ulim=(*bx)+GLIMIT*(*cx-*bx); 
                    977:     if ((*bx-u)*(u-*cx) > 0.0) { 
                    978:       fu=(*func)(u); 
                    979:     } else if ((*cx-u)*(u-ulim) > 0.0) { 
                    980:       fu=(*func)(u); 
                    981:       if (fu < *fc) { 
                    982:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                    983:          SHFT(*fb,*fc,fu,(*func)(u)) 
                    984:          } 
                    985:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { 
                    986:       u=ulim; 
                    987:       fu=(*func)(u); 
                    988:     } else { 
                    989:       u=(*cx)+GOLD*(*cx-*bx); 
                    990:       fu=(*func)(u); 
                    991:     } 
                    992:     SHFT(*ax,*bx,*cx,u) 
                    993:       SHFT(*fa,*fb,*fc,fu) 
                    994:       } 
                    995: } 
                    996: 
                    997: /*************** linmin ************************/
                    998: 
                    999: int ncom; 
                   1000: double *pcom,*xicom;
                   1001: double (*nrfunc)(double []); 
                   1002:  
                   1003: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1004: { 
                   1005:   double brent(double ax, double bx, double cx, 
                   1006:               double (*f)(double), double tol, double *xmin); 
                   1007:   double f1dim(double x); 
                   1008:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1009:              double *fc, double (*func)(double)); 
                   1010:   int j; 
                   1011:   double xx,xmin,bx,ax; 
                   1012:   double fx,fb,fa;
                   1013:  
                   1014:   ncom=n; 
                   1015:   pcom=vector(1,n); 
                   1016:   xicom=vector(1,n); 
                   1017:   nrfunc=func; 
                   1018:   for (j=1;j<=n;j++) { 
                   1019:     pcom[j]=p[j]; 
                   1020:     xicom[j]=xi[j]; 
                   1021:   } 
                   1022:   ax=0.0; 
                   1023:   xx=1.0; 
                   1024:   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); 
                   1025:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); 
                   1026: #ifdef DEBUG
                   1027:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1028:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1029: #endif
                   1030:   for (j=1;j<=n;j++) { 
                   1031:     xi[j] *= xmin; 
                   1032:     p[j] += xi[j]; 
                   1033:   } 
                   1034:   free_vector(xicom,1,n); 
                   1035:   free_vector(pcom,1,n); 
                   1036: } 
                   1037: 
                   1038: char *asc_diff_time(long time_sec, char ascdiff[])
                   1039: {
                   1040:   long sec_left, days, hours, minutes;
                   1041:   days = (time_sec) / (60*60*24);
                   1042:   sec_left = (time_sec) % (60*60*24);
                   1043:   hours = (sec_left) / (60*60) ;
                   1044:   sec_left = (sec_left) %(60*60);
                   1045:   minutes = (sec_left) /60;
                   1046:   sec_left = (sec_left) % (60);
                   1047:   sprintf(ascdiff,"%d day(s) %d hour(s) %d minute(s) %d second(s)",days, hours, minutes, sec_left);  
                   1048:   return ascdiff;
                   1049: }
                   1050: 
                   1051: /*************** powell ************************/
                   1052: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1053:            double (*func)(double [])) 
                   1054: { 
                   1055:   void linmin(double p[], double xi[], int n, double *fret, 
                   1056:              double (*func)(double [])); 
                   1057:   int i,ibig,j; 
                   1058:   double del,t,*pt,*ptt,*xit;
                   1059:   double fp,fptt;
                   1060:   double *xits;
                   1061:   int niterf, itmp;
                   1062: 
                   1063:   pt=vector(1,n); 
                   1064:   ptt=vector(1,n); 
                   1065:   xit=vector(1,n); 
                   1066:   xits=vector(1,n); 
                   1067:   *fret=(*func)(p); 
                   1068:   for (j=1;j<=n;j++) pt[j]=p[j]; 
                   1069:   for (*iter=1;;++(*iter)) { 
                   1070:     fp=(*fret); 
                   1071:     ibig=0; 
                   1072:     del=0.0; 
                   1073:     last_time=curr_time;
                   1074:     (void) gettimeofday(&curr_time,&tzp);
                   1075:     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);
                   1076:     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);
                   1077: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec); */
                   1078:    for (i=1;i<=n;i++) {
                   1079:       printf(" %d %.12f",i, p[i]);
                   1080:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1081:       fprintf(ficrespow," %.12lf", p[i]);
                   1082:     }
                   1083:     printf("\n");
                   1084:     fprintf(ficlog,"\n");
                   1085:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1086:     if(*iter <=3){
                   1087:       tm = *localtime(&curr_time.tv_sec);
                   1088:       strcpy(strcurr,asctime(&tm));
                   1089: /*       asctime_r(&tm,strcurr); */
                   1090:       forecast_time=curr_time; 
                   1091:       itmp = strlen(strcurr);
                   1092:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1093:        strcurr[itmp-1]='\0';
                   1094:       printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
                   1095:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
                   1096:       for(niterf=10;niterf<=30;niterf+=10){
                   1097:        forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);
                   1098:        tmf = *localtime(&forecast_time.tv_sec);
                   1099: /*     asctime_r(&tmf,strfor); */
                   1100:        strcpy(strfor,asctime(&tmf));
                   1101:        itmp = strlen(strfor);
                   1102:        if(strfor[itmp-1]=='\n')
                   1103:        strfor[itmp-1]='\0';
                   1104:        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);
                   1105:        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);
                   1106:       }
                   1107:     }
                   1108:     for (i=1;i<=n;i++) { 
                   1109:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; 
                   1110:       fptt=(*fret); 
                   1111: #ifdef DEBUG
                   1112:       printf("fret=%lf \n",*fret);
                   1113:       fprintf(ficlog,"fret=%lf \n",*fret);
                   1114: #endif
                   1115:       printf("%d",i);fflush(stdout);
                   1116:       fprintf(ficlog,"%d",i);fflush(ficlog);
                   1117:       linmin(p,xit,n,fret,func); 
                   1118:       if (fabs(fptt-(*fret)) > del) { 
                   1119:        del=fabs(fptt-(*fret)); 
                   1120:        ibig=i; 
                   1121:       } 
                   1122: #ifdef DEBUG
                   1123:       printf("%d %.12e",i,(*fret));
                   1124:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1125:       for (j=1;j<=n;j++) {
                   1126:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1127:        printf(" x(%d)=%.12e",j,xit[j]);
                   1128:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1129:       }
                   1130:       for(j=1;j<=n;j++) {
                   1131:        printf(" p=%.12e",p[j]);
                   1132:        fprintf(ficlog," p=%.12e",p[j]);
                   1133:       }
                   1134:       printf("\n");
                   1135:       fprintf(ficlog,"\n");
                   1136: #endif
                   1137:     } 
                   1138:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
                   1139: #ifdef DEBUG
                   1140:       int k[2],l;
                   1141:       k[0]=1;
                   1142:       k[1]=-1;
                   1143:       printf("Max: %.12e",(*func)(p));
                   1144:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1145:       for (j=1;j<=n;j++) {
                   1146:        printf(" %.12e",p[j]);
                   1147:        fprintf(ficlog," %.12e",p[j]);
                   1148:       }
                   1149:       printf("\n");
                   1150:       fprintf(ficlog,"\n");
                   1151:       for(l=0;l<=1;l++) {
                   1152:        for (j=1;j<=n;j++) {
                   1153:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1154:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1155:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1156:        }
                   1157:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1158:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1159:       }
                   1160: #endif
                   1161: 
                   1162: 
                   1163:       free_vector(xit,1,n); 
                   1164:       free_vector(xits,1,n); 
                   1165:       free_vector(ptt,1,n); 
                   1166:       free_vector(pt,1,n); 
                   1167:       return; 
                   1168:     } 
                   1169:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
                   1170:     for (j=1;j<=n;j++) { 
                   1171:       ptt[j]=2.0*p[j]-pt[j]; 
                   1172:       xit[j]=p[j]-pt[j]; 
                   1173:       pt[j]=p[j]; 
                   1174:     } 
                   1175:     fptt=(*func)(ptt); 
                   1176:     if (fptt < fp) { 
                   1177:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); 
                   1178:       if (t < 0.0) { 
                   1179:        linmin(p,xit,n,fret,func); 
                   1180:        for (j=1;j<=n;j++) { 
                   1181:          xi[j][ibig]=xi[j][n]; 
                   1182:          xi[j][n]=xit[j]; 
                   1183:        }
                   1184: #ifdef DEBUG
                   1185:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1186:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1187:        for(j=1;j<=n;j++){
                   1188:          printf(" %.12e",xit[j]);
                   1189:          fprintf(ficlog," %.12e",xit[j]);
                   1190:        }
                   1191:        printf("\n");
                   1192:        fprintf(ficlog,"\n");
                   1193: #endif
                   1194:       }
                   1195:     } 
                   1196:   } 
                   1197: } 
                   1198: 
                   1199: /**** Prevalence limit (stable or period prevalence)  ****************/
                   1200: 
                   1201: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
                   1202: {
                   1203:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
                   1204:      matrix by transitions matrix until convergence is reached */
                   1205: 
                   1206:   int i, ii,j,k;
                   1207:   double min, max, maxmin, maxmax,sumnew=0.;
                   1208:   double **matprod2();
1.131     brouard  1209:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  1210:   double **newm;
                   1211:   double agefin, delaymax=50 ; /* Max number of years to converge */
                   1212: 
                   1213:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   1214:     for (j=1;j<=nlstate+ndeath;j++){
                   1215:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1216:     }
                   1217: 
                   1218:    cov[1]=1.;
                   1219:  
                   1220:  /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   1221:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
                   1222:     newm=savm;
                   1223:     /* Covariates have to be included here again */
                   1224:      cov[2]=agefin;
                   1225:   
                   1226:       for (k=1; k<=cptcovn;k++) {
                   1227:        cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
                   1228:        /*      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]]);*/
                   1229:       }
                   1230:       for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
                   1231:       for (k=1; k<=cptcovprod;k++)
1.136   ! brouard  1232:        cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1.126     brouard  1233: 
                   1234:       /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   1235:       /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   1236:       /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   1237:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
                   1238: 
                   1239:     savm=oldm;
                   1240:     oldm=newm;
                   1241:     maxmax=0.;
                   1242:     for(j=1;j<=nlstate;j++){
                   1243:       min=1.;
                   1244:       max=0.;
                   1245:       for(i=1; i<=nlstate; i++) {
                   1246:        sumnew=0;
                   1247:        for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   1248:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   1249:        max=FMAX(max,prlim[i][j]);
                   1250:        min=FMIN(min,prlim[i][j]);
                   1251:       }
                   1252:       maxmin=max-min;
                   1253:       maxmax=FMAX(maxmax,maxmin);
                   1254:     }
                   1255:     if(maxmax < ftolpl){
                   1256:       return prlim;
                   1257:     }
                   1258:   }
                   1259: }
                   1260: 
                   1261: /*************** transition probabilities ***************/ 
                   1262: 
                   1263: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   1264: {
                   1265:   double s1, s2;
                   1266:   /*double t34;*/
                   1267:   int i,j,j1, nc, ii, jj;
                   1268: 
                   1269:     for(i=1; i<= nlstate; i++){
                   1270:       for(j=1; j<i;j++){
                   1271:        for (nc=1, s2=0.;nc <=ncovmodel; nc++){
                   1272:          /*s2 += param[i][j][nc]*cov[nc];*/
                   1273:          s2 += x[(i-1)*nlstate*ncovmodel+(j-1)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
                   1274: /*      printf("Int j<i s1=%.17e, s2=%.17e\n",s1,s2); */
                   1275:        }
                   1276:        ps[i][j]=s2;
                   1277: /*     printf("s1=%.17e, s2=%.17e\n",s1,s2); */
                   1278:       }
                   1279:       for(j=i+1; j<=nlstate+ndeath;j++){
                   1280:        for (nc=1, s2=0.;nc <=ncovmodel; nc++){
                   1281:          s2 += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];
                   1282: /*       printf("Int j>i s1=%.17e, s2=%.17e %lx %lx\n",s1,s2,s1,s2); */
                   1283:        }
                   1284:        ps[i][j]=s2;
                   1285:       }
                   1286:     }
                   1287:     /*ps[3][2]=1;*/
                   1288:     
                   1289:     for(i=1; i<= nlstate; i++){
                   1290:       s1=0;
1.131     brouard  1291:       for(j=1; j<i; j++){
1.126     brouard  1292:        s1+=exp(ps[i][j]);
1.131     brouard  1293:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1294:       }
                   1295:       for(j=i+1; j<=nlstate+ndeath; j++){
1.126     brouard  1296:        s1+=exp(ps[i][j]);
1.131     brouard  1297:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1298:       }
1.126     brouard  1299:       ps[i][i]=1./(s1+1.);
                   1300:       for(j=1; j<i; j++)
                   1301:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   1302:       for(j=i+1; j<=nlstate+ndeath; j++)
                   1303:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   1304:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   1305:     } /* end i */
                   1306:     
                   1307:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   1308:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   1309:        ps[ii][jj]=0;
                   1310:        ps[ii][ii]=1;
                   1311:       }
                   1312:     }
                   1313:     
                   1314: 
                   1315: /*        for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   1316: /*      for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   1317: /*        printf("ddd %lf ",ps[ii][jj]); */
                   1318: /*      } */
                   1319: /*      printf("\n "); */
                   1320: /*        } */
                   1321: /*        printf("\n ");printf("%lf ",cov[2]); */
                   1322:        /*
                   1323:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   1324:       goto end;*/
                   1325:     return ps;
                   1326: }
                   1327: 
                   1328: /**************** Product of 2 matrices ******************/
                   1329: 
                   1330: double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)
                   1331: {
                   1332:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   1333:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   1334:   /* in, b, out are matrice of pointers which should have been initialized 
                   1335:      before: only the contents of out is modified. The function returns
                   1336:      a pointer to pointers identical to out */
                   1337:   long i, j, k;
                   1338:   for(i=nrl; i<= nrh; i++)
                   1339:     for(k=ncolol; k<=ncoloh; k++)
                   1340:       for(j=ncl,out[i][k]=0.; j<=nch; j++)
                   1341:        out[i][k] +=in[i][j]*b[j][k];
                   1342: 
                   1343:   return out;
                   1344: }
                   1345: 
                   1346: 
                   1347: /************* Higher Matrix Product ***************/
                   1348: 
                   1349: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   1350: {
                   1351:   /* Computes the transition matrix starting at age 'age' over 
                   1352:      'nhstepm*hstepm*stepm' months (i.e. until
                   1353:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   1354:      nhstepm*hstepm matrices. 
                   1355:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   1356:      (typically every 2 years instead of every month which is too big 
                   1357:      for the memory).
                   1358:      Model is determined by parameters x and covariates have to be 
                   1359:      included manually here. 
                   1360: 
                   1361:      */
                   1362: 
                   1363:   int i, j, d, h, k;
1.131     brouard  1364:   double **out, cov[NCOVMAX+1];
1.126     brouard  1365:   double **newm;
                   1366: 
                   1367:   /* Hstepm could be zero and should return the unit matrix */
                   1368:   for (i=1;i<=nlstate+ndeath;i++)
                   1369:     for (j=1;j<=nlstate+ndeath;j++){
                   1370:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   1371:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   1372:     }
                   1373:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   1374:   for(h=1; h <=nhstepm; h++){
                   1375:     for(d=1; d <=hstepm; d++){
                   1376:       newm=savm;
                   1377:       /* Covariates have to be included here again */
                   1378:       cov[1]=1.;
                   1379:       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1.131     brouard  1380:       for (k=1; k<=cptcovn;k++) 
                   1381:        cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.126     brouard  1382:       for (k=1; k<=cptcovage;k++)
                   1383:        cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
                   1384:       for (k=1; k<=cptcovprod;k++)
                   1385:        cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
                   1386: 
                   1387: 
                   1388:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   1389:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   1390:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   1391:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1392:       savm=oldm;
                   1393:       oldm=newm;
                   1394:     }
                   1395:     for(i=1; i<=nlstate+ndeath; i++)
                   1396:       for(j=1;j<=nlstate+ndeath;j++) {
                   1397:        po[i][j][h]=newm[i][j];
1.128     brouard  1398:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  1399:       }
1.128     brouard  1400:     /*printf("h=%d ",h);*/
1.126     brouard  1401:   } /* end h */
1.128     brouard  1402: /*     printf("\n H=%d \n",h); */
1.126     brouard  1403:   return po;
                   1404: }
                   1405: 
                   1406: 
                   1407: /*************** log-likelihood *************/
                   1408: double func( double *x)
                   1409: {
                   1410:   int i, ii, j, k, mi, d, kk;
1.131     brouard  1411:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  1412:   double **out;
                   1413:   double sw; /* Sum of weights */
                   1414:   double lli; /* Individual log likelihood */
                   1415:   int s1, s2;
                   1416:   double bbh, survp;
                   1417:   long ipmx;
                   1418:   /*extern weight */
                   1419:   /* We are differentiating ll according to initial status */
                   1420:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   1421:   /*for(i=1;i<imx;i++) 
                   1422:     printf(" %d\n",s[4][i]);
                   1423:   */
                   1424:   cov[1]=1.;
                   1425: 
                   1426:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   1427: 
                   1428:   if(mle==1){
                   1429:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1430:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1431:       for(mi=1; mi<= wav[i]-1; mi++){
                   1432:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1433:          for (j=1;j<=nlstate+ndeath;j++){
                   1434:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1435:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1436:          }
                   1437:        for(d=0; d<dh[mi][i]; d++){
                   1438:          newm=savm;
                   1439:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1440:          for (kk=1; kk<=cptcovage;kk++) {
                   1441:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1442:          }
                   1443:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1444:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1445:          savm=oldm;
                   1446:          oldm=newm;
                   1447:        } /* end mult */
                   1448:       
                   1449:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   1450:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   1451:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   1452:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   1453:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   1454:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   1455:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   1456:         * probability in order to take into account the bias as a fraction of the way
                   1457:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   1458:         * -stepm/2 to stepm/2 .
                   1459:         * For stepm=1 the results are the same as for previous versions of Imach.
                   1460:         * For stepm > 1 the results are less biased than in previous versions. 
                   1461:         */
                   1462:        s1=s[mw[mi][i]][i];
                   1463:        s2=s[mw[mi+1][i]][i];
                   1464:        bbh=(double)bh[mi][i]/(double)stepm; 
                   1465:        /* bias bh is positive if real duration
                   1466:         * is higher than the multiple of stepm and negative otherwise.
                   1467:         */
                   1468:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   1469:        if( s2 > nlstate){ 
                   1470:          /* i.e. if s2 is a death state and if the date of death is known 
                   1471:             then the contribution to the likelihood is the probability to 
                   1472:             die between last step unit time and current  step unit time, 
                   1473:             which is also equal to probability to die before dh 
                   1474:             minus probability to die before dh-stepm . 
                   1475:             In version up to 0.92 likelihood was computed
                   1476:        as if date of death was unknown. Death was treated as any other
                   1477:        health state: the date of the interview describes the actual state
                   1478:        and not the date of a change in health state. The former idea was
                   1479:        to consider that at each interview the state was recorded
                   1480:        (healthy, disable or death) and IMaCh was corrected; but when we
                   1481:        introduced the exact date of death then we should have modified
                   1482:        the contribution of an exact death to the likelihood. This new
                   1483:        contribution is smaller and very dependent of the step unit
                   1484:        stepm. It is no more the probability to die between last interview
                   1485:        and month of death but the probability to survive from last
                   1486:        interview up to one month before death multiplied by the
                   1487:        probability to die within a month. Thanks to Chris
                   1488:        Jackson for correcting this bug.  Former versions increased
                   1489:        mortality artificially. The bad side is that we add another loop
                   1490:        which slows down the processing. The difference can be up to 10%
                   1491:        lower mortality.
                   1492:          */
                   1493:          lli=log(out[s1][s2] - savm[s1][s2]);
                   1494: 
                   1495: 
                   1496:        } else if  (s2==-2) {
                   1497:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   1498:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   1499:          /*survp += out[s1][j]; */
                   1500:          lli= log(survp);
                   1501:        }
                   1502:        
                   1503:        else if  (s2==-4) { 
                   1504:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   1505:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   1506:          lli= log(survp); 
                   1507:        } 
                   1508: 
                   1509:        else if  (s2==-5) { 
                   1510:          for (j=1,survp=0. ; j<=2; j++)  
                   1511:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   1512:          lli= log(survp); 
                   1513:        } 
                   1514:        
                   1515:        else{
                   1516:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   1517:          /*  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 */
                   1518:        } 
                   1519:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   1520:        /*if(lli ==000.0)*/
                   1521:        /*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); */
                   1522:        ipmx +=1;
                   1523:        sw += weight[i];
                   1524:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1525:       } /* end of wave */
                   1526:     } /* end of individual */
                   1527:   }  else if(mle==2){
                   1528:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1529:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1530:       for(mi=1; mi<= wav[i]-1; mi++){
                   1531:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1532:          for (j=1;j<=nlstate+ndeath;j++){
                   1533:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1534:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1535:          }
                   1536:        for(d=0; d<=dh[mi][i]; d++){
                   1537:          newm=savm;
                   1538:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1539:          for (kk=1; kk<=cptcovage;kk++) {
                   1540:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1541:          }
                   1542:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1543:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1544:          savm=oldm;
                   1545:          oldm=newm;
                   1546:        } /* end mult */
                   1547:       
                   1548:        s1=s[mw[mi][i]][i];
                   1549:        s2=s[mw[mi+1][i]][i];
                   1550:        bbh=(double)bh[mi][i]/(double)stepm; 
                   1551:        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 */
                   1552:        ipmx +=1;
                   1553:        sw += weight[i];
                   1554:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1555:       } /* end of wave */
                   1556:     } /* end of individual */
                   1557:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   1558:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1559:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1560:       for(mi=1; mi<= wav[i]-1; mi++){
                   1561:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1562:          for (j=1;j<=nlstate+ndeath;j++){
                   1563:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1564:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1565:          }
                   1566:        for(d=0; d<dh[mi][i]; d++){
                   1567:          newm=savm;
                   1568:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1569:          for (kk=1; kk<=cptcovage;kk++) {
                   1570:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1571:          }
                   1572:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1573:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1574:          savm=oldm;
                   1575:          oldm=newm;
                   1576:        } /* end mult */
                   1577:       
                   1578:        s1=s[mw[mi][i]][i];
                   1579:        s2=s[mw[mi+1][i]][i];
                   1580:        bbh=(double)bh[mi][i]/(double)stepm; 
                   1581:        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 */
                   1582:        ipmx +=1;
                   1583:        sw += weight[i];
                   1584:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1585:       } /* end of wave */
                   1586:     } /* end of individual */
                   1587:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   1588:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1589:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1590:       for(mi=1; mi<= wav[i]-1; mi++){
                   1591:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1592:          for (j=1;j<=nlstate+ndeath;j++){
                   1593:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1594:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1595:          }
                   1596:        for(d=0; d<dh[mi][i]; d++){
                   1597:          newm=savm;
                   1598:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1599:          for (kk=1; kk<=cptcovage;kk++) {
                   1600:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1601:          }
                   1602:        
                   1603:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1604:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1605:          savm=oldm;
                   1606:          oldm=newm;
                   1607:        } /* end mult */
                   1608:       
                   1609:        s1=s[mw[mi][i]][i];
                   1610:        s2=s[mw[mi+1][i]][i];
                   1611:        if( s2 > nlstate){ 
                   1612:          lli=log(out[s1][s2] - savm[s1][s2]);
                   1613:        }else{
                   1614:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   1615:        }
                   1616:        ipmx +=1;
                   1617:        sw += weight[i];
                   1618:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1619: /*     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]); */
                   1620:       } /* end of wave */
                   1621:     } /* end of individual */
                   1622:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   1623:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1624:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1625:       for(mi=1; mi<= wav[i]-1; mi++){
                   1626:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1627:          for (j=1;j<=nlstate+ndeath;j++){
                   1628:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1629:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1630:          }
                   1631:        for(d=0; d<dh[mi][i]; d++){
                   1632:          newm=savm;
                   1633:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1634:          for (kk=1; kk<=cptcovage;kk++) {
                   1635:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1636:          }
                   1637:        
                   1638:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1639:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1640:          savm=oldm;
                   1641:          oldm=newm;
                   1642:        } /* end mult */
                   1643:       
                   1644:        s1=s[mw[mi][i]][i];
                   1645:        s2=s[mw[mi+1][i]][i];
                   1646:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   1647:        ipmx +=1;
                   1648:        sw += weight[i];
                   1649:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1650:        /*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]);*/
                   1651:       } /* end of wave */
                   1652:     } /* end of individual */
                   1653:   } /* End of if */
                   1654:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   1655:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   1656:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   1657:   return -l;
                   1658: }
                   1659: 
                   1660: /*************** log-likelihood *************/
                   1661: double funcone( double *x)
                   1662: {
                   1663:   /* Same as likeli but slower because of a lot of printf and if */
                   1664:   int i, ii, j, k, mi, d, kk;
1.131     brouard  1665:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  1666:   double **out;
                   1667:   double lli; /* Individual log likelihood */
                   1668:   double llt;
                   1669:   int s1, s2;
                   1670:   double bbh, survp;
                   1671:   /*extern weight */
                   1672:   /* We are differentiating ll according to initial status */
                   1673:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   1674:   /*for(i=1;i<imx;i++) 
                   1675:     printf(" %d\n",s[4][i]);
                   1676:   */
                   1677:   cov[1]=1.;
                   1678: 
                   1679:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   1680: 
                   1681:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1682:     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1683:     for(mi=1; mi<= wav[i]-1; mi++){
                   1684:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   1685:        for (j=1;j<=nlstate+ndeath;j++){
                   1686:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1687:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1688:        }
                   1689:       for(d=0; d<dh[mi][i]; d++){
                   1690:        newm=savm;
                   1691:        cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1692:        for (kk=1; kk<=cptcovage;kk++) {
                   1693:          cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1694:        }
                   1695:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1696:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1697:        savm=oldm;
                   1698:        oldm=newm;
                   1699:       } /* end mult */
                   1700:       
                   1701:       s1=s[mw[mi][i]][i];
                   1702:       s2=s[mw[mi+1][i]][i];
                   1703:       bbh=(double)bh[mi][i]/(double)stepm; 
                   1704:       /* bias is positive if real duration
                   1705:        * is higher than the multiple of stepm and negative otherwise.
                   1706:        */
                   1707:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   1708:        lli=log(out[s1][s2] - savm[s1][s2]);
                   1709:       } else if  (s2==-2) {
                   1710:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   1711:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   1712:        lli= log(survp);
                   1713:       }else if (mle==1){
                   1714:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   1715:       } else if(mle==2){
                   1716:        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 */
                   1717:       } else if(mle==3){  /* exponential inter-extrapolation */
                   1718:        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 */
                   1719:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   1720:        lli=log(out[s1][s2]); /* Original formula */
1.136   ! brouard  1721:       } else{  /* mle=0 back to 1 */
        !          1722:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
        !          1723:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  1724:       } /* End of if */
                   1725:       ipmx +=1;
                   1726:       sw += weight[i];
                   1727:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  1728:       /*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]); */
1.126     brouard  1729:       if(globpr){
                   1730:        fprintf(ficresilk,"%9d %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
                   1731:  %11.6f %11.6f %11.6f ", \
                   1732:                num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
                   1733:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   1734:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   1735:          llt +=ll[k]*gipmx/gsw;
                   1736:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   1737:        }
                   1738:        fprintf(ficresilk," %10.6f\n", -llt);
                   1739:       }
                   1740:     } /* end of wave */
                   1741:   } /* end of individual */
                   1742:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   1743:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   1744:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   1745:   if(globpr==0){ /* First time we count the contributions and weights */
                   1746:     gipmx=ipmx;
                   1747:     gsw=sw;
                   1748:   }
                   1749:   return -l;
                   1750: }
                   1751: 
                   1752: 
                   1753: /*************** function likelione ***********/
                   1754: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   1755: {
                   1756:   /* This routine should help understanding what is done with 
                   1757:      the selection of individuals/waves and
                   1758:      to check the exact contribution to the likelihood.
                   1759:      Plotting could be done.
                   1760:    */
                   1761:   int k;
                   1762: 
                   1763:   if(*globpri !=0){ /* Just counts and sums, no printings */
                   1764:     strcpy(fileresilk,"ilk"); 
                   1765:     strcat(fileresilk,fileres);
                   1766:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   1767:       printf("Problem with resultfile: %s\n", fileresilk);
                   1768:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   1769:     }
                   1770:     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");
                   1771:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
                   1772:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   1773:     for(k=1; k<=nlstate; k++) 
                   1774:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   1775:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   1776:   }
                   1777: 
                   1778:   *fretone=(*funcone)(p);
                   1779:   if(*globpri !=0){
                   1780:     fclose(ficresilk);
                   1781:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
                   1782:     fflush(fichtm); 
                   1783:   } 
                   1784:   return;
                   1785: }
                   1786: 
                   1787: 
                   1788: /*********** Maximum Likelihood Estimation ***************/
                   1789: 
                   1790: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   1791: {
                   1792:   int i,j, iter;
                   1793:   double **xi;
                   1794:   double fret;
                   1795:   double fretone; /* Only one call to likelihood */
                   1796:   /*  char filerespow[FILENAMELENGTH];*/
                   1797:   xi=matrix(1,npar,1,npar);
                   1798:   for (i=1;i<=npar;i++)
                   1799:     for (j=1;j<=npar;j++)
                   1800:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   1801:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
                   1802:   strcpy(filerespow,"pow"); 
                   1803:   strcat(filerespow,fileres);
                   1804:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   1805:     printf("Problem with resultfile: %s\n", filerespow);
                   1806:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   1807:   }
                   1808:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   1809:   for (i=1;i<=nlstate;i++)
                   1810:     for(j=1;j<=nlstate+ndeath;j++)
                   1811:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   1812:   fprintf(ficrespow,"\n");
                   1813: 
                   1814:   powell(p,xi,npar,ftol,&iter,&fret,func);
                   1815: 
                   1816:   free_matrix(xi,1,npar,1,npar);
                   1817:   fclose(ficrespow);
                   1818:   printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
                   1819:   fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
                   1820:   fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
                   1821: 
                   1822: }
                   1823: 
                   1824: /**** Computes Hessian and covariance matrix ***/
                   1825: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
                   1826: {
                   1827:   double  **a,**y,*x,pd;
                   1828:   double **hess;
                   1829:   int i, j,jk;
                   1830:   int *indx;
                   1831: 
                   1832:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
                   1833:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
                   1834:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   1835:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   1836:   double gompertz(double p[]);
                   1837:   hess=matrix(1,npar,1,npar);
                   1838: 
                   1839:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   1840:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   1841:   for (i=1;i<=npar;i++){
                   1842:     printf("%d",i);fflush(stdout);
                   1843:     fprintf(ficlog,"%d",i);fflush(ficlog);
                   1844:    
                   1845:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   1846:     
                   1847:     /*  printf(" %f ",p[i]);
                   1848:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   1849:   }
                   1850:   
                   1851:   for (i=1;i<=npar;i++) {
                   1852:     for (j=1;j<=npar;j++)  {
                   1853:       if (j>i) { 
                   1854:        printf(".%d%d",i,j);fflush(stdout);
                   1855:        fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
                   1856:        hess[i][j]=hessij(p,delti,i,j,func,npar);
                   1857:        
                   1858:        hess[j][i]=hess[i][j];    
                   1859:        /*printf(" %lf ",hess[i][j]);*/
                   1860:       }
                   1861:     }
                   1862:   }
                   1863:   printf("\n");
                   1864:   fprintf(ficlog,"\n");
                   1865: 
                   1866:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   1867:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   1868:   
                   1869:   a=matrix(1,npar,1,npar);
                   1870:   y=matrix(1,npar,1,npar);
                   1871:   x=vector(1,npar);
                   1872:   indx=ivector(1,npar);
                   1873:   for (i=1;i<=npar;i++)
                   1874:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   1875:   ludcmp(a,npar,indx,&pd);
                   1876: 
                   1877:   for (j=1;j<=npar;j++) {
                   1878:     for (i=1;i<=npar;i++) x[i]=0;
                   1879:     x[j]=1;
                   1880:     lubksb(a,npar,indx,x);
                   1881:     for (i=1;i<=npar;i++){ 
                   1882:       matcov[i][j]=x[i];
                   1883:     }
                   1884:   }
                   1885: 
                   1886:   printf("\n#Hessian matrix#\n");
                   1887:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   1888:   for (i=1;i<=npar;i++) { 
                   1889:     for (j=1;j<=npar;j++) { 
                   1890:       printf("%.3e ",hess[i][j]);
                   1891:       fprintf(ficlog,"%.3e ",hess[i][j]);
                   1892:     }
                   1893:     printf("\n");
                   1894:     fprintf(ficlog,"\n");
                   1895:   }
                   1896: 
                   1897:   /* Recompute Inverse */
                   1898:   for (i=1;i<=npar;i++)
                   1899:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
                   1900:   ludcmp(a,npar,indx,&pd);
                   1901: 
                   1902:   /*  printf("\n#Hessian matrix recomputed#\n");
                   1903: 
                   1904:   for (j=1;j<=npar;j++) {
                   1905:     for (i=1;i<=npar;i++) x[i]=0;
                   1906:     x[j]=1;
                   1907:     lubksb(a,npar,indx,x);
                   1908:     for (i=1;i<=npar;i++){ 
                   1909:       y[i][j]=x[i];
                   1910:       printf("%.3e ",y[i][j]);
                   1911:       fprintf(ficlog,"%.3e ",y[i][j]);
                   1912:     }
                   1913:     printf("\n");
                   1914:     fprintf(ficlog,"\n");
                   1915:   }
                   1916:   */
                   1917: 
                   1918:   free_matrix(a,1,npar,1,npar);
                   1919:   free_matrix(y,1,npar,1,npar);
                   1920:   free_vector(x,1,npar);
                   1921:   free_ivector(indx,1,npar);
                   1922:   free_matrix(hess,1,npar,1,npar);
                   1923: 
                   1924: 
                   1925: }
                   1926: 
                   1927: /*************** hessian matrix ****************/
                   1928: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
                   1929: {
                   1930:   int i;
                   1931:   int l=1, lmax=20;
                   1932:   double k1,k2;
1.132     brouard  1933:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  1934:   double res;
                   1935:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   1936:   double fx;
                   1937:   int k=0,kmax=10;
                   1938:   double l1;
                   1939: 
                   1940:   fx=func(x);
                   1941:   for (i=1;i<=npar;i++) p2[i]=x[i];
                   1942:   for(l=0 ; l <=lmax; l++){
                   1943:     l1=pow(10,l);
                   1944:     delts=delt;
                   1945:     for(k=1 ; k <kmax; k=k+1){
                   1946:       delt = delta*(l1*k);
                   1947:       p2[theta]=x[theta] +delt;
                   1948:       k1=func(p2)-fx;
                   1949:       p2[theta]=x[theta]-delt;
                   1950:       k2=func(p2)-fx;
                   1951:       /*res= (k1-2.0*fx+k2)/delt/delt; */
                   1952:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
                   1953:       
1.132     brouard  1954: #ifdef DEBUGHESS
1.126     brouard  1955:       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);
                   1956:       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);
                   1957: #endif
                   1958:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   1959:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   1960:        k=kmax;
                   1961:       }
                   1962:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
                   1963:        k=kmax; l=lmax*10.;
                   1964:       }
                   1965:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   1966:        delts=delt;
                   1967:       }
                   1968:     }
                   1969:   }
                   1970:   delti[theta]=delts;
                   1971:   return res; 
                   1972:   
                   1973: }
                   1974: 
                   1975: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
                   1976: {
                   1977:   int i;
                   1978:   int l=1, l1, lmax=20;
                   1979:   double k1,k2,k3,k4,res,fx;
1.132     brouard  1980:   double p2[MAXPARM+1];
1.126     brouard  1981:   int k;
                   1982: 
                   1983:   fx=func(x);
                   1984:   for (k=1; k<=2; k++) {
                   1985:     for (i=1;i<=npar;i++) p2[i]=x[i];
                   1986:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   1987:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   1988:     k1=func(p2)-fx;
                   1989:   
                   1990:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   1991:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   1992:     k2=func(p2)-fx;
                   1993:   
                   1994:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   1995:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   1996:     k3=func(p2)-fx;
                   1997:   
                   1998:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   1999:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2000:     k4=func(p2)-fx;
                   2001:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
                   2002: #ifdef DEBUG
                   2003:     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);
                   2004:     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);
                   2005: #endif
                   2006:   }
                   2007:   return res;
                   2008: }
                   2009: 
                   2010: /************** Inverse of matrix **************/
                   2011: void ludcmp(double **a, int n, int *indx, double *d) 
                   2012: { 
                   2013:   int i,imax,j,k; 
                   2014:   double big,dum,sum,temp; 
                   2015:   double *vv; 
                   2016:  
                   2017:   vv=vector(1,n); 
                   2018:   *d=1.0; 
                   2019:   for (i=1;i<=n;i++) { 
                   2020:     big=0.0; 
                   2021:     for (j=1;j<=n;j++) 
                   2022:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   2023:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   2024:     vv[i]=1.0/big; 
                   2025:   } 
                   2026:   for (j=1;j<=n;j++) { 
                   2027:     for (i=1;i<j;i++) { 
                   2028:       sum=a[i][j]; 
                   2029:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   2030:       a[i][j]=sum; 
                   2031:     } 
                   2032:     big=0.0; 
                   2033:     for (i=j;i<=n;i++) { 
                   2034:       sum=a[i][j]; 
                   2035:       for (k=1;k<j;k++) 
                   2036:        sum -= a[i][k]*a[k][j]; 
                   2037:       a[i][j]=sum; 
                   2038:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   2039:        big=dum; 
                   2040:        imax=i; 
                   2041:       } 
                   2042:     } 
                   2043:     if (j != imax) { 
                   2044:       for (k=1;k<=n;k++) { 
                   2045:        dum=a[imax][k]; 
                   2046:        a[imax][k]=a[j][k]; 
                   2047:        a[j][k]=dum; 
                   2048:       } 
                   2049:       *d = -(*d); 
                   2050:       vv[imax]=vv[j]; 
                   2051:     } 
                   2052:     indx[j]=imax; 
                   2053:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   2054:     if (j != n) { 
                   2055:       dum=1.0/(a[j][j]); 
                   2056:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   2057:     } 
                   2058:   } 
                   2059:   free_vector(vv,1,n);  /* Doesn't work */
                   2060: ;
                   2061: } 
                   2062: 
                   2063: void lubksb(double **a, int n, int *indx, double b[]) 
                   2064: { 
                   2065:   int i,ii=0,ip,j; 
                   2066:   double sum; 
                   2067:  
                   2068:   for (i=1;i<=n;i++) { 
                   2069:     ip=indx[i]; 
                   2070:     sum=b[ip]; 
                   2071:     b[ip]=b[i]; 
                   2072:     if (ii) 
                   2073:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   2074:     else if (sum) ii=i; 
                   2075:     b[i]=sum; 
                   2076:   } 
                   2077:   for (i=n;i>=1;i--) { 
                   2078:     sum=b[i]; 
                   2079:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   2080:     b[i]=sum/a[i][i]; 
                   2081:   } 
                   2082: } 
                   2083: 
                   2084: void pstamp(FILE *fichier)
                   2085: {
                   2086:   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
                   2087: }
                   2088: 
                   2089: /************ Frequencies ********************/
                   2090: 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[])
                   2091: {  /* Some frequencies */
                   2092:   
1.130     brouard  2093:   int i, m, jk, k1,i1, j1, bool, z1,j;
1.126     brouard  2094:   int first;
                   2095:   double ***freq; /* Frequencies */
                   2096:   double *pp, **prop;
                   2097:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
                   2098:   char fileresp[FILENAMELENGTH];
                   2099:   
                   2100:   pp=vector(1,nlstate);
                   2101:   prop=matrix(1,nlstate,iagemin,iagemax+3);
                   2102:   strcpy(fileresp,"p");
                   2103:   strcat(fileresp,fileres);
                   2104:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   2105:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   2106:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   2107:     exit(0);
                   2108:   }
                   2109:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   2110:   j1=0;
                   2111:   
                   2112:   j=cptcoveff;
                   2113:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2114: 
                   2115:   first=1;
                   2116: 
                   2117:   for(k1=1; k1<=j;k1++){
                   2118:     for(i1=1; i1<=ncodemax[k1];i1++){
                   2119:       j1++;
                   2120:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   2121:        scanf("%d", i);*/
                   2122:       for (i=-5; i<=nlstate+ndeath; i++)  
                   2123:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   2124:          for(m=iagemin; m <= iagemax+3; m++)
                   2125:            freq[i][jk][m]=0;
                   2126: 
                   2127:     for (i=1; i<=nlstate; i++)  
                   2128:       for(m=iagemin; m <= iagemax+3; m++)
                   2129:        prop[i][m]=0;
                   2130:       
                   2131:       dateintsum=0;
                   2132:       k2cpt=0;
                   2133:       for (i=1; i<=imx; i++) {
                   2134:        bool=1;
                   2135:        if  (cptcovn>0) {
                   2136:          for (z1=1; z1<=cptcoveff; z1++) 
                   2137:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
                   2138:              bool=0;
                   2139:        }
                   2140:        if (bool==1){
                   2141:          for(m=firstpass; m<=lastpass; m++){
                   2142:            k2=anint[m][i]+(mint[m][i]/12.);
                   2143:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   2144:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   2145:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   2146:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   2147:              if (m<lastpass) {
                   2148:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   2149:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   2150:              }
                   2151:              
                   2152:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                   2153:                dateintsum=dateintsum+k2;
                   2154:                k2cpt++;
                   2155:              }
                   2156:              /*}*/
                   2157:          }
                   2158:        }
                   2159:       }
                   2160:        
                   2161:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   2162:       pstamp(ficresp);
                   2163:       if  (cptcovn>0) {
                   2164:        fprintf(ficresp, "\n#********** Variable "); 
                   2165:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2166:        fprintf(ficresp, "**********\n#");
                   2167:       }
                   2168:       for(i=1; i<=nlstate;i++) 
                   2169:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   2170:       fprintf(ficresp, "\n");
                   2171:       
                   2172:       for(i=iagemin; i <= iagemax+3; i++){
                   2173:        if(i==iagemax+3){
                   2174:          fprintf(ficlog,"Total");
                   2175:        }else{
                   2176:          if(first==1){
                   2177:            first=0;
                   2178:            printf("See log file for details...\n");
                   2179:          }
                   2180:          fprintf(ficlog,"Age %d", i);
                   2181:        }
                   2182:        for(jk=1; jk <=nlstate ; jk++){
                   2183:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   2184:            pp[jk] += freq[jk][m][i]; 
                   2185:        }
                   2186:        for(jk=1; jk <=nlstate ; jk++){
                   2187:          for(m=-1, pos=0; m <=0 ; m++)
                   2188:            pos += freq[jk][m][i];
                   2189:          if(pp[jk]>=1.e-10){
                   2190:            if(first==1){
1.132     brouard  2191:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  2192:            }
                   2193:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   2194:          }else{
                   2195:            if(first==1)
                   2196:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   2197:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   2198:          }
                   2199:        }
                   2200: 
                   2201:        for(jk=1; jk <=nlstate ; jk++){
                   2202:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   2203:            pp[jk] += freq[jk][m][i];
                   2204:        }       
                   2205:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   2206:          pos += pp[jk];
                   2207:          posprop += prop[jk][i];
                   2208:        }
                   2209:        for(jk=1; jk <=nlstate ; jk++){
                   2210:          if(pos>=1.e-5){
                   2211:            if(first==1)
                   2212:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   2213:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   2214:          }else{
                   2215:            if(first==1)
                   2216:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   2217:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   2218:          }
                   2219:          if( i <= iagemax){
                   2220:            if(pos>=1.e-5){
                   2221:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                   2222:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   2223:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   2224:            }
                   2225:            else
                   2226:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   2227:          }
                   2228:        }
                   2229:        
                   2230:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   2231:          for(m=-1; m <=nlstate+ndeath; m++)
                   2232:            if(freq[jk][m][i] !=0 ) {
                   2233:            if(first==1)
                   2234:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   2235:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   2236:            }
                   2237:        if(i <= iagemax)
                   2238:          fprintf(ficresp,"\n");
                   2239:        if(first==1)
                   2240:          printf("Others in log...\n");
                   2241:        fprintf(ficlog,"\n");
                   2242:       }
                   2243:     }
                   2244:   }
                   2245:   dateintmean=dateintsum/k2cpt; 
                   2246:  
                   2247:   fclose(ficresp);
                   2248:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   2249:   free_vector(pp,1,nlstate);
                   2250:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   2251:   /* End of Freq */
                   2252: }
                   2253: 
                   2254: /************ Prevalence ********************/
                   2255: 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)
                   2256: {  
                   2257:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   2258:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   2259:      We still use firstpass and lastpass as another selection.
                   2260:   */
                   2261:  
1.130     brouard  2262:   int i, m, jk, k1, i1, j1, bool, z1,j;
1.126     brouard  2263:   double ***freq; /* Frequencies */
                   2264:   double *pp, **prop;
                   2265:   double pos,posprop; 
                   2266:   double  y2; /* in fractional years */
                   2267:   int iagemin, iagemax;
                   2268: 
                   2269:   iagemin= (int) agemin;
                   2270:   iagemax= (int) agemax;
                   2271:   /*pp=vector(1,nlstate);*/
                   2272:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   2273:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   2274:   j1=0;
                   2275:   
                   2276:   j=cptcoveff;
                   2277:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2278:   
                   2279:   for(k1=1; k1<=j;k1++){
                   2280:     for(i1=1; i1<=ncodemax[k1];i1++){
                   2281:       j1++;
                   2282:       
                   2283:       for (i=1; i<=nlstate; i++)  
                   2284:        for(m=iagemin; m <= iagemax+3; m++)
                   2285:          prop[i][m]=0.0;
                   2286:      
                   2287:       for (i=1; i<=imx; i++) { /* Each individual */
                   2288:        bool=1;
                   2289:        if  (cptcovn>0) {
                   2290:          for (z1=1; z1<=cptcoveff; z1++) 
                   2291:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
                   2292:              bool=0;
                   2293:        } 
                   2294:        if (bool==1) { 
                   2295:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                   2296:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   2297:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   2298:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   2299:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   2300:              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); 
                   2301:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   2302:                /*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]]);*/
                   2303:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   2304:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   2305:              } 
                   2306:            }
                   2307:          } /* end selection of waves */
                   2308:        }
                   2309:       }
                   2310:       for(i=iagemin; i <= iagemax+3; i++){  
                   2311:        
                   2312:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   2313:          posprop += prop[jk][i]; 
                   2314:        } 
                   2315: 
                   2316:        for(jk=1; jk <=nlstate ; jk++){     
                   2317:          if( i <=  iagemax){ 
                   2318:            if(posprop>=1.e-5){ 
                   2319:              probs[i][jk][j1]= prop[jk][i]/posprop;
1.128     brouard  2320:            } else
                   2321:              printf("Warning Observed prevalence probs[%d][%d][%d]=%lf because of lack of cases\n",jk,i,j1,probs[i][jk][j1]);
1.126     brouard  2322:          } 
                   2323:        }/* end jk */ 
                   2324:       }/* end i */ 
                   2325:     } /* end i1 */
                   2326:   } /* end k1 */
                   2327:   
                   2328:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   2329:   /*free_vector(pp,1,nlstate);*/
                   2330:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   2331: }  /* End of prevalence */
                   2332: 
                   2333: /************* Waves Concatenation ***************/
                   2334: 
                   2335: 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)
                   2336: {
                   2337:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   2338:      Death is a valid wave (if date is known).
                   2339:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   2340:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   2341:      and mw[mi+1][i]. dh depends on stepm.
                   2342:      */
                   2343: 
                   2344:   int i, mi, m;
                   2345:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   2346:      double sum=0., jmean=0.;*/
                   2347:   int first;
                   2348:   int j, k=0,jk, ju, jl;
                   2349:   double sum=0.;
                   2350:   first=0;
                   2351:   jmin=1e+5;
                   2352:   jmax=-1;
                   2353:   jmean=0.;
                   2354:   for(i=1; i<=imx; i++){
                   2355:     mi=0;
                   2356:     m=firstpass;
                   2357:     while(s[m][i] <= nlstate){
                   2358:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   2359:        mw[++mi][i]=m;
                   2360:       if(m >=lastpass)
                   2361:        break;
                   2362:       else
                   2363:        m++;
                   2364:     }/* end while */
                   2365:     if (s[m][i] > nlstate){
                   2366:       mi++;    /* Death is another wave */
                   2367:       /* if(mi==0)  never been interviewed correctly before death */
                   2368:         /* Only death is a correct wave */
                   2369:       mw[mi][i]=m;
                   2370:     }
                   2371: 
                   2372:     wav[i]=mi;
                   2373:     if(mi==0){
                   2374:       nbwarn++;
                   2375:       if(first==0){
                   2376:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   2377:        first=1;
                   2378:       }
                   2379:       if(first==1){
                   2380:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   2381:       }
                   2382:     } /* end mi==0 */
                   2383:   } /* End individuals */
                   2384: 
                   2385:   for(i=1; i<=imx; i++){
                   2386:     for(mi=1; mi<wav[i];mi++){
                   2387:       if (stepm <=0)
                   2388:        dh[mi][i]=1;
                   2389:       else{
                   2390:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   2391:          if (agedc[i] < 2*AGESUP) {
                   2392:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   2393:            if(j==0) j=1;  /* Survives at least one month after exam */
                   2394:            else if(j<0){
                   2395:              nberr++;
                   2396:              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]);
                   2397:              j=1; /* Temporary Dangerous patch */
                   2398:              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);
                   2399:              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]);
                   2400:              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);
                   2401:            }
                   2402:            k=k+1;
                   2403:            if (j >= jmax){
                   2404:              jmax=j;
                   2405:              ijmax=i;
                   2406:            }
                   2407:            if (j <= jmin){
                   2408:              jmin=j;
                   2409:              ijmin=i;
                   2410:            }
                   2411:            sum=sum+j;
                   2412:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   2413:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   2414:          }
                   2415:        }
                   2416:        else{
                   2417:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   2418: /*       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]); */
                   2419: 
                   2420:          k=k+1;
                   2421:          if (j >= jmax) {
                   2422:            jmax=j;
                   2423:            ijmax=i;
                   2424:          }
                   2425:          else if (j <= jmin){
                   2426:            jmin=j;
                   2427:            ijmin=i;
                   2428:          }
                   2429:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   2430:          /*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]);*/
                   2431:          if(j<0){
                   2432:            nberr++;
                   2433:            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]);
                   2434:            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]);
                   2435:          }
                   2436:          sum=sum+j;
                   2437:        }
                   2438:        jk= j/stepm;
                   2439:        jl= j -jk*stepm;
                   2440:        ju= j -(jk+1)*stepm;
                   2441:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   2442:          if(jl==0){
                   2443:            dh[mi][i]=jk;
                   2444:            bh[mi][i]=0;
                   2445:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136   ! brouard  2446:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  2447:            dh[mi][i]=jk+1;
                   2448:            bh[mi][i]=ju;
                   2449:          }
                   2450:        }else{
                   2451:          if(jl <= -ju){
                   2452:            dh[mi][i]=jk;
                   2453:            bh[mi][i]=jl;       /* bias is positive if real duration
                   2454:                                 * is higher than the multiple of stepm and negative otherwise.
                   2455:                                 */
                   2456:          }
                   2457:          else{
                   2458:            dh[mi][i]=jk+1;
                   2459:            bh[mi][i]=ju;
                   2460:          }
                   2461:          if(dh[mi][i]==0){
                   2462:            dh[mi][i]=1; /* At least one step */
                   2463:            bh[mi][i]=ju; /* At least one step */
                   2464:            /*  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);*/
                   2465:          }
                   2466:        } /* end if mle */
                   2467:       }
                   2468:     } /* end wave */
                   2469:   }
                   2470:   jmean=sum/k;
                   2471:   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);
                   2472:   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);
                   2473:  }
                   2474: 
                   2475: /*********** Tricode ****************************/
                   2476: void tricode(int *Tvar, int **nbcode, int imx)
                   2477: {
1.136   ! brouard  2478:   /* Uses cptcovn+2*cptcovprod as the number of covariates */
1.130     brouard  2479:   /*     Tvar[i]=atoi(stre); /* find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 */
                   2480: 
1.131     brouard  2481:   int Ndum[20],ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136   ! brouard  2482:   int modmaxcovj=0; /* Modality max of covariates j */
1.126     brouard  2483:   cptcoveff=0; 
                   2484:  
                   2485:   for (k=0; k<maxncov; k++) Ndum[k]=0;
1.131     brouard  2486:   for (k=1; k<=7; k++) ncodemax[k]=0; /* Horrible constant again */
1.126     brouard  2487: 
1.136   ! brouard  2488:   for (j=1; j<=(cptcovn+2*cptcovprod); j++) { /* For each covariate j */
        !          2489:     for (i=1; i<=imx; i++) { /*reads the data file to get the maximum value of the 
        !          2490:                               modality of this covariate Vj*/ 
        !          2491:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Finds for covariate j, n=Tvar[j] of Vn . ij is the
        !          2492:                                      modality of the nth covariate of individual i. */
        !          2493:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.126     brouard  2494:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136   ! brouard  2495:       if (ij > modmaxcovj) modmaxcovj=ij; 
        !          2496:       /* getting the maximum value of the modality of the covariate
        !          2497:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
        !          2498:         female is 1, then modmaxcovj=1.*/
1.126     brouard  2499:     }
                   2500: 
1.136   ! brouard  2501:     for (i=0; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*/
        !          2502:       if( Ndum[i] != 0 )
        !          2503:        ncodemax[j]++; 
        !          2504:       /* Number of modalities of the j th covariate. In fact
        !          2505:         ncodemax[j]=2 (dichotom. variables only) but it could be more for
        !          2506:         historical reasons */
1.131     brouard  2507:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  2508: 
1.136   ! brouard  2509:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.126     brouard  2510:     ij=1; 
1.136   ! brouard  2511:     for (i=1; i<=ncodemax[j]; i++) { /* i= 1 to 2 for dichotomous */
        !          2512:       for (k=0; k<= maxncov; k++) { /* k=-1 ? NCOVMAX*/
1.131     brouard  2513:        if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
                   2514:          nbcode[Tvar[j]][ij]=k;  /* stores the modality in an array nbcode. 
                   2515:                                     k is a modality. If we have model=V1+V1*sex 
                   2516:                                     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126     brouard  2517:          ij++;
                   2518:        }
                   2519:        if (ij > ncodemax[j]) break; 
                   2520:       }  
                   2521:     } 
                   2522:   }  
                   2523: 
                   2524:  for (k=0; k< maxncov; k++) Ndum[k]=0;
                   2525: 
1.131     brouard  2526:  for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
1.126     brouard  2527:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
1.131     brouard  2528:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
1.126     brouard  2529:    Ndum[ij]++;
                   2530:  }
                   2531: 
                   2532:  ij=1;
                   2533:  for (i=1; i<= maxncov; i++) {
                   2534:    if((Ndum[i]!=0) && (i<=ncovcol)){
                   2535:      Tvaraff[ij]=i; /*For printing */
                   2536:      ij++;
                   2537:    }
                   2538:  }
1.131     brouard  2539:  ij--;
                   2540:  cptcoveff=ij; /*Number of simple covariates*/
1.126     brouard  2541: }
                   2542: 
                   2543: /*********** Health Expectancies ****************/
                   2544: 
1.127     brouard  2545: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
1.126     brouard  2546: 
                   2547: {
                   2548:   /* Health expectancies, no variances */
                   2549:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
                   2550:   int nhstepma, nstepma; /* Decreasing with age */
                   2551:   double age, agelim, hf;
                   2552:   double ***p3mat;
                   2553:   double eip;
                   2554: 
                   2555:   pstamp(ficreseij);
                   2556:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   2557:   fprintf(ficreseij,"# Age");
                   2558:   for(i=1; i<=nlstate;i++){
                   2559:     for(j=1; j<=nlstate;j++){
                   2560:       fprintf(ficreseij," e%1d%1d ",i,j);
                   2561:     }
                   2562:     fprintf(ficreseij," e%1d. ",i);
                   2563:   }
                   2564:   fprintf(ficreseij,"\n");
                   2565: 
                   2566:   
                   2567:   if(estepm < stepm){
                   2568:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   2569:   }
                   2570:   else  hstepm=estepm;   
                   2571:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   2572:    * This is mainly to measure the difference between two models: for example
                   2573:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   2574:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   2575:    * progression in between and thus overestimating or underestimating according
                   2576:    * to the curvature of the survival function. If, for the same date, we 
                   2577:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   2578:    * to compare the new estimate of Life expectancy with the same linear 
                   2579:    * hypothesis. A more precise result, taking into account a more precise
                   2580:    * curvature will be obtained if estepm is as small as stepm. */
                   2581: 
                   2582:   /* For example we decided to compute the life expectancy with the smallest unit */
                   2583:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   2584:      nhstepm is the number of hstepm from age to agelim 
                   2585:      nstepm is the number of stepm from age to agelin. 
                   2586:      Look at hpijx to understand the reason of that which relies in memory size
                   2587:      and note for a fixed period like estepm months */
                   2588:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   2589:      survival function given by stepm (the optimization length). Unfortunately it
                   2590:      means that if the survival funtion is printed only each two years of age and if
                   2591:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   2592:      results. So we changed our mind and took the option of the best precision.
                   2593:   */
                   2594:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   2595: 
                   2596:   agelim=AGESUP;
                   2597:   /* If stepm=6 months */
                   2598:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   2599:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   2600:     
                   2601: /* nhstepm age range expressed in number of stepm */
                   2602:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   2603:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   2604:   /* if (stepm >= YEARM) hstepm=1;*/
                   2605:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   2606:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   2607: 
                   2608:   for (age=bage; age<=fage; age ++){ 
                   2609:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   2610:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   2611:     /* if (stepm >= YEARM) hstepm=1;*/
                   2612:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   2613: 
                   2614:     /* If stepm=6 months */
                   2615:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   2616:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   2617:     
                   2618:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   2619:     
                   2620:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   2621:     
                   2622:     printf("%d|",(int)age);fflush(stdout);
                   2623:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   2624:     
                   2625:     /* Computing expectancies */
                   2626:     for(i=1; i<=nlstate;i++)
                   2627:       for(j=1; j<=nlstate;j++)
                   2628:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   2629:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   2630:          
                   2631:          /* 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]);*/
                   2632: 
                   2633:        }
                   2634: 
                   2635:     fprintf(ficreseij,"%3.0f",age );
                   2636:     for(i=1; i<=nlstate;i++){
                   2637:       eip=0;
                   2638:       for(j=1; j<=nlstate;j++){
                   2639:        eip +=eij[i][j][(int)age];
                   2640:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   2641:       }
                   2642:       fprintf(ficreseij,"%9.4f", eip );
                   2643:     }
                   2644:     fprintf(ficreseij,"\n");
                   2645:     
                   2646:   }
                   2647:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   2648:   printf("\n");
                   2649:   fprintf(ficlog,"\n");
                   2650:   
                   2651: }
                   2652: 
1.127     brouard  2653: void cvevsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,double delti[],double **matcov,char strstart[] )
1.126     brouard  2654: 
                   2655: {
                   2656:   /* Covariances of health expectancies eij and of total life expectancies according
                   2657:    to initial status i, ei. .
                   2658:   */
                   2659:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   2660:   int nhstepma, nstepma; /* Decreasing with age */
                   2661:   double age, agelim, hf;
                   2662:   double ***p3matp, ***p3matm, ***varhe;
                   2663:   double **dnewm,**doldm;
                   2664:   double *xp, *xm;
                   2665:   double **gp, **gm;
                   2666:   double ***gradg, ***trgradg;
                   2667:   int theta;
                   2668: 
                   2669:   double eip, vip;
                   2670: 
                   2671:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   2672:   xp=vector(1,npar);
                   2673:   xm=vector(1,npar);
                   2674:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   2675:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   2676:   
                   2677:   pstamp(ficresstdeij);
                   2678:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   2679:   fprintf(ficresstdeij,"# Age");
                   2680:   for(i=1; i<=nlstate;i++){
                   2681:     for(j=1; j<=nlstate;j++)
                   2682:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   2683:     fprintf(ficresstdeij," e%1d. ",i);
                   2684:   }
                   2685:   fprintf(ficresstdeij,"\n");
                   2686: 
                   2687:   pstamp(ficrescveij);
                   2688:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   2689:   fprintf(ficrescveij,"# Age");
                   2690:   for(i=1; i<=nlstate;i++)
                   2691:     for(j=1; j<=nlstate;j++){
                   2692:       cptj= (j-1)*nlstate+i;
                   2693:       for(i2=1; i2<=nlstate;i2++)
                   2694:        for(j2=1; j2<=nlstate;j2++){
                   2695:          cptj2= (j2-1)*nlstate+i2;
                   2696:          if(cptj2 <= cptj)
                   2697:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   2698:        }
                   2699:     }
                   2700:   fprintf(ficrescveij,"\n");
                   2701:   
                   2702:   if(estepm < stepm){
                   2703:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   2704:   }
                   2705:   else  hstepm=estepm;   
                   2706:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   2707:    * This is mainly to measure the difference between two models: for example
                   2708:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   2709:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   2710:    * progression in between and thus overestimating or underestimating according
                   2711:    * to the curvature of the survival function. If, for the same date, we 
                   2712:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   2713:    * to compare the new estimate of Life expectancy with the same linear 
                   2714:    * hypothesis. A more precise result, taking into account a more precise
                   2715:    * curvature will be obtained if estepm is as small as stepm. */
                   2716: 
                   2717:   /* For example we decided to compute the life expectancy with the smallest unit */
                   2718:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   2719:      nhstepm is the number of hstepm from age to agelim 
                   2720:      nstepm is the number of stepm from age to agelin. 
                   2721:      Look at hpijx to understand the reason of that which relies in memory size
                   2722:      and note for a fixed period like estepm months */
                   2723:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   2724:      survival function given by stepm (the optimization length). Unfortunately it
                   2725:      means that if the survival funtion is printed only each two years of age and if
                   2726:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   2727:      results. So we changed our mind and took the option of the best precision.
                   2728:   */
                   2729:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   2730: 
                   2731:   /* If stepm=6 months */
                   2732:   /* nhstepm age range expressed in number of stepm */
                   2733:   agelim=AGESUP;
                   2734:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   2735:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   2736:   /* if (stepm >= YEARM) hstepm=1;*/
                   2737:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   2738:   
                   2739:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   2740:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   2741:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   2742:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   2743:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   2744:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   2745: 
                   2746:   for (age=bage; age<=fage; age ++){ 
                   2747:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   2748:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   2749:     /* if (stepm >= YEARM) hstepm=1;*/
                   2750:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   2751: 
                   2752:     /* If stepm=6 months */
                   2753:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   2754:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   2755:     
                   2756:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   2757: 
                   2758:     /* Computing  Variances of health expectancies */
                   2759:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   2760:        decrease memory allocation */
                   2761:     for(theta=1; theta <=npar; theta++){
                   2762:       for(i=1; i<=npar; i++){ 
                   2763:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   2764:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   2765:       }
                   2766:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   2767:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   2768:   
                   2769:       for(j=1; j<= nlstate; j++){
                   2770:        for(i=1; i<=nlstate; i++){
                   2771:          for(h=0; h<=nhstepm-1; h++){
                   2772:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   2773:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   2774:          }
                   2775:        }
                   2776:       }
                   2777:      
                   2778:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   2779:        for(h=0; h<=nhstepm-1; h++){
                   2780:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   2781:        }
                   2782:     }/* End theta */
                   2783:     
                   2784:     
                   2785:     for(h=0; h<=nhstepm-1; h++)
                   2786:       for(j=1; j<=nlstate*nlstate;j++)
                   2787:        for(theta=1; theta <=npar; theta++)
                   2788:          trgradg[h][j][theta]=gradg[h][theta][j];
                   2789:     
                   2790: 
                   2791:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   2792:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   2793:        varhe[ij][ji][(int)age] =0.;
                   2794: 
                   2795:      printf("%d|",(int)age);fflush(stdout);
                   2796:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   2797:      for(h=0;h<=nhstepm-1;h++){
                   2798:       for(k=0;k<=nhstepm-1;k++){
                   2799:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   2800:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   2801:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   2802:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   2803:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   2804:       }
                   2805:     }
                   2806: 
                   2807:     /* Computing expectancies */
                   2808:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   2809:     for(i=1; i<=nlstate;i++)
                   2810:       for(j=1; j<=nlstate;j++)
                   2811:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   2812:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   2813:          
                   2814:          /* 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]);*/
                   2815: 
                   2816:        }
                   2817: 
                   2818:     fprintf(ficresstdeij,"%3.0f",age );
                   2819:     for(i=1; i<=nlstate;i++){
                   2820:       eip=0.;
                   2821:       vip=0.;
                   2822:       for(j=1; j<=nlstate;j++){
                   2823:        eip += eij[i][j][(int)age];
                   2824:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   2825:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   2826:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   2827:       }
                   2828:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   2829:     }
                   2830:     fprintf(ficresstdeij,"\n");
                   2831: 
                   2832:     fprintf(ficrescveij,"%3.0f",age );
                   2833:     for(i=1; i<=nlstate;i++)
                   2834:       for(j=1; j<=nlstate;j++){
                   2835:        cptj= (j-1)*nlstate+i;
                   2836:        for(i2=1; i2<=nlstate;i2++)
                   2837:          for(j2=1; j2<=nlstate;j2++){
                   2838:            cptj2= (j2-1)*nlstate+i2;
                   2839:            if(cptj2 <= cptj)
                   2840:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   2841:          }
                   2842:       }
                   2843:     fprintf(ficrescveij,"\n");
                   2844:    
                   2845:   }
                   2846:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   2847:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   2848:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   2849:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   2850:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   2851:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   2852:   printf("\n");
                   2853:   fprintf(ficlog,"\n");
                   2854: 
                   2855:   free_vector(xm,1,npar);
                   2856:   free_vector(xp,1,npar);
                   2857:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   2858:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   2859:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   2860: }
                   2861: 
                   2862: /************ Variance ******************/
                   2863: 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[])
                   2864: {
                   2865:   /* Variance of health expectancies */
                   2866:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   2867:   /* double **newm;*/
                   2868:   double **dnewm,**doldm;
                   2869:   double **dnewmp,**doldmp;
                   2870:   int i, j, nhstepm, hstepm, h, nstepm ;
                   2871:   int k, cptcode;
                   2872:   double *xp;
                   2873:   double **gp, **gm;  /* for var eij */
                   2874:   double ***gradg, ***trgradg; /*for var eij */
                   2875:   double **gradgp, **trgradgp; /* for var p point j */
                   2876:   double *gpp, *gmp; /* for var p point j */
                   2877:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   2878:   double ***p3mat;
                   2879:   double age,agelim, hf;
                   2880:   double ***mobaverage;
                   2881:   int theta;
                   2882:   char digit[4];
                   2883:   char digitp[25];
                   2884: 
                   2885:   char fileresprobmorprev[FILENAMELENGTH];
                   2886: 
                   2887:   if(popbased==1){
                   2888:     if(mobilav!=0)
                   2889:       strcpy(digitp,"-populbased-mobilav-");
                   2890:     else strcpy(digitp,"-populbased-nomobil-");
                   2891:   }
                   2892:   else 
                   2893:     strcpy(digitp,"-stablbased-");
                   2894: 
                   2895:   if (mobilav!=0) {
                   2896:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   2897:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   2898:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   2899:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   2900:     }
                   2901:   }
                   2902: 
                   2903:   strcpy(fileresprobmorprev,"prmorprev"); 
                   2904:   sprintf(digit,"%-d",ij);
                   2905:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   2906:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   2907:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   2908:   strcat(fileresprobmorprev,fileres);
                   2909:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   2910:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   2911:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   2912:   }
                   2913:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   2914:  
                   2915:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   2916:   pstamp(ficresprobmorprev);
                   2917:   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);
                   2918:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   2919:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   2920:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   2921:     for(i=1; i<=nlstate;i++)
                   2922:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   2923:   }  
                   2924:   fprintf(ficresprobmorprev,"\n");
                   2925:   fprintf(ficgp,"\n# Routine varevsij");
                   2926:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   2927:   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");
                   2928:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   2929: /*   } */
                   2930:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   2931:   pstamp(ficresvij);
                   2932:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   2933:   if(popbased==1)
1.128     brouard  2934:     fprintf(ficresvij,"the age specific prevalence observed (cross-sectionally) in the population i.e cross-sectionally\n in each health state (popbased=1) (mobilav=%d\n",mobilav);
1.126     brouard  2935:   else
                   2936:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   2937:   fprintf(ficresvij,"# Age");
                   2938:   for(i=1; i<=nlstate;i++)
                   2939:     for(j=1; j<=nlstate;j++)
                   2940:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   2941:   fprintf(ficresvij,"\n");
                   2942: 
                   2943:   xp=vector(1,npar);
                   2944:   dnewm=matrix(1,nlstate,1,npar);
                   2945:   doldm=matrix(1,nlstate,1,nlstate);
                   2946:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   2947:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   2948: 
                   2949:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   2950:   gpp=vector(nlstate+1,nlstate+ndeath);
                   2951:   gmp=vector(nlstate+1,nlstate+ndeath);
                   2952:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   2953:   
                   2954:   if(estepm < stepm){
                   2955:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   2956:   }
                   2957:   else  hstepm=estepm;   
                   2958:   /* For example we decided to compute the life expectancy with the smallest unit */
                   2959:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   2960:      nhstepm is the number of hstepm from age to agelim 
                   2961:      nstepm is the number of stepm from age to agelin. 
1.128     brouard  2962:      Look at function hpijx to understand why (it is linked to memory size questions) */
1.126     brouard  2963:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   2964:      survival function given by stepm (the optimization length). Unfortunately it
                   2965:      means that if the survival funtion is printed every two years of age and if
                   2966:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   2967:      results. So we changed our mind and took the option of the best precision.
                   2968:   */
                   2969:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   2970:   agelim = AGESUP;
                   2971:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   2972:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   2973:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   2974:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   2975:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   2976:     gp=matrix(0,nhstepm,1,nlstate);
                   2977:     gm=matrix(0,nhstepm,1,nlstate);
                   2978: 
                   2979: 
                   2980:     for(theta=1; theta <=npar; theta++){
                   2981:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   2982:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   2983:       }
                   2984:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   2985:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   2986: 
                   2987:       if (popbased==1) {
                   2988:        if(mobilav ==0){
                   2989:          for(i=1; i<=nlstate;i++)
                   2990:            prlim[i][i]=probs[(int)age][i][ij];
                   2991:        }else{ /* mobilav */ 
                   2992:          for(i=1; i<=nlstate;i++)
                   2993:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   2994:        }
                   2995:       }
                   2996:   
                   2997:       for(j=1; j<= nlstate; j++){
                   2998:        for(h=0; h<=nhstepm; h++){
                   2999:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   3000:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3001:        }
                   3002:       }
                   3003:       /* This for computing probability of death (h=1 means
                   3004:          computed over hstepm matrices product = hstepm*stepm months) 
                   3005:          as a weighted average of prlim.
                   3006:       */
                   3007:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3008:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   3009:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   3010:       }    
                   3011:       /* end probability of death */
                   3012: 
                   3013:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   3014:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3015:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3016:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3017:  
                   3018:       if (popbased==1) {
                   3019:        if(mobilav ==0){
                   3020:          for(i=1; i<=nlstate;i++)
                   3021:            prlim[i][i]=probs[(int)age][i][ij];
                   3022:        }else{ /* mobilav */ 
                   3023:          for(i=1; i<=nlstate;i++)
                   3024:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3025:        }
                   3026:       }
                   3027: 
1.128     brouard  3028:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  3029:        for(h=0; h<=nhstepm; h++){
                   3030:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   3031:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3032:        }
                   3033:       }
                   3034:       /* This for computing probability of death (h=1 means
                   3035:          computed over hstepm matrices product = hstepm*stepm months) 
                   3036:          as a weighted average of prlim.
                   3037:       */
                   3038:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3039:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   3040:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   3041:       }    
                   3042:       /* end probability of death */
                   3043: 
                   3044:       for(j=1; j<= nlstate; j++) /* vareij */
                   3045:        for(h=0; h<=nhstepm; h++){
                   3046:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   3047:        }
                   3048: 
                   3049:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   3050:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   3051:       }
                   3052: 
                   3053:     } /* End theta */
                   3054: 
                   3055:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   3056: 
                   3057:     for(h=0; h<=nhstepm; h++) /* veij */
                   3058:       for(j=1; j<=nlstate;j++)
                   3059:        for(theta=1; theta <=npar; theta++)
                   3060:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3061: 
                   3062:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   3063:       for(theta=1; theta <=npar; theta++)
                   3064:        trgradgp[j][theta]=gradgp[theta][j];
                   3065:   
                   3066: 
                   3067:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3068:     for(i=1;i<=nlstate;i++)
                   3069:       for(j=1;j<=nlstate;j++)
                   3070:        vareij[i][j][(int)age] =0.;
                   3071: 
                   3072:     for(h=0;h<=nhstepm;h++){
                   3073:       for(k=0;k<=nhstepm;k++){
                   3074:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   3075:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   3076:        for(i=1;i<=nlstate;i++)
                   3077:          for(j=1;j<=nlstate;j++)
                   3078:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   3079:       }
                   3080:     }
                   3081:   
                   3082:     /* pptj */
                   3083:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   3084:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   3085:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   3086:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   3087:        varppt[j][i]=doldmp[j][i];
                   3088:     /* end ppptj */
                   3089:     /*  x centered again */
                   3090:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   3091:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
                   3092:  
                   3093:     if (popbased==1) {
                   3094:       if(mobilav ==0){
                   3095:        for(i=1; i<=nlstate;i++)
                   3096:          prlim[i][i]=probs[(int)age][i][ij];
                   3097:       }else{ /* mobilav */ 
                   3098:        for(i=1; i<=nlstate;i++)
                   3099:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   3100:       }
                   3101:     }
                   3102:              
                   3103:     /* This for computing probability of death (h=1 means
                   3104:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   3105:        as a weighted average of prlim.
                   3106:     */
                   3107:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3108:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   3109:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   3110:     }    
                   3111:     /* end probability of death */
                   3112: 
                   3113:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   3114:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3115:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   3116:       for(i=1; i<=nlstate;i++){
                   3117:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   3118:       }
                   3119:     } 
                   3120:     fprintf(ficresprobmorprev,"\n");
                   3121: 
                   3122:     fprintf(ficresvij,"%.0f ",age );
                   3123:     for(i=1; i<=nlstate;i++)
                   3124:       for(j=1; j<=nlstate;j++){
                   3125:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   3126:       }
                   3127:     fprintf(ficresvij,"\n");
                   3128:     free_matrix(gp,0,nhstepm,1,nlstate);
                   3129:     free_matrix(gm,0,nhstepm,1,nlstate);
                   3130:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   3131:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   3132:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3133:   } /* End age */
                   3134:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   3135:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   3136:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   3137:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.131     brouard  3138:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small;set size 0.65, 0.65");
1.126     brouard  3139:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  3140:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126     brouard  3141: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   3142: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   3143: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   3144:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l 1 ",subdirf(fileresprobmorprev));
                   3145:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l 2 ",subdirf(fileresprobmorprev));
                   3146:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l 2 ",subdirf(fileresprobmorprev));
                   3147:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   3148:   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);
                   3149:   /*  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);
                   3150: */
                   3151: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
                   3152:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
                   3153: 
                   3154:   free_vector(xp,1,npar);
                   3155:   free_matrix(doldm,1,nlstate,1,nlstate);
                   3156:   free_matrix(dnewm,1,nlstate,1,npar);
                   3157:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3158:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   3159:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3160:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3161:   fclose(ficresprobmorprev);
                   3162:   fflush(ficgp);
                   3163:   fflush(fichtm); 
                   3164: }  /* end varevsij */
                   3165: 
                   3166: /************ Variance of prevlim ******************/
                   3167: 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[])
                   3168: {
                   3169:   /* Variance of prevalence limit */
                   3170:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   3171:   double **newm;
                   3172:   double **dnewm,**doldm;
                   3173:   int i, j, nhstepm, hstepm;
                   3174:   int k, cptcode;
                   3175:   double *xp;
                   3176:   double *gp, *gm;
                   3177:   double **gradg, **trgradg;
                   3178:   double age,agelim;
                   3179:   int theta;
                   3180:   
                   3181:   pstamp(ficresvpl);
                   3182:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   3183:   fprintf(ficresvpl,"# Age");
                   3184:   for(i=1; i<=nlstate;i++)
                   3185:       fprintf(ficresvpl," %1d-%1d",i,i);
                   3186:   fprintf(ficresvpl,"\n");
                   3187: 
                   3188:   xp=vector(1,npar);
                   3189:   dnewm=matrix(1,nlstate,1,npar);
                   3190:   doldm=matrix(1,nlstate,1,nlstate);
                   3191:   
                   3192:   hstepm=1*YEARM; /* Every year of age */
                   3193:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   3194:   agelim = AGESUP;
                   3195:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3196:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3197:     if (stepm >= YEARM) hstepm=1;
                   3198:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   3199:     gradg=matrix(1,npar,1,nlstate);
                   3200:     gp=vector(1,nlstate);
                   3201:     gm=vector(1,nlstate);
                   3202: 
                   3203:     for(theta=1; theta <=npar; theta++){
                   3204:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   3205:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3206:       }
                   3207:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3208:       for(i=1;i<=nlstate;i++)
                   3209:        gp[i] = prlim[i][i];
                   3210:     
                   3211:       for(i=1; i<=npar; i++) /* Computes gradient */
                   3212:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3213:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3214:       for(i=1;i<=nlstate;i++)
                   3215:        gm[i] = prlim[i][i];
                   3216: 
                   3217:       for(i=1;i<=nlstate;i++)
                   3218:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   3219:     } /* End theta */
                   3220: 
                   3221:     trgradg =matrix(1,nlstate,1,npar);
                   3222: 
                   3223:     for(j=1; j<=nlstate;j++)
                   3224:       for(theta=1; theta <=npar; theta++)
                   3225:        trgradg[j][theta]=gradg[theta][j];
                   3226: 
                   3227:     for(i=1;i<=nlstate;i++)
                   3228:       varpl[i][(int)age] =0.;
                   3229:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   3230:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   3231:     for(i=1;i<=nlstate;i++)
                   3232:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   3233: 
                   3234:     fprintf(ficresvpl,"%.0f ",age );
                   3235:     for(i=1; i<=nlstate;i++)
                   3236:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   3237:     fprintf(ficresvpl,"\n");
                   3238:     free_vector(gp,1,nlstate);
                   3239:     free_vector(gm,1,nlstate);
                   3240:     free_matrix(gradg,1,npar,1,nlstate);
                   3241:     free_matrix(trgradg,1,nlstate,1,npar);
                   3242:   } /* End age */
                   3243: 
                   3244:   free_vector(xp,1,npar);
                   3245:   free_matrix(doldm,1,nlstate,1,npar);
                   3246:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   3247: 
                   3248: }
                   3249: 
                   3250: /************ Variance of one-step probabilities  ******************/
                   3251: 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[])
                   3252: {
                   3253:   int i, j=0,  i1, k1, l1, t, tj;
                   3254:   int k2, l2, j1,  z1;
                   3255:   int k=0,l, cptcode;
                   3256:   int first=1, first1;
                   3257:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   3258:   double **dnewm,**doldm;
                   3259:   double *xp;
                   3260:   double *gp, *gm;
                   3261:   double **gradg, **trgradg;
                   3262:   double **mu;
                   3263:   double age,agelim, cov[NCOVMAX];
                   3264:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   3265:   int theta;
                   3266:   char fileresprob[FILENAMELENGTH];
                   3267:   char fileresprobcov[FILENAMELENGTH];
                   3268:   char fileresprobcor[FILENAMELENGTH];
                   3269: 
                   3270:   double ***varpij;
                   3271: 
                   3272:   strcpy(fileresprob,"prob"); 
                   3273:   strcat(fileresprob,fileres);
                   3274:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   3275:     printf("Problem with resultfile: %s\n", fileresprob);
                   3276:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   3277:   }
                   3278:   strcpy(fileresprobcov,"probcov"); 
                   3279:   strcat(fileresprobcov,fileres);
                   3280:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   3281:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   3282:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   3283:   }
                   3284:   strcpy(fileresprobcor,"probcor"); 
                   3285:   strcat(fileresprobcor,fileres);
                   3286:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   3287:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   3288:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   3289:   }
                   3290:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   3291:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   3292:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   3293:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   3294:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   3295:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   3296:   pstamp(ficresprob);
                   3297:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   3298:   fprintf(ficresprob,"# Age");
                   3299:   pstamp(ficresprobcov);
                   3300:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   3301:   fprintf(ficresprobcov,"# Age");
                   3302:   pstamp(ficresprobcor);
                   3303:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   3304:   fprintf(ficresprobcor,"# Age");
                   3305: 
                   3306: 
                   3307:   for(i=1; i<=nlstate;i++)
                   3308:     for(j=1; j<=(nlstate+ndeath);j++){
                   3309:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   3310:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   3311:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   3312:     }  
                   3313:  /* fprintf(ficresprob,"\n");
                   3314:   fprintf(ficresprobcov,"\n");
                   3315:   fprintf(ficresprobcor,"\n");
                   3316:  */
1.131     brouard  3317:   xp=vector(1,npar);
1.126     brouard  3318:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   3319:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   3320:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   3321:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   3322:   first=1;
                   3323:   fprintf(ficgp,"\n# Routine varprob");
                   3324:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   3325:   fprintf(fichtm,"\n");
                   3326: 
                   3327:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
                   3328:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
                   3329:   file %s<br>\n",optionfilehtmcov);
                   3330:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
                   3331: and drawn. It helps understanding how is the covariance between two incidences.\
                   3332:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   3333:   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. \
                   3334: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   3335: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   3336: standard deviations wide on each axis. <br>\
                   3337:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   3338:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   3339: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   3340: 
                   3341:   cov[1]=1;
                   3342:   tj=cptcoveff;
                   3343:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   3344:   j1=0;
                   3345:   for(t=1; t<=tj;t++){
                   3346:     for(i1=1; i1<=ncodemax[t];i1++){ 
                   3347:       j1++;
                   3348:       if  (cptcovn>0) {
                   3349:        fprintf(ficresprob, "\n#********** Variable "); 
                   3350:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3351:        fprintf(ficresprob, "**********\n#\n");
                   3352:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   3353:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3354:        fprintf(ficresprobcov, "**********\n#\n");
                   3355:        
                   3356:        fprintf(ficgp, "\n#********** Variable "); 
                   3357:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3358:        fprintf(ficgp, "**********\n#\n");
                   3359:        
                   3360:        
                   3361:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   3362:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3363:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   3364:        
                   3365:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   3366:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3367:        fprintf(ficresprobcor, "**********\n#");    
                   3368:       }
                   3369:       
                   3370:       for (age=bage; age<=fage; age ++){ 
                   3371:        cov[2]=age;
                   3372:        for (k=1; k<=cptcovn;k++) {
                   3373:          cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];
                   3374:        }
                   3375:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
                   3376:        for (k=1; k<=cptcovprod;k++)
                   3377:          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
                   3378:        
                   3379:        gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   3380:        trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   3381:        gp=vector(1,(nlstate)*(nlstate+ndeath));
                   3382:        gm=vector(1,(nlstate)*(nlstate+ndeath));
                   3383:     
                   3384:        for(theta=1; theta <=npar; theta++){
                   3385:          for(i=1; i<=npar; i++)
                   3386:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   3387:          
                   3388:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   3389:          
                   3390:          k=0;
                   3391:          for(i=1; i<= (nlstate); i++){
                   3392:            for(j=1; j<=(nlstate+ndeath);j++){
                   3393:              k=k+1;
                   3394:              gp[k]=pmmij[i][j];
                   3395:            }
                   3396:          }
                   3397:          
                   3398:          for(i=1; i<=npar; i++)
                   3399:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   3400:     
                   3401:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   3402:          k=0;
                   3403:          for(i=1; i<=(nlstate); i++){
                   3404:            for(j=1; j<=(nlstate+ndeath);j++){
                   3405:              k=k+1;
                   3406:              gm[k]=pmmij[i][j];
                   3407:            }
                   3408:          }
                   3409:      
                   3410:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   3411:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   3412:        }
                   3413: 
                   3414:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   3415:          for(theta=1; theta <=npar; theta++)
                   3416:            trgradg[j][theta]=gradg[theta][j];
                   3417:        
                   3418:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   3419:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   3420:        free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   3421:        free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   3422:        free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   3423:        free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   3424: 
                   3425:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   3426:        
                   3427:        k=0;
                   3428:        for(i=1; i<=(nlstate); i++){
                   3429:          for(j=1; j<=(nlstate+ndeath);j++){
                   3430:            k=k+1;
                   3431:            mu[k][(int) age]=pmmij[i][j];
                   3432:          }
                   3433:        }
                   3434:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   3435:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   3436:            varpij[i][j][(int)age] = doldm[i][j];
                   3437: 
                   3438:        /*printf("\n%d ",(int)age);
                   3439:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   3440:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   3441:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   3442:          }*/
                   3443: 
                   3444:        fprintf(ficresprob,"\n%d ",(int)age);
                   3445:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   3446:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   3447: 
                   3448:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   3449:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   3450:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   3451:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   3452:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   3453:        }
                   3454:        i=0;
                   3455:        for (k=1; k<=(nlstate);k++){
                   3456:          for (l=1; l<=(nlstate+ndeath);l++){ 
                   3457:            i=i++;
                   3458:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   3459:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   3460:            for (j=1; j<=i;j++){
                   3461:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   3462:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   3463:            }
                   3464:          }
                   3465:        }/* end of loop for state */
                   3466:       } /* end of loop for age */
                   3467: 
                   3468:       /* Confidence intervalle of pij  */
                   3469:       /*
1.131     brouard  3470:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  3471:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   3472:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   3473:        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);
                   3474:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   3475:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   3476:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   3477:       */
                   3478: 
                   3479:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   3480:       first1=1;
                   3481:       for (k2=1; k2<=(nlstate);k2++){
                   3482:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   3483:          if(l2==k2) continue;
                   3484:          j=(k2-1)*(nlstate+ndeath)+l2;
                   3485:          for (k1=1; k1<=(nlstate);k1++){
                   3486:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   3487:              if(l1==k1) continue;
                   3488:              i=(k1-1)*(nlstate+ndeath)+l1;
                   3489:              if(i<=j) continue;
                   3490:              for (age=bage; age<=fage; age ++){ 
                   3491:                if ((int)age %5==0){
                   3492:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   3493:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   3494:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   3495:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   3496:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   3497:                  c12=cv12/sqrt(v1*v2);
                   3498:                  /* Computing eigen value of matrix of covariance */
                   3499:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3500:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  3501:                  if ((lc2 <0) || (lc1 <0) ){
                   3502:                    printf("Error: One eigen value of 2x2 matrix of covariance is negative, lc1=%11.3e, lc2=%11.3e, v1=%11.3e, v2=%11.3e, cv12=%11.3e.\n It means that the matrix was not well estimated (varpij), for i=%2d, j=%2d, age=%4d .\n See files %s and %s. Continuing by making them positive: WRONG RESULTS.\n", lc1, lc2, v1, v2, cv12, i, j, (int)age,fileresprobcov, fileresprobcor);
                   3503:                    fprintf(ficlog,"Error: One eigen value of 2x2 matrix of covariance is negative, lc1=%11.3e, lc2=%11.3e, v1=%11.3e, v2=%11.3e, cv12=%11.3e\n", lc1, lc2, v1, v2, cv12);fflush(ficlog);
                   3504:                    lc1=fabs(lc1);
                   3505:                    lc2=fabs(lc2);
                   3506:                  }
                   3507: 
1.126     brouard  3508:                  /* Eigen vectors */
                   3509:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   3510:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   3511:                  v21=(lc1-v1)/cv12*v11;
                   3512:                  v12=-v21;
                   3513:                  v22=v11;
                   3514:                  tnalp=v21/v11;
                   3515:                  if(first1==1){
                   3516:                    first1=0;
                   3517:                    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);
                   3518:                  }
                   3519:                  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);
                   3520:                  /*printf(fignu*/
                   3521:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   3522:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   3523:                  if(first==1){
                   3524:                    first=0;
                   3525:                    fprintf(ficgp,"\nset parametric;unset label");
                   3526:                    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);
                   3527:                    fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   3528:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
                   3529:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
                   3530: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
                   3531:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
                   3532:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   3533:                    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   3534:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   3535:                    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   3536:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   3537:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   3538:                    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",\
                   3539:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   3540:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   3541:                  }else{
                   3542:                    first=0;
                   3543:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   3544:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   3545:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   3546:                    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",\
                   3547:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   3548:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   3549:                  }/* if first */
                   3550:                } /* age mod 5 */
                   3551:              } /* end loop age */
                   3552:              fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   3553:              first=1;
                   3554:            } /*l12 */
                   3555:          } /* k12 */
                   3556:        } /*l1 */
                   3557:       }/* k1 */
                   3558:     } /* loop covariates */
                   3559:   }
                   3560:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   3561:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   3562:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   3563:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   3564:   free_vector(xp,1,npar);
                   3565:   fclose(ficresprob);
                   3566:   fclose(ficresprobcov);
                   3567:   fclose(ficresprobcor);
                   3568:   fflush(ficgp);
                   3569:   fflush(fichtmcov);
                   3570: }
                   3571: 
                   3572: 
                   3573: /******************* Printing html file ***********/
                   3574: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
                   3575:                  int lastpass, int stepm, int weightopt, char model[],\
                   3576:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   3577:                  int popforecast, int estepm ,\
                   3578:                  double jprev1, double mprev1,double anprev1, \
                   3579:                  double jprev2, double mprev2,double anprev2){
                   3580:   int jj1, k1, i1, cpt;
                   3581: 
                   3582:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   3583:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   3584: </ul>");
                   3585:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                   3586:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
                   3587:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
                   3588:    fprintf(fichtm,"\
                   3589:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   3590:           stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
                   3591:    fprintf(fichtm,"\
                   3592:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   3593:           subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
                   3594:    fprintf(fichtm,"\
1.128     brouard  3595:  - (a) Life expectancies by health status at initial age, ei. (b) health expectancies by health status at initial age, eij . If one or more covariates are included, specific tables for each value of the covariate are output in sequences within the same file (estepm=%2d months): \
1.126     brouard  3596:    <a href=\"%s\">%s</a> <br>\n",
                   3597:           estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
                   3598:    fprintf(fichtm,"\
                   3599:  - Population projections by age and states: \
                   3600:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
                   3601: 
                   3602: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   3603: 
                   3604:  m=cptcoveff;
                   3605:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   3606: 
                   3607:  jj1=0;
                   3608:  for(k1=1; k1<=m;k1++){
                   3609:    for(i1=1; i1<=ncodemax[k1];i1++){
                   3610:      jj1++;
                   3611:      if (cptcovn > 0) {
                   3612:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   3613:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   3614:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   3615:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   3616:      }
                   3617:      /* Pij */
                   3618:      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> \
                   3619: <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
                   3620:      /* Quasi-incidences */
                   3621:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
                   3622:  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> \
                   3623: <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
                   3624:        /* Period (stable) prevalence in each health state */
                   3625:        for(cpt=1; cpt<nlstate;cpt++){
                   3626:         fprintf(fichtm,"<br>- Period (stable) prevalence in each health state : <a href=\"%s%d%d.png\">%s%d%d.png</a><br> \
                   3627: <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
                   3628:        }
                   3629:      for(cpt=1; cpt<=nlstate;cpt++) {
                   3630:         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> \
                   3631: <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
                   3632:      }
                   3633:    } /* end i1 */
                   3634:  }/* End k1 */
                   3635:  fprintf(fichtm,"</ul>");
                   3636: 
                   3637: 
                   3638:  fprintf(fichtm,"\
                   3639: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
                   3640:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
                   3641: 
                   3642:  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   3643:         subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
                   3644:  fprintf(fichtm,"\
                   3645:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   3646:         subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
                   3647: 
                   3648:  fprintf(fichtm,"\
                   3649:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   3650:         subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
                   3651:  fprintf(fichtm,"\
                   3652:  - 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): \
                   3653:    <a href=\"%s\">%s</a> <br>\n</li>",
                   3654:           estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
                   3655:  fprintf(fichtm,"\
                   3656:  - (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): \
                   3657:    <a href=\"%s\">%s</a> <br>\n</li>",
                   3658:           estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
                   3659:  fprintf(fichtm,"\
1.128     brouard  3660:  - Variances and covariances of health expectancies by age. Status (i) based health expectancies (in state j), e<sup>ij</sup> are weighted by the period prevalences in each state i (if popbased=1, an additional computation is done using the cross-sectional prevalences, i.e population based) (estepm=%d months): <a href=\"%s\">%s</a><br>\n",
1.126     brouard  3661:         estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
                   3662:  fprintf(fichtm,"\
1.128     brouard  3663:  - Total life expectancy and total health expectancies to be spent in each health state e<sup>.j</sup> with their standard errors (if popbased=1, an additional computation is done using the cross-sectional prevalences, i.e population based) (estepm=%d months): <a href=\"%s\">%s</a> <br>\n",
                   3664:         estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126     brouard  3665:  fprintf(fichtm,"\
                   3666:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
                   3667:         subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
                   3668: 
                   3669: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   3670: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   3671: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   3672: /*     <br>",fileres,fileres,fileres,fileres); */
                   3673: /*  else  */
                   3674: /*    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); */
                   3675:  fflush(fichtm);
                   3676:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   3677: 
                   3678:  m=cptcoveff;
                   3679:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   3680: 
                   3681:  jj1=0;
                   3682:  for(k1=1; k1<=m;k1++){
                   3683:    for(i1=1; i1<=ncodemax[k1];i1++){
                   3684:      jj1++;
                   3685:      if (cptcovn > 0) {
                   3686:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   3687:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   3688:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   3689:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   3690:      }
                   3691:      for(cpt=1; cpt<=nlstate;cpt++) {
                   3692:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
                   3693: prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\
                   3694: <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
                   3695:      }
                   3696:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  3697: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   3698: true period expectancies (those weighted with period prevalences are also\
                   3699:  drawn in addition to the population based expectancies computed using\
                   3700:  observed and cahotic prevalences: %s%d.png<br>\
1.126     brouard  3701: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
                   3702:    } /* end i1 */
                   3703:  }/* End k1 */
                   3704:  fprintf(fichtm,"</ul>");
                   3705:  fflush(fichtm);
                   3706: }
                   3707: 
                   3708: /******************* Gnuplot file **************/
                   3709: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   3710: 
                   3711:   char dirfileres[132],optfileres[132];
1.130     brouard  3712:   int m0,cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
                   3713:   int ng=0;
1.126     brouard  3714: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   3715: /*     printf("Problem with file %s",optionfilegnuplot); */
                   3716: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   3717: /*   } */
                   3718: 
                   3719:   /*#ifdef windows */
                   3720:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   3721:     /*#endif */
                   3722:   m=pow(2,cptcoveff);
                   3723: 
                   3724:   strcpy(dirfileres,optionfilefiname);
                   3725:   strcpy(optfileres,"vpl");
                   3726:  /* 1eme*/
                   3727:   for (cpt=1; cpt<= nlstate ; cpt ++) {
                   3728:    for (k1=1; k1<= m ; k1 ++) {
                   3729:      fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
                   3730:      fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);
                   3731:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   3732: set ylabel \"Probability\" \n\
                   3733: set ter png small\n\
                   3734: set size 0.65,0.65\n\
                   3735: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
                   3736: 
                   3737:      for (i=1; i<= nlstate ; i ++) {
                   3738:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
1.131     brouard  3739:        else        fprintf(ficgp," \%%*lf (\%%*lf)");
1.126     brouard  3740:      }
                   3741:      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);
                   3742:      for (i=1; i<= nlstate ; i ++) {
                   3743:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
                   3744:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   3745:      } 
                   3746:      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); 
                   3747:      for (i=1; i<= nlstate ; i ++) {
                   3748:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
                   3749:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   3750:      }  
                   3751:      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));
                   3752:    }
                   3753:   }
                   3754:   /*2 eme*/
                   3755:   
                   3756:   for (k1=1; k1<= m ; k1 ++) { 
                   3757:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
                   3758:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);
                   3759:     
                   3760:     for (i=1; i<= nlstate+1 ; i ++) {
                   3761:       k=2*i;
                   3762:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
                   3763:       for (j=1; j<= nlstate+1 ; j ++) {
                   3764:        if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                   3765:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   3766:       }   
                   3767:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
                   3768:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
                   3769:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
                   3770:       for (j=1; j<= nlstate+1 ; j ++) {
                   3771:        if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                   3772:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   3773:       }   
                   3774:       fprintf(ficgp,"\" t\"\" w l 0,");
                   3775:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
                   3776:       for (j=1; j<= nlstate+1 ; j ++) {
                   3777:        if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                   3778:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   3779:       }   
                   3780:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l 0");
                   3781:       else fprintf(ficgp,"\" t\"\" w l 0,");
                   3782:     }
                   3783:   }
                   3784:   
                   3785:   /*3eme*/
                   3786:   
                   3787:   for (k1=1; k1<= m ; k1 ++) { 
                   3788:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   3789:       /*       k=2+nlstate*(2*cpt-2); */
                   3790:       k=2+(nlstate+1)*(cpt-1);
                   3791:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
                   3792:       fprintf(ficgp,"set ter png small\n\
                   3793: set size 0.65,0.65\n\
                   3794: 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);
                   3795:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   3796:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   3797:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   3798:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   3799:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   3800:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   3801:        
                   3802:       */
                   3803:       for (i=1; i< nlstate ; i ++) {
                   3804:        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);
                   3805:        /*      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);*/
                   3806:        
                   3807:       } 
                   3808:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
                   3809:     }
                   3810:   }
                   3811:   
                   3812:   /* CV preval stable (period) */
                   3813:   for (k1=1; k1<= m ; k1 ++) { 
                   3814:     for (cpt=1; cpt<=nlstate ; cpt ++) {
                   3815:       k=3;
                   3816:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
                   3817:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
                   3818: set ter png small\nset size 0.65,0.65\n\
                   3819: unset log y\n\
                   3820: plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);
                   3821:       
                   3822:       for (i=1; i< nlstate ; i ++)
                   3823:        fprintf(ficgp,"+$%d",k+i+1);
                   3824:       fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);
                   3825:       
                   3826:       l=3+(nlstate+ndeath)*cpt;
                   3827:       fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);
                   3828:       for (i=1; i< nlstate ; i ++) {
                   3829:        l=3+(nlstate+ndeath)*cpt;
                   3830:        fprintf(ficgp,"+$%d",l+i+1);
                   3831:       }
                   3832:       fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);   
                   3833:     } 
                   3834:   }  
                   3835:   
                   3836:   /* proba elementaires */
                   3837:   for(i=1,jk=1; i <=nlstate; i++){
                   3838:     for(k=1; k <=(nlstate+ndeath); k++){
                   3839:       if (k != i) {
                   3840:        for(j=1; j <=ncovmodel; j++){
                   3841:          fprintf(ficgp,"p%d=%f ",jk,p[jk]);
                   3842:          jk++; 
                   3843:          fprintf(ficgp,"\n");
                   3844:        }
                   3845:       }
                   3846:     }
                   3847:    }
                   3848: 
                   3849:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
                   3850:      for(jk=1; jk <=m; jk++) {
                   3851:        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
                   3852:        if (ng==2)
                   3853:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   3854:        else
                   3855:         fprintf(ficgp,"\nset title \"Probability\"\n");
                   3856:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   3857:        i=1;
                   3858:        for(k2=1; k2<=nlstate; k2++) {
                   3859:         k3=i;
                   3860:         for(k=1; k<=(nlstate+ndeath); k++) {
                   3861:           if (k != k2){
                   3862:             if(ng==2)
                   3863:               fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   3864:             else
                   3865:               fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   3866:             ij=1;
                   3867:             for(j=3; j <=ncovmodel; j++) {
                   3868:               if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
                   3869:                 fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
                   3870:                 ij++;
                   3871:               }
                   3872:               else
                   3873:                 fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
                   3874:             }
                   3875:             fprintf(ficgp,")/(1");
                   3876:             
                   3877:             for(k1=1; k1 <=nlstate; k1++){   
                   3878:               fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   3879:               ij=1;
                   3880:               for(j=3; j <=ncovmodel; j++){
                   3881:                 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
                   3882:                   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
                   3883:                   ij++;
                   3884:                 }
                   3885:                 else
                   3886:                   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
                   3887:               }
                   3888:               fprintf(ficgp,")");
                   3889:             }
                   3890:             fprintf(ficgp,") t \"p%d%d\" ", k2,k);
                   3891:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   3892:             i=i+ncovmodel;
                   3893:           }
                   3894:         } /* end k */
                   3895:        } /* end k2 */
                   3896:      } /* end jk */
                   3897:    } /* end ng */
                   3898:    fflush(ficgp); 
                   3899: }  /* end gnuplot */
                   3900: 
                   3901: 
                   3902: /*************** Moving average **************/
                   3903: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   3904: 
                   3905:   int i, cpt, cptcod;
                   3906:   int modcovmax =1;
                   3907:   int mobilavrange, mob;
                   3908:   double age;
                   3909: 
                   3910:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   3911:                           a covariate has 2 modalities */
                   3912:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   3913: 
                   3914:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   3915:     if(mobilav==1) mobilavrange=5; /* default */
                   3916:     else mobilavrange=mobilav;
                   3917:     for (age=bage; age<=fage; age++)
                   3918:       for (i=1; i<=nlstate;i++)
                   3919:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   3920:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   3921:     /* We keep the original values on the extreme ages bage, fage and for 
                   3922:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   3923:        we use a 5 terms etc. until the borders are no more concerned. 
                   3924:     */ 
                   3925:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   3926:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   3927:        for (i=1; i<=nlstate;i++){
                   3928:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   3929:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   3930:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   3931:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   3932:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   3933:              }
                   3934:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   3935:          }
                   3936:        }
                   3937:       }/* end age */
                   3938:     }/* end mob */
                   3939:   }else return -1;
                   3940:   return 0;
                   3941: }/* End movingaverage */
                   3942: 
                   3943: 
                   3944: /************** Forecasting ******************/
                   3945: 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){
                   3946:   /* proj1, year, month, day of starting projection 
                   3947:      agemin, agemax range of age
                   3948:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   3949:      anproj2 year of en of projection (same day and month as proj1).
                   3950:   */
                   3951:   int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
                   3952:   int *popage;
                   3953:   double agec; /* generic age */
                   3954:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   3955:   double *popeffectif,*popcount;
                   3956:   double ***p3mat;
                   3957:   double ***mobaverage;
                   3958:   char fileresf[FILENAMELENGTH];
                   3959: 
                   3960:   agelim=AGESUP;
                   3961:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   3962:  
                   3963:   strcpy(fileresf,"f"); 
                   3964:   strcat(fileresf,fileres);
                   3965:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   3966:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   3967:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   3968:   }
                   3969:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   3970:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   3971: 
                   3972:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   3973: 
                   3974:   if (mobilav!=0) {
                   3975:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3976:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   3977:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   3978:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   3979:     }
                   3980:   }
                   3981: 
                   3982:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   3983:   if (stepm<=12) stepsize=1;
                   3984:   if(estepm < stepm){
                   3985:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3986:   }
                   3987:   else  hstepm=estepm;   
                   3988: 
                   3989:   hstepm=hstepm/stepm; 
                   3990:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   3991:                                fractional in yp1 */
                   3992:   anprojmean=yp;
                   3993:   yp2=modf((yp1*12),&yp);
                   3994:   mprojmean=yp;
                   3995:   yp1=modf((yp2*30.5),&yp);
                   3996:   jprojmean=yp;
                   3997:   if(jprojmean==0) jprojmean=1;
                   3998:   if(mprojmean==0) jprojmean=1;
                   3999: 
                   4000:   i1=cptcoveff;
                   4001:   if (cptcovn < 1){i1=1;}
                   4002:   
                   4003:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   4004:   
                   4005:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   4006: 
                   4007: /*           if (h==(int)(YEARM*yearp)){ */
                   4008:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   4009:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4010:       k=k+1;
                   4011:       fprintf(ficresf,"\n#******");
                   4012:       for(j=1;j<=cptcoveff;j++) {
                   4013:        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]]);
                   4014:       }
                   4015:       fprintf(ficresf,"******\n");
                   4016:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
                   4017:       for(j=1; j<=nlstate+ndeath;j++){ 
                   4018:        for(i=1; i<=nlstate;i++)              
                   4019:           fprintf(ficresf," p%d%d",i,j);
                   4020:        fprintf(ficresf," p.%d",j);
                   4021:       }
                   4022:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   4023:        fprintf(ficresf,"\n");
                   4024:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   4025: 
                   4026:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   4027:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   4028:          nhstepm = nhstepm/hstepm; 
                   4029:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4030:          oldm=oldms;savm=savms;
                   4031:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4032:        
                   4033:          for (h=0; h<=nhstepm; h++){
                   4034:            if (h*hstepm/YEARM*stepm ==yearp) {
                   4035:               fprintf(ficresf,"\n");
                   4036:               for(j=1;j<=cptcoveff;j++) 
                   4037:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4038:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   4039:            } 
                   4040:            for(j=1; j<=nlstate+ndeath;j++) {
                   4041:              ppij=0.;
                   4042:              for(i=1; i<=nlstate;i++) {
                   4043:                if (mobilav==1) 
                   4044:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   4045:                else {
                   4046:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   4047:                }
                   4048:                if (h*hstepm/YEARM*stepm== yearp) {
                   4049:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   4050:                }
                   4051:              } /* end i */
                   4052:              if (h*hstepm/YEARM*stepm==yearp) {
                   4053:                fprintf(ficresf," %.3f", ppij);
                   4054:              }
                   4055:            }/* end j */
                   4056:          } /* end h */
                   4057:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4058:        } /* end agec */
                   4059:       } /* end yearp */
                   4060:     } /* end cptcod */
                   4061:   } /* end  cptcov */
                   4062:        
                   4063:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4064: 
                   4065:   fclose(ficresf);
                   4066: }
                   4067: 
                   4068: /************** Forecasting *****not tested NB*************/
                   4069: 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){
                   4070:   
                   4071:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   4072:   int *popage;
                   4073:   double calagedatem, agelim, kk1, kk2;
                   4074:   double *popeffectif,*popcount;
                   4075:   double ***p3mat,***tabpop,***tabpopprev;
                   4076:   double ***mobaverage;
                   4077:   char filerespop[FILENAMELENGTH];
                   4078: 
                   4079:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4080:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4081:   agelim=AGESUP;
                   4082:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   4083:   
                   4084:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4085:   
                   4086:   
                   4087:   strcpy(filerespop,"pop"); 
                   4088:   strcat(filerespop,fileres);
                   4089:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   4090:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   4091:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   4092:   }
                   4093:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   4094:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   4095: 
                   4096:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4097: 
                   4098:   if (mobilav!=0) {
                   4099:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4100:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4101:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4102:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4103:     }
                   4104:   }
                   4105: 
                   4106:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4107:   if (stepm<=12) stepsize=1;
                   4108:   
                   4109:   agelim=AGESUP;
                   4110:   
                   4111:   hstepm=1;
                   4112:   hstepm=hstepm/stepm; 
                   4113:   
                   4114:   if (popforecast==1) {
                   4115:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   4116:       printf("Problem with population file : %s\n",popfile);exit(0);
                   4117:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   4118:     } 
                   4119:     popage=ivector(0,AGESUP);
                   4120:     popeffectif=vector(0,AGESUP);
                   4121:     popcount=vector(0,AGESUP);
                   4122:     
                   4123:     i=1;   
                   4124:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   4125:    
                   4126:     imx=i;
                   4127:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   4128:   }
                   4129: 
                   4130:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   4131:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4132:       k=k+1;
                   4133:       fprintf(ficrespop,"\n#******");
                   4134:       for(j=1;j<=cptcoveff;j++) {
                   4135:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4136:       }
                   4137:       fprintf(ficrespop,"******\n");
                   4138:       fprintf(ficrespop,"# Age");
                   4139:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   4140:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   4141:       
                   4142:       for (cpt=0; cpt<=0;cpt++) { 
                   4143:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   4144:        
                   4145:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   4146:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   4147:          nhstepm = nhstepm/hstepm; 
                   4148:          
                   4149:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4150:          oldm=oldms;savm=savms;
                   4151:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4152:        
                   4153:          for (h=0; h<=nhstepm; h++){
                   4154:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   4155:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   4156:            } 
                   4157:            for(j=1; j<=nlstate+ndeath;j++) {
                   4158:              kk1=0.;kk2=0;
                   4159:              for(i=1; i<=nlstate;i++) {              
                   4160:                if (mobilav==1) 
                   4161:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   4162:                else {
                   4163:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   4164:                }
                   4165:              }
                   4166:              if (h==(int)(calagedatem+12*cpt)){
                   4167:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   4168:                  /*fprintf(ficrespop," %.3f", kk1);
                   4169:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   4170:              }
                   4171:            }
                   4172:            for(i=1; i<=nlstate;i++){
                   4173:              kk1=0.;
                   4174:                for(j=1; j<=nlstate;j++){
                   4175:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   4176:                }
                   4177:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   4178:            }
                   4179: 
                   4180:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   4181:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   4182:          }
                   4183:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4184:        }
                   4185:       }
                   4186:  
                   4187:   /******/
                   4188: 
                   4189:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   4190:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   4191:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   4192:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   4193:          nhstepm = nhstepm/hstepm; 
                   4194:          
                   4195:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4196:          oldm=oldms;savm=savms;
                   4197:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4198:          for (h=0; h<=nhstepm; h++){
                   4199:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   4200:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   4201:            } 
                   4202:            for(j=1; j<=nlstate+ndeath;j++) {
                   4203:              kk1=0.;kk2=0;
                   4204:              for(i=1; i<=nlstate;i++) {              
                   4205:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   4206:              }
                   4207:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   4208:            }
                   4209:          }
                   4210:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4211:        }
                   4212:       }
                   4213:    } 
                   4214:   }
                   4215:  
                   4216:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4217: 
                   4218:   if (popforecast==1) {
                   4219:     free_ivector(popage,0,AGESUP);
                   4220:     free_vector(popeffectif,0,AGESUP);
                   4221:     free_vector(popcount,0,AGESUP);
                   4222:   }
                   4223:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4224:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4225:   fclose(ficrespop);
                   4226: } /* End of popforecast */
                   4227: 
                   4228: int fileappend(FILE *fichier, char *optionfich)
                   4229: {
                   4230:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   4231:     printf("Problem with file: %s\n", optionfich);
                   4232:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   4233:     return (0);
                   4234:   }
                   4235:   fflush(fichier);
                   4236:   return (1);
                   4237: }
                   4238: 
                   4239: 
                   4240: /**************** function prwizard **********************/
                   4241: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   4242: {
                   4243: 
                   4244:   /* Wizard to print covariance matrix template */
                   4245: 
                   4246:   char ca[32], cb[32], cc[32];
                   4247:   int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
                   4248:   int numlinepar;
                   4249: 
                   4250:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   4251:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   4252:   for(i=1; i <=nlstate; i++){
                   4253:     jj=0;
                   4254:     for(j=1; j <=nlstate+ndeath; j++){
                   4255:       if(j==i) continue;
                   4256:       jj++;
                   4257:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   4258:       printf("%1d%1d",i,j);
                   4259:       fprintf(ficparo,"%1d%1d",i,j);
                   4260:       for(k=1; k<=ncovmodel;k++){
                   4261:        /*        printf(" %lf",param[i][j][k]); */
                   4262:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   4263:        printf(" 0.");
                   4264:        fprintf(ficparo," 0.");
                   4265:       }
                   4266:       printf("\n");
                   4267:       fprintf(ficparo,"\n");
                   4268:     }
                   4269:   }
                   4270:   printf("# Scales (for hessian or gradient estimation)\n");
                   4271:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   4272:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   4273:   for(i=1; i <=nlstate; i++){
                   4274:     jj=0;
                   4275:     for(j=1; j <=nlstate+ndeath; j++){
                   4276:       if(j==i) continue;
                   4277:       jj++;
                   4278:       fprintf(ficparo,"%1d%1d",i,j);
                   4279:       printf("%1d%1d",i,j);
                   4280:       fflush(stdout);
                   4281:       for(k=1; k<=ncovmodel;k++){
                   4282:        /*      printf(" %le",delti3[i][j][k]); */
                   4283:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   4284:        printf(" 0.");
                   4285:        fprintf(ficparo," 0.");
                   4286:       }
                   4287:       numlinepar++;
                   4288:       printf("\n");
                   4289:       fprintf(ficparo,"\n");
                   4290:     }
                   4291:   }
                   4292:   printf("# Covariance matrix\n");
                   4293: /* # 121 Var(a12)\n\ */
                   4294: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   4295: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   4296: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   4297: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   4298: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   4299: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   4300: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   4301:   fflush(stdout);
                   4302:   fprintf(ficparo,"# Covariance matrix\n");
                   4303:   /* # 121 Var(a12)\n\ */
                   4304:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   4305:   /* #   ...\n\ */
                   4306:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   4307:   
                   4308:   for(itimes=1;itimes<=2;itimes++){
                   4309:     jj=0;
                   4310:     for(i=1; i <=nlstate; i++){
                   4311:       for(j=1; j <=nlstate+ndeath; j++){
                   4312:        if(j==i) continue;
                   4313:        for(k=1; k<=ncovmodel;k++){
                   4314:          jj++;
                   4315:          ca[0]= k+'a'-1;ca[1]='\0';
                   4316:          if(itimes==1){
                   4317:            printf("#%1d%1d%d",i,j,k);
                   4318:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   4319:          }else{
                   4320:            printf("%1d%1d%d",i,j,k);
                   4321:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   4322:            /*  printf(" %.5le",matcov[i][j]); */
                   4323:          }
                   4324:          ll=0;
                   4325:          for(li=1;li <=nlstate; li++){
                   4326:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   4327:              if(lj==li) continue;
                   4328:              for(lk=1;lk<=ncovmodel;lk++){
                   4329:                ll++;
                   4330:                if(ll<=jj){
                   4331:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   4332:                  if(ll<jj){
                   4333:                    if(itimes==1){
                   4334:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   4335:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   4336:                    }else{
                   4337:                      printf(" 0.");
                   4338:                      fprintf(ficparo," 0.");
                   4339:                    }
                   4340:                  }else{
                   4341:                    if(itimes==1){
                   4342:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   4343:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   4344:                    }else{
                   4345:                      printf(" 0.");
                   4346:                      fprintf(ficparo," 0.");
                   4347:                    }
                   4348:                  }
                   4349:                }
                   4350:              } /* end lk */
                   4351:            } /* end lj */
                   4352:          } /* end li */
                   4353:          printf("\n");
                   4354:          fprintf(ficparo,"\n");
                   4355:          numlinepar++;
                   4356:        } /* end k*/
                   4357:       } /*end j */
                   4358:     } /* end i */
                   4359:   } /* end itimes */
                   4360: 
                   4361: } /* end of prwizard */
                   4362: /******************* Gompertz Likelihood ******************************/
                   4363: double gompertz(double x[])
                   4364: { 
                   4365:   double A,B,L=0.0,sump=0.,num=0.;
                   4366:   int i,n=0; /* n is the size of the sample */
                   4367: 
                   4368:   for (i=0;i<=imx-1 ; i++) {
                   4369:     sump=sump+weight[i];
                   4370:     /*    sump=sump+1;*/
                   4371:     num=num+1;
                   4372:   }
                   4373:  
                   4374:  
                   4375:   /* for (i=0; i<=imx; i++) 
                   4376:      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]);*/
                   4377: 
                   4378:   for (i=1;i<=imx ; i++)
                   4379:     {
                   4380:       if (cens[i] == 1 && wav[i]>1)
                   4381:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   4382:       
                   4383:       if (cens[i] == 0 && wav[i]>1)
                   4384:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   4385:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   4386:       
                   4387:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   4388:       if (wav[i] > 1 ) { /* ??? */
                   4389:        L=L+A*weight[i];
                   4390:        /*      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]);*/
                   4391:       }
                   4392:     }
                   4393: 
                   4394:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   4395:  
                   4396:   return -2*L*num/sump;
                   4397: }
                   4398: 
1.136   ! brouard  4399: #ifdef GSL
        !          4400: /******************* Gompertz_f Likelihood ******************************/
        !          4401: double gompertz_f(const gsl_vector *v, void *params)
        !          4402: { 
        !          4403:   double A,B,LL=0.0,sump=0.,num=0.;
        !          4404:   double *x= (double *) v->data;
        !          4405:   int i,n=0; /* n is the size of the sample */
        !          4406: 
        !          4407:   for (i=0;i<=imx-1 ; i++) {
        !          4408:     sump=sump+weight[i];
        !          4409:     /*    sump=sump+1;*/
        !          4410:     num=num+1;
        !          4411:   }
        !          4412:  
        !          4413:  
        !          4414:   /* for (i=0; i<=imx; i++) 
        !          4415:      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]);*/
        !          4416:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
        !          4417:   for (i=1;i<=imx ; i++)
        !          4418:     {
        !          4419:       if (cens[i] == 1 && wav[i]>1)
        !          4420:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
        !          4421:       
        !          4422:       if (cens[i] == 0 && wav[i]>1)
        !          4423:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
        !          4424:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
        !          4425:       
        !          4426:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
        !          4427:       if (wav[i] > 1 ) { /* ??? */
        !          4428:        LL=LL+A*weight[i];
        !          4429:        /*      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]);*/
        !          4430:       }
        !          4431:     }
        !          4432: 
        !          4433:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
        !          4434:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
        !          4435:  
        !          4436:   return -2*LL*num/sump;
        !          4437: }
        !          4438: #endif
        !          4439: 
1.126     brouard  4440: /******************* Printing html file ***********/
                   4441: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
                   4442:                  int lastpass, int stepm, int weightopt, char model[],\
                   4443:                  int imx,  double p[],double **matcov,double agemortsup){
                   4444:   int i,k;
                   4445: 
                   4446:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   4447:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   4448:   for (i=1;i<=2;i++) 
                   4449:     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]));
                   4450:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
                   4451:   fprintf(fichtm,"</ul>");
                   4452: 
                   4453: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   4454: 
                   4455:  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>");
                   4456: 
                   4457:  for (k=agegomp;k<(agemortsup-2);k++) 
                   4458:    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]);
                   4459: 
                   4460:  
                   4461:   fflush(fichtm);
                   4462: }
                   4463: 
                   4464: /******************* Gnuplot file **************/
                   4465: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   4466: 
                   4467:   char dirfileres[132],optfileres[132];
                   4468:   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
                   4469:   int ng;
                   4470: 
                   4471: 
                   4472:   /*#ifdef windows */
                   4473:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4474:     /*#endif */
                   4475: 
                   4476: 
                   4477:   strcpy(dirfileres,optionfilefiname);
                   4478:   strcpy(optfileres,"vpl");
                   4479:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
                   4480:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
                   4481:   fprintf(ficgp, "set ter png small\n set log y\n"); 
                   4482:   fprintf(ficgp, "set size 0.65,0.65\n");
                   4483:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   4484: 
                   4485: } 
                   4486: 
1.136   ! brouard  4487: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
        !          4488: {
1.126     brouard  4489: 
1.136   ! brouard  4490:   /*-------- data file ----------*/
        !          4491:   FILE *fic;
        !          4492:   char dummy[]="                         ";
        !          4493:   int i, j, n;
        !          4494:   int linei, month, year,iout;
        !          4495:   char line[MAXLINE], linetmp[MAXLINE];
        !          4496:   char stra[80], strb[80];
        !          4497:   char *stratrunc;
        !          4498:   int lstra;
1.126     brouard  4499: 
                   4500: 
1.136   ! brouard  4501:   if((fic=fopen(datafile,"r"))==NULL)    {
        !          4502:     printf("Problem while opening datafile: %s\n", datafile);return 1;
        !          4503:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
        !          4504:   }
1.126     brouard  4505: 
1.136   ! brouard  4506:   i=1;
        !          4507:   linei=0;
        !          4508:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
        !          4509:     linei=linei+1;
        !          4510:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
        !          4511:       if(line[j] == '\t')
        !          4512:        line[j] = ' ';
        !          4513:     }
        !          4514:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
        !          4515:       ;
        !          4516:     };
        !          4517:     line[j+1]=0;  /* Trims blanks at end of line */
        !          4518:     if(line[0]=='#'){
        !          4519:       fprintf(ficlog,"Comment line\n%s\n",line);
        !          4520:       printf("Comment line\n%s\n",line);
        !          4521:       continue;
        !          4522:     }
        !          4523:     trimbb(linetmp,line); /* Trims multiple blanks in line */
        !          4524:     for (j=0; line[j]!='\0';j++){
        !          4525:       line[j]=linetmp[j];
        !          4526:     }
        !          4527:   
1.126     brouard  4528: 
1.136   ! brouard  4529:     for (j=maxwav;j>=1;j--){
        !          4530:       cutv(stra, strb,line,' '); 
        !          4531:       if(strb[0]=='.') { /* Missing status */
        !          4532:        lval=-1;
        !          4533:       }else{
        !          4534:        errno=0;
        !          4535:        lval=strtol(strb,&endptr,10); 
        !          4536:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
        !          4537:        if( strb[0]=='\0' || (*endptr != '\0')){
        !          4538:          printf("Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a status of wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,j,maxwav);
        !          4539:          fprintf(ficlog,"Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a status of wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,j,maxwav);fflush(ficlog);
        !          4540:          return 1;
        !          4541:        }
        !          4542:       }
        !          4543:       s[j][i]=lval;
        !          4544:       
        !          4545:       strcpy(line,stra);
        !          4546:       cutv(stra, strb,line,' ');
        !          4547:       if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
        !          4548:       }
        !          4549:       else  if(iout=sscanf(strb,"%s.") != 0){
        !          4550:        month=99;
        !          4551:        year=9999;
        !          4552:       }else{
        !          4553:        printf("Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a date of interview (mm/yyyy or .) at wave %d.  Exiting.\n",strb, linei,i, line,j);
        !          4554:        fprintf(ficlog,"Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a date of interview (mm/yyyy or .) at wave %d.  Exiting.\n",strb, linei,i, line,j);fflush(ficlog);
        !          4555:        return 1;
        !          4556:       }
        !          4557:       anint[j][i]= (double) year; 
        !          4558:       mint[j][i]= (double)month; 
        !          4559:       strcpy(line,stra);
        !          4560:     } /* ENd Waves */
        !          4561:     
        !          4562:     cutv(stra, strb,line,' '); 
        !          4563:     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
        !          4564:     }
        !          4565:     else  if(iout=sscanf(strb,"%s.",dummy) != 0){
        !          4566:       month=99;
        !          4567:       year=9999;
        !          4568:     }else{
        !          4569:       printf("Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a date of death (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);
        !          4570:        fprintf(ficlog,"Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a date of death (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);fflush(ficlog);
        !          4571:        return 1;
        !          4572:     }
        !          4573:     andc[i]=(double) year; 
        !          4574:     moisdc[i]=(double) month; 
        !          4575:     strcpy(line,stra);
        !          4576:     
        !          4577:     cutv(stra, strb,line,' '); 
        !          4578:     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
        !          4579:     }
        !          4580:     else  if(iout=sscanf(strb,"%s.") != 0){
        !          4581:       month=99;
        !          4582:       year=9999;
        !          4583:     }else{
        !          4584:       printf("Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);
        !          4585:       fprintf(ficlog,"Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .).  Exiting.\n",strb, linei,i,line);fflush(ficlog);
        !          4586:        return 1;
        !          4587:     }
        !          4588:     if (year==9999) {
        !          4589:       printf("Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a date of birth (mm/yyyy) but at least the year of birth should be given.  Exiting.\n",strb, linei,i,line);
        !          4590:       fprintf(ficlog,"Error reading data around '%s' at line number %ld for individual %d, '%s'\nShould be a date of birth (mm/yyyy) but at least the year of birth should be given. Exiting.\n",strb, linei,i,line);fflush(ficlog);
        !          4591:        return 1;
1.126     brouard  4592: 
1.136   ! brouard  4593:     }
        !          4594:     annais[i]=(double)(year);
        !          4595:     moisnais[i]=(double)(month); 
        !          4596:     strcpy(line,stra);
        !          4597:     
        !          4598:     cutv(stra, strb,line,' '); 
        !          4599:     errno=0;
        !          4600:     dval=strtod(strb,&endptr); 
        !          4601:     if( strb[0]=='\0' || (*endptr != '\0')){
        !          4602:       printf("Error reading data around '%f' at line number %ld, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
        !          4603:       fprintf(ficlog,"Error reading data around '%f' at line number %ld, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
        !          4604:       fflush(ficlog);
        !          4605:       return 1;
        !          4606:     }
        !          4607:     weight[i]=dval; 
        !          4608:     strcpy(line,stra);
        !          4609:     
        !          4610:     for (j=ncovcol;j>=1;j--){
        !          4611:       cutv(stra, strb,line,' '); 
        !          4612:       if(strb[0]=='.') { /* Missing status */
        !          4613:        lval=-1;
        !          4614:       }else{
        !          4615:        errno=0;
        !          4616:        lval=strtol(strb,&endptr,10); 
        !          4617:        if( strb[0]=='\0' || (*endptr != '\0')){
        !          4618:          printf("Error reading data around '%d' at line number %ld for individual %d, '%s'\nShould be a covariate value (=0 for the reference or 1 for alternative).  Exiting.\n",lval, linei,i, line);
        !          4619:          fprintf(ficlog,"Error reading data around '%d' at line number %ld for individual %d, '%s'\nShould be a covariate value (=0 for the reference or 1 for alternative).  Exiting.\n",lval, linei,i, line);fflush(ficlog);
        !          4620:          return 1;
        !          4621:        }
        !          4622:       }
        !          4623:       if(lval <-1 || lval >1){
        !          4624:        printf("Error reading data around '%d' at line number %ld for individual %d, '%s'\n \
        !          4625:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
        !          4626:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
        !          4627:  For example, for multinomial values like 1, 2 and 3,\n \
        !          4628:  build V1=0 V2=0 for the reference value (1),\n \
        !          4629:         V1=1 V2=0 for (2) \n \
        !          4630:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
        !          4631:  output of IMaCh is often meaningless.\n \
        !          4632:  Exiting.\n",lval,linei, i,line,j);
        !          4633:        fprintf(ficlog,"Error reading data around '%d' at line number %ld for individual %d, '%s'\n \
        !          4634:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
        !          4635:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
        !          4636:  For example, for multinomial values like 1, 2 and 3,\n \
        !          4637:  build V1=0 V2=0 for the reference value (1),\n \
        !          4638:         V1=1 V2=0 for (2) \n \
        !          4639:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
        !          4640:  output of IMaCh is often meaningless.\n \
        !          4641:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
        !          4642:        return 1;
        !          4643:       }
        !          4644:       covar[j][i]=(double)(lval);
        !          4645:       strcpy(line,stra);
        !          4646:     }  
        !          4647:     lstra=strlen(stra);
        !          4648:      
        !          4649:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
        !          4650:       stratrunc = &(stra[lstra-9]);
        !          4651:       num[i]=atol(stratrunc);
        !          4652:     }
        !          4653:     else
        !          4654:       num[i]=atol(stra);
        !          4655:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
        !          4656:       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;}*/
        !          4657:     
        !          4658:     i=i+1;
        !          4659:   } /* End loop reading  data */
1.126     brouard  4660: 
1.136   ! brouard  4661:   *imax=i-1; /* Number of individuals */
        !          4662:   fclose(fic);
        !          4663:  
        !          4664:   return (0);
        !          4665:   endread:
        !          4666:     printf("Exiting readdata: ");
        !          4667:     fclose(fic);
        !          4668:     return (1);
1.126     brouard  4669: 
                   4670: 
                   4671: 
1.136   ! brouard  4672: }
1.126     brouard  4673: 
1.136   ! brouard  4674: int decodemodel ( char model[], int lastobs)
        !          4675: {
        !          4676:   int i, j, k;
        !          4677:   int i1, j1, k1, k2;
        !          4678:   char modelsav[80];
        !          4679:    char stra[80], strb[80], strc[80], strd[80],stre[80];
        !          4680: 
        !          4681:   if (strlen(model) >1){ /* If there is at least 1 covariate */
        !          4682:     j=0, j1=0, k1=1, k2=1;
        !          4683:     j=nbocc(model,'+'); /* j=Number of '+' */
        !          4684:     j1=nbocc(model,'*'); /* j1=Number of '*' */
        !          4685:     cptcovn=j+1; /* Number of covariates V1+V2*age+V3 =>(2 plus signs) + 1=3 
        !          4686:                  but the covariates which are product must be computed and stored. */
        !          4687:     cptcovprod=j1; /*Number of products  V1*V2 +v3*age = 2 */
        !          4688:     
        !          4689:     strcpy(modelsav,model); 
        !          4690:     if ((strcmp(model,"age")==0) || (strcmp(model,"age*age")==0)){
        !          4691:       printf("Error. Non available option model=%s ",model);
        !          4692:       fprintf(ficlog,"Error. Non available option model=%s ",model);fflush(ficlog);
        !          4693:       return 1;
        !          4694:     }
        !          4695:     
        !          4696:     /* This loop fills the array Tvar from the string 'model'.*/
        !          4697:     /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
        !          4698:     /*    modelsav=V3*age+V2+V1+V4 strb=V3*age stra=V2+V1+V4 
        !          4699:        i=1 Tvar[1]=3 Tage[1]=1  
        !          4700:        i=2 Tvar[2]=2
        !          4701:        i=3 Tvar[3]=1
        !          4702:        i=4 Tvar[4]= 4
        !          4703:        i=5 Tvar[5]
        !          4704:       for (k=1; k<=cptcovn;k++) {
        !          4705:        cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
        !          4706:      */
        !          4707:     for(k=1; k<=(j+1);k++){
        !          4708:       cutv(strb,stra,modelsav,'+'); /* keeps in strb after the first '+' 
        !          4709:                                     modelsav=V3*age+V2+V1+V4 strb=V3*age stra=V2+V1+V4 
        !          4710:                                    */ 
        !          4711:       /* if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav);*/ /* and analyzes it */
        !          4712:       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
        !          4713:       /*scanf("%d",i);*/
        !          4714:       if (strchr(strb,'*')) {  /* Model includes a product V3*age+V2+V1+V4 strb=V3*age */
        !          4715:        cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn: strb=V3*age strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
        !          4716:        if (strcmp(strc,"age")==0) { /* Vn*age */
        !          4717:          cptcovprod--;
        !          4718:          cutv(strb,stre,strd,'V'); /* stre="V3" */
        !          4719:          Tvar[k]=atoi(stre);  /* V1+V3*age+V2 Tvar[2]=3, and Tvar[3]=2 */
        !          4720:          cptcovage++; /* Sums the number of covariates which include age as a product */
        !          4721:          Tage[cptcovage]=k;  /* Tage[1] =2 */
        !          4722:          /*printf("stre=%s ", stre);*/
        !          4723:        }
        !          4724:        else if (strcmp(strd,"age")==0) { /* or age*Vn */
        !          4725:          cptcovprod--;
        !          4726:          cutv(strb,stre,strc,'V');
        !          4727:          Tvar[k]=atoi(stre);
        !          4728:          cptcovage++;
        !          4729:          Tage[cptcovage]=k;
        !          4730:        }
        !          4731:        else {  /* Age is not in the model V1+V3*V2+V2  strb=V3*V2*/
        !          4732:          cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
        !          4733:          Tvar[k]=ncovcol+k1;  /* find 'n' in Vn and stores in Tvar. 
        !          4734:                                  If already ncovcol=2 and model=V2*V1 Tvar[1]=2+1 and Tvar[2]=2+2 etc */
        !          4735:          cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */
        !          4736:          Tprod[k1]=k;  /* Tprod[1]  */
        !          4737:          Tvard[k1][1]=atoi(strc); /* m*/
        !          4738:          Tvard[k1][2]=atoi(stre); /* n */
        !          4739:          Tvar[cptcovn+k2]=Tvard[k1][1];
        !          4740:          Tvar[cptcovn+k2+1]=Tvard[k1][2]; 
        !          4741:          for (i=1; i<=lastobs;i++) /* Computes the new covariate which is a product of covar[n][i]* covar[m][i]
        !          4742:                                     and is stored at ncovol+k1 */
        !          4743:            covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
        !          4744:          k1++;
        !          4745:          k2=k2+2;
        !          4746:        }
        !          4747:       }
        !          4748:       else { /* no more sum */
        !          4749:        /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
        !          4750:        /*  scanf("%d",i);*/
        !          4751:        cutv(strd,strc,strb,'V');
        !          4752:        Tvar[i]=atoi(strc);
        !          4753:       }
        !          4754:       strcpy(modelsav,stra);  /* modelsav=V2+V3*age+V1+V4 strb=V3*age+V1+V4 */ 
        !          4755:       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
        !          4756:        scanf("%d",i);*/
        !          4757:     } /* end of loop + */
        !          4758:   } /* end model */
        !          4759:   
        !          4760:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
        !          4761:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
        !          4762: 
        !          4763:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
        !          4764:   printf("cptcovprod=%d ", cptcovprod);
        !          4765:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
        !          4766: 
        !          4767:   scanf("%d ",i);*/
        !          4768: 
        !          4769: 
        !          4770:   return (0);
        !          4771:   endread:
        !          4772:     printf("Exiting decodemodel: ");
        !          4773:     return (1);
        !          4774: }
        !          4775: 
        !          4776: calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
        !          4777: {
        !          4778:   int i, m;
        !          4779: 
        !          4780:   for (i=1; i<=imx; i++) {
        !          4781:     for(m=2; (m<= maxwav); m++) {
        !          4782:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
        !          4783:        anint[m][i]=9999;
        !          4784:        s[m][i]=-1;
        !          4785:       }
        !          4786:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
        !          4787:        *nberr++;
        !          4788:        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);
        !          4789:        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);
        !          4790:        s[m][i]=-1;
        !          4791:       }
        !          4792:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
        !          4793:        *nberr++;
        !          4794:        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]); 
        !          4795:        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]); 
        !          4796:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
        !          4797:       }
        !          4798:     }
        !          4799:   }
        !          4800: 
        !          4801:   for (i=1; i<=imx; i++)  {
        !          4802:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
        !          4803:     for(m=firstpass; (m<= lastpass); m++){
        !          4804:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
        !          4805:        if (s[m][i] >= nlstate+1) {
        !          4806:          if(agedc[i]>0)
        !          4807:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
        !          4808:              agev[m][i]=agedc[i];
        !          4809:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
        !          4810:            else {
        !          4811:              if ((int)andc[i]!=9999){
        !          4812:                nbwarn++;
        !          4813:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
        !          4814:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
        !          4815:                agev[m][i]=-1;
        !          4816:              }
        !          4817:            }
        !          4818:        }
        !          4819:        else if(s[m][i] !=9){ /* Standard case, age in fractional
        !          4820:                                 years but with the precision of a month */
        !          4821:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
        !          4822:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
        !          4823:            agev[m][i]=1;
        !          4824:          else if(agev[m][i] < *agemin){ 
        !          4825:            *agemin=agev[m][i];
        !          4826:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
        !          4827:          }
        !          4828:          else if(agev[m][i] >*agemax){
        !          4829:            *agemax=agev[m][i];
        !          4830:            /* printf(" anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.0f\n",m,i,anint[m][i], i,annais[i], agemax);*/
        !          4831:          }
        !          4832:          /*agev[m][i]=anint[m][i]-annais[i];*/
        !          4833:          /*     agev[m][i] = age[i]+2*m;*/
        !          4834:        }
        !          4835:        else { /* =9 */
        !          4836:          agev[m][i]=1;
        !          4837:          s[m][i]=-1;
        !          4838:        }
        !          4839:       }
        !          4840:       else /*= 0 Unknown */
        !          4841:        agev[m][i]=1;
        !          4842:     }
        !          4843:     
        !          4844:   }
        !          4845:   for (i=1; i<=imx; i++)  {
        !          4846:     for(m=firstpass; (m<=lastpass); m++){
        !          4847:       if (s[m][i] > (nlstate+ndeath)) {
        !          4848:        *nberr++;
        !          4849:        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);     
        !          4850:        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);     
        !          4851:        return 1;
        !          4852:       }
        !          4853:     }
        !          4854:   }
        !          4855: 
        !          4856:   /*for (i=1; i<=imx; i++){
        !          4857:   for (m=firstpass; (m<lastpass); m++){
        !          4858:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
        !          4859: }
        !          4860: 
        !          4861: }*/
        !          4862: 
        !          4863: 
        !          4864:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax);
        !          4865:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, agemin, agemax); 
        !          4866: 
        !          4867:   return (0);
        !          4868:   endread:
        !          4869:     printf("Exiting calandcheckages: ");
        !          4870:     return (1);
        !          4871: }
        !          4872: 
        !          4873: 
        !          4874: /***********************************************/
        !          4875: /**************** Main Program *****************/
        !          4876: /***********************************************/
        !          4877: 
        !          4878: int main(int argc, char *argv[])
        !          4879: {
        !          4880: #ifdef GSL
        !          4881:   const gsl_multimin_fminimizer_type *T;
        !          4882:   size_t iteri = 0, it;
        !          4883:   int rval = GSL_CONTINUE;
        !          4884:   int status = GSL_SUCCESS;
        !          4885:   double ssval;
        !          4886: #endif
        !          4887:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
        !          4888:   int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
        !          4889:   int linei, month, year,iout;
        !          4890:   int jj, ll, li, lj, lk, imk;
        !          4891:   int numlinepar=0; /* Current linenumber of parameter file */
        !          4892:   int itimes;
        !          4893:   int NDIM=2;
        !          4894:   int vpopbased=0;
        !          4895: 
        !          4896:   char ca[32], cb[32], cc[32];
        !          4897:   /*  FILE *fichtm; *//* Html File */
        !          4898:   /* FILE *ficgp;*/ /*Gnuplot File */
        !          4899:   struct stat info;
        !          4900:   double agedeb, agefin,hf;
        !          4901:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
        !          4902: 
        !          4903:   double fret;
        !          4904:   double **xi,tmp,delta;
        !          4905: 
        !          4906:   double dum; /* Dummy variable */
        !          4907:   double ***p3mat;
        !          4908:   double ***mobaverage;
        !          4909:   int *indx;
        !          4910:   char line[MAXLINE], linepar[MAXLINE];
        !          4911:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
        !          4912:   char pathr[MAXLINE], pathimach[MAXLINE]; 
        !          4913:   char **bp, *tok, *val; /* pathtot */
        !          4914:   int firstobs=1, lastobs=10;
        !          4915:   int sdeb, sfin; /* Status at beginning and end */
        !          4916:   int c,  h , cpt,l;
        !          4917:   int ju,jl, mi;
        !          4918:   int i1,j1, jk,aa,bb, stepsize, ij;
        !          4919:   int jnais,jdc,jint4,jint1,jint2,jint3,*tab; 
        !          4920:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
        !          4921:   int mobilav=0,popforecast=0;
        !          4922:   int hstepm, nhstepm;
        !          4923:   int agemortsup;
        !          4924:   float  sumlpop=0.;
        !          4925:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
        !          4926:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
        !          4927: 
        !          4928:   double bage, fage, age, agelim, agebase;
        !          4929:   double ftolpl=FTOL;
        !          4930:   double **prlim;
        !          4931:   double ***param; /* Matrix of parameters */
        !          4932:   double  *p;
        !          4933:   double **matcov; /* Matrix of covariance */
        !          4934:   double ***delti3; /* Scale */
        !          4935:   double *delti; /* Scale */
        !          4936:   double ***eij, ***vareij;
        !          4937:   double **varpl; /* Variances of prevalence limits by age */
        !          4938:   double *epj, vepp;
        !          4939:   double kk1, kk2;
        !          4940:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
        !          4941:   double **ximort;
        !          4942:   char *alph[]={"a","a","b","c","d","e"}, str[4];
        !          4943:   int *dcwave;
        !          4944: 
        !          4945:   char z[1]="c", occ;
        !          4946: 
        !          4947:   /*char  *strt;*/
        !          4948:   char strtend[80];
1.126     brouard  4949: 
                   4950:   long total_usecs;
                   4951:  
                   4952: /*   setlocale (LC_ALL, ""); */
                   4953: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   4954: /*   textdomain (PACKAGE); */
                   4955: /*   setlocale (LC_CTYPE, ""); */
                   4956: /*   setlocale (LC_MESSAGES, ""); */
                   4957: 
                   4958:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
                   4959:   (void) gettimeofday(&start_time,&tzp);
                   4960:   curr_time=start_time;
                   4961:   tm = *localtime(&start_time.tv_sec);
                   4962:   tmg = *gmtime(&start_time.tv_sec);
                   4963:   strcpy(strstart,asctime(&tm));
                   4964: 
                   4965: /*  printf("Localtime (at start)=%s",strstart); */
                   4966: /*  tp.tv_sec = tp.tv_sec +86400; */
                   4967: /*  tm = *localtime(&start_time.tv_sec); */
                   4968: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   4969: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   4970: /*   tmg.tm_hour=tmg.tm_hour + 1; */
                   4971: /*   tp.tv_sec = mktime(&tmg); */
                   4972: /*   strt=asctime(&tmg); */
                   4973: /*   printf("Time(after) =%s",strstart);  */
                   4974: /*  (void) time (&time_value);
                   4975: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   4976: *  tm = *localtime(&time_value);
                   4977: *  strstart=asctime(&tm);
                   4978: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   4979: */
                   4980: 
                   4981:   nberr=0; /* Number of errors and warnings */
                   4982:   nbwarn=0;
                   4983:   getcwd(pathcd, size);
                   4984: 
                   4985:   printf("\n%s\n%s",version,fullversion);
                   4986:   if(argc <=1){
                   4987:     printf("\nEnter the parameter file name: ");
                   4988:     fgets(pathr,FILENAMELENGTH,stdin);
                   4989:     i=strlen(pathr);
                   4990:     if(pathr[i-1]=='\n')
                   4991:       pathr[i-1]='\0';
                   4992:    for (tok = pathr; tok != NULL; ){
                   4993:       printf("Pathr |%s|\n",pathr);
                   4994:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   4995:       printf("val= |%s| pathr=%s\n",val,pathr);
                   4996:       strcpy (pathtot, val);
                   4997:       if(pathr[0] == '\0') break; /* Dirty */
                   4998:     }
                   4999:   }
                   5000:   else{
                   5001:     strcpy(pathtot,argv[1]);
                   5002:   }
                   5003:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   5004:   /*cygwin_split_path(pathtot,path,optionfile);
                   5005:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   5006:   /* cutv(path,optionfile,pathtot,'\\');*/
                   5007: 
                   5008:   /* Split argv[0], imach program to get pathimach */
                   5009:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   5010:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   5011:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   5012:  /*   strcpy(pathimach,argv[0]); */
                   5013:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   5014:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   5015:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
                   5016:   chdir(path); /* Can be a relative path */
                   5017:   if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   5018:     printf("Current directory %s!\n",pathcd);
                   5019:   strcpy(command,"mkdir ");
                   5020:   strcat(command,optionfilefiname);
                   5021:   if((outcmd=system(command)) != 0){
                   5022:     printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
                   5023:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   5024:     /* fclose(ficlog); */
                   5025: /*     exit(1); */
                   5026:   }
                   5027: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   5028: /*     perror("mkdir"); */
                   5029: /*   } */
                   5030: 
                   5031:   /*-------- arguments in the command line --------*/
                   5032: 
                   5033:   /* Log file */
                   5034:   strcat(filelog, optionfilefiname);
                   5035:   strcat(filelog,".log");    /* */
                   5036:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   5037:     printf("Problem with logfile %s\n",filelog);
                   5038:     goto end;
                   5039:   }
                   5040:   fprintf(ficlog,"Log filename:%s\n",filelog);
                   5041:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
                   5042:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   5043:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   5044:  path=%s \n\
                   5045:  optionfile=%s\n\
                   5046:  optionfilext=%s\n\
                   5047:  optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
                   5048: 
                   5049:   printf("Local time (at start):%s",strstart);
                   5050:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   5051:   fflush(ficlog);
                   5052: /*   (void) gettimeofday(&curr_time,&tzp); */
                   5053: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */
                   5054: 
                   5055:   /* */
                   5056:   strcpy(fileres,"r");
                   5057:   strcat(fileres, optionfilefiname);
                   5058:   strcat(fileres,".txt");    /* Other files have txt extension */
                   5059: 
                   5060:   /*---------arguments file --------*/
                   5061: 
                   5062:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
                   5063:     printf("Problem with optionfile %s\n",optionfile);
                   5064:     fprintf(ficlog,"Problem with optionfile %s\n",optionfile);
                   5065:     fflush(ficlog);
                   5066:     goto end;
                   5067:   }
                   5068: 
                   5069: 
                   5070: 
                   5071:   strcpy(filereso,"o");
                   5072:   strcat(filereso,fileres);
                   5073:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   5074:     printf("Problem with Output resultfile: %s\n", filereso);
                   5075:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   5076:     fflush(ficlog);
                   5077:     goto end;
                   5078:   }
                   5079: 
                   5080:   /* Reads comments: lines beginning with '#' */
                   5081:   numlinepar=0;
                   5082:   while((c=getc(ficpar))=='#' && c!= EOF){
                   5083:     ungetc(c,ficpar);
                   5084:     fgets(line, MAXLINE, ficpar);
                   5085:     numlinepar++;
                   5086:     puts(line);
                   5087:     fputs(line,ficparo);
                   5088:     fputs(line,ficlog);
                   5089:   }
                   5090:   ungetc(c,ficpar);
                   5091: 
                   5092:   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);
                   5093:   numlinepar++;
                   5094:   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);
                   5095:   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);
                   5096:   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);
                   5097:   fflush(ficlog);
                   5098:   while((c=getc(ficpar))=='#' && c!= EOF){
                   5099:     ungetc(c,ficpar);
                   5100:     fgets(line, MAXLINE, ficpar);
                   5101:     numlinepar++;
                   5102:     puts(line);
                   5103:     fputs(line,ficparo);
                   5104:     fputs(line,ficlog);
                   5105:   }
                   5106:   ungetc(c,ficpar);
                   5107: 
                   5108:    
                   5109:   covar=matrix(0,NCOVMAX,1,n); 
1.136   ! brouard  5110:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
        !          5111:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
        !          5112:      v1+v2*age+v2*v3 makes cptcovn = 3
        !          5113:   */
        !          5114:   if (strlen(model)>1) 
        !          5115:     cptcovn=nbocc(model,'+')+1;
        !          5116:   /* ncovprod */
        !          5117:   ncovmodel=2+cptcovn; /*Number of variables including intercept and age = cptcovn + intercept + age : v1+v2+v3+v2*v4+v5*age makes 5+2=7*/
1.126     brouard  5118:   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
1.133     brouard  5119:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   5120:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  5121:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   5122:     printf("Too complex model for current IMaCh: npar=(nlstate+ndeath-1)*nlstate*ncovmodel=%d >= %d(MAXPARM) or nlstate=%d >= %d(NLSTATEMAX) or ndeath=%d >= %d(NDEATHMAX) or ncovmodel=(k+age+#of+signs)=%d(NCOVMAX) >= %d\n",npar, MAXPARM, nlstate, NLSTATEMAX, ndeath, NDEATHMAX, ncovmodel, NCOVMAX);
                   5123:     fprintf(ficlog,"Too complex model for current IMaCh: %d >=%d(MAXPARM) or %d >=%d(NLSTATEMAX) or %d >=%d(NDEATHMAX) or %d(NCOVMAX) >=%d\n",npar, MAXPARM, nlstate, NLSTATEMAX, ndeath, NDEATHMAX, ncovmodel, NCOVMAX);
                   5124:     fflush(stdout);
                   5125:     fclose (ficlog);
                   5126:     goto end;
                   5127:   }
1.126     brouard  5128:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   5129:   delti=delti3[1][1];
                   5130:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   5131:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   5132:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   5133:     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   5134:     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   5135:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   5136:     fclose (ficparo);
                   5137:     fclose (ficlog);
                   5138:     goto end;
                   5139:     exit(0);
                   5140:   }
                   5141:   else if(mle==-3) {
                   5142:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   5143:     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   5144:     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   5145:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   5146:     matcov=matrix(1,npar,1,npar);
                   5147:   }
                   5148:   else{
                   5149:     /* Read guess parameters */
                   5150:     /* Reads comments: lines beginning with '#' */
                   5151:     while((c=getc(ficpar))=='#' && c!= EOF){
                   5152:       ungetc(c,ficpar);
                   5153:       fgets(line, MAXLINE, ficpar);
                   5154:       numlinepar++;
                   5155:       puts(line);
                   5156:       fputs(line,ficparo);
                   5157:       fputs(line,ficlog);
                   5158:     }
                   5159:     ungetc(c,ficpar);
                   5160:     
                   5161:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   5162:     for(i=1; i <=nlstate; i++){
                   5163:       j=0;
                   5164:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   5165:        if(jj==i) continue;
                   5166:        j++;
                   5167:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   5168:        if ((i1 != i) && (j1 != j)){
                   5169:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   5170: It might be a problem of design; if ncovcol and the model are correct\n \
                   5171: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   5172:          exit(1);
                   5173:        }
                   5174:        fprintf(ficparo,"%1d%1d",i1,j1);
                   5175:        if(mle==1)
                   5176:          printf("%1d%1d",i,j);
                   5177:        fprintf(ficlog,"%1d%1d",i,j);
                   5178:        for(k=1; k<=ncovmodel;k++){
                   5179:          fscanf(ficpar," %lf",&param[i][j][k]);
                   5180:          if(mle==1){
                   5181:            printf(" %lf",param[i][j][k]);
                   5182:            fprintf(ficlog," %lf",param[i][j][k]);
                   5183:          }
                   5184:          else
                   5185:            fprintf(ficlog," %lf",param[i][j][k]);
                   5186:          fprintf(ficparo," %lf",param[i][j][k]);
                   5187:        }
                   5188:        fscanf(ficpar,"\n");
                   5189:        numlinepar++;
                   5190:        if(mle==1)
                   5191:          printf("\n");
                   5192:        fprintf(ficlog,"\n");
                   5193:        fprintf(ficparo,"\n");
                   5194:       }
                   5195:     }  
                   5196:     fflush(ficlog);
                   5197: 
                   5198:     p=param[1][1];
                   5199:     
                   5200:     /* Reads comments: lines beginning with '#' */
                   5201:     while((c=getc(ficpar))=='#' && c!= EOF){
                   5202:       ungetc(c,ficpar);
                   5203:       fgets(line, MAXLINE, ficpar);
                   5204:       numlinepar++;
                   5205:       puts(line);
                   5206:       fputs(line,ficparo);
                   5207:       fputs(line,ficlog);
                   5208:     }
                   5209:     ungetc(c,ficpar);
                   5210: 
                   5211:     for(i=1; i <=nlstate; i++){
                   5212:       for(j=1; j <=nlstate+ndeath-1; j++){
                   5213:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   5214:        if ((i1-i)*(j1-j)!=0){
                   5215:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   5216:          exit(1);
                   5217:        }
                   5218:        printf("%1d%1d",i,j);
                   5219:        fprintf(ficparo,"%1d%1d",i1,j1);
                   5220:        fprintf(ficlog,"%1d%1d",i1,j1);
                   5221:        for(k=1; k<=ncovmodel;k++){
                   5222:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   5223:          printf(" %le",delti3[i][j][k]);
                   5224:          fprintf(ficparo," %le",delti3[i][j][k]);
                   5225:          fprintf(ficlog," %le",delti3[i][j][k]);
                   5226:        }
                   5227:        fscanf(ficpar,"\n");
                   5228:        numlinepar++;
                   5229:        printf("\n");
                   5230:        fprintf(ficparo,"\n");
                   5231:        fprintf(ficlog,"\n");
                   5232:       }
                   5233:     }
                   5234:     fflush(ficlog);
                   5235: 
                   5236:     delti=delti3[1][1];
                   5237: 
                   5238: 
                   5239:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   5240:   
                   5241:     /* Reads comments: lines beginning with '#' */
                   5242:     while((c=getc(ficpar))=='#' && c!= EOF){
                   5243:       ungetc(c,ficpar);
                   5244:       fgets(line, MAXLINE, ficpar);
                   5245:       numlinepar++;
                   5246:       puts(line);
                   5247:       fputs(line,ficparo);
                   5248:       fputs(line,ficlog);
                   5249:     }
                   5250:     ungetc(c,ficpar);
                   5251:   
                   5252:     matcov=matrix(1,npar,1,npar);
1.131     brouard  5253:     for(i=1; i <=npar; i++)
                   5254:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   5255:       
1.126     brouard  5256:     for(i=1; i <=npar; i++){
                   5257:       fscanf(ficpar,"%s",&str);
                   5258:       if(mle==1)
                   5259:        printf("%s",str);
                   5260:       fprintf(ficlog,"%s",str);
                   5261:       fprintf(ficparo,"%s",str);
                   5262:       for(j=1; j <=i; j++){
                   5263:        fscanf(ficpar," %le",&matcov[i][j]);
                   5264:        if(mle==1){
                   5265:          printf(" %.5le",matcov[i][j]);
                   5266:        }
                   5267:        fprintf(ficlog," %.5le",matcov[i][j]);
                   5268:        fprintf(ficparo," %.5le",matcov[i][j]);
                   5269:       }
                   5270:       fscanf(ficpar,"\n");
                   5271:       numlinepar++;
                   5272:       if(mle==1)
                   5273:        printf("\n");
                   5274:       fprintf(ficlog,"\n");
                   5275:       fprintf(ficparo,"\n");
                   5276:     }
                   5277:     for(i=1; i <=npar; i++)
                   5278:       for(j=i+1;j<=npar;j++)
                   5279:        matcov[i][j]=matcov[j][i];
                   5280:     
                   5281:     if(mle==1)
                   5282:       printf("\n");
                   5283:     fprintf(ficlog,"\n");
                   5284:     
                   5285:     fflush(ficlog);
                   5286:     
                   5287:     /*-------- Rewriting parameter file ----------*/
                   5288:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   5289:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   5290:     strcat(rfileres,".");    /* */
                   5291:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   5292:     if((ficres =fopen(rfileres,"w"))==NULL) {
                   5293:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
                   5294:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
                   5295:     }
                   5296:     fprintf(ficres,"#%s\n",version);
                   5297:   }    /* End of mle != -3 */
                   5298: 
                   5299: 
                   5300:   n= lastobs;
                   5301:   num=lvector(1,n);
                   5302:   moisnais=vector(1,n);
                   5303:   annais=vector(1,n);
                   5304:   moisdc=vector(1,n);
                   5305:   andc=vector(1,n);
                   5306:   agedc=vector(1,n);
                   5307:   cod=ivector(1,n);
                   5308:   weight=vector(1,n);
                   5309:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   5310:   mint=matrix(1,maxwav,1,n);
                   5311:   anint=matrix(1,maxwav,1,n);
1.131     brouard  5312:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  5313:   tab=ivector(1,NCOVMAX);
                   5314:   ncodemax=ivector(1,8);
                   5315: 
1.136   ! brouard  5316:   /* Reads data from file datafile */
        !          5317:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
        !          5318:     goto end;
        !          5319: 
        !          5320:   /* Calculation of the number of parameters from char model */
        !          5321:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. Stores the number n of the covariates in Vm+Vn at 1 and m at 2 */
        !          5322:   Tprod=ivector(1,15); 
        !          5323:   Tvaraff=ivector(1,15); 
        !          5324:   Tvard=imatrix(1,15,1,2);
        !          5325:   Tage=ivector(1,15);      
        !          5326: 
        !          5327:   if(decodemodel(model, lastobs) == 1)
        !          5328:     goto end;
        !          5329: 
        !          5330:     /*  if(mle==1){*/
        !          5331:   if (weightopt != 1) { /* Maximisation without weights*/
        !          5332:     for(i=1;i<=n;i++) weight[i]=1.0;
        !          5333:   }
        !          5334: 
        !          5335:     /*-calculation of age at interview from date of interview and age at death -*/
        !          5336:   agev=matrix(1,maxwav,1,imx);
        !          5337: 
        !          5338:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
        !          5339:     goto end;
        !          5340: 
1.126     brouard  5341: 
1.136   ! brouard  5342:   agegomp=(int)agemin;
        !          5343:   free_vector(moisnais,1,n);
        !          5344:   free_vector(annais,1,n);
1.126     brouard  5345:   /* free_matrix(mint,1,maxwav,1,n);
                   5346:      free_matrix(anint,1,maxwav,1,n);*/
                   5347:   free_vector(moisdc,1,n);
                   5348:   free_vector(andc,1,n);
                   5349: 
                   5350:    
                   5351:   wav=ivector(1,imx);
                   5352:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   5353:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
                   5354:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   5355:    
                   5356:   /* Concatenates waves */
                   5357:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
                   5358: 
                   5359:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   5360: 
                   5361:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   5362:   ncodemax[1]=1;
                   5363:   if (cptcovn > 0) tricode(Tvar,nbcode,imx);
                   5364:       
                   5365:   codtab=imatrix(1,100,1,10); /* Cross tabulation to get the order of 
                   5366:                                 the estimations*/
                   5367:   h=0;
                   5368:   m=pow(2,cptcoveff);
                   5369:  
1.131     brouard  5370:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
                   5371:     for(i=1; i <=(m/pow(2,k));i++){ /* i=1 to 8/1=8; i=1 to 8/2=4; i=1 to 8/8=1 */ 
                   5372:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate */
                   5373:        for(cpt=1; cpt <=(m/pow(2,cptcoveff+1-k)); cpt++){  /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */ 
1.126     brouard  5374:          h++;
1.136   ! brouard  5375:          if (h>m) {
        !          5376:            h=1;
        !          5377:            codtab[h][k]=j;
        !          5378:            codtab[h][Tvar[k]]=j;
        !          5379:          }
1.130     brouard  5380:          printf("h=%d k=%d j=%d codtab[h][k]=%d Tvar[k]=%d codtab[h][Tvar[k]]=%d \n",h, k,j,codtab[h][k],Tvar[k],codtab[h][Tvar[k]]);
1.126     brouard  5381:        } 
                   5382:       }
                   5383:     }
                   5384:   } 
                   5385:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   5386:      codtab[1][2]=1;codtab[2][2]=2; */
                   5387:   /* for(i=1; i <=m ;i++){ 
                   5388:      for(k=1; k <=cptcovn; k++){
1.131     brouard  5389:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126     brouard  5390:      }
                   5391:      printf("\n");
                   5392:      }
                   5393:      scanf("%d",i);*/
                   5394:     
                   5395:   /*------------ gnuplot -------------*/
                   5396:   strcpy(optionfilegnuplot,optionfilefiname);
                   5397:   if(mle==-3)
                   5398:     strcat(optionfilegnuplot,"-mort");
                   5399:   strcat(optionfilegnuplot,".gp");
                   5400: 
                   5401:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   5402:     printf("Problem with file %s",optionfilegnuplot);
                   5403:   }
                   5404:   else{
                   5405:     fprintf(ficgp,"\n# %s\n", version); 
                   5406:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
                   5407:     fprintf(ficgp,"set missing 'NaNq'\n");
                   5408:   }
                   5409:   /*  fclose(ficgp);*/
                   5410:   /*--------- index.htm --------*/
                   5411: 
                   5412:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   5413:   if(mle==-3)
                   5414:     strcat(optionfilehtm,"-mort");
                   5415:   strcat(optionfilehtm,".htm");
                   5416:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  5417:     printf("Problem with %s \n",optionfilehtm);
                   5418:     exit(0);
1.126     brouard  5419:   }
                   5420: 
                   5421:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   5422:   strcat(optionfilehtmcov,"-cov.htm");
                   5423:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   5424:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   5425:   }
                   5426:   else{
                   5427:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   5428: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   5429: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
                   5430:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5431:   }
                   5432: 
                   5433:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   5434: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   5435: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
                   5436: \n\
                   5437: <hr  size=\"2\" color=\"#EC5E5E\">\
                   5438:  <ul><li><h4>Parameter files</h4>\n\
                   5439:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   5440:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   5441:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   5442:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   5443:  - Date and time at start: %s</ul>\n",\
                   5444:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   5445:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   5446:          fileres,fileres,\
                   5447:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   5448:   fflush(fichtm);
                   5449: 
                   5450:   strcpy(pathr,path);
                   5451:   strcat(pathr,optionfilefiname);
                   5452:   chdir(optionfilefiname); /* Move to directory named optionfile */
                   5453:   
                   5454:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   5455:      and prints on file fileres'p'. */
                   5456:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                   5457: 
                   5458:   fprintf(fichtm,"\n");
                   5459:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   5460: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   5461: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   5462:          imx,agemin,agemax,jmin,jmax,jmean);
                   5463:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   5464:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   5465:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   5466:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   5467:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   5468:     
                   5469:    
                   5470:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   5471:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   5472:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   5473: 
                   5474:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
                   5475: 
                   5476:   if (mle==-3){
1.136   ! brouard  5477:     ximort=matrix(1,NDIM,1,NDIM); 
        !          5478: /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  5479:     cens=ivector(1,n);
                   5480:     ageexmed=vector(1,n);
                   5481:     agecens=vector(1,n);
                   5482:     dcwave=ivector(1,n);
                   5483:  
                   5484:     for (i=1; i<=imx; i++){
                   5485:       dcwave[i]=-1;
                   5486:       for (m=firstpass; m<=lastpass; m++)
                   5487:        if (s[m][i]>nlstate) {
                   5488:          dcwave[i]=m;
                   5489:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   5490:          break;
                   5491:        }
                   5492:     }
                   5493: 
                   5494:     for (i=1; i<=imx; i++) {
                   5495:       if (wav[i]>0){
                   5496:        ageexmed[i]=agev[mw[1][i]][i];
                   5497:        j=wav[i];
                   5498:        agecens[i]=1.; 
                   5499: 
                   5500:        if (ageexmed[i]> 1 && wav[i] > 0){
                   5501:          agecens[i]=agev[mw[j][i]][i];
                   5502:          cens[i]= 1;
                   5503:        }else if (ageexmed[i]< 1) 
                   5504:          cens[i]= -1;
                   5505:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   5506:          cens[i]=0 ;
                   5507:       }
                   5508:       else cens[i]=-1;
                   5509:     }
                   5510:     
                   5511:     for (i=1;i<=NDIM;i++) {
                   5512:       for (j=1;j<=NDIM;j++)
                   5513:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   5514:     }
                   5515:     
                   5516:     p[1]=0.0268; p[NDIM]=0.083;
                   5517:     /*printf("%lf %lf", p[1], p[2]);*/
                   5518:     
                   5519:     
1.136   ! brouard  5520: #ifdef GSL
        !          5521:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
        !          5522: #elsedef
1.126     brouard  5523:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136   ! brouard  5524: #endif
1.126     brouard  5525:     strcpy(filerespow,"pow-mort"); 
                   5526:     strcat(filerespow,fileres);
                   5527:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   5528:       printf("Problem with resultfile: %s\n", filerespow);
                   5529:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   5530:     }
1.136   ! brouard  5531: #ifdef GSL
        !          5532:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
        !          5533: #elsedef
1.126     brouard  5534:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136   ! brouard  5535: #endif
1.126     brouard  5536:     /*  for (i=1;i<=nlstate;i++)
                   5537:        for(j=1;j<=nlstate+ndeath;j++)
                   5538:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   5539:     */
                   5540:     fprintf(ficrespow,"\n");
1.136   ! brouard  5541: #ifdef GSL
        !          5542:     /* gsl starts here */ 
        !          5543:     T = gsl_multimin_fminimizer_nmsimplex;
        !          5544:     gsl_multimin_fminimizer *sfm = NULL;
        !          5545:     gsl_vector *ss, *x;
        !          5546:     gsl_multimin_function minex_func;
        !          5547: 
        !          5548:     /* Initial vertex size vector */
        !          5549:     ss = gsl_vector_alloc (NDIM);
        !          5550:     
        !          5551:     if (ss == NULL){
        !          5552:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
        !          5553:     }
        !          5554:     /* Set all step sizes to 1 */
        !          5555:     gsl_vector_set_all (ss, 0.001);
        !          5556: 
        !          5557:     /* Starting point */
1.126     brouard  5558:     
1.136   ! brouard  5559:     x = gsl_vector_alloc (NDIM);
        !          5560:     
        !          5561:     if (x == NULL){
        !          5562:       gsl_vector_free(ss);
        !          5563:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
        !          5564:     }
        !          5565:   
        !          5566:     /* Initialize method and iterate */
        !          5567:     /*     p[1]=0.0268; p[NDIM]=0.083; */
        !          5568: /*     gsl_vector_set(x, 0, 0.0268); */
        !          5569: /*     gsl_vector_set(x, 1, 0.083); */
        !          5570:     gsl_vector_set(x, 0, p[1]);
        !          5571:     gsl_vector_set(x, 1, p[2]);
        !          5572: 
        !          5573:     minex_func.f = &gompertz_f;
        !          5574:     minex_func.n = NDIM;
        !          5575:     minex_func.params = (void *)&p; /* ??? */
        !          5576:     
        !          5577:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
        !          5578:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
        !          5579:     
        !          5580:     printf("Iterations beginning .....\n\n");
        !          5581:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
        !          5582: 
        !          5583:     iteri=0;
        !          5584:     while (rval == GSL_CONTINUE){
        !          5585:       iteri++;
        !          5586:       status = gsl_multimin_fminimizer_iterate(sfm);
        !          5587:       
        !          5588:       if (status) printf("error: %s\n", gsl_strerror (status));
        !          5589:       fflush(0);
        !          5590:       
        !          5591:       if (status) 
        !          5592:         break;
        !          5593:       
        !          5594:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
        !          5595:       ssval = gsl_multimin_fminimizer_size (sfm);
        !          5596:       
        !          5597:       if (rval == GSL_SUCCESS)
        !          5598:         printf ("converged to a local maximum at\n");
        !          5599:       
        !          5600:       printf("%5d ", iteri);
        !          5601:       for (it = 0; it < NDIM; it++){
        !          5602:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
        !          5603:       }
        !          5604:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
        !          5605:     }
        !          5606:     
        !          5607:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
        !          5608:     
        !          5609:     gsl_vector_free(x); /* initial values */
        !          5610:     gsl_vector_free(ss); /* inital step size */
        !          5611:     for (it=0; it<NDIM; it++){
        !          5612:       p[it+1]=gsl_vector_get(sfm->x,it);
        !          5613:       fprintf(ficrespow," %.12lf", p[it]);
        !          5614:     }
        !          5615:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
        !          5616: #endif
        !          5617: #ifdef POWELL
        !          5618:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
        !          5619: #endif  
1.126     brouard  5620:     fclose(ficrespow);
                   5621:     
                   5622:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
                   5623: 
                   5624:     for(i=1; i <=NDIM; i++)
                   5625:       for(j=i+1;j<=NDIM;j++)
                   5626:        matcov[i][j]=matcov[j][i];
                   5627:     
                   5628:     printf("\nCovariance matrix\n ");
                   5629:     for(i=1; i <=NDIM; i++) {
                   5630:       for(j=1;j<=NDIM;j++){ 
                   5631:        printf("%f ",matcov[i][j]);
                   5632:       }
                   5633:       printf("\n ");
                   5634:     }
                   5635:     
                   5636:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
                   5637:     for (i=1;i<=NDIM;i++) 
                   5638:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   5639: 
                   5640:     lsurv=vector(1,AGESUP);
                   5641:     lpop=vector(1,AGESUP);
                   5642:     tpop=vector(1,AGESUP);
                   5643:     lsurv[agegomp]=100000;
                   5644:     
                   5645:     for (k=agegomp;k<=AGESUP;k++) {
                   5646:       agemortsup=k;
                   5647:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   5648:     }
                   5649:     
                   5650:     for (k=agegomp;k<agemortsup;k++)
                   5651:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   5652:     
                   5653:     for (k=agegomp;k<agemortsup;k++){
                   5654:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   5655:       sumlpop=sumlpop+lpop[k];
                   5656:     }
                   5657:     
                   5658:     tpop[agegomp]=sumlpop;
                   5659:     for (k=agegomp;k<(agemortsup-3);k++){
                   5660:       /*  tpop[k+1]=2;*/
                   5661:       tpop[k+1]=tpop[k]-lpop[k];
                   5662:     }
                   5663:     
                   5664:     
                   5665:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   5666:     for (k=agegomp;k<(agemortsup-2);k++) 
                   5667:       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]);
                   5668:     
                   5669:     
                   5670:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   5671:     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   5672:     
                   5673:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
                   5674:                     stepm, weightopt,\
                   5675:                     model,imx,p,matcov,agemortsup);
                   5676:     
                   5677:     free_vector(lsurv,1,AGESUP);
                   5678:     free_vector(lpop,1,AGESUP);
                   5679:     free_vector(tpop,1,AGESUP);
1.136   ! brouard  5680: #ifdef GSL
        !          5681:     free_ivector(cens,1,n);
        !          5682:     free_vector(agecens,1,n);
        !          5683:     free_ivector(dcwave,1,n);
        !          5684:     free_matrix(ximort,1,NDIM,1,NDIM);
        !          5685: #endif
1.126     brouard  5686:   } /* Endof if mle==-3 */
                   5687:   
                   5688:   else{ /* For mle >=1 */
1.132     brouard  5689:     globpr=0;/* debug */
                   5690:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  5691:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   5692:     for (k=1; k<=npar;k++)
                   5693:       printf(" %d %8.5f",k,p[k]);
                   5694:     printf("\n");
                   5695:     globpr=1; /* to print the contributions */
                   5696:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   5697:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   5698:     for (k=1; k<=npar;k++)
                   5699:       printf(" %d %8.5f",k,p[k]);
                   5700:     printf("\n");
                   5701:     if(mle>=1){ /* Could be 1 or 2 */
                   5702:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   5703:     }
                   5704:     
                   5705:     /*--------- results files --------------*/
                   5706:     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);
                   5707:     
                   5708:     
                   5709:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5710:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5711:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5712:     for(i=1,jk=1; i <=nlstate; i++){
                   5713:       for(k=1; k <=(nlstate+ndeath); k++){
                   5714:        if (k != i) {
                   5715:          printf("%d%d ",i,k);
                   5716:          fprintf(ficlog,"%d%d ",i,k);
                   5717:          fprintf(ficres,"%1d%1d ",i,k);
                   5718:          for(j=1; j <=ncovmodel; j++){
                   5719:            printf("%lf ",p[jk]);
                   5720:            fprintf(ficlog,"%lf ",p[jk]);
                   5721:            fprintf(ficres,"%lf ",p[jk]);
                   5722:            jk++; 
                   5723:          }
                   5724:          printf("\n");
                   5725:          fprintf(ficlog,"\n");
                   5726:          fprintf(ficres,"\n");
                   5727:        }
                   5728:       }
                   5729:     }
                   5730:     if(mle!=0){
                   5731:       /* Computing hessian and covariance matrix */
                   5732:       ftolhess=ftol; /* Usually correct */
                   5733:       hesscov(matcov, p, npar, delti, ftolhess, func);
                   5734:     }
                   5735:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   5736:     printf("# Scales (for hessian or gradient estimation)\n");
                   5737:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   5738:     for(i=1,jk=1; i <=nlstate; i++){
                   5739:       for(j=1; j <=nlstate+ndeath; j++){
                   5740:        if (j!=i) {
                   5741:          fprintf(ficres,"%1d%1d",i,j);
                   5742:          printf("%1d%1d",i,j);
                   5743:          fprintf(ficlog,"%1d%1d",i,j);
                   5744:          for(k=1; k<=ncovmodel;k++){
                   5745:            printf(" %.5e",delti[jk]);
                   5746:            fprintf(ficlog," %.5e",delti[jk]);
                   5747:            fprintf(ficres," %.5e",delti[jk]);
                   5748:            jk++;
                   5749:          }
                   5750:          printf("\n");
                   5751:          fprintf(ficlog,"\n");
                   5752:          fprintf(ficres,"\n");
                   5753:        }
                   5754:       }
                   5755:     }
                   5756:     
                   5757:     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");
                   5758:     if(mle>=1)
                   5759:       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");
                   5760:     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");
                   5761:     /* # 121 Var(a12)\n\ */
                   5762:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5763:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   5764:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   5765:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   5766:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   5767:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   5768:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   5769:     
                   5770:     
                   5771:     /* Just to have a covariance matrix which will be more understandable
                   5772:        even is we still don't want to manage dictionary of variables
                   5773:     */
                   5774:     for(itimes=1;itimes<=2;itimes++){
                   5775:       jj=0;
                   5776:       for(i=1; i <=nlstate; i++){
                   5777:        for(j=1; j <=nlstate+ndeath; j++){
                   5778:          if(j==i) continue;
                   5779:          for(k=1; k<=ncovmodel;k++){
                   5780:            jj++;
                   5781:            ca[0]= k+'a'-1;ca[1]='\0';
                   5782:            if(itimes==1){
                   5783:              if(mle>=1)
                   5784:                printf("#%1d%1d%d",i,j,k);
                   5785:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   5786:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   5787:            }else{
                   5788:              if(mle>=1)
                   5789:                printf("%1d%1d%d",i,j,k);
                   5790:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   5791:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   5792:            }
                   5793:            ll=0;
                   5794:            for(li=1;li <=nlstate; li++){
                   5795:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   5796:                if(lj==li) continue;
                   5797:                for(lk=1;lk<=ncovmodel;lk++){
                   5798:                  ll++;
                   5799:                  if(ll<=jj){
                   5800:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   5801:                    if(ll<jj){
                   5802:                      if(itimes==1){
                   5803:                        if(mle>=1)
                   5804:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5805:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5806:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5807:                      }else{
                   5808:                        if(mle>=1)
                   5809:                          printf(" %.5e",matcov[jj][ll]); 
                   5810:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   5811:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   5812:                      }
                   5813:                    }else{
                   5814:                      if(itimes==1){
                   5815:                        if(mle>=1)
                   5816:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   5817:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   5818:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   5819:                      }else{
                   5820:                        if(mle>=1)
                   5821:                          printf(" %.5e",matcov[jj][ll]); 
                   5822:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   5823:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   5824:                      }
                   5825:                    }
                   5826:                  }
                   5827:                } /* end lk */
                   5828:              } /* end lj */
                   5829:            } /* end li */
                   5830:            if(mle>=1)
                   5831:              printf("\n");
                   5832:            fprintf(ficlog,"\n");
                   5833:            fprintf(ficres,"\n");
                   5834:            numlinepar++;
                   5835:          } /* end k*/
                   5836:        } /*end j */
                   5837:       } /* end i */
                   5838:     } /* end itimes */
                   5839:     
                   5840:     fflush(ficlog);
                   5841:     fflush(ficres);
                   5842:     
                   5843:     while((c=getc(ficpar))=='#' && c!= EOF){
                   5844:       ungetc(c,ficpar);
                   5845:       fgets(line, MAXLINE, ficpar);
                   5846:       puts(line);
                   5847:       fputs(line,ficparo);
                   5848:     }
                   5849:     ungetc(c,ficpar);
                   5850:     
                   5851:     estepm=0;
                   5852:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
                   5853:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   5854:     if (fage <= 2) {
                   5855:       bage = ageminpar;
                   5856:       fage = agemaxpar;
                   5857:     }
                   5858:     
                   5859:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   5860:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   5861:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   5862:     
                   5863:     while((c=getc(ficpar))=='#' && c!= EOF){
                   5864:       ungetc(c,ficpar);
                   5865:       fgets(line, MAXLINE, ficpar);
                   5866:       puts(line);
                   5867:       fputs(line,ficparo);
                   5868:     }
                   5869:     ungetc(c,ficpar);
                   5870:     
                   5871:     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);
                   5872:     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);
                   5873:     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);
                   5874:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   5875:     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);
                   5876:     
                   5877:     while((c=getc(ficpar))=='#' && c!= EOF){
                   5878:       ungetc(c,ficpar);
                   5879:       fgets(line, MAXLINE, ficpar);
                   5880:       puts(line);
                   5881:       fputs(line,ficparo);
                   5882:     }
                   5883:     ungetc(c,ficpar);
                   5884:     
                   5885:     
                   5886:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   5887:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   5888:     
                   5889:     fscanf(ficpar,"pop_based=%d\n",&popbased);
                   5890:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   5891:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   5892:     
                   5893:     while((c=getc(ficpar))=='#' && c!= EOF){
                   5894:       ungetc(c,ficpar);
                   5895:       fgets(line, MAXLINE, ficpar);
                   5896:       puts(line);
                   5897:       fputs(line,ficparo);
                   5898:     }
                   5899:     ungetc(c,ficpar);
                   5900:     
                   5901:     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);
                   5902:     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);
                   5903:     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);
                   5904:     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);
                   5905:     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);
                   5906:     /* day and month of proj2 are not used but only year anproj2.*/
                   5907:     
                   5908:     
                   5909:     
                   5910:     /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/
                   5911:     /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   5912:     
                   5913:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   5914:     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   5915:     
                   5916:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
                   5917:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                   5918:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   5919:       
                   5920:    /*------------ free_vector  -------------*/
                   5921:    /*  chdir(path); */
                   5922:  
                   5923:     free_ivector(wav,1,imx);
                   5924:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   5925:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
                   5926:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   5927:     free_lvector(num,1,n);
                   5928:     free_vector(agedc,1,n);
                   5929:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   5930:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   5931:     fclose(ficparo);
                   5932:     fclose(ficres);
                   5933: 
                   5934: 
                   5935:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   5936:   
                   5937:     strcpy(filerespl,"pl");
                   5938:     strcat(filerespl,fileres);
                   5939:     if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   5940:       printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
                   5941:       fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
                   5942:     }
                   5943:     printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   5944:     fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   5945:     pstamp(ficrespl);
                   5946:     fprintf(ficrespl,"# Period (stable) prevalence \n");
                   5947:     fprintf(ficrespl,"#Age ");
                   5948:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   5949:     fprintf(ficrespl,"\n");
                   5950:   
                   5951:     prlim=matrix(1,nlstate,1,nlstate);
                   5952: 
                   5953:     agebase=ageminpar;
                   5954:     agelim=agemaxpar;
                   5955:     ftolpl=1.e-10;
                   5956:     i1=cptcoveff;
                   5957:     if (cptcovn < 1){i1=1;}
                   5958: 
                   5959:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   5960:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   5961:        k=k+1;
1.131     brouard  5962:        /* to clean */
                   5963:        printf("cptcov=%d cptcod=%d codtab=%d nbcode=%d\n",cptcov, cptcod,codtab[cptcod][cptcov],nbcode);
1.126     brouard  5964:        fprintf(ficrespl,"\n#******");
                   5965:        printf("\n#******");
                   5966:        fprintf(ficlog,"\n#******");
                   5967:        for(j=1;j<=cptcoveff;j++) {
                   5968:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   5969:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   5970:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   5971:        }
                   5972:        fprintf(ficrespl,"******\n");
                   5973:        printf("******\n");
                   5974:        fprintf(ficlog,"******\n");
                   5975:        
                   5976:        for (age=agebase; age<=agelim; age++){
                   5977:          prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   5978:          fprintf(ficrespl,"%.0f ",age );
                   5979:          for(j=1;j<=cptcoveff;j++)
                   5980:            fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   5981:          for(i=1; i<=nlstate;i++)
                   5982:            fprintf(ficrespl," %.5f", prlim[i][i]);
                   5983:          fprintf(ficrespl,"\n");
                   5984:        }
                   5985:       }
                   5986:     }
                   5987:     fclose(ficrespl);
                   5988: 
                   5989:     /*------------- h Pij x at various ages ------------*/
                   5990:   
                   5991:     strcpy(filerespij,"pij");  strcat(filerespij,fileres);
                   5992:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   5993:       printf("Problem with Pij resultfile: %s\n", filerespij);goto end;
                   5994:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;
                   5995:     }
                   5996:     printf("Computing pij: result on file '%s' \n", filerespij);
                   5997:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   5998:   
                   5999:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6000:     /*if (stepm<=24) stepsize=2;*/
                   6001: 
                   6002:     agelim=AGESUP;
                   6003:     hstepm=stepsize*YEARM; /* Every year of age */
                   6004:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   6005: 
                   6006:     /* hstepm=1;   aff par mois*/
                   6007:     pstamp(ficrespij);
                   6008:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   6009:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6010:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6011:        k=k+1;
                   6012:        fprintf(ficrespij,"\n#****** ");
                   6013:        for(j=1;j<=cptcoveff;j++) 
                   6014:          fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6015:        fprintf(ficrespij,"******\n");
                   6016:        
                   6017:        for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   6018:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6019:          nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6020: 
                   6021:          /*      nhstepm=nhstepm*YEARM; aff par mois*/
                   6022: 
                   6023:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6024:          oldm=oldms;savm=savms;
                   6025:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6026:          fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   6027:          for(i=1; i<=nlstate;i++)
                   6028:            for(j=1; j<=nlstate+ndeath;j++)
                   6029:              fprintf(ficrespij," %1d-%1d",i,j);
                   6030:          fprintf(ficrespij,"\n");
                   6031:          for (h=0; h<=nhstepm; h++){
                   6032:            fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );
                   6033:            for(i=1; i<=nlstate;i++)
                   6034:              for(j=1; j<=nlstate+ndeath;j++)
                   6035:                fprintf(ficrespij," %.5f", p3mat[i][j][h]);
                   6036:            fprintf(ficrespij,"\n");
                   6037:          }
                   6038:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6039:          fprintf(ficrespij,"\n");
                   6040:        }
                   6041:       }
                   6042:     }
                   6043: 
                   6044:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   6045: 
                   6046:     fclose(ficrespij);
                   6047: 
                   6048:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6049:     for(i=1;i<=AGESUP;i++)
                   6050:       for(j=1;j<=NCOVMAX;j++)
                   6051:        for(k=1;k<=NCOVMAX;k++)
                   6052:          probs[i][j][k]=0.;
                   6053: 
                   6054:     /*---------- Forecasting ------------------*/
                   6055:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   6056:     if(prevfcast==1){
                   6057:       /*    if(stepm ==1){*/
                   6058:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
                   6059:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   6060:       /*      }  */
                   6061:       /*      else{ */
                   6062:       /*        erreur=108; */
                   6063:       /*        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); */
                   6064:       /*        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); */
                   6065:       /*      } */
                   6066:     }
                   6067:   
                   6068: 
1.127     brouard  6069:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   6070: 
                   6071:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   6072:     /*  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",\
                   6073:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   6074:     */
1.126     brouard  6075: 
1.127     brouard  6076:     if (mobilav!=0) {
                   6077:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6078:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   6079:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   6080:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   6081:       }
1.126     brouard  6082:     }
                   6083: 
                   6084: 
1.127     brouard  6085:     /*---------- Health expectancies, no variances ------------*/
                   6086: 
1.126     brouard  6087:     strcpy(filerese,"e");
                   6088:     strcat(filerese,fileres);
                   6089:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   6090:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   6091:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   6092:     }
                   6093:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
                   6094:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.127     brouard  6095:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6096:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6097:        k=k+1; 
                   6098:        fprintf(ficreseij,"\n#****** ");
                   6099:        for(j=1;j<=cptcoveff;j++) {
                   6100:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6101:        }
                   6102:        fprintf(ficreseij,"******\n");
                   6103: 
                   6104:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   6105:        oldm=oldms;savm=savms;
                   6106:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   6107:       
                   6108:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   6109:       }
                   6110:     }
                   6111:     fclose(ficreseij);
                   6112: 
                   6113: 
                   6114:     /*---------- Health expectancies and variances ------------*/
                   6115: 
                   6116: 
                   6117:     strcpy(filerest,"t");
                   6118:     strcat(filerest,fileres);
                   6119:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   6120:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   6121:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   6122:     }
                   6123:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   6124:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   6125: 
1.126     brouard  6126: 
                   6127:     strcpy(fileresstde,"stde");
                   6128:     strcat(fileresstde,fileres);
                   6129:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   6130:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   6131:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   6132:     }
                   6133:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   6134:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   6135: 
                   6136:     strcpy(filerescve,"cve");
                   6137:     strcat(filerescve,fileres);
                   6138:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   6139:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   6140:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   6141:     }
                   6142:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   6143:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   6144: 
                   6145:     strcpy(fileresv,"v");
                   6146:     strcat(fileresv,fileres);
                   6147:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   6148:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   6149:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   6150:     }
                   6151:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   6152:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   6153: 
                   6154:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6155:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6156:        k=k+1; 
                   6157:        fprintf(ficrest,"\n#****** ");
                   6158:        for(j=1;j<=cptcoveff;j++) 
                   6159:          fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6160:        fprintf(ficrest,"******\n");
                   6161: 
                   6162:        fprintf(ficresstdeij,"\n#****** ");
                   6163:        fprintf(ficrescveij,"\n#****** ");
                   6164:        for(j=1;j<=cptcoveff;j++) {
                   6165:          fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6166:          fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6167:        }
                   6168:        fprintf(ficresstdeij,"******\n");
                   6169:        fprintf(ficrescveij,"******\n");
                   6170: 
                   6171:        fprintf(ficresvij,"\n#****** ");
                   6172:        for(j=1;j<=cptcoveff;j++) 
                   6173:          fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6174:        fprintf(ficresvij,"******\n");
                   6175: 
                   6176:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   6177:        oldm=oldms;savm=savms;
1.127     brouard  6178:        cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
1.126     brouard  6179:  
                   6180:        vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   6181:        pstamp(ficrest);
1.128     brouard  6182:        for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   6183:          oldm=oldms;savm=savms;
                   6184:          varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart);   fprintf(ficrest,"# Total life expectancy with std error and decomposition into time to be expected in each health state\n#  (weighted average of eij where weights are ");
                   6185:          if(vpopbased==1)
                   6186:            fprintf(ficrest,"the age specific prevalence observed (cross-sectionally) in the population i.e cross-sectionally\n in each health state (popbased=1) (mobilav=%d)\n",mobilav);
                   6187:          else
                   6188:            fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   6189:          fprintf(ficrest,"# Age e.. (std) ");
                   6190:          for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   6191:          fprintf(ficrest,"\n");
1.126     brouard  6192: 
1.128     brouard  6193:          epj=vector(1,nlstate+1);
                   6194:          for(age=bage; age <=fage ;age++){
                   6195:            prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   6196:            if (vpopbased==1) {
                   6197:              if(mobilav ==0){
                   6198:                for(i=1; i<=nlstate;i++)
                   6199:                  prlim[i][i]=probs[(int)age][i][k];
                   6200:              }else{ /* mobilav */ 
                   6201:                for(i=1; i<=nlstate;i++)
                   6202:                  prlim[i][i]=mobaverage[(int)age][i][k];
                   6203:              }
1.126     brouard  6204:            }
                   6205:        
1.128     brouard  6206:            fprintf(ficrest," %4.0f",age);
                   6207:            for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   6208:              for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   6209:                epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   6210:                /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   6211:              }
                   6212:              epj[nlstate+1] +=epj[j];
1.126     brouard  6213:            }
                   6214: 
1.128     brouard  6215:            for(i=1, vepp=0.;i <=nlstate;i++)
                   6216:              for(j=1;j <=nlstate;j++)
                   6217:                vepp += vareij[i][j][(int)age];
                   6218:            fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   6219:            for(j=1;j <=nlstate;j++){
                   6220:              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   6221:            }
                   6222:            fprintf(ficrest,"\n");
1.126     brouard  6223:          }
                   6224:        }
                   6225:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   6226:        free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   6227:        free_vector(epj,1,nlstate+1);
                   6228:       }
                   6229:     }
                   6230:     free_vector(weight,1,n);
                   6231:     free_imatrix(Tvard,1,15,1,2);
                   6232:     free_imatrix(s,1,maxwav+1,1,n);
                   6233:     free_matrix(anint,1,maxwav,1,n); 
                   6234:     free_matrix(mint,1,maxwav,1,n);
                   6235:     free_ivector(cod,1,n);
                   6236:     free_ivector(tab,1,NCOVMAX);
                   6237:     fclose(ficresstdeij);
                   6238:     fclose(ficrescveij);
                   6239:     fclose(ficresvij);
                   6240:     fclose(ficrest);
                   6241:     fclose(ficpar);
                   6242:   
                   6243:     /*------- Variance of period (stable) prevalence------*/   
                   6244: 
                   6245:     strcpy(fileresvpl,"vpl");
                   6246:     strcat(fileresvpl,fileres);
                   6247:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   6248:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   6249:       exit(0);
                   6250:     }
                   6251:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
                   6252: 
                   6253:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6254:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6255:        k=k+1;
                   6256:        fprintf(ficresvpl,"\n#****** ");
                   6257:        for(j=1;j<=cptcoveff;j++) 
                   6258:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6259:        fprintf(ficresvpl,"******\n");
                   6260:       
                   6261:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   6262:        oldm=oldms;savm=savms;
                   6263:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
                   6264:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   6265:       }
                   6266:     }
                   6267: 
                   6268:     fclose(ficresvpl);
                   6269: 
                   6270:     /*---------- End : free ----------------*/
                   6271:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6272:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6273: 
                   6274:   }  /* mle==-3 arrives here for freeing */
1.131     brouard  6275:  endfree:
1.126     brouard  6276:   free_matrix(prlim,1,nlstate,1,nlstate);
                   6277:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   6278:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   6279:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   6280:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   6281:     free_matrix(covar,0,NCOVMAX,1,n);
                   6282:     free_matrix(matcov,1,npar,1,npar);
                   6283:     /*free_vector(delti,1,npar);*/
                   6284:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   6285:     free_matrix(agev,1,maxwav,1,imx);
                   6286:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   6287: 
                   6288:     free_ivector(ncodemax,1,8);
                   6289:     free_ivector(Tvar,1,15);
                   6290:     free_ivector(Tprod,1,15);
                   6291:     free_ivector(Tvaraff,1,15);
                   6292:     free_ivector(Tage,1,15);
                   6293: 
                   6294:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   6295:     free_imatrix(codtab,1,100,1,10);
                   6296:   fflush(fichtm);
                   6297:   fflush(ficgp);
                   6298:   
                   6299: 
                   6300:   if((nberr >0) || (nbwarn>0)){
                   6301:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   6302:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   6303:   }else{
                   6304:     printf("End of Imach\n");
                   6305:     fprintf(ficlog,"End of Imach\n");
                   6306:   }
                   6307:   printf("See log file on %s\n",filelog);
                   6308:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
                   6309:   (void) gettimeofday(&end_time,&tzp);
                   6310:   tm = *localtime(&end_time.tv_sec);
                   6311:   tmg = *gmtime(&end_time.tv_sec);
                   6312:   strcpy(strtend,asctime(&tm));
                   6313:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   6314:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
                   6315:   printf("Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
                   6316: 
                   6317:   printf("Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);
                   6318:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
                   6319:   fprintf(ficlog,"Total time was %d Sec.\n", end_time.tv_sec -start_time.tv_sec);
                   6320:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   6321: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   6322:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   6323:   fclose(fichtm);
                   6324:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   6325:   fclose(fichtmcov);
                   6326:   fclose(ficgp);
                   6327:   fclose(ficlog);
                   6328:   /*------ End -----------*/
                   6329: 
                   6330: 
                   6331:    printf("Before Current directory %s!\n",pathcd);
                   6332:    if(chdir(pathcd) != 0)
                   6333:     printf("Can't move to directory %s!\n",path);
                   6334:   if(getcwd(pathcd,MAXLINE) > 0)
                   6335:     printf("Current directory %s!\n",pathcd);
                   6336:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   6337:   sprintf(plotcmd,"gnuplot");
                   6338: #ifndef UNIX
                   6339:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   6340: #endif
                   6341:   if(!stat(plotcmd,&info)){
                   6342:     printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
                   6343:     if(!stat(getenv("GNUPLOTBIN"),&info)){
                   6344:       printf("Error gnuplot program not found: %s Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
                   6345:     }else
                   6346:       strcpy(pplotcmd,plotcmd);
                   6347: #ifdef UNIX
                   6348:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   6349:     if(!stat(plotcmd,&info)){
                   6350:       printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
                   6351:     }else
                   6352:       strcpy(pplotcmd,plotcmd);
                   6353: #endif
                   6354:   }else
                   6355:     strcpy(pplotcmd,plotcmd);
                   6356:   
                   6357:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
                   6358:   printf("Starting graphs with: %s\n",plotcmd);fflush(stdout);
                   6359: 
                   6360:   if((outcmd=system(plotcmd)) != 0){
                   6361:     printf("\n Problem with gnuplot\n");
                   6362:   }
                   6363:   printf(" Wait...");
                   6364:   while (z[0] != 'q') {
                   6365:     /* chdir(path); */
                   6366:     printf("\nType e to edit output files, g to graph again and q for exiting: ");
                   6367:     scanf("%s",z);
                   6368: /*     if (z[0] == 'c') system("./imach"); */
                   6369:     if (z[0] == 'e') {
                   6370:       printf("Starting browser with: %s",optionfilehtm);fflush(stdout);
                   6371:       system(optionfilehtm);
                   6372:     }
                   6373:     else if (z[0] == 'g') system(plotcmd);
                   6374:     else if (z[0] == 'q') exit(0);
                   6375:   }
                   6376:   end:
                   6377:   while (z[0] != 'q') {
                   6378:     printf("\nType  q for exiting: ");
                   6379:     scanf("%s",z);
                   6380:   }
                   6381: }
                   6382: 
                   6383: 
                   6384: 

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