File:  [Local Repository] / imach / src / imach.c
Revision 1.129: download - view: text, annotated - select for diffs
Fri Aug 31 13:49:27 2007 UTC (16 years, 8 months ago) by lievre
Branches: MAIN
CVS tags: HEAD
Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting

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

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