File:  [Local Repository] / imach / src / imach.c
Revision 1.144: download - view: text, annotated - select for diffs
Mon Feb 10 22:17:31 2014 UTC (10 years, 3 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
*** empty log message ***

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

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