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

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

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