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

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

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