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

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

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