File:  [Local Repository] / imach / src / imach.c
Revision 1.122: download - view: text, annotated - select for diffs
Mon Mar 20 09:45:41 2006 UTC (18 years, 2 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
(Module): Weights can have a decimal point as for
English (a comma might work with a correct LC_NUMERIC environment,
otherwise the weight is truncated).
Modification of warning when the covariates values are not 0 or
1.
Version 0.98g

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

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