File:  [Local Repository] / imach / src / imach.c
Revision 1.135: download - view: text, annotated - select for diffs
Thu Oct 29 15:33:14 2009 UTC (14 years, 7 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
(Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.

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

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