File:  [Local Repository] / imach / src / imach.c
Revision 1.136: download - view: text, annotated - select for diffs
Mon Apr 26 20:30:53 2010 UTC (14 years, 1 month ago) by brouard
Branches: MAIN
CVS tags: HEAD
(Module): merging some libgsl code. Fixing computation
of likelione (using inter/intrapolation if mle = 0) in order to
get same likelihood as if mle=1.
Some cleaning of code and comments added.

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

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