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

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

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