File:  [Local Repository] / imach / src / imach.c
Revision 1.164: download - view: text, annotated - select for diffs
Tue Dec 16 10:52:11 2014 UTC (9 years, 6 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn

* imach.c (Module): Merging 1.61 to 1.162

    1: /* $Id: imach.c,v 1.164 2014/12/16 10:52:11 brouard Exp $
    2:   $State: Exp $
    3:   $Log: imach.c,v $
    4:   Revision 1.164  2014/12/16 10:52:11  brouard
    5:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
    6: 
    7:   * imach.c (Module): Merging 1.61 to 1.162
    8: 
    9:   Revision 1.163  2014/12/16 10:30:11  brouard
   10:   * imach.c (Module): Merging 1.61 to 1.162
   11: 
   12:   Revision 1.162  2014/09/25 11:43:39  brouard
   13:   Summary: temporary backup 0.99!
   14: 
   15:   Revision 1.1  2014/09/16 11:06:58  brouard
   16:   Summary: With some code (wrong) for nlopt
   17: 
   18:   Author:
   19: 
   20:   Revision 1.161  2014/09/15 20:41:41  brouard
   21:   Summary: Problem with macro SQR on Intel compiler
   22: 
   23:   Revision 1.160  2014/09/02 09:24:05  brouard
   24:   *** empty log message ***
   25: 
   26:   Revision 1.159  2014/09/01 10:34:10  brouard
   27:   Summary: WIN32
   28:   Author: Brouard
   29: 
   30:   Revision 1.158  2014/08/27 17:11:51  brouard
   31:   *** empty log message ***
   32: 
   33:   Revision 1.157  2014/08/27 16:26:55  brouard
   34:   Summary: Preparing windows Visual studio version
   35:   Author: Brouard
   36: 
   37:   In order to compile on Visual studio, time.h is now correct and time_t
   38:   and tm struct should be used. difftime should be used but sometimes I
   39:   just make the differences in raw time format (time(&now).
   40:   Trying to suppress #ifdef LINUX
   41:   Add xdg-open for __linux in order to open default browser.
   42: 
   43:   Revision 1.156  2014/08/25 20:10:10  brouard
   44:   *** empty log message ***
   45: 
   46:   Revision 1.155  2014/08/25 18:32:34  brouard
   47:   Summary: New compile, minor changes
   48:   Author: Brouard
   49: 
   50:   Revision 1.154  2014/06/20 17:32:08  brouard
   51:   Summary: Outputs now all graphs of convergence to period prevalence
   52: 
   53:   Revision 1.153  2014/06/20 16:45:46  brouard
   54:   Summary: If 3 live state, convergence to period prevalence on same graph
   55:   Author: Brouard
   56: 
   57:   Revision 1.152  2014/06/18 17:54:09  brouard
   58:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
   59: 
   60:   Revision 1.151  2014/06/18 16:43:30  brouard
   61:   *** empty log message ***
   62: 
   63:   Revision 1.150  2014/06/18 16:42:35  brouard
   64:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
   65:   Author: brouard
   66: 
   67:   Revision 1.149  2014/06/18 15:51:14  brouard
   68:   Summary: Some fixes in parameter files errors
   69:   Author: Nicolas Brouard
   70: 
   71:   Revision 1.148  2014/06/17 17:38:48  brouard
   72:   Summary: Nothing new
   73:   Author: Brouard
   74: 
   75:   Just a new packaging for OS/X version 0.98nS
   76: 
   77:   Revision 1.147  2014/06/16 10:33:11  brouard
   78:   *** empty log message ***
   79: 
   80:   Revision 1.146  2014/06/16 10:20:28  brouard
   81:   Summary: Merge
   82:   Author: Brouard
   83: 
   84:   Merge, before building revised version.
   85: 
   86:   Revision 1.145  2014/06/10 21:23:15  brouard
   87:   Summary: Debugging with valgrind
   88:   Author: Nicolas Brouard
   89: 
   90:   Lot of changes in order to output the results with some covariates
   91:   After the Edimburgh REVES conference 2014, it seems mandatory to
   92:   improve the code.
   93:   No more memory valgrind error but a lot has to be done in order to
   94:   continue the work of splitting the code into subroutines.
   95:   Also, decodemodel has been improved. Tricode is still not
   96:   optimal. nbcode should be improved. Documentation has been added in
   97:   the source code.
   98: 
   99:   Revision 1.143  2014/01/26 09:45:38  brouard
  100:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
  101: 
  102:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  103:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
  104: 
  105:   Revision 1.142  2014/01/26 03:57:36  brouard
  106:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
  107: 
  108:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  109: 
  110:   Revision 1.141  2014/01/26 02:42:01  brouard
  111:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  112: 
  113:   Revision 1.140  2011/09/02 10:37:54  brouard
  114:   Summary: times.h is ok with mingw32 now.
  115: 
  116:   Revision 1.139  2010/06/14 07:50:17  brouard
  117:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
  118:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
  119: 
  120:   Revision 1.138  2010/04/30 18:19:40  brouard
  121:   *** empty log message ***
  122: 
  123:   Revision 1.137  2010/04/29 18:11:38  brouard
  124:   (Module): Checking covariates for more complex models
  125:   than V1+V2. A lot of change to be done. Unstable.
  126: 
  127:   Revision 1.136  2010/04/26 20:30:53  brouard
  128:   (Module): merging some libgsl code. Fixing computation
  129:   of likelione (using inter/intrapolation if mle = 0) in order to
  130:   get same likelihood as if mle=1.
  131:   Some cleaning of code and comments added.
  132: 
  133:   Revision 1.135  2009/10/29 15:33:14  brouard
  134:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  135: 
  136:   Revision 1.134  2009/10/29 13:18:53  brouard
  137:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  138: 
  139:   Revision 1.133  2009/07/06 10:21:25  brouard
  140:   just nforces
  141: 
  142:   Revision 1.132  2009/07/06 08:22:05  brouard
  143:   Many tings
  144: 
  145:   Revision 1.131  2009/06/20 16:22:47  brouard
  146:   Some dimensions resccaled
  147: 
  148:   Revision 1.130  2009/05/26 06:44:34  brouard
  149:   (Module): Max Covariate is now set to 20 instead of 8. A
  150:   lot of cleaning with variables initialized to 0. Trying to make
  151:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
  152: 
  153:   Revision 1.129  2007/08/31 13:49:27  lievre
  154:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
  155: 
  156:   Revision 1.128  2006/06/30 13:02:05  brouard
  157:   (Module): Clarifications on computing e.j
  158: 
  159:   Revision 1.127  2006/04/28 18:11:50  brouard
  160:   (Module): Yes the sum of survivors was wrong since
  161:   imach-114 because nhstepm was no more computed in the age
  162:   loop. Now we define nhstepma in the age loop.
  163:   (Module): In order to speed up (in case of numerous covariates) we
  164:   compute health expectancies (without variances) in a first step
  165:   and then all the health expectancies with variances or standard
  166:   deviation (needs data from the Hessian matrices) which slows the
  167:   computation.
  168:   In the future we should be able to stop the program is only health
  169:   expectancies and graph are needed without standard deviations.
  170: 
  171:   Revision 1.126  2006/04/28 17:23:28  brouard
  172:   (Module): Yes the sum of survivors was wrong since
  173:   imach-114 because nhstepm was no more computed in the age
  174:   loop. Now we define nhstepma in the age loop.
  175:   Version 0.98h
  176: 
  177:   Revision 1.125  2006/04/04 15:20:31  lievre
  178:   Errors in calculation of health expectancies. Age was not initialized.
  179:   Forecasting file added.
  180: 
  181:   Revision 1.124  2006/03/22 17:13:53  lievre
  182:   Parameters are printed with %lf instead of %f (more numbers after the comma).
  183:   The log-likelihood is printed in the log file
  184: 
  185:   Revision 1.123  2006/03/20 10:52:43  brouard
  186:   * imach.c (Module): <title> changed, corresponds to .htm file
  187:   name. <head> headers where missing.
  188: 
  189:   * imach.c (Module): Weights can have a decimal point as for
  190:   English (a comma might work with a correct LC_NUMERIC environment,
  191:   otherwise the weight is truncated).
  192:   Modification of warning when the covariates values are not 0 or
  193:   1.
  194:   Version 0.98g
  195: 
  196:   Revision 1.122  2006/03/20 09:45:41  brouard
  197:   (Module): Weights can have a decimal point as for
  198:   English (a comma might work with a correct LC_NUMERIC environment,
  199:   otherwise the weight is truncated).
  200:   Modification of warning when the covariates values are not 0 or
  201:   1.
  202:   Version 0.98g
  203: 
  204:   Revision 1.121  2006/03/16 17:45:01  lievre
  205:   * imach.c (Module): Comments concerning covariates added
  206: 
  207:   * imach.c (Module): refinements in the computation of lli if
  208:   status=-2 in order to have more reliable computation if stepm is
  209:   not 1 month. Version 0.98f
  210: 
  211:   Revision 1.120  2006/03/16 15:10:38  lievre
  212:   (Module): refinements in the computation of lli if
  213:   status=-2 in order to have more reliable computation if stepm is
  214:   not 1 month. Version 0.98f
  215: 
  216:   Revision 1.119  2006/03/15 17:42:26  brouard
  217:   (Module): Bug if status = -2, the loglikelihood was
  218:   computed as likelihood omitting the logarithm. Version O.98e
  219: 
  220:   Revision 1.118  2006/03/14 18:20:07  brouard
  221:   (Module): varevsij Comments added explaining the second
  222:   table of variances if popbased=1 .
  223:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  224:   (Module): Function pstamp added
  225:   (Module): Version 0.98d
  226: 
  227:   Revision 1.117  2006/03/14 17:16:22  brouard
  228:   (Module): varevsij Comments added explaining the second
  229:   table of variances if popbased=1 .
  230:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  231:   (Module): Function pstamp added
  232:   (Module): Version 0.98d
  233: 
  234:   Revision 1.116  2006/03/06 10:29:27  brouard
  235:   (Module): Variance-covariance wrong links and
  236:   varian-covariance of ej. is needed (Saito).
  237: 
  238:   Revision 1.115  2006/02/27 12:17:45  brouard
  239:   (Module): One freematrix added in mlikeli! 0.98c
  240: 
  241:   Revision 1.114  2006/02/26 12:57:58  brouard
  242:   (Module): Some improvements in processing parameter
  243:   filename with strsep.
  244: 
  245:   Revision 1.113  2006/02/24 14:20:24  brouard
  246:   (Module): Memory leaks checks with valgrind and:
  247:   datafile was not closed, some imatrix were not freed and on matrix
  248:   allocation too.
  249: 
  250:   Revision 1.112  2006/01/30 09:55:26  brouard
  251:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
  252: 
  253:   Revision 1.111  2006/01/25 20:38:18  brouard
  254:   (Module): Lots of cleaning and bugs added (Gompertz)
  255:   (Module): Comments can be added in data file. Missing date values
  256:   can be a simple dot '.'.
  257: 
  258:   Revision 1.110  2006/01/25 00:51:50  brouard
  259:   (Module): Lots of cleaning and bugs added (Gompertz)
  260: 
  261:   Revision 1.109  2006/01/24 19:37:15  brouard
  262:   (Module): Comments (lines starting with a #) are allowed in data.
  263: 
  264:   Revision 1.108  2006/01/19 18:05:42  lievre
  265:   Gnuplot problem appeared...
  266:   To be fixed
  267: 
  268:   Revision 1.107  2006/01/19 16:20:37  brouard
  269:   Test existence of gnuplot in imach path
  270: 
  271:   Revision 1.106  2006/01/19 13:24:36  brouard
  272:   Some cleaning and links added in html output
  273: 
  274:   Revision 1.105  2006/01/05 20:23:19  lievre
  275:   *** empty log message ***
  276: 
  277:   Revision 1.104  2005/09/30 16:11:43  lievre
  278:   (Module): sump fixed, loop imx fixed, and simplifications.
  279:   (Module): If the status is missing at the last wave but we know
  280:   that the person is alive, then we can code his/her status as -2
  281:   (instead of missing=-1 in earlier versions) and his/her
  282:   contributions to the likelihood is 1 - Prob of dying from last
  283:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
  284:   the healthy state at last known wave). Version is 0.98
  285: 
  286:   Revision 1.103  2005/09/30 15:54:49  lievre
  287:   (Module): sump fixed, loop imx fixed, and simplifications.
  288: 
  289:   Revision 1.102  2004/09/15 17:31:30  brouard
  290:   Add the possibility to read data file including tab characters.
  291: 
  292:   Revision 1.101  2004/09/15 10:38:38  brouard
  293:   Fix on curr_time
  294: 
  295:   Revision 1.100  2004/07/12 18:29:06  brouard
  296:   Add version for Mac OS X. Just define UNIX in Makefile
  297: 
  298:   Revision 1.99  2004/06/05 08:57:40  brouard
  299:   *** empty log message ***
  300: 
  301:   Revision 1.98  2004/05/16 15:05:56  brouard
  302:   New version 0.97 . First attempt to estimate force of mortality
  303:   directly from the data i.e. without the need of knowing the health
  304:   state at each age, but using a Gompertz model: log u =a + b*age .
  305:   This is the basic analysis of mortality and should be done before any
  306:   other analysis, in order to test if the mortality estimated from the
  307:   cross-longitudinal survey is different from the mortality estimated
  308:   from other sources like vital statistic data.
  309: 
  310:   The same imach parameter file can be used but the option for mle should be -3.
  311: 
  312:   Agnès, who wrote this part of the code, tried to keep most of the
  313:   former routines in order to include the new code within the former code.
  314: 
  315:   The output is very simple: only an estimate of the intercept and of
  316:   the slope with 95% confident intervals.
  317: 
  318:   Current limitations:
  319:   A) Even if you enter covariates, i.e. with the
  320:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
  321:   B) There is no computation of Life Expectancy nor Life Table.
  322: 
  323:   Revision 1.97  2004/02/20 13:25:42  lievre
  324:   Version 0.96d. Population forecasting command line is (temporarily)
  325:   suppressed.
  326: 
  327:   Revision 1.96  2003/07/15 15:38:55  brouard
  328:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
  329:   rewritten within the same printf. Workaround: many printfs.
  330: 
  331:   Revision 1.95  2003/07/08 07:54:34  brouard
  332:   * imach.c (Repository):
  333:   (Repository): Using imachwizard code to output a more meaningful covariance
  334:   matrix (cov(a12,c31) instead of numbers.
  335: 
  336:   Revision 1.94  2003/06/27 13:00:02  brouard
  337:   Just cleaning
  338: 
  339:   Revision 1.93  2003/06/25 16:33:55  brouard
  340:   (Module): On windows (cygwin) function asctime_r doesn't
  341:   exist so I changed back to asctime which exists.
  342:   (Module): Version 0.96b
  343: 
  344:   Revision 1.92  2003/06/25 16:30:45  brouard
  345:   (Module): On windows (cygwin) function asctime_r doesn't
  346:   exist so I changed back to asctime which exists.
  347: 
  348:   Revision 1.91  2003/06/25 15:30:29  brouard
  349:   * imach.c (Repository): Duplicated warning errors corrected.
  350:   (Repository): Elapsed time after each iteration is now output. It
  351:   helps to forecast when convergence will be reached. Elapsed time
  352:   is stamped in powell.  We created a new html file for the graphs
  353:   concerning matrix of covariance. It has extension -cov.htm.
  354: 
  355:   Revision 1.90  2003/06/24 12:34:15  brouard
  356:   (Module): Some bugs corrected for windows. Also, when
  357:   mle=-1 a template is output in file "or"mypar.txt with the design
  358:   of the covariance matrix to be input.
  359: 
  360:   Revision 1.89  2003/06/24 12:30:52  brouard
  361:   (Module): Some bugs corrected for windows. Also, when
  362:   mle=-1 a template is output in file "or"mypar.txt with the design
  363:   of the covariance matrix to be input.
  364: 
  365:   Revision 1.88  2003/06/23 17:54:56  brouard
  366:   * 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.
  367: 
  368:   Revision 1.87  2003/06/18 12:26:01  brouard
  369:   Version 0.96
  370: 
  371:   Revision 1.86  2003/06/17 20:04:08  brouard
  372:   (Module): Change position of html and gnuplot routines and added
  373:   routine fileappend.
  374: 
  375:   Revision 1.85  2003/06/17 13:12:43  brouard
  376:   * imach.c (Repository): Check when date of death was earlier that
  377:   current date of interview. It may happen when the death was just
  378:   prior to the death. In this case, dh was negative and likelihood
  379:   was wrong (infinity). We still send an "Error" but patch by
  380:   assuming that the date of death was just one stepm after the
  381:   interview.
  382:   (Repository): Because some people have very long ID (first column)
  383:   we changed int to long in num[] and we added a new lvector for
  384:   memory allocation. But we also truncated to 8 characters (left
  385:   truncation)
  386:   (Repository): No more line truncation errors.
  387: 
  388:   Revision 1.84  2003/06/13 21:44:43  brouard
  389:   * imach.c (Repository): Replace "freqsummary" at a correct
  390:   place. It differs from routine "prevalence" which may be called
  391:   many times. Probs is memory consuming and must be used with
  392:   parcimony.
  393:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
  394: 
  395:   Revision 1.83  2003/06/10 13:39:11  lievre
  396:   *** empty log message ***
  397: 
  398:   Revision 1.82  2003/06/05 15:57:20  brouard
  399:   Add log in  imach.c and  fullversion number is now printed.
  400: 
  401: */
  402: /*
  403:    Interpolated Markov Chain
  404: 
  405:   Short summary of the programme:
  406:   
  407:   This program computes Healthy Life Expectancies from
  408:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
  409:   first survey ("cross") where individuals from different ages are
  410:   interviewed on their health status or degree of disability (in the
  411:   case of a health survey which is our main interest) -2- at least a
  412:   second wave of interviews ("longitudinal") which measure each change
  413:   (if any) in individual health status.  Health expectancies are
  414:   computed from the time spent in each health state according to a
  415:   model. More health states you consider, more time is necessary to reach the
  416:   Maximum Likelihood of the parameters involved in the model.  The
  417:   simplest model is the multinomial logistic model where pij is the
  418:   probability to be observed in state j at the second wave
  419:   conditional to be observed in state i at the first wave. Therefore
  420:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
  421:   'age' is age and 'sex' is a covariate. If you want to have a more
  422:   complex model than "constant and age", you should modify the program
  423:   where the markup *Covariates have to be included here again* invites
  424:   you to do it.  More covariates you add, slower the
  425:   convergence.
  426: 
  427:   The advantage of this computer programme, compared to a simple
  428:   multinomial logistic model, is clear when the delay between waves is not
  429:   identical for each individual. Also, if a individual missed an
  430:   intermediate interview, the information is lost, but taken into
  431:   account using an interpolation or extrapolation.  
  432: 
  433:   hPijx is the probability to be observed in state i at age x+h
  434:   conditional to the observed state i at age x. The delay 'h' can be
  435:   split into an exact number (nh*stepm) of unobserved intermediate
  436:   states. This elementary transition (by month, quarter,
  437:   semester or year) is modelled as a multinomial logistic.  The hPx
  438:   matrix is simply the matrix product of nh*stepm elementary matrices
  439:   and the contribution of each individual to the likelihood is simply
  440:   hPijx.
  441: 
  442:   Also this programme outputs the covariance matrix of the parameters but also
  443:   of the life expectancies. It also computes the period (stable) prevalence. 
  444:   
  445:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
  446:            Institut national d'études démographiques, Paris.
  447:   This software have been partly granted by Euro-REVES, a concerted action
  448:   from the European Union.
  449:   It is copyrighted identically to a GNU software product, ie programme and
  450:   software can be distributed freely for non commercial use. Latest version
  451:   can be accessed at http://euroreves.ined.fr/imach .
  452: 
  453:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
  454:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
  455:   
  456:   **********************************************************************/
  457: /*
  458:   main
  459:   read parameterfile
  460:   read datafile
  461:   concatwav
  462:   freqsummary
  463:   if (mle >= 1)
  464:     mlikeli
  465:   print results files
  466:   if mle==1 
  467:      computes hessian
  468:   read end of parameter file: agemin, agemax, bage, fage, estepm
  469:       begin-prev-date,...
  470:   open gnuplot file
  471:   open html file
  472:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
  473:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
  474:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
  475:     freexexit2 possible for memory heap.
  476: 
  477:   h Pij x                         | pij_nom  ficrestpij
  478:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
  479:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
  480:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
  481: 
  482:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
  483:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
  484:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
  485:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
  486:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
  487: 
  488:   forecasting if prevfcast==1 prevforecast call prevalence()
  489:   health expectancies
  490:   Variance-covariance of DFLE
  491:   prevalence()
  492:    movingaverage()
  493:   varevsij() 
  494:   if popbased==1 varevsij(,popbased)
  495:   total life expectancies
  496:   Variance of period (stable) prevalence
  497:  end
  498: */
  499: 
  500: 
  501: 
  502:  
  503: #include <math.h>
  504: #include <stdio.h>
  505: #include <stdlib.h>
  506: #include <string.h>
  507: 
  508: #ifdef _WIN32
  509: #include <io.h>
  510: #else
  511: #include <unistd.h>
  512: #endif
  513: 
  514: #include <limits.h>
  515: #include <sys/types.h>
  516: #include <sys/stat.h>
  517: #include <errno.h>
  518: /* extern int errno; */
  519: 
  520: /* #ifdef LINUX */
  521: /* #include <time.h> */
  522: /* #include "timeval.h" */
  523: /* #else */
  524: /* #include <sys/time.h> */
  525: /* #endif */
  526: 
  527: #include <time.h>
  528: 
  529: #ifdef GSL
  530: #include <gsl/gsl_errno.h>
  531: #include <gsl/gsl_multimin.h>
  532: #endif
  533: 
  534: #ifdef NLOPT
  535: #include <nlopt.h>
  536: typedef struct {
  537:   double (* function)(double [] );
  538: } myfunc_data ;
  539: #endif
  540: 
  541: /* #include <libintl.h> */
  542: /* #define _(String) gettext (String) */
  543: 
  544: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
  545: 
  546: #define GNUPLOTPROGRAM "gnuplot"
  547: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
  548: #define FILENAMELENGTH 132
  549: 
  550: #define	GLOCK_ERROR_NOPATH		-1	/* empty path */
  551: #define	GLOCK_ERROR_GETCWD		-2	/* cannot get cwd */
  552: 
  553: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
  554: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
  555: 
  556: #define NINTERVMAX 8
  557: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
  558: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
  559: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
  560: #define codtabm(h,k)  1 & (h-1) >> (k-1) ;
  561: #define MAXN 20000
  562: #define YEARM 12. /**< Number of months per year */
  563: #define AGESUP 130
  564: #define AGEBASE 40
  565: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
  566: #ifdef _WIN32
  567: #define DIRSEPARATOR '\\'
  568: #define CHARSEPARATOR "\\"
  569: #define ODIRSEPARATOR '/'
  570: #else
  571: #define DIRSEPARATOR '/'
  572: #define CHARSEPARATOR "/"
  573: #define ODIRSEPARATOR '\\'
  574: #endif
  575: 
  576: /* $Id: imach.c,v 1.164 2014/12/16 10:52:11 brouard Exp $ */
  577: /* $State: Exp $ */
  578: 
  579: char version[]="Imach version 0.99, September 2014,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121)";
  580: char fullversion[]="$Revision: 1.164 $ $Date: 2014/12/16 10:52:11 $"; 
  581: char strstart[80];
  582: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
  583: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
  584: int nvar=0, nforce=0; /* Number of variables, number of forces */
  585: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
  586: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
  587: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
  588: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
  589: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
  590: int cptcovprodnoage=0; /**< Number of covariate products without age */   
  591: int cptcoveff=0; /* Total number of covariates to vary for printing results */
  592: int cptcov=0; /* Working variable */
  593: int npar=NPARMAX;
  594: int nlstate=2; /* Number of live states */
  595: int ndeath=1; /* Number of dead states */
  596: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
  597: int popbased=0;
  598: 
  599: int *wav; /* Number of waves for this individuual 0 is possible */
  600: int maxwav=0; /* Maxim number of waves */
  601: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
  602: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
  603: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
  604: 		   to the likelihood and the sum of weights (done by funcone)*/
  605: int mle=1, weightopt=0;
  606: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
  607: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
  608: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
  609: 	   * wave mi and wave mi+1 is not an exact multiple of stepm. */
  610: int countcallfunc=0;  /* Count the number of calls to func */
  611: double jmean=1; /* Mean space between 2 waves */
  612: double **matprod2(); /* test */
  613: double **oldm, **newm, **savm; /* Working pointers to matrices */
  614: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
  615: /*FILE *fic ; */ /* Used in readdata only */
  616: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
  617: FILE *ficlog, *ficrespow;
  618: int globpr=0; /* Global variable for printing or not */
  619: double fretone; /* Only one call to likelihood */
  620: long ipmx=0; /* Number of contributions */
  621: double sw; /* Sum of weights */
  622: char filerespow[FILENAMELENGTH];
  623: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
  624: FILE *ficresilk;
  625: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
  626: FILE *ficresprobmorprev;
  627: FILE *fichtm, *fichtmcov; /* Html File */
  628: FILE *ficreseij;
  629: char filerese[FILENAMELENGTH];
  630: FILE *ficresstdeij;
  631: char fileresstde[FILENAMELENGTH];
  632: FILE *ficrescveij;
  633: char filerescve[FILENAMELENGTH];
  634: FILE  *ficresvij;
  635: char fileresv[FILENAMELENGTH];
  636: FILE  *ficresvpl;
  637: char fileresvpl[FILENAMELENGTH];
  638: char title[MAXLINE];
  639: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
  640: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
  641: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
  642: char command[FILENAMELENGTH];
  643: int  outcmd=0;
  644: 
  645: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
  646: 
  647: char filelog[FILENAMELENGTH]; /* Log file */
  648: char filerest[FILENAMELENGTH];
  649: char fileregp[FILENAMELENGTH];
  650: char popfile[FILENAMELENGTH];
  651: 
  652: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
  653: 
  654: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
  655: /* struct timezone tzp; */
  656: /* extern int gettimeofday(); */
  657: struct tm tml, *gmtime(), *localtime();
  658: 
  659: extern time_t time();
  660: 
  661: struct tm start_time, end_time, curr_time, last_time, forecast_time;
  662: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
  663: struct tm tm;
  664: 
  665: char strcurr[80], strfor[80];
  666: 
  667: char *endptr;
  668: long lval;
  669: double dval;
  670: 
  671: #define NR_END 1
  672: #define FREE_ARG char*
  673: #define FTOL 1.0e-10
  674: 
  675: #define NRANSI 
  676: #define ITMAX 200 
  677: 
  678: #define TOL 2.0e-4 
  679: 
  680: #define CGOLD 0.3819660 
  681: #define ZEPS 1.0e-10 
  682: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
  683: 
  684: #define GOLD 1.618034 
  685: #define GLIMIT 100.0 
  686: #define TINY 1.0e-20 
  687: 
  688: static double maxarg1,maxarg2;
  689: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
  690: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
  691:   
  692: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
  693: #define rint(a) floor(a+0.5)
  694: 
  695: static double sqrarg;
  696: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
  697: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
  698: int agegomp= AGEGOMP;
  699: 
  700: int imx; 
  701: int stepm=1;
  702: /* Stepm, step in month: minimum step interpolation*/
  703: 
  704: int estepm;
  705: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
  706: 
  707: int m,nb;
  708: long *num;
  709: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
  710: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
  711: double **pmmij, ***probs;
  712: double *ageexmed,*agecens;
  713: double dateintmean=0;
  714: 
  715: double *weight;
  716: int **s; /* Status */
  717: double *agedc;
  718: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
  719: 		  * covar=matrix(0,NCOVMAX,1,n); 
  720: 		  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
  721: double  idx; 
  722: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
  723: int *Ndum; /** Freq of modality (tricode */
  724: int **codtab; /**< codtab=imatrix(1,100,1,10); */
  725: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
  726: double *lsurv, *lpop, *tpop;
  727: 
  728: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
  729: double ftolhess; /**< Tolerance for computing hessian */
  730: 
  731: /**************** split *************************/
  732: static	int split( char *path, char *dirc, char *name, char *ext, char *finame )
  733: {
  734:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
  735:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
  736:   */ 
  737:   char	*ss;				/* pointer */
  738:   int	l1, l2;				/* length counters */
  739: 
  740:   l1 = strlen(path );			/* length of path */
  741:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
  742:   ss= strrchr( path, DIRSEPARATOR );		/* find last / */
  743:   if ( ss == NULL ) {			/* no directory, so determine current directory */
  744:     strcpy( name, path );		/* we got the fullname name because no directory */
  745:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
  746:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
  747:     /* get current working directory */
  748:     /*    extern  char* getcwd ( char *buf , int len);*/
  749:     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
  750:       return( GLOCK_ERROR_GETCWD );
  751:     }
  752:     /* got dirc from getcwd*/
  753:     printf(" DIRC = %s \n",dirc);
  754:   } else {				/* strip direcotry from path */
  755:     ss++;				/* after this, the filename */
  756:     l2 = strlen( ss );			/* length of filename */
  757:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
  758:     strcpy( name, ss );		/* save file name */
  759:     strncpy( dirc, path, l1 - l2 );	/* now the directory */
  760:     dirc[l1-l2] = 0;			/* add zero */
  761:     printf(" DIRC2 = %s \n",dirc);
  762:   }
  763:   /* We add a separator at the end of dirc if not exists */
  764:   l1 = strlen( dirc );			/* length of directory */
  765:   if( dirc[l1-1] != DIRSEPARATOR ){
  766:     dirc[l1] =  DIRSEPARATOR;
  767:     dirc[l1+1] = 0; 
  768:     printf(" DIRC3 = %s \n",dirc);
  769:   }
  770:   ss = strrchr( name, '.' );		/* find last / */
  771:   if (ss >0){
  772:     ss++;
  773:     strcpy(ext,ss);			/* save extension */
  774:     l1= strlen( name);
  775:     l2= strlen(ss)+1;
  776:     strncpy( finame, name, l1-l2);
  777:     finame[l1-l2]= 0;
  778:   }
  779: 
  780:   return( 0 );				/* we're done */
  781: }
  782: 
  783: 
  784: /******************************************/
  785: 
  786: void replace_back_to_slash(char *s, char*t)
  787: {
  788:   int i;
  789:   int lg=0;
  790:   i=0;
  791:   lg=strlen(t);
  792:   for(i=0; i<= lg; i++) {
  793:     (s[i] = t[i]);
  794:     if (t[i]== '\\') s[i]='/';
  795:   }
  796: }
  797: 
  798: char *trimbb(char *out, char *in)
  799: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
  800:   char *s;
  801:   s=out;
  802:   while (*in != '\0'){
  803:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
  804:       in++;
  805:     }
  806:     *out++ = *in++;
  807:   }
  808:   *out='\0';
  809:   return s;
  810: }
  811: 
  812: char *cutl(char *blocc, char *alocc, char *in, char occ)
  813: {
  814:   /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ' 
  815:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
  816:      gives blocc="abcdef2ghi" and alocc="j".
  817:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
  818:   */
  819:   char *s, *t;
  820:   t=in;s=in;
  821:   while ((*in != occ) && (*in != '\0')){
  822:     *alocc++ = *in++;
  823:   }
  824:   if( *in == occ){
  825:     *(alocc)='\0';
  826:     s=++in;
  827:   }
  828:  
  829:   if (s == t) {/* occ not found */
  830:     *(alocc-(in-s))='\0';
  831:     in=s;
  832:   }
  833:   while ( *in != '\0'){
  834:     *blocc++ = *in++;
  835:   }
  836: 
  837:   *blocc='\0';
  838:   return t;
  839: }
  840: char *cutv(char *blocc, char *alocc, char *in, char occ)
  841: {
  842:   /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ' 
  843:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
  844:      gives blocc="abcdef2ghi" and alocc="j".
  845:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
  846:   */
  847:   char *s, *t;
  848:   t=in;s=in;
  849:   while (*in != '\0'){
  850:     while( *in == occ){
  851:       *blocc++ = *in++;
  852:       s=in;
  853:     }
  854:     *blocc++ = *in++;
  855:   }
  856:   if (s == t) /* occ not found */
  857:     *(blocc-(in-s))='\0';
  858:   else
  859:     *(blocc-(in-s)-1)='\0';
  860:   in=s;
  861:   while ( *in != '\0'){
  862:     *alocc++ = *in++;
  863:   }
  864: 
  865:   *alocc='\0';
  866:   return s;
  867: }
  868: 
  869: int nbocc(char *s, char occ)
  870: {
  871:   int i,j=0;
  872:   int lg=20;
  873:   i=0;
  874:   lg=strlen(s);
  875:   for(i=0; i<= lg; i++) {
  876:   if  (s[i] == occ ) j++;
  877:   }
  878:   return j;
  879: }
  880: 
  881: /* void cutv(char *u,char *v, char*t, char occ) */
  882: /* { */
  883: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
  884: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
  885: /*      gives u="abcdef2ghi" and v="j" *\/ */
  886: /*   int i,lg,j,p=0; */
  887: /*   i=0; */
  888: /*   lg=strlen(t); */
  889: /*   for(j=0; j<=lg-1; j++) { */
  890: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
  891: /*   } */
  892: 
  893: /*   for(j=0; j<p; j++) { */
  894: /*     (u[j] = t[j]); */
  895: /*   } */
  896: /*      u[p]='\0'; */
  897: 
  898: /*    for(j=0; j<= lg; j++) { */
  899: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
  900: /*   } */
  901: /* } */
  902: 
  903: #ifdef _WIN32
  904: char * strsep(char **pp, const char *delim)
  905: {
  906:   char *p, *q;
  907:          
  908:   if ((p = *pp) == NULL)
  909:     return 0;
  910:   if ((q = strpbrk (p, delim)) != NULL)
  911:   {
  912:     *pp = q + 1;
  913:     *q = '\0';
  914:   }
  915:   else
  916:     *pp = 0;
  917:   return p;
  918: }
  919: #endif
  920: 
  921: /********************** nrerror ********************/
  922: 
  923: void nrerror(char error_text[])
  924: {
  925:   fprintf(stderr,"ERREUR ...\n");
  926:   fprintf(stderr,"%s\n",error_text);
  927:   exit(EXIT_FAILURE);
  928: }
  929: /*********************** vector *******************/
  930: double *vector(int nl, int nh)
  931: {
  932:   double *v;
  933:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
  934:   if (!v) nrerror("allocation failure in vector");
  935:   return v-nl+NR_END;
  936: }
  937: 
  938: /************************ free vector ******************/
  939: void free_vector(double*v, int nl, int nh)
  940: {
  941:   free((FREE_ARG)(v+nl-NR_END));
  942: }
  943: 
  944: /************************ivector *******************************/
  945: int *ivector(long nl,long nh)
  946: {
  947:   int *v;
  948:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
  949:   if (!v) nrerror("allocation failure in ivector");
  950:   return v-nl+NR_END;
  951: }
  952: 
  953: /******************free ivector **************************/
  954: void free_ivector(int *v, long nl, long nh)
  955: {
  956:   free((FREE_ARG)(v+nl-NR_END));
  957: }
  958: 
  959: /************************lvector *******************************/
  960: long *lvector(long nl,long nh)
  961: {
  962:   long *v;
  963:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
  964:   if (!v) nrerror("allocation failure in ivector");
  965:   return v-nl+NR_END;
  966: }
  967: 
  968: /******************free lvector **************************/
  969: void free_lvector(long *v, long nl, long nh)
  970: {
  971:   free((FREE_ARG)(v+nl-NR_END));
  972: }
  973: 
  974: /******************* imatrix *******************************/
  975: int **imatrix(long nrl, long nrh, long ncl, long nch) 
  976:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
  977: { 
  978:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
  979:   int **m; 
  980:   
  981:   /* allocate pointers to rows */ 
  982:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
  983:   if (!m) nrerror("allocation failure 1 in matrix()"); 
  984:   m += NR_END; 
  985:   m -= nrl; 
  986:   
  987:   
  988:   /* allocate rows and set pointers to them */ 
  989:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
  990:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
  991:   m[nrl] += NR_END; 
  992:   m[nrl] -= ncl; 
  993:   
  994:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
  995:   
  996:   /* return pointer to array of pointers to rows */ 
  997:   return m; 
  998: } 
  999: 
 1000: /****************** free_imatrix *************************/
 1001: void free_imatrix(m,nrl,nrh,ncl,nch)
 1002:       int **m;
 1003:       long nch,ncl,nrh,nrl; 
 1004:      /* free an int matrix allocated by imatrix() */ 
 1005: { 
 1006:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
 1007:   free((FREE_ARG) (m+nrl-NR_END)); 
 1008: } 
 1009: 
 1010: /******************* matrix *******************************/
 1011: double **matrix(long nrl, long nrh, long ncl, long nch)
 1012: {
 1013:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
 1014:   double **m;
 1015: 
 1016:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1017:   if (!m) nrerror("allocation failure 1 in matrix()");
 1018:   m += NR_END;
 1019:   m -= nrl;
 1020: 
 1021:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1022:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1023:   m[nrl] += NR_END;
 1024:   m[nrl] -= ncl;
 1025: 
 1026:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1027:   return m;
 1028:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
 1029: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
 1030: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
 1031:    */
 1032: }
 1033: 
 1034: /*************************free matrix ************************/
 1035: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
 1036: {
 1037:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1038:   free((FREE_ARG)(m+nrl-NR_END));
 1039: }
 1040: 
 1041: /******************* ma3x *******************************/
 1042: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
 1043: {
 1044:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
 1045:   double ***m;
 1046: 
 1047:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1048:   if (!m) nrerror("allocation failure 1 in matrix()");
 1049:   m += NR_END;
 1050:   m -= nrl;
 1051: 
 1052:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1053:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1054:   m[nrl] += NR_END;
 1055:   m[nrl] -= ncl;
 1056: 
 1057:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1058: 
 1059:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
 1060:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
 1061:   m[nrl][ncl] += NR_END;
 1062:   m[nrl][ncl] -= nll;
 1063:   for (j=ncl+1; j<=nch; j++) 
 1064:     m[nrl][j]=m[nrl][j-1]+nlay;
 1065:   
 1066:   for (i=nrl+1; i<=nrh; i++) {
 1067:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
 1068:     for (j=ncl+1; j<=nch; j++) 
 1069:       m[i][j]=m[i][j-1]+nlay;
 1070:   }
 1071:   return m; 
 1072:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
 1073:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
 1074:   */
 1075: }
 1076: 
 1077: /*************************free ma3x ************************/
 1078: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
 1079: {
 1080:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
 1081:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1082:   free((FREE_ARG)(m+nrl-NR_END));
 1083: }
 1084: 
 1085: /*************** function subdirf ***********/
 1086: char *subdirf(char fileres[])
 1087: {
 1088:   /* Caution optionfilefiname is hidden */
 1089:   strcpy(tmpout,optionfilefiname);
 1090:   strcat(tmpout,"/"); /* Add to the right */
 1091:   strcat(tmpout,fileres);
 1092:   return tmpout;
 1093: }
 1094: 
 1095: /*************** function subdirf2 ***********/
 1096: char *subdirf2(char fileres[], char *preop)
 1097: {
 1098:   
 1099:   /* Caution optionfilefiname is hidden */
 1100:   strcpy(tmpout,optionfilefiname);
 1101:   strcat(tmpout,"/");
 1102:   strcat(tmpout,preop);
 1103:   strcat(tmpout,fileres);
 1104:   return tmpout;
 1105: }
 1106: 
 1107: /*************** function subdirf3 ***********/
 1108: char *subdirf3(char fileres[], char *preop, char *preop2)
 1109: {
 1110:   
 1111:   /* Caution optionfilefiname is hidden */
 1112:   strcpy(tmpout,optionfilefiname);
 1113:   strcat(tmpout,"/");
 1114:   strcat(tmpout,preop);
 1115:   strcat(tmpout,preop2);
 1116:   strcat(tmpout,fileres);
 1117:   return tmpout;
 1118: }
 1119: 
 1120: char *asc_diff_time(long time_sec, char ascdiff[])
 1121: {
 1122:   long sec_left, days, hours, minutes;
 1123:   days = (time_sec) / (60*60*24);
 1124:   sec_left = (time_sec) % (60*60*24);
 1125:   hours = (sec_left) / (60*60) ;
 1126:   sec_left = (sec_left) %(60*60);
 1127:   minutes = (sec_left) /60;
 1128:   sec_left = (sec_left) % (60);
 1129:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
 1130:   return ascdiff;
 1131: }
 1132: 
 1133: /***************** f1dim *************************/
 1134: extern int ncom; 
 1135: extern double *pcom,*xicom;
 1136: extern double (*nrfunc)(double []); 
 1137:  
 1138: double f1dim(double x) 
 1139: { 
 1140:   int j; 
 1141:   double f;
 1142:   double *xt; 
 1143:  
 1144:   xt=vector(1,ncom); 
 1145:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
 1146:   f=(*nrfunc)(xt); 
 1147:   free_vector(xt,1,ncom); 
 1148:   return f; 
 1149: } 
 1150: 
 1151: /*****************brent *************************/
 1152: double brent(double ax, double bx, double cx, double (*f)(double), double tol, 	double *xmin) 
 1153: { 
 1154:   int iter; 
 1155:   double a,b,d,etemp;
 1156:   double fu=0,fv,fw,fx;
 1157:   double ftemp=0.;
 1158:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
 1159:   double e=0.0; 
 1160:  
 1161:   a=(ax < cx ? ax : cx); 
 1162:   b=(ax > cx ? ax : cx); 
 1163:   x=w=v=bx; 
 1164:   fw=fv=fx=(*f)(x); 
 1165:   for (iter=1;iter<=ITMAX;iter++) { 
 1166:     xm=0.5*(a+b); 
 1167:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
 1168:     /*		if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
 1169:     printf(".");fflush(stdout);
 1170:     fprintf(ficlog,".");fflush(ficlog);
 1171: #ifdef DEBUGBRENT
 1172:     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);
 1173:     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);
 1174:     /*		if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
 1175: #endif
 1176:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
 1177:       *xmin=x; 
 1178:       return fx; 
 1179:     } 
 1180:     ftemp=fu;
 1181:     if (fabs(e) > tol1) { 
 1182:       r=(x-w)*(fx-fv); 
 1183:       q=(x-v)*(fx-fw); 
 1184:       p=(x-v)*q-(x-w)*r; 
 1185:       q=2.0*(q-r); 
 1186:       if (q > 0.0) p = -p; 
 1187:       q=fabs(q); 
 1188:       etemp=e; 
 1189:       e=d; 
 1190:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
 1191: 	d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1192:       else { 
 1193: 	d=p/q; 
 1194: 	u=x+d; 
 1195: 	if (u-a < tol2 || b-u < tol2) 
 1196: 	  d=SIGN(tol1,xm-x); 
 1197:       } 
 1198:     } else { 
 1199:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1200:     } 
 1201:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
 1202:     fu=(*f)(u); 
 1203:     if (fu <= fx) { 
 1204:       if (u >= x) a=x; else b=x; 
 1205:       SHFT(v,w,x,u) 
 1206: 	SHFT(fv,fw,fx,fu) 
 1207: 	} else { 
 1208: 	  if (u < x) a=u; else b=u; 
 1209: 	  if (fu <= fw || w == x) { 
 1210: 	    v=w; 
 1211: 	    w=u; 
 1212: 	    fv=fw; 
 1213: 	    fw=fu; 
 1214: 	  } else if (fu <= fv || v == x || v == w) { 
 1215: 	    v=u; 
 1216: 	    fv=fu; 
 1217: 	  } 
 1218: 	} 
 1219:   } 
 1220:   nrerror("Too many iterations in brent"); 
 1221:   *xmin=x; 
 1222:   return fx; 
 1223: } 
 1224: 
 1225: /****************** mnbrak ***********************/
 1226: 
 1227: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
 1228: 	    double (*func)(double)) 
 1229: { 
 1230:   double ulim,u,r,q, dum;
 1231:   double fu; 
 1232:  
 1233:   *fa=(*func)(*ax); 
 1234:   *fb=(*func)(*bx); 
 1235:   if (*fb > *fa) { 
 1236:     SHFT(dum,*ax,*bx,dum) 
 1237:       SHFT(dum,*fb,*fa,dum) 
 1238:       } 
 1239:   *cx=(*bx)+GOLD*(*bx-*ax); 
 1240:   *fc=(*func)(*cx); 
 1241:   while (*fb > *fc) { /* Declining fa, fb, fc */
 1242:     r=(*bx-*ax)*(*fb-*fc); 
 1243:     q=(*bx-*cx)*(*fb-*fa); 
 1244:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
 1245:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
 1246:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */
 1247:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */
 1248:       fu=(*func)(u); 
 1249: #ifdef DEBUG
 1250:       /* f(x)=A(x-u)**2+f(u) */
 1251:       double A, fparabu; 
 1252:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 1253:       fparabu= *fa - A*(*ax-u)*(*ax-u);
 1254:       printf("mnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf, fparabu=%.12f)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu);
 1255:       fprintf(ficlog, "mnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf, fparabu=%.12f)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu);
 1256: #endif 
 1257:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
 1258:       fu=(*func)(u); 
 1259:       if (fu < *fc) { 
 1260: 	SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
 1261: 	  SHFT(*fb,*fc,fu,(*func)(u)) 
 1262: 	  } 
 1263:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
 1264:       u=ulim; 
 1265:       fu=(*func)(u); 
 1266:     } else { 
 1267:       u=(*cx)+GOLD*(*cx-*bx); 
 1268:       fu=(*func)(u); 
 1269:     } 
 1270:     SHFT(*ax,*bx,*cx,u) 
 1271:       SHFT(*fa,*fb,*fc,fu) 
 1272:       } 
 1273: } 
 1274: 
 1275: /*************** linmin ************************/
 1276: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
 1277: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
 1278: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
 1279: the value of func at the returned location p . This is actually all accomplished by calling the
 1280: routines mnbrak and brent .*/
 1281: int ncom; 
 1282: double *pcom,*xicom;
 1283: double (*nrfunc)(double []); 
 1284:  
 1285: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
 1286: { 
 1287:   double brent(double ax, double bx, double cx, 
 1288: 	       double (*f)(double), double tol, double *xmin); 
 1289:   double f1dim(double x); 
 1290:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
 1291: 	      double *fc, double (*func)(double)); 
 1292:   int j; 
 1293:   double xx,xmin,bx,ax; 
 1294:   double fx,fb,fa;
 1295:  
 1296:   ncom=n; 
 1297:   pcom=vector(1,n); 
 1298:   xicom=vector(1,n); 
 1299:   nrfunc=func; 
 1300:   for (j=1;j<=n;j++) { 
 1301:     pcom[j]=p[j]; 
 1302:     xicom[j]=xi[j]; 
 1303:   } 
 1304:   ax=0.0; 
 1305:   xx=1.0; 
 1306:   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
 1307:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Find a minimum P+lambda n in that direction (lambdamin), with TOL between abscisses */
 1308: #ifdef DEBUG
 1309:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1310:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1311: #endif
 1312:   for (j=1;j<=n;j++) { 
 1313:     xi[j] *= xmin; 
 1314:     p[j] += xi[j]; 
 1315:   } 
 1316:   free_vector(xicom,1,n); 
 1317:   free_vector(pcom,1,n); 
 1318: } 
 1319: 
 1320: 
 1321: /*************** powell ************************/
 1322: /*
 1323: Minimization of a function func of n variables. Input consists of an initial starting point
 1324: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
 1325: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
 1326: such that failure to decrease by more than this amount on one iteration signals doneness. On
 1327: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
 1328: function value at p , and iter is the number of iterations taken. The routine linmin is used.
 1329:  */
 1330: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
 1331: 	    double (*func)(double [])) 
 1332: { 
 1333:   void linmin(double p[], double xi[], int n, double *fret, 
 1334: 	      double (*func)(double [])); 
 1335:   int i,ibig,j; 
 1336:   double del,t,*pt,*ptt,*xit;
 1337:   double fp,fptt;
 1338:   double *xits;
 1339:   int niterf, itmp;
 1340: 
 1341:   pt=vector(1,n); 
 1342:   ptt=vector(1,n); 
 1343:   xit=vector(1,n); 
 1344:   xits=vector(1,n); 
 1345:   *fret=(*func)(p); 
 1346:   for (j=1;j<=n;j++) pt[j]=p[j]; 
 1347:     rcurr_time = time(NULL);  
 1348:   for (*iter=1;;++(*iter)) { 
 1349:     fp=(*fret); 
 1350:     ibig=0; 
 1351:     del=0.0; 
 1352:     rlast_time=rcurr_time;
 1353:     /* (void) gettimeofday(&curr_time,&tzp); */
 1354:     rcurr_time = time(NULL);  
 1355:     curr_time = *localtime(&rcurr_time);
 1356:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
 1357:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
 1358: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
 1359:    for (i=1;i<=n;i++) {
 1360:       printf(" %d %.12f",i, p[i]);
 1361:       fprintf(ficlog," %d %.12lf",i, p[i]);
 1362:       fprintf(ficrespow," %.12lf", p[i]);
 1363:     }
 1364:     printf("\n");
 1365:     fprintf(ficlog,"\n");
 1366:     fprintf(ficrespow,"\n");fflush(ficrespow);
 1367:     if(*iter <=3){
 1368:       tml = *localtime(&rcurr_time);
 1369:       strcpy(strcurr,asctime(&tml));
 1370:       rforecast_time=rcurr_time; 
 1371:       itmp = strlen(strcurr);
 1372:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
 1373: 	strcurr[itmp-1]='\0';
 1374:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1375:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1376:       for(niterf=10;niterf<=30;niterf+=10){
 1377: 	rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
 1378: 	forecast_time = *localtime(&rforecast_time);
 1379: 	strcpy(strfor,asctime(&forecast_time));
 1380: 	itmp = strlen(strfor);
 1381: 	if(strfor[itmp-1]=='\n')
 1382: 	strfor[itmp-1]='\0';
 1383: 	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(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
 1384: 	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(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
 1385:       }
 1386:     }
 1387:     for (i=1;i<=n;i++) { 
 1388:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; 
 1389:       fptt=(*fret); 
 1390: #ifdef DEBUG
 1391: 	  printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1392: 	  fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1393: #endif
 1394:       printf("%d",i);fflush(stdout);
 1395:       fprintf(ficlog,"%d",i);fflush(ficlog);
 1396:       linmin(p,xit,n,fret,func); 
 1397:       if (fabs(fptt-(*fret)) > del) { 
 1398: 	del=fabs(fptt-(*fret)); 
 1399: 	ibig=i; 
 1400:       } 
 1401: #ifdef DEBUG
 1402:       printf("%d %.12e",i,(*fret));
 1403:       fprintf(ficlog,"%d %.12e",i,(*fret));
 1404:       for (j=1;j<=n;j++) {
 1405: 	xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
 1406: 	printf(" x(%d)=%.12e",j,xit[j]);
 1407: 	fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
 1408:       }
 1409:       for(j=1;j<=n;j++) {
 1410: 	printf(" p(%d)=%.12e",j,p[j]);
 1411: 	fprintf(ficlog," p(%d)=%.12e",j,p[j]);
 1412:       }
 1413:       printf("\n");
 1414:       fprintf(ficlog,"\n");
 1415: #endif
 1416:     } /* end i */
 1417:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
 1418: #ifdef DEBUG
 1419:       int k[2],l;
 1420:       k[0]=1;
 1421:       k[1]=-1;
 1422:       printf("Max: %.12e",(*func)(p));
 1423:       fprintf(ficlog,"Max: %.12e",(*func)(p));
 1424:       for (j=1;j<=n;j++) {
 1425: 	printf(" %.12e",p[j]);
 1426: 	fprintf(ficlog," %.12e",p[j]);
 1427:       }
 1428:       printf("\n");
 1429:       fprintf(ficlog,"\n");
 1430:       for(l=0;l<=1;l++) {
 1431: 	for (j=1;j<=n;j++) {
 1432: 	  ptt[j]=p[j]+(p[j]-pt[j])*k[l];
 1433: 	  printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1434: 	  fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1435: 	}
 1436: 	printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1437: 	fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1438:       }
 1439: #endif
 1440: 
 1441: 
 1442:       free_vector(xit,1,n); 
 1443:       free_vector(xits,1,n); 
 1444:       free_vector(ptt,1,n); 
 1445:       free_vector(pt,1,n); 
 1446:       return; 
 1447:     } 
 1448:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
 1449:     for (j=1;j<=n;j++) { /* Computes an extrapolated point */
 1450:       ptt[j]=2.0*p[j]-pt[j]; 
 1451:       xit[j]=p[j]-pt[j]; 
 1452:       pt[j]=p[j]; 
 1453:     } 
 1454:     fptt=(*func)(ptt); 
 1455:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
 1456:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
 1457:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
 1458:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
 1459:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
 1460:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
 1461:       /* f1-f3 = delta(2h) = 2 h**2 f'' = 2(f1- 2f2 +f3) */
 1462:       /* Thus we compare delta(2h) with observed f1-f3 */
 1463:       /* or best gain on one ancient line 'del' with total  */
 1464:       /* gain f1-f2 = f1 - f2 - 'del' with del  */
 1465:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
 1466: 
 1467:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del);
 1468:       t= t- del*SQR(fp-fptt);
 1469:       printf("t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
 1470:       fprintf(ficlog,"t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
 1471: #ifdef DEBUG
 1472:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 1473: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 1474:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 1475: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 1476:       printf("tt= %.12lf, t=%.12lf\n",2.0*(fp-2.0*(*fret)+fptt)*(fp-(*fret)-del)*(fp-(*fret)-del)-del*(fp-fptt)*(fp-fptt),t);
 1477:       fprintf(ficlog, "tt= %.12lf, t=%.12lf\n",2.0*(fp-2.0*(*fret)+fptt)*(fp-(*fret)-del)*(fp-(*fret)-del)-del*(fp-fptt)*(fp-fptt),t);
 1478: #endif
 1479:       if (t < 0.0) { /* Then we use it for last direction */
 1480: 	linmin(p,xit,n,fret,func); /* computes mean on the extrapolated direction.*/
 1481: 	for (j=1;j<=n;j++) { 
 1482: 	  xi[j][ibig]=xi[j][n]; /* Replace the direction with biggest decrease by n */
 1483: 	  xi[j][n]=xit[j];      /* and nth direction by the extrapolated */
 1484: 	}
 1485: 	printf("Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 1486: 	fprintf(ficlog,"Gaining to use average direction of P0 P%d instead of biggest increase direction :\n",n,ibig);
 1487: 
 1488: #ifdef DEBUG
 1489: 	printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1490: 	fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1491: 	for(j=1;j<=n;j++){
 1492: 	  printf(" %.12e",xit[j]);
 1493: 	  fprintf(ficlog," %.12e",xit[j]);
 1494: 	}
 1495: 	printf("\n");
 1496: 	fprintf(ficlog,"\n");
 1497: #endif
 1498:       } /* end of t negative */
 1499:     } /* end if (fptt < fp)  */
 1500:   } 
 1501: } 
 1502: 
 1503: /**** Prevalence limit (stable or period prevalence)  ****************/
 1504: 
 1505: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
 1506: {
 1507:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
 1508:      matrix by transitions matrix until convergence is reached */
 1509: 
 1510:   int i, ii,j,k;
 1511:   double min, max, maxmin, maxmax,sumnew=0.;
 1512:   /* double **matprod2(); */ /* test */
 1513:   double **out, cov[NCOVMAX+1], **pmij();
 1514:   double **newm;
 1515:   double agefin, delaymax=50 ; /* Max number of years to converge */
 1516: 
 1517:   for (ii=1;ii<=nlstate+ndeath;ii++)
 1518:     for (j=1;j<=nlstate+ndeath;j++){
 1519:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1520:     }
 1521: 
 1522:    cov[1]=1.;
 1523:  
 1524:  /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 1525:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
 1526:     newm=savm;
 1527:     /* Covariates have to be included here again */
 1528:     cov[2]=agefin;
 1529:     
 1530:     for (k=1; k<=cptcovn;k++) {
 1531:       cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 1532:       /*printf("prevalim ij=%d k=%d Tvar[%d]=%d nbcode=%d cov=%lf codtab[%d][Tvar[%d]]=%d \n",ij,k, k, Tvar[k],nbcode[Tvar[k]][codtab[ij][Tvar[k]]],cov[2+k], ij, k, codtab[ij][Tvar[k]]);*/
 1533:     }
 1534:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 1535:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
 1536:     /*   cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]]; */
 1537:     
 1538:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 1539:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 1540:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 1541:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 1542:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 1543:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
 1544:     
 1545:     savm=oldm;
 1546:     oldm=newm;
 1547:     maxmax=0.;
 1548:     for(j=1;j<=nlstate;j++){
 1549:       min=1.;
 1550:       max=0.;
 1551:       for(i=1; i<=nlstate; i++) {
 1552: 	sumnew=0;
 1553: 	for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
 1554: 	prlim[i][j]= newm[i][j]/(1-sumnew);
 1555:         /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
 1556: 	max=FMAX(max,prlim[i][j]);
 1557: 	min=FMIN(min,prlim[i][j]);
 1558:       }
 1559:       maxmin=max-min;
 1560:       maxmax=FMAX(maxmax,maxmin);
 1561:     }
 1562:     if(maxmax < ftolpl){
 1563:       return prlim;
 1564:     }
 1565:   }
 1566: }
 1567: 
 1568: /*************** transition probabilities ***************/ 
 1569: 
 1570: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 1571: {
 1572:   /* According to parameters values stored in x and the covariate's values stored in cov,
 1573:      computes the probability to be observed in state j being in state i by appying the
 1574:      model to the ncovmodel covariates (including constant and age).
 1575:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 1576:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 1577:      ncth covariate in the global vector x is given by the formula:
 1578:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 1579:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 1580:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 1581:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 1582:      Outputs ps[i][j] the probability to be observed in j being in j according to
 1583:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 1584:   */
 1585:   double s1, lnpijopii;
 1586:   /*double t34;*/
 1587:   int i,j, nc, ii, jj;
 1588: 
 1589:     for(i=1; i<= nlstate; i++){
 1590:       for(j=1; j<i;j++){
 1591: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 1592: 	  /*lnpijopii += param[i][j][nc]*cov[nc];*/
 1593: 	  lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 1594: /* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 1595: 	}
 1596: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 1597: /* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 1598:       }
 1599:       for(j=i+1; j<=nlstate+ndeath;j++){
 1600: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 1601: 	  /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 1602: 	  lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 1603: /* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 1604: 	}
 1605: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 1606:       }
 1607:     }
 1608:     
 1609:     for(i=1; i<= nlstate; i++){
 1610:       s1=0;
 1611:       for(j=1; j<i; j++){
 1612: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 1613: 	/*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 1614:       }
 1615:       for(j=i+1; j<=nlstate+ndeath; j++){
 1616: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 1617: 	/*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 1618:       }
 1619:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 1620:       ps[i][i]=1./(s1+1.);
 1621:       /* Computing other pijs */
 1622:       for(j=1; j<i; j++)
 1623: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 1624:       for(j=i+1; j<=nlstate+ndeath; j++)
 1625: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 1626:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 1627:     } /* end i */
 1628:     
 1629:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 1630:       for(jj=1; jj<= nlstate+ndeath; jj++){
 1631: 	ps[ii][jj]=0;
 1632: 	ps[ii][ii]=1;
 1633:       }
 1634:     }
 1635:     
 1636:     
 1637:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 1638:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 1639:     /* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 1640:     /*   } */
 1641:     /*   printf("\n "); */
 1642:     /* } */
 1643:     /* printf("\n ");printf("%lf ",cov[2]);*/
 1644:     /*
 1645:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
 1646:       goto end;*/
 1647:     return ps;
 1648: }
 1649: 
 1650: /**************** Product of 2 matrices ******************/
 1651: 
 1652: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
 1653: {
 1654:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
 1655:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
 1656:   /* in, b, out are matrice of pointers which should have been initialized 
 1657:      before: only the contents of out is modified. The function returns
 1658:      a pointer to pointers identical to out */
 1659:   int i, j, k;
 1660:   for(i=nrl; i<= nrh; i++)
 1661:     for(k=ncolol; k<=ncoloh; k++){
 1662:       out[i][k]=0.;
 1663:       for(j=ncl; j<=nch; j++)
 1664:   	out[i][k] +=in[i][j]*b[j][k];
 1665:     }
 1666:   return out;
 1667: }
 1668: 
 1669: 
 1670: /************* Higher Matrix Product ***************/
 1671: 
 1672: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
 1673: {
 1674:   /* Computes the transition matrix starting at age 'age' over 
 1675:      'nhstepm*hstepm*stepm' months (i.e. until
 1676:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
 1677:      nhstepm*hstepm matrices. 
 1678:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
 1679:      (typically every 2 years instead of every month which is too big 
 1680:      for the memory).
 1681:      Model is determined by parameters x and covariates have to be 
 1682:      included manually here. 
 1683: 
 1684:      */
 1685: 
 1686:   int i, j, d, h, k;
 1687:   double **out, cov[NCOVMAX+1];
 1688:   double **newm;
 1689: 
 1690:   /* Hstepm could be zero and should return the unit matrix */
 1691:   for (i=1;i<=nlstate+ndeath;i++)
 1692:     for (j=1;j<=nlstate+ndeath;j++){
 1693:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 1694:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 1695:     }
 1696:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 1697:   for(h=1; h <=nhstepm; h++){
 1698:     for(d=1; d <=hstepm; d++){
 1699:       newm=savm;
 1700:       /* Covariates have to be included here again */
 1701:       cov[1]=1.;
 1702:       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
 1703:       for (k=1; k<=cptcovn;k++) 
 1704: 	cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 1705:       for (k=1; k<=cptcovage;k++)
 1706: 	cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
 1707:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
 1708: 	cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 1709: 
 1710: 
 1711:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 1712:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 1713:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
 1714: 		   pmij(pmmij,cov,ncovmodel,x,nlstate));
 1715:       savm=oldm;
 1716:       oldm=newm;
 1717:     }
 1718:     for(i=1; i<=nlstate+ndeath; i++)
 1719:       for(j=1;j<=nlstate+ndeath;j++) {
 1720: 	po[i][j][h]=newm[i][j];
 1721: 	/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 1722:       }
 1723:     /*printf("h=%d ",h);*/
 1724:   } /* end h */
 1725: /*     printf("\n H=%d \n",h); */
 1726:   return po;
 1727: }
 1728: 
 1729: #ifdef NLOPT
 1730:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
 1731:   double fret;
 1732:   double *xt;
 1733:   int j;
 1734:   myfunc_data *d2 = (myfunc_data *) pd;
 1735: /* xt = (p1-1); */
 1736:   xt=vector(1,n); 
 1737:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
 1738: 
 1739:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
 1740:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
 1741:   printf("Function = %.12lf ",fret);
 1742:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
 1743:   printf("\n");
 1744:  free_vector(xt,1,n);
 1745:   return fret;
 1746: }
 1747: #endif
 1748: 
 1749: /*************** log-likelihood *************/
 1750: double func( double *x)
 1751: {
 1752:   int i, ii, j, k, mi, d, kk;
 1753:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 1754:   double **out;
 1755:   double sw; /* Sum of weights */
 1756:   double lli; /* Individual log likelihood */
 1757:   int s1, s2;
 1758:   double bbh, survp;
 1759:   long ipmx;
 1760:   /*extern weight */
 1761:   /* We are differentiating ll according to initial status */
 1762:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 1763:   /*for(i=1;i<imx;i++) 
 1764:     printf(" %d\n",s[4][i]);
 1765:   */
 1766: 
 1767:   ++countcallfunc;
 1768: 
 1769:   cov[1]=1.;
 1770: 
 1771:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 1772: 
 1773:   if(mle==1){
 1774:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1775:       /* Computes the values of the ncovmodel covariates of the model
 1776: 	 depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
 1777: 	 Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
 1778: 	 to be observed in j being in i according to the model.
 1779:        */
 1780:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
 1781: 	cov[2+k]=covar[Tvar[k]][i];
 1782:       }
 1783:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
 1784: 	 is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
 1785: 	 has been calculated etc */
 1786:       for(mi=1; mi<= wav[i]-1; mi++){
 1787: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1788: 	  for (j=1;j<=nlstate+ndeath;j++){
 1789: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1790: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1791: 	  }
 1792: 	for(d=0; d<dh[mi][i]; d++){
 1793: 	  newm=savm;
 1794: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1795: 	  for (kk=1; kk<=cptcovage;kk++) {
 1796: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
 1797: 	  }
 1798: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1799: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1800: 	  savm=oldm;
 1801: 	  oldm=newm;
 1802: 	} /* end mult */
 1803:       
 1804: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 1805: 	/* But now since version 0.9 we anticipate for bias at large stepm.
 1806: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 1807: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
 1808: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
 1809: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 1810: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
 1811: 	 * probability in order to take into account the bias as a fraction of the way
 1812: 	 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
 1813: 	 * -stepm/2 to stepm/2 .
 1814: 	 * For stepm=1 the results are the same as for previous versions of Imach.
 1815: 	 * For stepm > 1 the results are less biased than in previous versions. 
 1816: 	 */
 1817: 	s1=s[mw[mi][i]][i];
 1818: 	s2=s[mw[mi+1][i]][i];
 1819: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1820: 	/* bias bh is positive if real duration
 1821: 	 * is higher than the multiple of stepm and negative otherwise.
 1822: 	 */
 1823: 	/* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
 1824: 	if( s2 > nlstate){ 
 1825: 	  /* i.e. if s2 is a death state and if the date of death is known 
 1826: 	     then the contribution to the likelihood is the probability to 
 1827: 	     die between last step unit time and current  step unit time, 
 1828: 	     which is also equal to probability to die before dh 
 1829: 	     minus probability to die before dh-stepm . 
 1830: 	     In version up to 0.92 likelihood was computed
 1831: 	as if date of death was unknown. Death was treated as any other
 1832: 	health state: the date of the interview describes the actual state
 1833: 	and not the date of a change in health state. The former idea was
 1834: 	to consider that at each interview the state was recorded
 1835: 	(healthy, disable or death) and IMaCh was corrected; but when we
 1836: 	introduced the exact date of death then we should have modified
 1837: 	the contribution of an exact death to the likelihood. This new
 1838: 	contribution is smaller and very dependent of the step unit
 1839: 	stepm. It is no more the probability to die between last interview
 1840: 	and month of death but the probability to survive from last
 1841: 	interview up to one month before death multiplied by the
 1842: 	probability to die within a month. Thanks to Chris
 1843: 	Jackson for correcting this bug.  Former versions increased
 1844: 	mortality artificially. The bad side is that we add another loop
 1845: 	which slows down the processing. The difference can be up to 10%
 1846: 	lower mortality.
 1847: 	  */
 1848: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 1849: 
 1850: 
 1851: 	} else if  (s2==-2) {
 1852: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 1853: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 1854: 	  /*survp += out[s1][j]; */
 1855: 	  lli= log(survp);
 1856: 	}
 1857: 	
 1858:  	else if  (s2==-4) { 
 1859: 	  for (j=3,survp=0. ; j<=nlstate; j++)  
 1860: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 1861:  	  lli= log(survp); 
 1862:  	} 
 1863: 
 1864:  	else if  (s2==-5) { 
 1865:  	  for (j=1,survp=0. ; j<=2; j++)  
 1866: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 1867:  	  lli= log(survp); 
 1868:  	} 
 1869: 	
 1870: 	else{
 1871: 	  lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 1872: 	  /*  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 */
 1873: 	} 
 1874: 	/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 1875: 	/*if(lli ==000.0)*/
 1876: 	/*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); */
 1877:   	ipmx +=1;
 1878: 	sw += weight[i];
 1879: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1880:       } /* end of wave */
 1881:     } /* end of individual */
 1882:   }  else if(mle==2){
 1883:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1884:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1885:       for(mi=1; mi<= wav[i]-1; mi++){
 1886: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1887: 	  for (j=1;j<=nlstate+ndeath;j++){
 1888: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1889: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1890: 	  }
 1891: 	for(d=0; d<=dh[mi][i]; d++){
 1892: 	  newm=savm;
 1893: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1894: 	  for (kk=1; kk<=cptcovage;kk++) {
 1895: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1896: 	  }
 1897: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1898: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1899: 	  savm=oldm;
 1900: 	  oldm=newm;
 1901: 	} /* end mult */
 1902:       
 1903: 	s1=s[mw[mi][i]][i];
 1904: 	s2=s[mw[mi+1][i]][i];
 1905: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1906: 	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 */
 1907: 	ipmx +=1;
 1908: 	sw += weight[i];
 1909: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1910:       } /* end of wave */
 1911:     } /* end of individual */
 1912:   }  else if(mle==3){  /* exponential inter-extrapolation */
 1913:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1914:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1915:       for(mi=1; mi<= wav[i]-1; mi++){
 1916: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1917: 	  for (j=1;j<=nlstate+ndeath;j++){
 1918: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1919: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1920: 	  }
 1921: 	for(d=0; d<dh[mi][i]; d++){
 1922: 	  newm=savm;
 1923: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1924: 	  for (kk=1; kk<=cptcovage;kk++) {
 1925: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1926: 	  }
 1927: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1928: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1929: 	  savm=oldm;
 1930: 	  oldm=newm;
 1931: 	} /* end mult */
 1932:       
 1933: 	s1=s[mw[mi][i]][i];
 1934: 	s2=s[mw[mi+1][i]][i];
 1935: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1936: 	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 */
 1937: 	ipmx +=1;
 1938: 	sw += weight[i];
 1939: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1940:       } /* end of wave */
 1941:     } /* end of individual */
 1942:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
 1943:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1944:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1945:       for(mi=1; mi<= wav[i]-1; mi++){
 1946: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1947: 	  for (j=1;j<=nlstate+ndeath;j++){
 1948: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1949: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1950: 	  }
 1951: 	for(d=0; d<dh[mi][i]; d++){
 1952: 	  newm=savm;
 1953: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1954: 	  for (kk=1; kk<=cptcovage;kk++) {
 1955: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1956: 	  }
 1957: 	
 1958: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1959: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1960: 	  savm=oldm;
 1961: 	  oldm=newm;
 1962: 	} /* end mult */
 1963:       
 1964: 	s1=s[mw[mi][i]][i];
 1965: 	s2=s[mw[mi+1][i]][i];
 1966: 	if( s2 > nlstate){ 
 1967: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 1968: 	}else{
 1969: 	  lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 1970: 	}
 1971: 	ipmx +=1;
 1972: 	sw += weight[i];
 1973: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1974: /* 	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]); */
 1975:       } /* end of wave */
 1976:     } /* end of individual */
 1977:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
 1978:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1979:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1980:       for(mi=1; mi<= wav[i]-1; mi++){
 1981: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1982: 	  for (j=1;j<=nlstate+ndeath;j++){
 1983: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1984: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1985: 	  }
 1986: 	for(d=0; d<dh[mi][i]; d++){
 1987: 	  newm=savm;
 1988: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1989: 	  for (kk=1; kk<=cptcovage;kk++) {
 1990: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1991: 	  }
 1992: 	
 1993: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1994: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1995: 	  savm=oldm;
 1996: 	  oldm=newm;
 1997: 	} /* end mult */
 1998:       
 1999: 	s1=s[mw[mi][i]][i];
 2000: 	s2=s[mw[mi+1][i]][i];
 2001: 	lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 2002: 	ipmx +=1;
 2003: 	sw += weight[i];
 2004: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2005: 	/*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]);*/
 2006:       } /* end of wave */
 2007:     } /* end of individual */
 2008:   } /* End of if */
 2009:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 2010:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 2011:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 2012:   return -l;
 2013: }
 2014: 
 2015: /*************** log-likelihood *************/
 2016: double funcone( double *x)
 2017: {
 2018:   /* Same as likeli but slower because of a lot of printf and if */
 2019:   int i, ii, j, k, mi, d, kk;
 2020:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 2021:   double **out;
 2022:   double lli; /* Individual log likelihood */
 2023:   double llt;
 2024:   int s1, s2;
 2025:   double bbh, survp;
 2026:   /*extern weight */
 2027:   /* We are differentiating ll according to initial status */
 2028:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 2029:   /*for(i=1;i<imx;i++) 
 2030:     printf(" %d\n",s[4][i]);
 2031:   */
 2032:   cov[1]=1.;
 2033: 
 2034:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 2035: 
 2036:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2037:     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 2038:     for(mi=1; mi<= wav[i]-1; mi++){
 2039:       for (ii=1;ii<=nlstate+ndeath;ii++)
 2040: 	for (j=1;j<=nlstate+ndeath;j++){
 2041: 	  oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2042: 	  savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2043: 	}
 2044:       for(d=0; d<dh[mi][i]; d++){
 2045: 	newm=savm;
 2046: 	cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2047: 	for (kk=1; kk<=cptcovage;kk++) {
 2048: 	  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 2049: 	}
 2050: 	/* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2051: 	out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2052: 		     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2053: 	/* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
 2054: 	/* 	     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
 2055: 	savm=oldm;
 2056: 	oldm=newm;
 2057:       } /* end mult */
 2058:       
 2059:       s1=s[mw[mi][i]][i];
 2060:       s2=s[mw[mi+1][i]][i];
 2061:       bbh=(double)bh[mi][i]/(double)stepm; 
 2062:       /* bias is positive if real duration
 2063:        * is higher than the multiple of stepm and negative otherwise.
 2064:        */
 2065:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
 2066: 	lli=log(out[s1][s2] - savm[s1][s2]);
 2067:       } else if  (s2==-2) {
 2068: 	for (j=1,survp=0. ; j<=nlstate; j++) 
 2069: 	  survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2070: 	lli= log(survp);
 2071:       }else if (mle==1){
 2072: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2073:       } else if(mle==2){
 2074: 	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 */
 2075:       } else if(mle==3){  /* exponential inter-extrapolation */
 2076: 	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 */
 2077:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
 2078: 	lli=log(out[s1][s2]); /* Original formula */
 2079:       } else{  /* mle=0 back to 1 */
 2080: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2081: 	/*lli=log(out[s1][s2]); */ /* Original formula */
 2082:       } /* End of if */
 2083:       ipmx +=1;
 2084:       sw += weight[i];
 2085:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2086:       /*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]); */
 2087:       if(globpr){
 2088: 	fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
 2089:  %11.6f %11.6f %11.6f ", \
 2090: 		num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
 2091: 		2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
 2092: 	for(k=1,llt=0.,l=0.; k<=nlstate; k++){
 2093: 	  llt +=ll[k]*gipmx/gsw;
 2094: 	  fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
 2095: 	}
 2096: 	fprintf(ficresilk," %10.6f\n", -llt);
 2097:       }
 2098:     } /* end of wave */
 2099:   } /* end of individual */
 2100:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 2101:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 2102:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 2103:   if(globpr==0){ /* First time we count the contributions and weights */
 2104:     gipmx=ipmx;
 2105:     gsw=sw;
 2106:   }
 2107:   return -l;
 2108: }
 2109: 
 2110: 
 2111: /*************** function likelione ***********/
 2112: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
 2113: {
 2114:   /* This routine should help understanding what is done with 
 2115:      the selection of individuals/waves and
 2116:      to check the exact contribution to the likelihood.
 2117:      Plotting could be done.
 2118:    */
 2119:   int k;
 2120: 
 2121:   if(*globpri !=0){ /* Just counts and sums, no printings */
 2122:     strcpy(fileresilk,"ilk"); 
 2123:     strcat(fileresilk,fileres);
 2124:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
 2125:       printf("Problem with resultfile: %s\n", fileresilk);
 2126:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
 2127:     }
 2128:     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");
 2129:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
 2130:     /* 	i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
 2131:     for(k=1; k<=nlstate; k++) 
 2132:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
 2133:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
 2134:   }
 2135: 
 2136:   *fretone=(*funcone)(p);
 2137:   if(*globpri !=0){
 2138:     fclose(ficresilk);
 2139:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
 2140:     fflush(fichtm); 
 2141:   } 
 2142:   return;
 2143: }
 2144: 
 2145: 
 2146: /*********** Maximum Likelihood Estimation ***************/
 2147: 
 2148: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
 2149: {
 2150:   int i,j, iter;
 2151:   double **xi;
 2152:   double fret;
 2153:   double fretone; /* Only one call to likelihood */
 2154:   /*  char filerespow[FILENAMELENGTH];*/
 2155: 
 2156: #ifdef NLOPT
 2157:   int creturn;
 2158:   nlopt_opt opt;
 2159:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
 2160:   double *lb;
 2161:   double minf; /* the minimum objective value, upon return */
 2162:   double * p1; /* Shifted parameters from 0 instead of 1 */
 2163:   myfunc_data dinst, *d = &dinst;
 2164: #endif
 2165: 
 2166: 
 2167:   xi=matrix(1,npar,1,npar);
 2168:   for (i=1;i<=npar;i++)
 2169:     for (j=1;j<=npar;j++)
 2170:       xi[i][j]=(i==j ? 1.0 : 0.0);
 2171:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
 2172:   strcpy(filerespow,"pow"); 
 2173:   strcat(filerespow,fileres);
 2174:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
 2175:     printf("Problem with resultfile: %s\n", filerespow);
 2176:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 2177:   }
 2178:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
 2179:   for (i=1;i<=nlstate;i++)
 2180:     for(j=1;j<=nlstate+ndeath;j++)
 2181:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 2182:   fprintf(ficrespow,"\n");
 2183: #ifdef POWELL
 2184:   powell(p,xi,npar,ftol,&iter,&fret,func);
 2185: #endif
 2186: 
 2187: #ifdef NLOPT
 2188: #ifdef NEWUOA
 2189:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
 2190: #else
 2191:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
 2192: #endif
 2193:   lb=vector(0,npar-1);
 2194:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
 2195:   nlopt_set_lower_bounds(opt, lb);
 2196:   nlopt_set_initial_step1(opt, 0.1);
 2197:   
 2198:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
 2199:   d->function = func;
 2200:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
 2201:   nlopt_set_min_objective(opt, myfunc, d);
 2202:   nlopt_set_xtol_rel(opt, ftol);
 2203:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
 2204:     printf("nlopt failed! %d\n",creturn); 
 2205:   }
 2206:   else {
 2207:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
 2208:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
 2209:     iter=1; /* not equal */
 2210:   }
 2211:   nlopt_destroy(opt);
 2212: #endif
 2213:   free_matrix(xi,1,npar,1,npar);
 2214:   fclose(ficrespow);
 2215:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2216:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2217:   fprintf(ficres,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2218: 
 2219: }
 2220: 
 2221: /**** Computes Hessian and covariance matrix ***/
 2222: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
 2223: {
 2224:   double  **a,**y,*x,pd;
 2225:   double **hess;
 2226:   int i, j;
 2227:   int *indx;
 2228: 
 2229:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
 2230:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
 2231:   void lubksb(double **a, int npar, int *indx, double b[]) ;
 2232:   void ludcmp(double **a, int npar, int *indx, double *d) ;
 2233:   double gompertz(double p[]);
 2234:   hess=matrix(1,npar,1,npar);
 2235: 
 2236:   printf("\nCalculation of the hessian matrix. Wait...\n");
 2237:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
 2238:   for (i=1;i<=npar;i++){
 2239:     printf("%d",i);fflush(stdout);
 2240:     fprintf(ficlog,"%d",i);fflush(ficlog);
 2241:    
 2242:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
 2243:     
 2244:     /*  printf(" %f ",p[i]);
 2245: 	printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
 2246:   }
 2247:   
 2248:   for (i=1;i<=npar;i++) {
 2249:     for (j=1;j<=npar;j++)  {
 2250:       if (j>i) { 
 2251: 	printf(".%d%d",i,j);fflush(stdout);
 2252: 	fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
 2253: 	hess[i][j]=hessij(p,delti,i,j,func,npar);
 2254: 	
 2255: 	hess[j][i]=hess[i][j];    
 2256: 	/*printf(" %lf ",hess[i][j]);*/
 2257:       }
 2258:     }
 2259:   }
 2260:   printf("\n");
 2261:   fprintf(ficlog,"\n");
 2262: 
 2263:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
 2264:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
 2265:   
 2266:   a=matrix(1,npar,1,npar);
 2267:   y=matrix(1,npar,1,npar);
 2268:   x=vector(1,npar);
 2269:   indx=ivector(1,npar);
 2270:   for (i=1;i<=npar;i++)
 2271:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
 2272:   ludcmp(a,npar,indx,&pd);
 2273: 
 2274:   for (j=1;j<=npar;j++) {
 2275:     for (i=1;i<=npar;i++) x[i]=0;
 2276:     x[j]=1;
 2277:     lubksb(a,npar,indx,x);
 2278:     for (i=1;i<=npar;i++){ 
 2279:       matcov[i][j]=x[i];
 2280:     }
 2281:   }
 2282: 
 2283:   printf("\n#Hessian matrix#\n");
 2284:   fprintf(ficlog,"\n#Hessian matrix#\n");
 2285:   for (i=1;i<=npar;i++) { 
 2286:     for (j=1;j<=npar;j++) { 
 2287:       printf("%.3e ",hess[i][j]);
 2288:       fprintf(ficlog,"%.3e ",hess[i][j]);
 2289:     }
 2290:     printf("\n");
 2291:     fprintf(ficlog,"\n");
 2292:   }
 2293: 
 2294:   /* Recompute Inverse */
 2295:   for (i=1;i<=npar;i++)
 2296:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
 2297:   ludcmp(a,npar,indx,&pd);
 2298: 
 2299:   /*  printf("\n#Hessian matrix recomputed#\n");
 2300: 
 2301:   for (j=1;j<=npar;j++) {
 2302:     for (i=1;i<=npar;i++) x[i]=0;
 2303:     x[j]=1;
 2304:     lubksb(a,npar,indx,x);
 2305:     for (i=1;i<=npar;i++){ 
 2306:       y[i][j]=x[i];
 2307:       printf("%.3e ",y[i][j]);
 2308:       fprintf(ficlog,"%.3e ",y[i][j]);
 2309:     }
 2310:     printf("\n");
 2311:     fprintf(ficlog,"\n");
 2312:   }
 2313:   */
 2314: 
 2315:   free_matrix(a,1,npar,1,npar);
 2316:   free_matrix(y,1,npar,1,npar);
 2317:   free_vector(x,1,npar);
 2318:   free_ivector(indx,1,npar);
 2319:   free_matrix(hess,1,npar,1,npar);
 2320: 
 2321: 
 2322: }
 2323: 
 2324: /*************** hessian matrix ****************/
 2325: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
 2326: {
 2327:   int i;
 2328:   int l=1, lmax=20;
 2329:   double k1,k2;
 2330:   double p2[MAXPARM+1]; /* identical to x */
 2331:   double res;
 2332:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 2333:   double fx;
 2334:   int k=0,kmax=10;
 2335:   double l1;
 2336: 
 2337:   fx=func(x);
 2338:   for (i=1;i<=npar;i++) p2[i]=x[i];
 2339:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
 2340:     l1=pow(10,l);
 2341:     delts=delt;
 2342:     for(k=1 ; k <kmax; k=k+1){
 2343:       delt = delta*(l1*k);
 2344:       p2[theta]=x[theta] +delt;
 2345:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
 2346:       p2[theta]=x[theta]-delt;
 2347:       k2=func(p2)-fx;
 2348:       /*res= (k1-2.0*fx+k2)/delt/delt; */
 2349:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
 2350:       
 2351: #ifdef DEBUGHESS
 2352:       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);
 2353:       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);
 2354: #endif
 2355:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
 2356:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 2357: 	k=kmax;
 2358:       }
 2359:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
 2360: 	k=kmax; l=lmax*10;
 2361:       }
 2362:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
 2363: 	delts=delt;
 2364:       }
 2365:     }
 2366:   }
 2367:   delti[theta]=delts;
 2368:   return res; 
 2369:   
 2370: }
 2371: 
 2372: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
 2373: {
 2374:   int i;
 2375:   int l=1, lmax=20;
 2376:   double k1,k2,k3,k4,res,fx;
 2377:   double p2[MAXPARM+1];
 2378:   int k;
 2379: 
 2380:   fx=func(x);
 2381:   for (k=1; k<=2; k++) {
 2382:     for (i=1;i<=npar;i++) p2[i]=x[i];
 2383:     p2[thetai]=x[thetai]+delti[thetai]/k;
 2384:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 2385:     k1=func(p2)-fx;
 2386:   
 2387:     p2[thetai]=x[thetai]+delti[thetai]/k;
 2388:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 2389:     k2=func(p2)-fx;
 2390:   
 2391:     p2[thetai]=x[thetai]-delti[thetai]/k;
 2392:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 2393:     k3=func(p2)-fx;
 2394:   
 2395:     p2[thetai]=x[thetai]-delti[thetai]/k;
 2396:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 2397:     k4=func(p2)-fx;
 2398:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
 2399: #ifdef DEBUG
 2400:     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);
 2401:     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);
 2402: #endif
 2403:   }
 2404:   return res;
 2405: }
 2406: 
 2407: /************** Inverse of matrix **************/
 2408: void ludcmp(double **a, int n, int *indx, double *d) 
 2409: { 
 2410:   int i,imax,j,k; 
 2411:   double big,dum,sum,temp; 
 2412:   double *vv; 
 2413:  
 2414:   vv=vector(1,n); 
 2415:   *d=1.0; 
 2416:   for (i=1;i<=n;i++) { 
 2417:     big=0.0; 
 2418:     for (j=1;j<=n;j++) 
 2419:       if ((temp=fabs(a[i][j])) > big) big=temp; 
 2420:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
 2421:     vv[i]=1.0/big; 
 2422:   } 
 2423:   for (j=1;j<=n;j++) { 
 2424:     for (i=1;i<j;i++) { 
 2425:       sum=a[i][j]; 
 2426:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
 2427:       a[i][j]=sum; 
 2428:     } 
 2429:     big=0.0; 
 2430:     for (i=j;i<=n;i++) { 
 2431:       sum=a[i][j]; 
 2432:       for (k=1;k<j;k++) 
 2433: 	sum -= a[i][k]*a[k][j]; 
 2434:       a[i][j]=sum; 
 2435:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
 2436: 	big=dum; 
 2437: 	imax=i; 
 2438:       } 
 2439:     } 
 2440:     if (j != imax) { 
 2441:       for (k=1;k<=n;k++) { 
 2442: 	dum=a[imax][k]; 
 2443: 	a[imax][k]=a[j][k]; 
 2444: 	a[j][k]=dum; 
 2445:       } 
 2446:       *d = -(*d); 
 2447:       vv[imax]=vv[j]; 
 2448:     } 
 2449:     indx[j]=imax; 
 2450:     if (a[j][j] == 0.0) a[j][j]=TINY; 
 2451:     if (j != n) { 
 2452:       dum=1.0/(a[j][j]); 
 2453:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
 2454:     } 
 2455:   } 
 2456:   free_vector(vv,1,n);  /* Doesn't work */
 2457: ;
 2458: } 
 2459: 
 2460: void lubksb(double **a, int n, int *indx, double b[]) 
 2461: { 
 2462:   int i,ii=0,ip,j; 
 2463:   double sum; 
 2464:  
 2465:   for (i=1;i<=n;i++) { 
 2466:     ip=indx[i]; 
 2467:     sum=b[ip]; 
 2468:     b[ip]=b[i]; 
 2469:     if (ii) 
 2470:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
 2471:     else if (sum) ii=i; 
 2472:     b[i]=sum; 
 2473:   } 
 2474:   for (i=n;i>=1;i--) { 
 2475:     sum=b[i]; 
 2476:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
 2477:     b[i]=sum/a[i][i]; 
 2478:   } 
 2479: } 
 2480: 
 2481: void pstamp(FILE *fichier)
 2482: {
 2483:   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
 2484: }
 2485: 
 2486: /************ Frequencies ********************/
 2487: 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[])
 2488: {  /* Some frequencies */
 2489:   
 2490:   int i, m, jk, j1, bool, z1,j;
 2491:   int first;
 2492:   double ***freq; /* Frequencies */
 2493:   double *pp, **prop;
 2494:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
 2495:   char fileresp[FILENAMELENGTH];
 2496:   
 2497:   pp=vector(1,nlstate);
 2498:   prop=matrix(1,nlstate,iagemin,iagemax+3);
 2499:   strcpy(fileresp,"p");
 2500:   strcat(fileresp,fileres);
 2501:   if((ficresp=fopen(fileresp,"w"))==NULL) {
 2502:     printf("Problem with prevalence resultfile: %s\n", fileresp);
 2503:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
 2504:     exit(0);
 2505:   }
 2506:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
 2507:   j1=0;
 2508:   
 2509:   j=cptcoveff;
 2510:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 2511: 
 2512:   first=1;
 2513: 
 2514:   /* for(k1=1; k1<=j ; k1++){   /* Loop on covariates */
 2515:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ /* Now it is 2 */
 2516:   /*    j1++;
 2517: */
 2518:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
 2519:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
 2520: 	scanf("%d", i);*/
 2521:       for (i=-5; i<=nlstate+ndeath; i++)  
 2522: 	for (jk=-5; jk<=nlstate+ndeath; jk++)  
 2523: 	  for(m=iagemin; m <= iagemax+3; m++)
 2524: 	    freq[i][jk][m]=0;
 2525:       
 2526:       for (i=1; i<=nlstate; i++)  
 2527: 	for(m=iagemin; m <= iagemax+3; m++)
 2528: 	  prop[i][m]=0;
 2529:       
 2530:       dateintsum=0;
 2531:       k2cpt=0;
 2532:       for (i=1; i<=imx; i++) {
 2533: 	bool=1;
 2534: 	if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
 2535: 	  for (z1=1; z1<=cptcoveff; z1++)       
 2536:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
 2537:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
 2538:               bool=0;
 2539:               /* printf("bool=%d i=%d, z1=%d, Tvaraff[%d]=%d, covar[Tvarff][%d]=%2f, codtab[%d][%d]=%d, nbcode[Tvaraff][codtab[%d][%d]=%d, j1=%d\n", 
 2540:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
 2541:                 j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
 2542:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
 2543:             } 
 2544: 	}
 2545:  
 2546: 	if (bool==1){
 2547: 	  for(m=firstpass; m<=lastpass; m++){
 2548: 	    k2=anint[m][i]+(mint[m][i]/12.);
 2549: 	    /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
 2550: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 2551: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 2552: 	      if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
 2553: 	      if (m<lastpass) {
 2554: 		freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
 2555: 		freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
 2556: 	      }
 2557: 	      
 2558: 	      if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
 2559: 		dateintsum=dateintsum+k2;
 2560: 		k2cpt++;
 2561: 	      }
 2562: 	      /*}*/
 2563: 	  }
 2564: 	}
 2565:       } /* end i */
 2566:        
 2567:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 2568:       pstamp(ficresp);
 2569:       if  (cptcovn>0) {
 2570: 	fprintf(ficresp, "\n#********** Variable "); 
 2571: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2572: 	fprintf(ficresp, "**********\n#");
 2573: 	fprintf(ficlog, "\n#********** Variable "); 
 2574: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2575: 	fprintf(ficlog, "**********\n#");
 2576:       }
 2577:       for(i=1; i<=nlstate;i++) 
 2578: 	fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
 2579:       fprintf(ficresp, "\n");
 2580:       
 2581:       for(i=iagemin; i <= iagemax+3; i++){
 2582: 	if(i==iagemax+3){
 2583: 	  fprintf(ficlog,"Total");
 2584: 	}else{
 2585: 	  if(first==1){
 2586: 	    first=0;
 2587: 	    printf("See log file for details...\n");
 2588: 	  }
 2589: 	  fprintf(ficlog,"Age %d", i);
 2590: 	}
 2591: 	for(jk=1; jk <=nlstate ; jk++){
 2592: 	  for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
 2593: 	    pp[jk] += freq[jk][m][i]; 
 2594: 	}
 2595: 	for(jk=1; jk <=nlstate ; jk++){
 2596: 	  for(m=-1, pos=0; m <=0 ; m++)
 2597: 	    pos += freq[jk][m][i];
 2598: 	  if(pp[jk]>=1.e-10){
 2599: 	    if(first==1){
 2600: 	      printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 2601: 	    }
 2602: 	    fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 2603: 	  }else{
 2604: 	    if(first==1)
 2605: 	      printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 2606: 	    fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 2607: 	  }
 2608: 	}
 2609: 
 2610: 	for(jk=1; jk <=nlstate ; jk++){
 2611: 	  for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
 2612: 	    pp[jk] += freq[jk][m][i];
 2613: 	}	
 2614: 	for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
 2615: 	  pos += pp[jk];
 2616: 	  posprop += prop[jk][i];
 2617: 	}
 2618: 	for(jk=1; jk <=nlstate ; jk++){
 2619: 	  if(pos>=1.e-5){
 2620: 	    if(first==1)
 2621: 	      printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 2622: 	    fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 2623: 	  }else{
 2624: 	    if(first==1)
 2625: 	      printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 2626: 	    fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 2627: 	  }
 2628: 	  if( i <= iagemax){
 2629: 	    if(pos>=1.e-5){
 2630: 	      fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
 2631: 	      /*probs[i][jk][j1]= pp[jk]/pos;*/
 2632: 	      /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
 2633: 	    }
 2634: 	    else
 2635: 	      fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
 2636: 	  }
 2637: 	}
 2638: 	
 2639: 	for(jk=-1; jk <=nlstate+ndeath; jk++)
 2640: 	  for(m=-1; m <=nlstate+ndeath; m++)
 2641: 	    if(freq[jk][m][i] !=0 ) {
 2642: 	    if(first==1)
 2643: 	      printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
 2644: 	      fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
 2645: 	    }
 2646: 	if(i <= iagemax)
 2647: 	  fprintf(ficresp,"\n");
 2648: 	if(first==1)
 2649: 	  printf("Others in log...\n");
 2650: 	fprintf(ficlog,"\n");
 2651:       }
 2652:       /*}*/
 2653:   }
 2654:   dateintmean=dateintsum/k2cpt; 
 2655:  
 2656:   fclose(ficresp);
 2657:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
 2658:   free_vector(pp,1,nlstate);
 2659:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
 2660:   /* End of Freq */
 2661: }
 2662: 
 2663: /************ Prevalence ********************/
 2664: 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)
 2665: {  
 2666:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 2667:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 2668:      We still use firstpass and lastpass as another selection.
 2669:   */
 2670:  
 2671:   int i, m, jk, j1, bool, z1,j;
 2672: 
 2673:   double **prop;
 2674:   double posprop; 
 2675:   double  y2; /* in fractional years */
 2676:   int iagemin, iagemax;
 2677:   int first; /** to stop verbosity which is redirected to log file */
 2678: 
 2679:   iagemin= (int) agemin;
 2680:   iagemax= (int) agemax;
 2681:   /*pp=vector(1,nlstate);*/
 2682:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
 2683:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
 2684:   j1=0;
 2685:   
 2686:   /*j=cptcoveff;*/
 2687:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 2688:   
 2689:   first=1;
 2690:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
 2691:     /*for(i1=1; i1<=ncodemax[k1];i1++){
 2692:       j1++;*/
 2693:       
 2694:       for (i=1; i<=nlstate; i++)  
 2695: 	for(m=iagemin; m <= iagemax+3; m++)
 2696: 	  prop[i][m]=0.0;
 2697:      
 2698:       for (i=1; i<=imx; i++) { /* Each individual */
 2699: 	bool=1;
 2700: 	if  (cptcovn>0) {
 2701: 	  for (z1=1; z1<=cptcoveff; z1++) 
 2702: 	    if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
 2703: 	      bool=0;
 2704: 	} 
 2705: 	if (bool==1) { 
 2706: 	  for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
 2707: 	    y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
 2708: 	    if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
 2709: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 2710: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 2711: 	      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); 
 2712:  	      if (s[m][i]>0 && s[m][i]<=nlstate) { 
 2713: 		/*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]]);*/
 2714:  		prop[s[m][i]][(int)agev[m][i]] += weight[i];
 2715:  		prop[s[m][i]][iagemax+3] += weight[i]; 
 2716:  	      } 
 2717: 	    }
 2718: 	  } /* end selection of waves */
 2719: 	}
 2720:       }
 2721:       for(i=iagemin; i <= iagemax+3; i++){  
 2722:  	for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
 2723:  	  posprop += prop[jk][i]; 
 2724:  	} 
 2725: 	
 2726:  	for(jk=1; jk <=nlstate ; jk++){	    
 2727:  	  if( i <=  iagemax){ 
 2728:  	    if(posprop>=1.e-5){ 
 2729:  	      probs[i][jk][j1]= prop[jk][i]/posprop;
 2730:  	    } else{
 2731: 	      if(first==1){
 2732: 		first=0;
 2733: 		printf("Warning Observed prevalence probs[%d][%d][%d]=%lf because of lack of cases\nSee others on log file...\n",jk,i,j1,probs[i][jk][j1]);
 2734: 	      }
 2735: 	    }
 2736:  	  } 
 2737:  	}/* end jk */ 
 2738:       }/* end i */ 
 2739:     /*} *//* end i1 */
 2740:   } /* end j1 */
 2741:   
 2742:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
 2743:   /*free_vector(pp,1,nlstate);*/
 2744:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
 2745: }  /* End of prevalence */
 2746: 
 2747: /************* Waves Concatenation ***************/
 2748: 
 2749: 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)
 2750: {
 2751:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 2752:      Death is a valid wave (if date is known).
 2753:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
 2754:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 2755:      and mw[mi+1][i]. dh depends on stepm.
 2756:      */
 2757: 
 2758:   int i, mi, m;
 2759:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
 2760:      double sum=0., jmean=0.;*/
 2761:   int first;
 2762:   int j, k=0,jk, ju, jl;
 2763:   double sum=0.;
 2764:   first=0;
 2765:   jmin=100000;
 2766:   jmax=-1;
 2767:   jmean=0.;
 2768:   for(i=1; i<=imx; i++){
 2769:     mi=0;
 2770:     m=firstpass;
 2771:     while(s[m][i] <= nlstate){
 2772:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
 2773: 	mw[++mi][i]=m;
 2774:       if(m >=lastpass)
 2775: 	break;
 2776:       else
 2777: 	m++;
 2778:     }/* end while */
 2779:     if (s[m][i] > nlstate){
 2780:       mi++;	/* Death is another wave */
 2781:       /* if(mi==0)  never been interviewed correctly before death */
 2782: 	 /* Only death is a correct wave */
 2783:       mw[mi][i]=m;
 2784:     }
 2785: 
 2786:     wav[i]=mi;
 2787:     if(mi==0){
 2788:       nbwarn++;
 2789:       if(first==0){
 2790: 	printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
 2791: 	first=1;
 2792:       }
 2793:       if(first==1){
 2794: 	fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
 2795:       }
 2796:     } /* end mi==0 */
 2797:   } /* End individuals */
 2798: 
 2799:   for(i=1; i<=imx; i++){
 2800:     for(mi=1; mi<wav[i];mi++){
 2801:       if (stepm <=0)
 2802: 	dh[mi][i]=1;
 2803:       else{
 2804: 	if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
 2805: 	  if (agedc[i] < 2*AGESUP) {
 2806: 	    j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
 2807: 	    if(j==0) j=1;  /* Survives at least one month after exam */
 2808: 	    else if(j<0){
 2809: 	      nberr++;
 2810: 	      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]);
 2811: 	      j=1; /* Temporary Dangerous patch */
 2812: 	      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);
 2813: 	      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]);
 2814: 	      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);
 2815: 	    }
 2816: 	    k=k+1;
 2817: 	    if (j >= jmax){
 2818: 	      jmax=j;
 2819: 	      ijmax=i;
 2820: 	    }
 2821: 	    if (j <= jmin){
 2822: 	      jmin=j;
 2823: 	      ijmin=i;
 2824: 	    }
 2825: 	    sum=sum+j;
 2826: 	    /*if (j<0) printf("j=%d num=%d \n",j,i);*/
 2827: 	    /*	  printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
 2828: 	  }
 2829: 	}
 2830: 	else{
 2831: 	  j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 2832: /* 	  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]); */
 2833: 
 2834: 	  k=k+1;
 2835: 	  if (j >= jmax) {
 2836: 	    jmax=j;
 2837: 	    ijmax=i;
 2838: 	  }
 2839: 	  else if (j <= jmin){
 2840: 	    jmin=j;
 2841: 	    ijmin=i;
 2842: 	  }
 2843: 	  /*	    if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
 2844: 	  /*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]);*/
 2845: 	  if(j<0){
 2846: 	    nberr++;
 2847: 	    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]);
 2848: 	    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]);
 2849: 	  }
 2850: 	  sum=sum+j;
 2851: 	}
 2852: 	jk= j/stepm;
 2853: 	jl= j -jk*stepm;
 2854: 	ju= j -(jk+1)*stepm;
 2855: 	if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
 2856: 	  if(jl==0){
 2857: 	    dh[mi][i]=jk;
 2858: 	    bh[mi][i]=0;
 2859: 	  }else{ /* We want a negative bias in order to only have interpolation ie
 2860: 		  * to avoid the price of an extra matrix product in likelihood */
 2861: 	    dh[mi][i]=jk+1;
 2862: 	    bh[mi][i]=ju;
 2863: 	  }
 2864: 	}else{
 2865: 	  if(jl <= -ju){
 2866: 	    dh[mi][i]=jk;
 2867: 	    bh[mi][i]=jl;	/* bias is positive if real duration
 2868: 				 * is higher than the multiple of stepm and negative otherwise.
 2869: 				 */
 2870: 	  }
 2871: 	  else{
 2872: 	    dh[mi][i]=jk+1;
 2873: 	    bh[mi][i]=ju;
 2874: 	  }
 2875: 	  if(dh[mi][i]==0){
 2876: 	    dh[mi][i]=1; /* At least one step */
 2877: 	    bh[mi][i]=ju; /* At least one step */
 2878: 	    /*  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);*/
 2879: 	  }
 2880: 	} /* end if mle */
 2881:       }
 2882:     } /* end wave */
 2883:   }
 2884:   jmean=sum/k;
 2885:   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);
 2886:   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);
 2887:  }
 2888: 
 2889: /*********** Tricode ****************************/
 2890: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
 2891: {
 2892:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
 2893:   /*	  Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
 2894:   /* Boring subroutine which should only output nbcode[Tvar[j]][k]
 2895:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
 2896:   /* nbcode[Tvar[j]][1]= 
 2897:   */
 2898: 
 2899:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
 2900:   int modmaxcovj=0; /* Modality max of covariates j */
 2901:   int cptcode=0; /* Modality max of covariates j */
 2902:   int modmincovj=0; /* Modality min of covariates j */
 2903: 
 2904: 
 2905:   cptcoveff=0; 
 2906:  
 2907:   for (k=-1; k < maxncov; k++) Ndum[k]=0;
 2908:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
 2909: 
 2910:   /* Loop on covariates without age and products */
 2911:   for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
 2912:     for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the 
 2913: 			       modality of this covariate Vj*/ 
 2914:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
 2915: 				    * If product of Vn*Vm, still boolean *:
 2916: 				    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
 2917: 				    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
 2918:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
 2919: 				      modality of the nth covariate of individual i. */
 2920:       if (ij > modmaxcovj)
 2921:         modmaxcovj=ij; 
 2922:       else if (ij < modmincovj) 
 2923: 	modmincovj=ij; 
 2924:       if ((ij < -1) && (ij > NCOVMAX)){
 2925: 	printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
 2926: 	exit(1);
 2927:       }else
 2928:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
 2929:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
 2930:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
 2931:       /* getting the maximum value of the modality of the covariate
 2932: 	 (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
 2933: 	 female is 1, then modmaxcovj=1.*/
 2934:     }
 2935:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
 2936:     cptcode=modmaxcovj;
 2937:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
 2938:    /*for (i=0; i<=cptcode; i++) {*/
 2939:     for (i=modmincovj;  i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
 2940:       printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
 2941:       if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
 2942: 	ncodemax[j]++;  /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
 2943:       }
 2944:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
 2945: 	 historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
 2946:     } /* Ndum[-1] number of undefined modalities */
 2947: 
 2948:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
 2949:     /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
 2950:     /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
 2951:        modmincovj=3; modmaxcovj = 7;
 2952:        There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
 2953:        which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy 
 2954:        variables V1_1 and V1_2.
 2955:        nbcode[Tvar[j]][ij]=k;
 2956:        nbcode[Tvar[j]][1]=0;
 2957:        nbcode[Tvar[j]][2]=1;
 2958:        nbcode[Tvar[j]][3]=2;
 2959:     */
 2960:     ij=1; /* ij is similar to i but can jumps over null modalities */
 2961:     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
 2962:       for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
 2963: 	/*recode from 0 */
 2964: 	if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
 2965: 	  nbcode[Tvar[j]][ij]=k;  /* stores the modality in an array nbcode. 
 2966: 				     k is a modality. If we have model=V1+V1*sex 
 2967: 				     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
 2968: 	  ij++;
 2969: 	}
 2970: 	if (ij > ncodemax[j]) break; 
 2971:       }  /* end of loop on */
 2972:     } /* end of loop on modality */ 
 2973:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
 2974:   
 2975:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
 2976:   
 2977:   for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */ 
 2978:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
 2979:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
 2980:    Ndum[ij]++; 
 2981:  } 
 2982: 
 2983:  ij=1;
 2984:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
 2985:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
 2986:    if((Ndum[i]!=0) && (i<=ncovcol)){
 2987:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
 2988:      Tvaraff[ij]=i; /*For printing (unclear) */
 2989:      ij++;
 2990:    }else
 2991:        Tvaraff[ij]=0;
 2992:  }
 2993:  ij--;
 2994:  cptcoveff=ij; /*Number of total covariates*/
 2995: 
 2996: }
 2997: 
 2998: 
 2999: /*********** Health Expectancies ****************/
 3000: 
 3001: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
 3002: 
 3003: {
 3004:   /* Health expectancies, no variances */
 3005:   int i, j, nhstepm, hstepm, h, nstepm;
 3006:   int nhstepma, nstepma; /* Decreasing with age */
 3007:   double age, agelim, hf;
 3008:   double ***p3mat;
 3009:   double eip;
 3010: 
 3011:   pstamp(ficreseij);
 3012:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
 3013:   fprintf(ficreseij,"# Age");
 3014:   for(i=1; i<=nlstate;i++){
 3015:     for(j=1; j<=nlstate;j++){
 3016:       fprintf(ficreseij," e%1d%1d ",i,j);
 3017:     }
 3018:     fprintf(ficreseij," e%1d. ",i);
 3019:   }
 3020:   fprintf(ficreseij,"\n");
 3021: 
 3022:   
 3023:   if(estepm < stepm){
 3024:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3025:   }
 3026:   else  hstepm=estepm;   
 3027:   /* We compute the life expectancy from trapezoids spaced every estepm months
 3028:    * This is mainly to measure the difference between two models: for example
 3029:    * if stepm=24 months pijx are given only every 2 years and by summing them
 3030:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 3031:    * progression in between and thus overestimating or underestimating according
 3032:    * to the curvature of the survival function. If, for the same date, we 
 3033:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 3034:    * to compare the new estimate of Life expectancy with the same linear 
 3035:    * hypothesis. A more precise result, taking into account a more precise
 3036:    * curvature will be obtained if estepm is as small as stepm. */
 3037: 
 3038:   /* For example we decided to compute the life expectancy with the smallest unit */
 3039:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3040:      nhstepm is the number of hstepm from age to agelim 
 3041:      nstepm is the number of stepm from age to agelin. 
 3042:      Look at hpijx to understand the reason of that which relies in memory size
 3043:      and note for a fixed period like estepm months */
 3044:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3045:      survival function given by stepm (the optimization length). Unfortunately it
 3046:      means that if the survival funtion is printed only each two years of age and if
 3047:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3048:      results. So we changed our mind and took the option of the best precision.
 3049:   */
 3050:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3051: 
 3052:   agelim=AGESUP;
 3053:   /* If stepm=6 months */
 3054:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
 3055:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 3056:     
 3057: /* nhstepm age range expressed in number of stepm */
 3058:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3059:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3060:   /* if (stepm >= YEARM) hstepm=1;*/
 3061:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3062:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3063: 
 3064:   for (age=bage; age<=fage; age ++){ 
 3065:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3066:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3067:     /* if (stepm >= YEARM) hstepm=1;*/
 3068:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 3069: 
 3070:     /* If stepm=6 months */
 3071:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 3072:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 3073:     
 3074:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 3075:     
 3076:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3077:     
 3078:     printf("%d|",(int)age);fflush(stdout);
 3079:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 3080:     
 3081:     /* Computing expectancies */
 3082:     for(i=1; i<=nlstate;i++)
 3083:       for(j=1; j<=nlstate;j++)
 3084: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 3085: 	  eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
 3086: 	  
 3087: 	  /* 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]);*/
 3088: 
 3089: 	}
 3090: 
 3091:     fprintf(ficreseij,"%3.0f",age );
 3092:     for(i=1; i<=nlstate;i++){
 3093:       eip=0;
 3094:       for(j=1; j<=nlstate;j++){
 3095: 	eip +=eij[i][j][(int)age];
 3096: 	fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
 3097:       }
 3098:       fprintf(ficreseij,"%9.4f", eip );
 3099:     }
 3100:     fprintf(ficreseij,"\n");
 3101:     
 3102:   }
 3103:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3104:   printf("\n");
 3105:   fprintf(ficlog,"\n");
 3106:   
 3107: }
 3108: 
 3109: 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[] )
 3110: 
 3111: {
 3112:   /* Covariances of health expectancies eij and of total life expectancies according
 3113:    to initial status i, ei. .
 3114:   */
 3115:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
 3116:   int nhstepma, nstepma; /* Decreasing with age */
 3117:   double age, agelim, hf;
 3118:   double ***p3matp, ***p3matm, ***varhe;
 3119:   double **dnewm,**doldm;
 3120:   double *xp, *xm;
 3121:   double **gp, **gm;
 3122:   double ***gradg, ***trgradg;
 3123:   int theta;
 3124: 
 3125:   double eip, vip;
 3126: 
 3127:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
 3128:   xp=vector(1,npar);
 3129:   xm=vector(1,npar);
 3130:   dnewm=matrix(1,nlstate*nlstate,1,npar);
 3131:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
 3132:   
 3133:   pstamp(ficresstdeij);
 3134:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
 3135:   fprintf(ficresstdeij,"# Age");
 3136:   for(i=1; i<=nlstate;i++){
 3137:     for(j=1; j<=nlstate;j++)
 3138:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
 3139:     fprintf(ficresstdeij," e%1d. ",i);
 3140:   }
 3141:   fprintf(ficresstdeij,"\n");
 3142: 
 3143:   pstamp(ficrescveij);
 3144:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
 3145:   fprintf(ficrescveij,"# Age");
 3146:   for(i=1; i<=nlstate;i++)
 3147:     for(j=1; j<=nlstate;j++){
 3148:       cptj= (j-1)*nlstate+i;
 3149:       for(i2=1; i2<=nlstate;i2++)
 3150: 	for(j2=1; j2<=nlstate;j2++){
 3151: 	  cptj2= (j2-1)*nlstate+i2;
 3152: 	  if(cptj2 <= cptj)
 3153: 	    fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
 3154: 	}
 3155:     }
 3156:   fprintf(ficrescveij,"\n");
 3157:   
 3158:   if(estepm < stepm){
 3159:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3160:   }
 3161:   else  hstepm=estepm;   
 3162:   /* We compute the life expectancy from trapezoids spaced every estepm months
 3163:    * This is mainly to measure the difference between two models: for example
 3164:    * if stepm=24 months pijx are given only every 2 years and by summing them
 3165:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 3166:    * progression in between and thus overestimating or underestimating according
 3167:    * to the curvature of the survival function. If, for the same date, we 
 3168:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 3169:    * to compare the new estimate of Life expectancy with the same linear 
 3170:    * hypothesis. A more precise result, taking into account a more precise
 3171:    * curvature will be obtained if estepm is as small as stepm. */
 3172: 
 3173:   /* For example we decided to compute the life expectancy with the smallest unit */
 3174:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3175:      nhstepm is the number of hstepm from age to agelim 
 3176:      nstepm is the number of stepm from age to agelin. 
 3177:      Look at hpijx to understand the reason of that which relies in memory size
 3178:      and note for a fixed period like estepm months */
 3179:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3180:      survival function given by stepm (the optimization length). Unfortunately it
 3181:      means that if the survival funtion is printed only each two years of age and if
 3182:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3183:      results. So we changed our mind and took the option of the best precision.
 3184:   */
 3185:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3186: 
 3187:   /* If stepm=6 months */
 3188:   /* nhstepm age range expressed in number of stepm */
 3189:   agelim=AGESUP;
 3190:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
 3191:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3192:   /* if (stepm >= YEARM) hstepm=1;*/
 3193:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3194:   
 3195:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3196:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3197:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
 3198:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
 3199:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
 3200:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
 3201: 
 3202:   for (age=bage; age<=fage; age ++){ 
 3203:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3204:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3205:     /* if (stepm >= YEARM) hstepm=1;*/
 3206:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 3207: 
 3208:     /* If stepm=6 months */
 3209:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 3210:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 3211:     
 3212:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3213: 
 3214:     /* Computing  Variances of health expectancies */
 3215:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
 3216:        decrease memory allocation */
 3217:     for(theta=1; theta <=npar; theta++){
 3218:       for(i=1; i<=npar; i++){ 
 3219: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3220: 	xm[i] = x[i] - (i==theta ?delti[theta]:0);
 3221:       }
 3222:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
 3223:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
 3224:   
 3225:       for(j=1; j<= nlstate; j++){
 3226: 	for(i=1; i<=nlstate; i++){
 3227: 	  for(h=0; h<=nhstepm-1; h++){
 3228: 	    gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
 3229: 	    gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
 3230: 	  }
 3231: 	}
 3232:       }
 3233:      
 3234:       for(ij=1; ij<= nlstate*nlstate; ij++)
 3235: 	for(h=0; h<=nhstepm-1; h++){
 3236: 	  gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
 3237: 	}
 3238:     }/* End theta */
 3239:     
 3240:     
 3241:     for(h=0; h<=nhstepm-1; h++)
 3242:       for(j=1; j<=nlstate*nlstate;j++)
 3243: 	for(theta=1; theta <=npar; theta++)
 3244: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 3245:     
 3246: 
 3247:      for(ij=1;ij<=nlstate*nlstate;ij++)
 3248:       for(ji=1;ji<=nlstate*nlstate;ji++)
 3249: 	varhe[ij][ji][(int)age] =0.;
 3250: 
 3251:      printf("%d|",(int)age);fflush(stdout);
 3252:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 3253:      for(h=0;h<=nhstepm-1;h++){
 3254:       for(k=0;k<=nhstepm-1;k++){
 3255: 	matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
 3256: 	matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
 3257: 	for(ij=1;ij<=nlstate*nlstate;ij++)
 3258: 	  for(ji=1;ji<=nlstate*nlstate;ji++)
 3259: 	    varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
 3260:       }
 3261:     }
 3262: 
 3263:     /* Computing expectancies */
 3264:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 3265:     for(i=1; i<=nlstate;i++)
 3266:       for(j=1; j<=nlstate;j++)
 3267: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 3268: 	  eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
 3269: 	  
 3270: 	  /* 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]);*/
 3271: 
 3272: 	}
 3273: 
 3274:     fprintf(ficresstdeij,"%3.0f",age );
 3275:     for(i=1; i<=nlstate;i++){
 3276:       eip=0.;
 3277:       vip=0.;
 3278:       for(j=1; j<=nlstate;j++){
 3279: 	eip += eij[i][j][(int)age];
 3280: 	for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
 3281: 	  vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
 3282: 	fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
 3283:       }
 3284:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
 3285:     }
 3286:     fprintf(ficresstdeij,"\n");
 3287: 
 3288:     fprintf(ficrescveij,"%3.0f",age );
 3289:     for(i=1; i<=nlstate;i++)
 3290:       for(j=1; j<=nlstate;j++){
 3291: 	cptj= (j-1)*nlstate+i;
 3292: 	for(i2=1; i2<=nlstate;i2++)
 3293: 	  for(j2=1; j2<=nlstate;j2++){
 3294: 	    cptj2= (j2-1)*nlstate+i2;
 3295: 	    if(cptj2 <= cptj)
 3296: 	      fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
 3297: 	  }
 3298:       }
 3299:     fprintf(ficrescveij,"\n");
 3300:    
 3301:   }
 3302:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
 3303:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
 3304:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
 3305:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
 3306:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3307:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3308:   printf("\n");
 3309:   fprintf(ficlog,"\n");
 3310: 
 3311:   free_vector(xm,1,npar);
 3312:   free_vector(xp,1,npar);
 3313:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
 3314:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
 3315:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
 3316: }
 3317: 
 3318: /************ Variance ******************/
 3319: 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[])
 3320: {
 3321:   /* Variance of health expectancies */
 3322:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
 3323:   /* double **newm;*/
 3324:   double **dnewm,**doldm;
 3325:   double **dnewmp,**doldmp;
 3326:   int i, j, nhstepm, hstepm, h, nstepm ;
 3327:   int k;
 3328:   double *xp;
 3329:   double **gp, **gm;  /* for var eij */
 3330:   double ***gradg, ***trgradg; /*for var eij */
 3331:   double **gradgp, **trgradgp; /* for var p point j */
 3332:   double *gpp, *gmp; /* for var p point j */
 3333:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
 3334:   double ***p3mat;
 3335:   double age,agelim, hf;
 3336:   double ***mobaverage;
 3337:   int theta;
 3338:   char digit[4];
 3339:   char digitp[25];
 3340: 
 3341:   char fileresprobmorprev[FILENAMELENGTH];
 3342: 
 3343:   if(popbased==1){
 3344:     if(mobilav!=0)
 3345:       strcpy(digitp,"-populbased-mobilav-");
 3346:     else strcpy(digitp,"-populbased-nomobil-");
 3347:   }
 3348:   else 
 3349:     strcpy(digitp,"-stablbased-");
 3350: 
 3351:   if (mobilav!=0) {
 3352:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3353:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 3354:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 3355:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 3356:     }
 3357:   }
 3358: 
 3359:   strcpy(fileresprobmorprev,"prmorprev"); 
 3360:   sprintf(digit,"%-d",ij);
 3361:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
 3362:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
 3363:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
 3364:   strcat(fileresprobmorprev,fileres);
 3365:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
 3366:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
 3367:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
 3368:   }
 3369:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 3370:  
 3371:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 3372:   pstamp(ficresprobmorprev);
 3373:   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);
 3374:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
 3375:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 3376:     fprintf(ficresprobmorprev," p.%-d SE",j);
 3377:     for(i=1; i<=nlstate;i++)
 3378:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 3379:   }  
 3380:   fprintf(ficresprobmorprev,"\n");
 3381:   fprintf(ficgp,"\n# Routine varevsij");
 3382:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
 3383:   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");
 3384:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
 3385: /*   } */
 3386:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3387:   pstamp(ficresvij);
 3388:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
 3389:   if(popbased==1)
 3390:     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);
 3391:   else
 3392:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
 3393:   fprintf(ficresvij,"# Age");
 3394:   for(i=1; i<=nlstate;i++)
 3395:     for(j=1; j<=nlstate;j++)
 3396:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
 3397:   fprintf(ficresvij,"\n");
 3398: 
 3399:   xp=vector(1,npar);
 3400:   dnewm=matrix(1,nlstate,1,npar);
 3401:   doldm=matrix(1,nlstate,1,nlstate);
 3402:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
 3403:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3404: 
 3405:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
 3406:   gpp=vector(nlstate+1,nlstate+ndeath);
 3407:   gmp=vector(nlstate+1,nlstate+ndeath);
 3408:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 3409:   
 3410:   if(estepm < stepm){
 3411:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3412:   }
 3413:   else  hstepm=estepm;   
 3414:   /* For example we decided to compute the life expectancy with the smallest unit */
 3415:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3416:      nhstepm is the number of hstepm from age to agelim 
 3417:      nstepm is the number of stepm from age to agelin. 
 3418:      Look at function hpijx to understand why (it is linked to memory size questions) */
 3419:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3420:      survival function given by stepm (the optimization length). Unfortunately it
 3421:      means that if the survival funtion is printed every two years of age and if
 3422:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3423:      results. So we changed our mind and took the option of the best precision.
 3424:   */
 3425:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3426:   agelim = AGESUP;
 3427:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 3428:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 3429:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3430:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3431:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
 3432:     gp=matrix(0,nhstepm,1,nlstate);
 3433:     gm=matrix(0,nhstepm,1,nlstate);
 3434: 
 3435: 
 3436:     for(theta=1; theta <=npar; theta++){
 3437:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
 3438: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3439:       }
 3440:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 3441:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3442: 
 3443:       if (popbased==1) {
 3444: 	if(mobilav ==0){
 3445: 	  for(i=1; i<=nlstate;i++)
 3446: 	    prlim[i][i]=probs[(int)age][i][ij];
 3447: 	}else{ /* mobilav */ 
 3448: 	  for(i=1; i<=nlstate;i++)
 3449: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 3450: 	}
 3451:       }
 3452:   
 3453:       for(j=1; j<= nlstate; j++){
 3454: 	for(h=0; h<=nhstepm; h++){
 3455: 	  for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 3456: 	    gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 3457: 	}
 3458:       }
 3459:       /* This for computing probability of death (h=1 means
 3460:          computed over hstepm matrices product = hstepm*stepm months) 
 3461:          as a weighted average of prlim.
 3462:       */
 3463:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3464: 	for(i=1,gpp[j]=0.; i<= nlstate; i++)
 3465: 	  gpp[j] += prlim[i][i]*p3mat[i][j][1];
 3466:       }    
 3467:       /* end probability of death */
 3468: 
 3469:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
 3470: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 3471:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 3472:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3473:  
 3474:       if (popbased==1) {
 3475: 	if(mobilav ==0){
 3476: 	  for(i=1; i<=nlstate;i++)
 3477: 	    prlim[i][i]=probs[(int)age][i][ij];
 3478: 	}else{ /* mobilav */ 
 3479: 	  for(i=1; i<=nlstate;i++)
 3480: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 3481: 	}
 3482:       }
 3483: 
 3484:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
 3485: 	for(h=0; h<=nhstepm; h++){
 3486: 	  for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 3487: 	    gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 3488: 	}
 3489:       }
 3490:       /* This for computing probability of death (h=1 means
 3491:          computed over hstepm matrices product = hstepm*stepm months) 
 3492:          as a weighted average of prlim.
 3493:       */
 3494:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3495: 	for(i=1,gmp[j]=0.; i<= nlstate; i++)
 3496:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
 3497:       }    
 3498:       /* end probability of death */
 3499: 
 3500:       for(j=1; j<= nlstate; j++) /* vareij */
 3501: 	for(h=0; h<=nhstepm; h++){
 3502: 	  gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 3503: 	}
 3504: 
 3505:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
 3506: 	gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
 3507:       }
 3508: 
 3509:     } /* End theta */
 3510: 
 3511:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
 3512: 
 3513:     for(h=0; h<=nhstepm; h++) /* veij */
 3514:       for(j=1; j<=nlstate;j++)
 3515: 	for(theta=1; theta <=npar; theta++)
 3516: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 3517: 
 3518:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
 3519:       for(theta=1; theta <=npar; theta++)
 3520: 	trgradgp[j][theta]=gradgp[theta][j];
 3521:   
 3522: 
 3523:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3524:     for(i=1;i<=nlstate;i++)
 3525:       for(j=1;j<=nlstate;j++)
 3526: 	vareij[i][j][(int)age] =0.;
 3527: 
 3528:     for(h=0;h<=nhstepm;h++){
 3529:       for(k=0;k<=nhstepm;k++){
 3530: 	matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 3531: 	matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
 3532: 	for(i=1;i<=nlstate;i++)
 3533: 	  for(j=1;j<=nlstate;j++)
 3534: 	    vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
 3535:       }
 3536:     }
 3537:   
 3538:     /* pptj */
 3539:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
 3540:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
 3541:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
 3542:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
 3543: 	varppt[j][i]=doldmp[j][i];
 3544:     /* end ppptj */
 3545:     /*  x centered again */
 3546:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
 3547:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
 3548:  
 3549:     if (popbased==1) {
 3550:       if(mobilav ==0){
 3551: 	for(i=1; i<=nlstate;i++)
 3552: 	  prlim[i][i]=probs[(int)age][i][ij];
 3553:       }else{ /* mobilav */ 
 3554: 	for(i=1; i<=nlstate;i++)
 3555: 	  prlim[i][i]=mobaverage[(int)age][i][ij];
 3556:       }
 3557:     }
 3558:              
 3559:     /* This for computing probability of death (h=1 means
 3560:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
 3561:        as a weighted average of prlim.
 3562:     */
 3563:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3564:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
 3565: 	gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
 3566:     }    
 3567:     /* end probability of death */
 3568: 
 3569:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
 3570:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 3571:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
 3572:       for(i=1; i<=nlstate;i++){
 3573: 	fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 3574:       }
 3575:     } 
 3576:     fprintf(ficresprobmorprev,"\n");
 3577: 
 3578:     fprintf(ficresvij,"%.0f ",age );
 3579:     for(i=1; i<=nlstate;i++)
 3580:       for(j=1; j<=nlstate;j++){
 3581: 	fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
 3582:       }
 3583:     fprintf(ficresvij,"\n");
 3584:     free_matrix(gp,0,nhstepm,1,nlstate);
 3585:     free_matrix(gm,0,nhstepm,1,nlstate);
 3586:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 3587:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 3588:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3589:   } /* End age */
 3590:   free_vector(gpp,nlstate+1,nlstate+ndeath);
 3591:   free_vector(gmp,nlstate+1,nlstate+ndeath);
 3592:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
 3593:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 3594:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
 3595:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
 3596:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
 3597: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
 3598: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
 3599: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
 3600:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
 3601:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
 3602:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
 3603:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
 3604:   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);
 3605:   /*  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);
 3606: */
 3607: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
 3608:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
 3609: 
 3610:   free_vector(xp,1,npar);
 3611:   free_matrix(doldm,1,nlstate,1,nlstate);
 3612:   free_matrix(dnewm,1,nlstate,1,npar);
 3613:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3614:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
 3615:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3616:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3617:   fclose(ficresprobmorprev);
 3618:   fflush(ficgp);
 3619:   fflush(fichtm); 
 3620: }  /* end varevsij */
 3621: 
 3622: /************ Variance of prevlim ******************/
 3623: 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[])
 3624: {
 3625:   /* Variance of prevalence limit */
 3626:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 3627: 
 3628:   double **dnewm,**doldm;
 3629:   int i, j, nhstepm, hstepm;
 3630:   double *xp;
 3631:   double *gp, *gm;
 3632:   double **gradg, **trgradg;
 3633:   double age,agelim;
 3634:   int theta;
 3635:   
 3636:   pstamp(ficresvpl);
 3637:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
 3638:   fprintf(ficresvpl,"# Age");
 3639:   for(i=1; i<=nlstate;i++)
 3640:       fprintf(ficresvpl," %1d-%1d",i,i);
 3641:   fprintf(ficresvpl,"\n");
 3642: 
 3643:   xp=vector(1,npar);
 3644:   dnewm=matrix(1,nlstate,1,npar);
 3645:   doldm=matrix(1,nlstate,1,nlstate);
 3646:   
 3647:   hstepm=1*YEARM; /* Every year of age */
 3648:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 3649:   agelim = AGESUP;
 3650:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 3651:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 3652:     if (stepm >= YEARM) hstepm=1;
 3653:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 3654:     gradg=matrix(1,npar,1,nlstate);
 3655:     gp=vector(1,nlstate);
 3656:     gm=vector(1,nlstate);
 3657: 
 3658:     for(theta=1; theta <=npar; theta++){
 3659:       for(i=1; i<=npar; i++){ /* Computes gradient */
 3660: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3661:       }
 3662:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3663:       for(i=1;i<=nlstate;i++)
 3664: 	gp[i] = prlim[i][i];
 3665:     
 3666:       for(i=1; i<=npar; i++) /* Computes gradient */
 3667: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 3668:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3669:       for(i=1;i<=nlstate;i++)
 3670: 	gm[i] = prlim[i][i];
 3671: 
 3672:       for(i=1;i<=nlstate;i++)
 3673: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 3674:     } /* End theta */
 3675: 
 3676:     trgradg =matrix(1,nlstate,1,npar);
 3677: 
 3678:     for(j=1; j<=nlstate;j++)
 3679:       for(theta=1; theta <=npar; theta++)
 3680: 	trgradg[j][theta]=gradg[theta][j];
 3681: 
 3682:     for(i=1;i<=nlstate;i++)
 3683:       varpl[i][(int)age] =0.;
 3684:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 3685:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 3686:     for(i=1;i<=nlstate;i++)
 3687:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 3688: 
 3689:     fprintf(ficresvpl,"%.0f ",age );
 3690:     for(i=1; i<=nlstate;i++)
 3691:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
 3692:     fprintf(ficresvpl,"\n");
 3693:     free_vector(gp,1,nlstate);
 3694:     free_vector(gm,1,nlstate);
 3695:     free_matrix(gradg,1,npar,1,nlstate);
 3696:     free_matrix(trgradg,1,nlstate,1,npar);
 3697:   } /* End age */
 3698: 
 3699:   free_vector(xp,1,npar);
 3700:   free_matrix(doldm,1,nlstate,1,npar);
 3701:   free_matrix(dnewm,1,nlstate,1,nlstate);
 3702: 
 3703: }
 3704: 
 3705: /************ Variance of one-step probabilities  ******************/
 3706: 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[])
 3707: {
 3708:   int i, j=0,  k1, l1, tj;
 3709:   int k2, l2, j1,  z1;
 3710:   int k=0, l;
 3711:   int first=1, first1, first2;
 3712:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
 3713:   double **dnewm,**doldm;
 3714:   double *xp;
 3715:   double *gp, *gm;
 3716:   double **gradg, **trgradg;
 3717:   double **mu;
 3718:   double age, cov[NCOVMAX+1];
 3719:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
 3720:   int theta;
 3721:   char fileresprob[FILENAMELENGTH];
 3722:   char fileresprobcov[FILENAMELENGTH];
 3723:   char fileresprobcor[FILENAMELENGTH];
 3724:   double ***varpij;
 3725: 
 3726:   strcpy(fileresprob,"prob"); 
 3727:   strcat(fileresprob,fileres);
 3728:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
 3729:     printf("Problem with resultfile: %s\n", fileresprob);
 3730:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
 3731:   }
 3732:   strcpy(fileresprobcov,"probcov"); 
 3733:   strcat(fileresprobcov,fileres);
 3734:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
 3735:     printf("Problem with resultfile: %s\n", fileresprobcov);
 3736:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 3737:   }
 3738:   strcpy(fileresprobcor,"probcor"); 
 3739:   strcat(fileresprobcor,fileres);
 3740:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 3741:     printf("Problem with resultfile: %s\n", fileresprobcor);
 3742:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 3743:   }
 3744:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 3745:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 3746:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 3747:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 3748:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 3749:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 3750:   pstamp(ficresprob);
 3751:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
 3752:   fprintf(ficresprob,"# Age");
 3753:   pstamp(ficresprobcov);
 3754:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
 3755:   fprintf(ficresprobcov,"# Age");
 3756:   pstamp(ficresprobcor);
 3757:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 3758:   fprintf(ficresprobcor,"# Age");
 3759: 
 3760: 
 3761:   for(i=1; i<=nlstate;i++)
 3762:     for(j=1; j<=(nlstate+ndeath);j++){
 3763:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
 3764:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
 3765:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
 3766:     }  
 3767:  /* fprintf(ficresprob,"\n");
 3768:   fprintf(ficresprobcov,"\n");
 3769:   fprintf(ficresprobcor,"\n");
 3770:  */
 3771:   xp=vector(1,npar);
 3772:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 3773:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 3774:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
 3775:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 3776:   first=1;
 3777:   fprintf(ficgp,"\n# Routine varprob");
 3778:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
 3779:   fprintf(fichtm,"\n");
 3780: 
 3781:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
 3782:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
 3783:   file %s<br>\n",optionfilehtmcov);
 3784:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
 3785: and drawn. It helps understanding how is the covariance between two incidences.\
 3786:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
 3787:   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. \
 3788: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
 3789: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
 3790: standard deviations wide on each axis. <br>\
 3791:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
 3792:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 3793: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
 3794: 
 3795:   cov[1]=1;
 3796:   /* tj=cptcoveff; */
 3797:   tj = (int) pow(2,cptcoveff);
 3798:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
 3799:   j1=0;
 3800:   for(j1=1; j1<=tj;j1++){
 3801:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
 3802:     /*j1++;*/
 3803:       if  (cptcovn>0) {
 3804: 	fprintf(ficresprob, "\n#********** Variable "); 
 3805: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3806: 	fprintf(ficresprob, "**********\n#\n");
 3807: 	fprintf(ficresprobcov, "\n#********** Variable "); 
 3808: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3809: 	fprintf(ficresprobcov, "**********\n#\n");
 3810: 	
 3811: 	fprintf(ficgp, "\n#********** Variable "); 
 3812: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3813: 	fprintf(ficgp, "**********\n#\n");
 3814: 	
 3815: 	
 3816: 	fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
 3817: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3818: 	fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
 3819: 	
 3820: 	fprintf(ficresprobcor, "\n#********** Variable ");    
 3821: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3822: 	fprintf(ficresprobcor, "**********\n#");    
 3823:       }
 3824:       
 3825:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
 3826:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 3827:       gp=vector(1,(nlstate)*(nlstate+ndeath));
 3828:       gm=vector(1,(nlstate)*(nlstate+ndeath));
 3829:       for (age=bage; age<=fage; age ++){ 
 3830: 	cov[2]=age;
 3831: 	for (k=1; k<=cptcovn;k++) {
 3832: 	  cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
 3833: 							 * 1  1 1 1 1
 3834: 							 * 2  2 1 1 1
 3835: 							 * 3  1 2 1 1
 3836: 							 */
 3837: 	  /* nbcode[1][1]=0 nbcode[1][2]=1;*/
 3838: 	}
 3839: 	for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
 3840: 	for (k=1; k<=cptcovprod;k++)
 3841: 	  cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 3842: 	
 3843:     
 3844: 	for(theta=1; theta <=npar; theta++){
 3845: 	  for(i=1; i<=npar; i++)
 3846: 	    xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
 3847: 	  
 3848: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 3849: 	  
 3850: 	  k=0;
 3851: 	  for(i=1; i<= (nlstate); i++){
 3852: 	    for(j=1; j<=(nlstate+ndeath);j++){
 3853: 	      k=k+1;
 3854: 	      gp[k]=pmmij[i][j];
 3855: 	    }
 3856: 	  }
 3857: 	  
 3858: 	  for(i=1; i<=npar; i++)
 3859: 	    xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
 3860:     
 3861: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 3862: 	  k=0;
 3863: 	  for(i=1; i<=(nlstate); i++){
 3864: 	    for(j=1; j<=(nlstate+ndeath);j++){
 3865: 	      k=k+1;
 3866: 	      gm[k]=pmmij[i][j];
 3867: 	    }
 3868: 	  }
 3869:      
 3870: 	  for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
 3871: 	    gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
 3872: 	}
 3873: 
 3874: 	for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
 3875: 	  for(theta=1; theta <=npar; theta++)
 3876: 	    trgradg[j][theta]=gradg[theta][j];
 3877: 	
 3878: 	matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
 3879: 	matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
 3880: 
 3881: 	pmij(pmmij,cov,ncovmodel,x,nlstate);
 3882: 	
 3883: 	k=0;
 3884: 	for(i=1; i<=(nlstate); i++){
 3885: 	  for(j=1; j<=(nlstate+ndeath);j++){
 3886: 	    k=k+1;
 3887: 	    mu[k][(int) age]=pmmij[i][j];
 3888: 	  }
 3889: 	}
 3890:      	for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 3891: 	  for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 3892: 	    varpij[i][j][(int)age] = doldm[i][j];
 3893: 
 3894: 	/*printf("\n%d ",(int)age);
 3895: 	  for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 3896: 	  printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 3897: 	  fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 3898: 	  }*/
 3899: 
 3900: 	fprintf(ficresprob,"\n%d ",(int)age);
 3901: 	fprintf(ficresprobcov,"\n%d ",(int)age);
 3902: 	fprintf(ficresprobcor,"\n%d ",(int)age);
 3903: 
 3904: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
 3905: 	  fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
 3906: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 3907: 	  fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
 3908: 	  fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
 3909: 	}
 3910: 	i=0;
 3911: 	for (k=1; k<=(nlstate);k++){
 3912:  	  for (l=1; l<=(nlstate+ndeath);l++){ 
 3913:  	    i++;
 3914: 	    fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 3915: 	    fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
 3916: 	    for (j=1; j<=i;j++){
 3917: 	      /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
 3918: 	      fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
 3919: 	      fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
 3920: 	    }
 3921: 	  }
 3922: 	}/* end of loop for state */
 3923:       } /* end of loop for age */
 3924:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
 3925:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 3926:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 3927:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 3928:       
 3929:       /* Confidence intervalle of pij  */
 3930:       /*
 3931: 	fprintf(ficgp,"\nunset parametric;unset label");
 3932: 	fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
 3933: 	fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 3934: 	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);
 3935: 	fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
 3936: 	fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
 3937: 	fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
 3938:       */
 3939: 
 3940:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
 3941:       first1=1;first2=2;
 3942:       for (k2=1; k2<=(nlstate);k2++){
 3943: 	for (l2=1; l2<=(nlstate+ndeath);l2++){ 
 3944: 	  if(l2==k2) continue;
 3945: 	  j=(k2-1)*(nlstate+ndeath)+l2;
 3946: 	  for (k1=1; k1<=(nlstate);k1++){
 3947: 	    for (l1=1; l1<=(nlstate+ndeath);l1++){ 
 3948: 	      if(l1==k1) continue;
 3949: 	      i=(k1-1)*(nlstate+ndeath)+l1;
 3950: 	      if(i<=j) continue;
 3951: 	      for (age=bage; age<=fage; age ++){ 
 3952: 		if ((int)age %5==0){
 3953: 		  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
 3954: 		  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
 3955: 		  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
 3956: 		  mu1=mu[i][(int) age]/stepm*YEARM ;
 3957: 		  mu2=mu[j][(int) age]/stepm*YEARM;
 3958: 		  c12=cv12/sqrt(v1*v2);
 3959: 		  /* Computing eigen value of matrix of covariance */
 3960: 		  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3961: 		  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3962: 		  if ((lc2 <0) || (lc1 <0) ){
 3963: 		    if(first2==1){
 3964: 		      first1=0;
 3965: 		    printf("Strange: j1=%d 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. Probably WRONG RESULTS. See log file for details...\n", j1, lc1, lc2, v1, v2, cv12, i, j, (int)age,fileresprobcov, fileresprobcor);
 3966: 		    }
 3967: 		    fprintf(ficlog,"Strange: j1=%d 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. Probably WRONG RESULTS.\n", j1, lc1, lc2, v1, v2, cv12, i, j, (int)age,fileresprobcov, fileresprobcor);fflush(ficlog);
 3968: 		    /* lc1=fabs(lc1); */ /* If we want to have them positive */
 3969: 		    /* lc2=fabs(lc2); */
 3970: 		  }
 3971: 
 3972: 		  /* Eigen vectors */
 3973: 		  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
 3974: 		  /*v21=sqrt(1.-v11*v11); *//* error */
 3975: 		  v21=(lc1-v1)/cv12*v11;
 3976: 		  v12=-v21;
 3977: 		  v22=v11;
 3978: 		  tnalp=v21/v11;
 3979: 		  if(first1==1){
 3980: 		    first1=0;
 3981: 		    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);
 3982: 		  }
 3983: 		  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);
 3984: 		  /*printf(fignu*/
 3985: 		  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
 3986: 		  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
 3987: 		  if(first==1){
 3988: 		    first=0;
 3989:  		    fprintf(ficgp,"\nset parametric;unset label");
 3990: 		    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);
 3991: 		    fprintf(ficgp,"\nset ter png small size 320, 240");
 3992: 		    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
 3993:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
 3994: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
 3995: 			    subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
 3996: 			    subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 3997: 		    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 3998: 		    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
 3999: 		    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4000: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 4001: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 4002: 		    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",\
 4003: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 4004: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 4005: 		  }else{
 4006: 		    first=0;
 4007: 		    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
 4008: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 4009: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 4010: 		    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",\
 4011: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 4012: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 4013: 		  }/* if first */
 4014: 		} /* age mod 5 */
 4015: 	      } /* end loop age */
 4016: 	      fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4017: 	      first=1;
 4018: 	    } /*l12 */
 4019: 	  } /* k12 */
 4020: 	} /*l1 */
 4021:       }/* k1 */
 4022:       /* } /* loop covariates */
 4023:   }
 4024:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 4025:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
 4026:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 4027:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
 4028:   free_vector(xp,1,npar);
 4029:   fclose(ficresprob);
 4030:   fclose(ficresprobcov);
 4031:   fclose(ficresprobcor);
 4032:   fflush(ficgp);
 4033:   fflush(fichtmcov);
 4034: }
 4035: 
 4036: 
 4037: /******************* Printing html file ***********/
 4038: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
 4039: 		  int lastpass, int stepm, int weightopt, char model[],\
 4040: 		  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 4041: 		  int popforecast, int estepm ,\
 4042: 		  double jprev1, double mprev1,double anprev1, \
 4043: 		  double jprev2, double mprev2,double anprev2){
 4044:   int jj1, k1, i1, cpt;
 4045: 
 4046:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
 4047:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
 4048: </ul>");
 4049:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
 4050:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
 4051: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
 4052:    fprintf(fichtm,"\
 4053:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 4054: 	   stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
 4055:    fprintf(fichtm,"\
 4056:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 4057: 	   subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
 4058:    fprintf(fichtm,"\
 4059:  - (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): \
 4060:    <a href=\"%s\">%s</a> <br>\n",
 4061: 	   estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
 4062:    fprintf(fichtm,"\
 4063:  - Population projections by age and states: \
 4064:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
 4065: 
 4066: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
 4067: 
 4068:  m=pow(2,cptcoveff);
 4069:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 4070: 
 4071:  jj1=0;
 4072:  for(k1=1; k1<=m;k1++){
 4073:    for(i1=1; i1<=ncodemax[k1];i1++){
 4074:      jj1++;
 4075:      if (cptcovn > 0) {
 4076:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 4077:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 4078: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 4079:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 4080:      }
 4081:      /* Pij */
 4082:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s%d_1.png\">%s%d_1.png</a><br> \
 4083: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
 4084:      /* Quasi-incidences */
 4085:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
 4086:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: <a href=\"%s%d_2.png\">%s%d_2.png</a><br> \
 4087: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
 4088:        /* Period (stable) prevalence in each health state */
 4089:        for(cpt=1; cpt<=nlstate;cpt++){
 4090: 	 fprintf(fichtm,"<br>- Convergence from cross-sectional prevalence in each state (1 to %d) to period (stable) prevalence in specific state %d <a href=\"%s%d_%d.png\">%s%d_%d.png</a><br> \
 4091: <img src=\"%s%d_%d.png\">",nlstate, cpt, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
 4092:        }
 4093:      for(cpt=1; cpt<=nlstate;cpt++) {
 4094:         fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies in each alive state (1 to %d) : <a href=\"%s%d%d.png\">%s%d%d.png</a> <br> \
 4095: <img src=\"%s%d%d.png\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
 4096:      }
 4097:    } /* end i1 */
 4098:  }/* End k1 */
 4099:  fprintf(fichtm,"</ul>");
 4100: 
 4101: 
 4102:  fprintf(fichtm,"\
 4103: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
 4104:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
 4105: 
 4106:  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4107: 	 subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
 4108:  fprintf(fichtm,"\
 4109:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4110: 	 subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
 4111: 
 4112:  fprintf(fichtm,"\
 4113:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4114: 	 subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
 4115:  fprintf(fichtm,"\
 4116:  - 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): \
 4117:    <a href=\"%s\">%s</a> <br>\n</li>",
 4118: 	   estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
 4119:  fprintf(fichtm,"\
 4120:  - (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): \
 4121:    <a href=\"%s\">%s</a> <br>\n</li>",
 4122: 	   estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
 4123:  fprintf(fichtm,"\
 4124:  - 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",
 4125: 	 estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
 4126:  fprintf(fichtm,"\
 4127:  - 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",
 4128: 	 estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
 4129:  fprintf(fichtm,"\
 4130:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
 4131: 	 subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
 4132: 
 4133: /*  if(popforecast==1) fprintf(fichtm,"\n */
 4134: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
 4135: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
 4136: /* 	<br>",fileres,fileres,fileres,fileres); */
 4137: /*  else  */
 4138: /*    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); */
 4139:  fflush(fichtm);
 4140:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
 4141: 
 4142:  m=pow(2,cptcoveff);
 4143:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 4144: 
 4145:  jj1=0;
 4146:  for(k1=1; k1<=m;k1++){
 4147:    for(i1=1; i1<=ncodemax[k1];i1++){
 4148:      jj1++;
 4149:      if (cptcovn > 0) {
 4150:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 4151:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 4152: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 4153:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 4154:      }
 4155:      for(cpt=1; cpt<=nlstate;cpt++) {
 4156:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
 4157: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
 4158: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
 4159:      }
 4160:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
 4161: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
 4162: true period expectancies (those weighted with period prevalences are also\
 4163:  drawn in addition to the population based expectancies computed using\
 4164:  observed and cahotic prevalences: %s%d.png<br>\
 4165: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
 4166:    } /* end i1 */
 4167:  }/* End k1 */
 4168:  fprintf(fichtm,"</ul>");
 4169:  fflush(fichtm);
 4170: }
 4171: 
 4172: /******************* Gnuplot file **************/
 4173: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 4174: 
 4175:   char dirfileres[132],optfileres[132];
 4176:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
 4177:   int ng=0;
 4178: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
 4179: /*     printf("Problem with file %s",optionfilegnuplot); */
 4180: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
 4181: /*   } */
 4182: 
 4183:   /*#ifdef windows */
 4184:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 4185:     /*#endif */
 4186:   m=pow(2,cptcoveff);
 4187: 
 4188:   strcpy(dirfileres,optionfilefiname);
 4189:   strcpy(optfileres,"vpl");
 4190:  /* 1eme*/
 4191:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
 4192:   for (cpt=1; cpt<= nlstate ; cpt ++) {
 4193:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
 4194:      fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
 4195:      fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
 4196:      fprintf(ficgp,"set xlabel \"Age\" \n\
 4197: set ylabel \"Probability\" \n\
 4198: set ter png small size 320, 240\n\
 4199: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
 4200: 
 4201:      for (i=1; i<= nlstate ; i ++) {
 4202:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
 4203:        else        fprintf(ficgp," \%%*lf (\%%*lf)");
 4204:      }
 4205:      fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);
 4206:      for (i=1; i<= nlstate ; i ++) {
 4207:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
 4208:        else fprintf(ficgp," \%%*lf (\%%*lf)");
 4209:      } 
 4210:      fprintf(ficgp,"\" t\"95\%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1); 
 4211:      for (i=1; i<= nlstate ; i ++) {
 4212:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
 4213:        else fprintf(ficgp," \%%*lf (\%%*lf)");
 4214:      }  
 4215:      fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence \" w l lt 2",subdirf2(fileres,"p"),k1-1,k1-1,2+4*(cpt-1));
 4216:    }
 4217:   }
 4218:   /*2 eme*/
 4219:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
 4220:   for (k1=1; k1<= m ; k1 ++) { 
 4221:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
 4222:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
 4223:     
 4224:     for (i=1; i<= nlstate+1 ; i ++) {
 4225:       k=2*i;
 4226:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4227:       for (j=1; j<= nlstate+1 ; j ++) {
 4228: 	if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
 4229: 	else fprintf(ficgp," \%%*lf (\%%*lf)");
 4230:       }   
 4231:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
 4232:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
 4233:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4234:       for (j=1; j<= nlstate+1 ; j ++) {
 4235: 	if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
 4236: 	else fprintf(ficgp," \%%*lf (\%%*lf)");
 4237:       }   
 4238:       fprintf(ficgp,"\" t\"\" w l lt 0,");
 4239:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4240:       for (j=1; j<= nlstate+1 ; j ++) {
 4241: 	if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
 4242: 	else fprintf(ficgp," \%%*lf (\%%*lf)");
 4243:       }   
 4244:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
 4245:       else fprintf(ficgp,"\" t\"\" w l lt 0,");
 4246:     }
 4247:   }
 4248:   
 4249:   /*3eme*/
 4250:   
 4251:   for (k1=1; k1<= m ; k1 ++) { 
 4252:     for (cpt=1; cpt<= nlstate ; cpt ++) {
 4253:       /*       k=2+nlstate*(2*cpt-2); */
 4254:       k=2+(nlstate+1)*(cpt-1);
 4255:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
 4256:       fprintf(ficgp,"set ter png small size 320, 240\n\
 4257: 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);
 4258:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 4259: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 4260: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 4261: 	fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 4262: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 4263: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 4264: 	
 4265:       */
 4266:       for (i=1; i< nlstate ; i ++) {
 4267: 	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);
 4268: 	/*	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);*/
 4269: 	
 4270:       } 
 4271:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
 4272:     }
 4273:   }
 4274:   
 4275:   /* CV preval stable (period) */
 4276:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
 4277:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 4278:       k=3;
 4279:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
 4280:       fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
 4281:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 4282: set ter png small size 320, 240\n\
 4283: unset log y\n\
 4284: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 4285:       for (i=1; i<= nlstate ; i ++){
 4286: 	if(i==1)
 4287: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
 4288: 	else
 4289: 	  fprintf(ficgp,", '' ");
 4290: 	l=(nlstate+ndeath)*(i-1)+1;
 4291: 	fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 4292: 	for (j=1; j<= (nlstate-1) ; j ++)
 4293: 	  fprintf(ficgp,"+$%d",k+l+j);
 4294: 	fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
 4295:       } /* nlstate */
 4296:       fprintf(ficgp,"\n");
 4297:     } /* end cpt state*/ 
 4298:   } /* end covariate */  
 4299:   
 4300:   /* proba elementaires */
 4301:   for(i=1,jk=1; i <=nlstate; i++){
 4302:     for(k=1; k <=(nlstate+ndeath); k++){
 4303:       if (k != i) {
 4304: 	for(j=1; j <=ncovmodel; j++){
 4305: 	  fprintf(ficgp,"p%d=%f ",jk,p[jk]);
 4306: 	  jk++; 
 4307: 	  fprintf(ficgp,"\n");
 4308: 	}
 4309:       }
 4310:     }
 4311:    }
 4312:   /*goto avoid;*/
 4313:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
 4314:      for(jk=1; jk <=m; jk++) {
 4315:        fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
 4316:        if (ng==2)
 4317: 	 fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
 4318:        else
 4319: 	 fprintf(ficgp,"\nset title \"Probability\"\n");
 4320:        fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
 4321:        i=1;
 4322:        for(k2=1; k2<=nlstate; k2++) {
 4323: 	 k3=i;
 4324: 	 for(k=1; k<=(nlstate+ndeath); k++) {
 4325: 	   if (k != k2){
 4326: 	     if(ng==2)
 4327: 	       fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
 4328: 	     else
 4329: 	       fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
 4330: 	     ij=1;/* To be checked else nbcode[0][0] wrong */
 4331: 	     for(j=3; j <=ncovmodel; j++) {
 4332: 	       /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
 4333: 	       /* 	 /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
 4334: 	       /* 	 ij++; */
 4335: 	       /* } */
 4336: 	       /* else */
 4337: 		 fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 4338: 	     }
 4339: 	     fprintf(ficgp,")/(1");
 4340: 	     
 4341: 	     for(k1=1; k1 <=nlstate; k1++){   
 4342: 	       fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
 4343: 	       ij=1;
 4344: 	       for(j=3; j <=ncovmodel; j++){
 4345: 		 /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
 4346: 		 /*   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
 4347: 		 /*   ij++; */
 4348: 		 /* } */
 4349: 		 /* else */
 4350: 		   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 4351: 	       }
 4352: 	       fprintf(ficgp,")");
 4353: 	     }
 4354: 	     fprintf(ficgp,") t \"p%d%d\" ", k2,k);
 4355: 	     if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
 4356: 	     i=i+ncovmodel;
 4357: 	   }
 4358: 	 } /* end k */
 4359:        } /* end k2 */
 4360:      } /* end jk */
 4361:    } /* end ng */
 4362:  /* avoid: */
 4363:    fflush(ficgp); 
 4364: }  /* end gnuplot */
 4365: 
 4366: 
 4367: /*************** Moving average **************/
 4368: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
 4369: 
 4370:   int i, cpt, cptcod;
 4371:   int modcovmax =1;
 4372:   int mobilavrange, mob;
 4373:   double age;
 4374: 
 4375:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
 4376: 			   a covariate has 2 modalities */
 4377:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
 4378: 
 4379:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
 4380:     if(mobilav==1) mobilavrange=5; /* default */
 4381:     else mobilavrange=mobilav;
 4382:     for (age=bage; age<=fage; age++)
 4383:       for (i=1; i<=nlstate;i++)
 4384: 	for (cptcod=1;cptcod<=modcovmax;cptcod++)
 4385: 	  mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 4386:     /* We keep the original values on the extreme ages bage, fage and for 
 4387:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
 4388:        we use a 5 terms etc. until the borders are no more concerned. 
 4389:     */ 
 4390:     for (mob=3;mob <=mobilavrange;mob=mob+2){
 4391:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
 4392: 	for (i=1; i<=nlstate;i++){
 4393: 	  for (cptcod=1;cptcod<=modcovmax;cptcod++){
 4394: 	    mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
 4395: 	      for (cpt=1;cpt<=(mob-1)/2;cpt++){
 4396: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
 4397: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
 4398: 	      }
 4399: 	    mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
 4400: 	  }
 4401: 	}
 4402:       }/* end age */
 4403:     }/* end mob */
 4404:   }else return -1;
 4405:   return 0;
 4406: }/* End movingaverage */
 4407: 
 4408: 
 4409: /************** Forecasting ******************/
 4410: 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){
 4411:   /* proj1, year, month, day of starting projection 
 4412:      agemin, agemax range of age
 4413:      dateprev1 dateprev2 range of dates during which prevalence is computed
 4414:      anproj2 year of en of projection (same day and month as proj1).
 4415:   */
 4416:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
 4417:   double agec; /* generic age */
 4418:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
 4419:   double *popeffectif,*popcount;
 4420:   double ***p3mat;
 4421:   double ***mobaverage;
 4422:   char fileresf[FILENAMELENGTH];
 4423: 
 4424:   agelim=AGESUP;
 4425:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 4426:  
 4427:   strcpy(fileresf,"f"); 
 4428:   strcat(fileresf,fileres);
 4429:   if((ficresf=fopen(fileresf,"w"))==NULL) {
 4430:     printf("Problem with forecast resultfile: %s\n", fileresf);
 4431:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
 4432:   }
 4433:   printf("Computing forecasting: result on file '%s' \n", fileresf);
 4434:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
 4435: 
 4436:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 4437: 
 4438:   if (mobilav!=0) {
 4439:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4440:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 4441:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 4442:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 4443:     }
 4444:   }
 4445: 
 4446:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 4447:   if (stepm<=12) stepsize=1;
 4448:   if(estepm < stepm){
 4449:     printf ("Problem %d lower than %d\n",estepm, stepm);
 4450:   }
 4451:   else  hstepm=estepm;   
 4452: 
 4453:   hstepm=hstepm/stepm; 
 4454:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
 4455:                                fractional in yp1 */
 4456:   anprojmean=yp;
 4457:   yp2=modf((yp1*12),&yp);
 4458:   mprojmean=yp;
 4459:   yp1=modf((yp2*30.5),&yp);
 4460:   jprojmean=yp;
 4461:   if(jprojmean==0) jprojmean=1;
 4462:   if(mprojmean==0) jprojmean=1;
 4463: 
 4464:   i1=cptcoveff;
 4465:   if (cptcovn < 1){i1=1;}
 4466:   
 4467:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
 4468:   
 4469:   fprintf(ficresf,"#****** Routine prevforecast **\n");
 4470: 
 4471: /* 	      if (h==(int)(YEARM*yearp)){ */
 4472:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
 4473:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 4474:       k=k+1;
 4475:       fprintf(ficresf,"\n#******");
 4476:       for(j=1;j<=cptcoveff;j++) {
 4477: 	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]]);
 4478:       }
 4479:       fprintf(ficresf,"******\n");
 4480:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
 4481:       for(j=1; j<=nlstate+ndeath;j++){ 
 4482: 	for(i=1; i<=nlstate;i++) 	      
 4483:           fprintf(ficresf," p%d%d",i,j);
 4484: 	fprintf(ficresf," p.%d",j);
 4485:       }
 4486:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
 4487: 	fprintf(ficresf,"\n");
 4488: 	fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
 4489: 
 4490:      	for (agec=fage; agec>=(ageminpar-1); agec--){ 
 4491: 	  nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
 4492: 	  nhstepm = nhstepm/hstepm; 
 4493: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4494: 	  oldm=oldms;savm=savms;
 4495: 	  hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4496: 	
 4497: 	  for (h=0; h<=nhstepm; h++){
 4498: 	    if (h*hstepm/YEARM*stepm ==yearp) {
 4499:               fprintf(ficresf,"\n");
 4500:               for(j=1;j<=cptcoveff;j++) 
 4501:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4502: 	      fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
 4503: 	    } 
 4504: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4505: 	      ppij=0.;
 4506: 	      for(i=1; i<=nlstate;i++) {
 4507: 		if (mobilav==1) 
 4508: 		  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
 4509: 		else {
 4510: 		  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
 4511: 		}
 4512: 		if (h*hstepm/YEARM*stepm== yearp) {
 4513: 		  fprintf(ficresf," %.3f", p3mat[i][j][h]);
 4514: 		}
 4515: 	      } /* end i */
 4516: 	      if (h*hstepm/YEARM*stepm==yearp) {
 4517: 		fprintf(ficresf," %.3f", ppij);
 4518: 	      }
 4519: 	    }/* end j */
 4520: 	  } /* end h */
 4521: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4522: 	} /* end agec */
 4523:       } /* end yearp */
 4524:     } /* end cptcod */
 4525:   } /* end  cptcov */
 4526:        
 4527:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4528: 
 4529:   fclose(ficresf);
 4530: }
 4531: 
 4532: /************** Forecasting *****not tested NB*************/
 4533: 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){
 4534:   
 4535:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
 4536:   int *popage;
 4537:   double calagedatem, agelim, kk1, kk2;
 4538:   double *popeffectif,*popcount;
 4539:   double ***p3mat,***tabpop,***tabpopprev;
 4540:   double ***mobaverage;
 4541:   char filerespop[FILENAMELENGTH];
 4542: 
 4543:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4544:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4545:   agelim=AGESUP;
 4546:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
 4547:   
 4548:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 4549:   
 4550:   
 4551:   strcpy(filerespop,"pop"); 
 4552:   strcat(filerespop,fileres);
 4553:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
 4554:     printf("Problem with forecast resultfile: %s\n", filerespop);
 4555:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
 4556:   }
 4557:   printf("Computing forecasting: result on file '%s' \n", filerespop);
 4558:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
 4559: 
 4560:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 4561: 
 4562:   if (mobilav!=0) {
 4563:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4564:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 4565:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 4566:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 4567:     }
 4568:   }
 4569: 
 4570:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 4571:   if (stepm<=12) stepsize=1;
 4572:   
 4573:   agelim=AGESUP;
 4574:   
 4575:   hstepm=1;
 4576:   hstepm=hstepm/stepm; 
 4577:   
 4578:   if (popforecast==1) {
 4579:     if((ficpop=fopen(popfile,"r"))==NULL) {
 4580:       printf("Problem with population file : %s\n",popfile);exit(0);
 4581:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
 4582:     } 
 4583:     popage=ivector(0,AGESUP);
 4584:     popeffectif=vector(0,AGESUP);
 4585:     popcount=vector(0,AGESUP);
 4586:     
 4587:     i=1;   
 4588:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
 4589:    
 4590:     imx=i;
 4591:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
 4592:   }
 4593: 
 4594:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
 4595:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 4596:       k=k+1;
 4597:       fprintf(ficrespop,"\n#******");
 4598:       for(j=1;j<=cptcoveff;j++) {
 4599: 	fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4600:       }
 4601:       fprintf(ficrespop,"******\n");
 4602:       fprintf(ficrespop,"# Age");
 4603:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
 4604:       if (popforecast==1)  fprintf(ficrespop," [Population]");
 4605:       
 4606:       for (cpt=0; cpt<=0;cpt++) { 
 4607: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 4608: 	
 4609:      	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 4610: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 4611: 	  nhstepm = nhstepm/hstepm; 
 4612: 	  
 4613: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4614: 	  oldm=oldms;savm=savms;
 4615: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4616: 	
 4617: 	  for (h=0; h<=nhstepm; h++){
 4618: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 4619: 	      fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 4620: 	    } 
 4621: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4622: 	      kk1=0.;kk2=0;
 4623: 	      for(i=1; i<=nlstate;i++) {	      
 4624: 		if (mobilav==1) 
 4625: 		  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
 4626: 		else {
 4627: 		  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
 4628: 		}
 4629: 	      }
 4630: 	      if (h==(int)(calagedatem+12*cpt)){
 4631: 		tabpop[(int)(agedeb)][j][cptcod]=kk1;
 4632: 		  /*fprintf(ficrespop," %.3f", kk1);
 4633: 		    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
 4634: 	      }
 4635: 	    }
 4636: 	    for(i=1; i<=nlstate;i++){
 4637: 	      kk1=0.;
 4638: 		for(j=1; j<=nlstate;j++){
 4639: 		  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
 4640: 		}
 4641: 		  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
 4642: 	    }
 4643: 
 4644: 	    if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
 4645: 	      fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
 4646: 	  }
 4647: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4648: 	}
 4649:       }
 4650:  
 4651:   /******/
 4652: 
 4653:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
 4654: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 4655: 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 4656: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 4657: 	  nhstepm = nhstepm/hstepm; 
 4658: 	  
 4659: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4660: 	  oldm=oldms;savm=savms;
 4661: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4662: 	  for (h=0; h<=nhstepm; h++){
 4663: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 4664: 	      fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 4665: 	    } 
 4666: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4667: 	      kk1=0.;kk2=0;
 4668: 	      for(i=1; i<=nlstate;i++) {	      
 4669: 		kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];	
 4670: 	      }
 4671: 	      if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);	
 4672: 	    }
 4673: 	  }
 4674: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4675: 	}
 4676:       }
 4677:    } 
 4678:   }
 4679:  
 4680:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4681: 
 4682:   if (popforecast==1) {
 4683:     free_ivector(popage,0,AGESUP);
 4684:     free_vector(popeffectif,0,AGESUP);
 4685:     free_vector(popcount,0,AGESUP);
 4686:   }
 4687:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4688:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4689:   fclose(ficrespop);
 4690: } /* End of popforecast */
 4691: 
 4692: int fileappend(FILE *fichier, char *optionfich)
 4693: {
 4694:   if((fichier=fopen(optionfich,"a"))==NULL) {
 4695:     printf("Problem with file: %s\n", optionfich);
 4696:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
 4697:     return (0);
 4698:   }
 4699:   fflush(fichier);
 4700:   return (1);
 4701: }
 4702: 
 4703: 
 4704: /**************** function prwizard **********************/
 4705: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
 4706: {
 4707: 
 4708:   /* Wizard to print covariance matrix template */
 4709: 
 4710:   char ca[32], cb[32];
 4711:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
 4712:   int numlinepar;
 4713: 
 4714:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 4715:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 4716:   for(i=1; i <=nlstate; i++){
 4717:     jj=0;
 4718:     for(j=1; j <=nlstate+ndeath; j++){
 4719:       if(j==i) continue;
 4720:       jj++;
 4721:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
 4722:       printf("%1d%1d",i,j);
 4723:       fprintf(ficparo,"%1d%1d",i,j);
 4724:       for(k=1; k<=ncovmodel;k++){
 4725: 	/* 	  printf(" %lf",param[i][j][k]); */
 4726: 	/* 	  fprintf(ficparo," %lf",param[i][j][k]); */
 4727: 	printf(" 0.");
 4728: 	fprintf(ficparo," 0.");
 4729:       }
 4730:       printf("\n");
 4731:       fprintf(ficparo,"\n");
 4732:     }
 4733:   }
 4734:   printf("# Scales (for hessian or gradient estimation)\n");
 4735:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
 4736:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
 4737:   for(i=1; i <=nlstate; i++){
 4738:     jj=0;
 4739:     for(j=1; j <=nlstate+ndeath; j++){
 4740:       if(j==i) continue;
 4741:       jj++;
 4742:       fprintf(ficparo,"%1d%1d",i,j);
 4743:       printf("%1d%1d",i,j);
 4744:       fflush(stdout);
 4745:       for(k=1; k<=ncovmodel;k++){
 4746: 	/* 	printf(" %le",delti3[i][j][k]); */
 4747: 	/* 	fprintf(ficparo," %le",delti3[i][j][k]); */
 4748: 	printf(" 0.");
 4749: 	fprintf(ficparo," 0.");
 4750:       }
 4751:       numlinepar++;
 4752:       printf("\n");
 4753:       fprintf(ficparo,"\n");
 4754:     }
 4755:   }
 4756:   printf("# Covariance matrix\n");
 4757: /* # 121 Var(a12)\n\ */
 4758: /* # 122 Cov(b12,a12) Var(b12)\n\ */
 4759: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 4760: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 4761: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 4762: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 4763: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 4764: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 4765:   fflush(stdout);
 4766:   fprintf(ficparo,"# Covariance matrix\n");
 4767:   /* # 121 Var(a12)\n\ */
 4768:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
 4769:   /* #   ...\n\ */
 4770:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
 4771:   
 4772:   for(itimes=1;itimes<=2;itimes++){
 4773:     jj=0;
 4774:     for(i=1; i <=nlstate; i++){
 4775:       for(j=1; j <=nlstate+ndeath; j++){
 4776: 	if(j==i) continue;
 4777: 	for(k=1; k<=ncovmodel;k++){
 4778: 	  jj++;
 4779: 	  ca[0]= k+'a'-1;ca[1]='\0';
 4780: 	  if(itimes==1){
 4781: 	    printf("#%1d%1d%d",i,j,k);
 4782: 	    fprintf(ficparo,"#%1d%1d%d",i,j,k);
 4783: 	  }else{
 4784: 	    printf("%1d%1d%d",i,j,k);
 4785: 	    fprintf(ficparo,"%1d%1d%d",i,j,k);
 4786: 	    /* 	printf(" %.5le",matcov[i][j]); */
 4787: 	  }
 4788: 	  ll=0;
 4789: 	  for(li=1;li <=nlstate; li++){
 4790: 	    for(lj=1;lj <=nlstate+ndeath; lj++){
 4791: 	      if(lj==li) continue;
 4792: 	      for(lk=1;lk<=ncovmodel;lk++){
 4793: 		ll++;
 4794: 		if(ll<=jj){
 4795: 		  cb[0]= lk +'a'-1;cb[1]='\0';
 4796: 		  if(ll<jj){
 4797: 		    if(itimes==1){
 4798: 		      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 4799: 		      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 4800: 		    }else{
 4801: 		      printf(" 0.");
 4802: 		      fprintf(ficparo," 0.");
 4803: 		    }
 4804: 		  }else{
 4805: 		    if(itimes==1){
 4806: 		      printf(" Var(%s%1d%1d)",ca,i,j);
 4807: 		      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
 4808: 		    }else{
 4809: 		      printf(" 0.");
 4810: 		      fprintf(ficparo," 0.");
 4811: 		    }
 4812: 		  }
 4813: 		}
 4814: 	      } /* end lk */
 4815: 	    } /* end lj */
 4816: 	  } /* end li */
 4817: 	  printf("\n");
 4818: 	  fprintf(ficparo,"\n");
 4819: 	  numlinepar++;
 4820: 	} /* end k*/
 4821:       } /*end j */
 4822:     } /* end i */
 4823:   } /* end itimes */
 4824: 
 4825: } /* end of prwizard */
 4826: /******************* Gompertz Likelihood ******************************/
 4827: double gompertz(double x[])
 4828: { 
 4829:   double A,B,L=0.0,sump=0.,num=0.;
 4830:   int i,n=0; /* n is the size of the sample */
 4831: 
 4832:   for (i=0;i<=imx-1 ; i++) {
 4833:     sump=sump+weight[i];
 4834:     /*    sump=sump+1;*/
 4835:     num=num+1;
 4836:   }
 4837:  
 4838:  
 4839:   /* for (i=0; i<=imx; i++) 
 4840:      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]);*/
 4841: 
 4842:   for (i=1;i<=imx ; i++)
 4843:     {
 4844:       if (cens[i] == 1 && wav[i]>1)
 4845: 	A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
 4846:       
 4847:       if (cens[i] == 0 && wav[i]>1)
 4848: 	A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
 4849: 	     +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
 4850:       
 4851:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 4852:       if (wav[i] > 1 ) { /* ??? */
 4853: 	L=L+A*weight[i];
 4854: 	/* 	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]);*/
 4855:       }
 4856:     }
 4857: 
 4858:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 4859:  
 4860:   return -2*L*num/sump;
 4861: }
 4862: 
 4863: #ifdef GSL
 4864: /******************* Gompertz_f Likelihood ******************************/
 4865: double gompertz_f(const gsl_vector *v, void *params)
 4866: { 
 4867:   double A,B,LL=0.0,sump=0.,num=0.;
 4868:   double *x= (double *) v->data;
 4869:   int i,n=0; /* n is the size of the sample */
 4870: 
 4871:   for (i=0;i<=imx-1 ; i++) {
 4872:     sump=sump+weight[i];
 4873:     /*    sump=sump+1;*/
 4874:     num=num+1;
 4875:   }
 4876:  
 4877:  
 4878:   /* for (i=0; i<=imx; i++) 
 4879:      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]);*/
 4880:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
 4881:   for (i=1;i<=imx ; i++)
 4882:     {
 4883:       if (cens[i] == 1 && wav[i]>1)
 4884: 	A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
 4885:       
 4886:       if (cens[i] == 0 && wav[i]>1)
 4887: 	A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
 4888: 	     +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
 4889:       
 4890:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 4891:       if (wav[i] > 1 ) { /* ??? */
 4892: 	LL=LL+A*weight[i];
 4893: 	/* 	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]);*/
 4894:       }
 4895:     }
 4896: 
 4897:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 4898:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
 4899:  
 4900:   return -2*LL*num/sump;
 4901: }
 4902: #endif
 4903: 
 4904: /******************* Printing html file ***********/
 4905: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
 4906: 		  int lastpass, int stepm, int weightopt, char model[],\
 4907: 		  int imx,  double p[],double **matcov,double agemortsup){
 4908:   int i,k;
 4909: 
 4910:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
 4911:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
 4912:   for (i=1;i<=2;i++) 
 4913:     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]));
 4914:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
 4915:   fprintf(fichtm,"</ul>");
 4916: 
 4917: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
 4918: 
 4919:  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>");
 4920: 
 4921:  for (k=agegomp;k<(agemortsup-2);k++) 
 4922:    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]);
 4923: 
 4924:  
 4925:   fflush(fichtm);
 4926: }
 4927: 
 4928: /******************* Gnuplot file **************/
 4929: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 4930: 
 4931:   char dirfileres[132],optfileres[132];
 4932: 
 4933:   int ng;
 4934: 
 4935: 
 4936:   /*#ifdef windows */
 4937:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 4938:     /*#endif */
 4939: 
 4940: 
 4941:   strcpy(dirfileres,optionfilefiname);
 4942:   strcpy(optfileres,"vpl");
 4943:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
 4944:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
 4945:   fprintf(ficgp, "set ter png small size 320, 240\n set log y\n"); 
 4946:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
 4947:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
 4948: 
 4949: } 
 4950: 
 4951: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
 4952: {
 4953: 
 4954:   /*-------- data file ----------*/
 4955:   FILE *fic;
 4956:   char dummy[]="                         ";
 4957:   int i=0, j=0, n=0;
 4958:   int linei, month, year,iout;
 4959:   char line[MAXLINE], linetmp[MAXLINE];
 4960:   char stra[MAXLINE], strb[MAXLINE];
 4961:   char *stratrunc;
 4962:   int lstra;
 4963: 
 4964: 
 4965:   if((fic=fopen(datafile,"r"))==NULL)    {
 4966:     printf("Problem while opening datafile: %s\n", datafile);return 1;
 4967:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
 4968:   }
 4969: 
 4970:   i=1;
 4971:   linei=0;
 4972:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
 4973:     linei=linei+1;
 4974:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
 4975:       if(line[j] == '\t')
 4976: 	line[j] = ' ';
 4977:     }
 4978:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
 4979:       ;
 4980:     };
 4981:     line[j+1]=0;  /* Trims blanks at end of line */
 4982:     if(line[0]=='#'){
 4983:       fprintf(ficlog,"Comment line\n%s\n",line);
 4984:       printf("Comment line\n%s\n",line);
 4985:       continue;
 4986:     }
 4987:     trimbb(linetmp,line); /* Trims multiple blanks in line */
 4988:     strcpy(line, linetmp);
 4989:   
 4990: 
 4991:     for (j=maxwav;j>=1;j--){
 4992:       cutv(stra, strb, line, ' '); 
 4993:       if(strb[0]=='.') { /* Missing status */
 4994: 	lval=-1;
 4995:       }else{
 4996: 	errno=0;
 4997: 	lval=strtol(strb,&endptr,10); 
 4998:       /*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
 4999: 	if( strb[0]=='\0' || (*endptr != '\0')){
 5000: 	  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);
 5001: 	  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);
 5002: 	  return 1;
 5003: 	}
 5004:       }
 5005:       s[j][i]=lval;
 5006:       
 5007:       strcpy(line,stra);
 5008:       cutv(stra, strb,line,' ');
 5009:       if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
 5010:       }
 5011:       else  if(iout=sscanf(strb,"%s.",dummy) != 0){
 5012: 	month=99;
 5013: 	year=9999;
 5014:       }else{
 5015: 	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);
 5016: 	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);
 5017: 	return 1;
 5018:       }
 5019:       anint[j][i]= (double) year; 
 5020:       mint[j][i]= (double)month; 
 5021:       strcpy(line,stra);
 5022:     } /* ENd Waves */
 5023:     
 5024:     cutv(stra, strb,line,' '); 
 5025:     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
 5026:     }
 5027:     else  if(iout=sscanf(strb,"%s.",dummy) != 0){
 5028:       month=99;
 5029:       year=9999;
 5030:     }else{
 5031:       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);
 5032: 	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);
 5033: 	return 1;
 5034:     }
 5035:     andc[i]=(double) year; 
 5036:     moisdc[i]=(double) month; 
 5037:     strcpy(line,stra);
 5038:     
 5039:     cutv(stra, strb,line,' '); 
 5040:     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
 5041:     }
 5042:     else  if(iout=sscanf(strb,"%s.", dummy) != 0){
 5043:       month=99;
 5044:       year=9999;
 5045:     }else{
 5046:       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);
 5047:       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);
 5048: 	return 1;
 5049:     }
 5050:     if (year==9999) {
 5051:       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);
 5052:       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);
 5053: 	return 1;
 5054: 
 5055:     }
 5056:     annais[i]=(double)(year);
 5057:     moisnais[i]=(double)(month); 
 5058:     strcpy(line,stra);
 5059:     
 5060:     cutv(stra, strb,line,' '); 
 5061:     errno=0;
 5062:     dval=strtod(strb,&endptr); 
 5063:     if( strb[0]=='\0' || (*endptr != '\0')){
 5064:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
 5065:       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);
 5066:       fflush(ficlog);
 5067:       return 1;
 5068:     }
 5069:     weight[i]=dval; 
 5070:     strcpy(line,stra);
 5071:     
 5072:     for (j=ncovcol;j>=1;j--){
 5073:       cutv(stra, strb,line,' '); 
 5074:       if(strb[0]=='.') { /* Missing status */
 5075: 	lval=-1;
 5076:       }else{
 5077: 	errno=0;
 5078: 	lval=strtol(strb,&endptr,10); 
 5079: 	if( strb[0]=='\0' || (*endptr != '\0')){
 5080: 	  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);
 5081: 	  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);
 5082: 	  return 1;
 5083: 	}
 5084:       }
 5085:       if(lval <-1 || lval >1){
 5086: 	printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 5087:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 5088:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 5089:  For example, for multinomial values like 1, 2 and 3,\n \
 5090:  build V1=0 V2=0 for the reference value (1),\n \
 5091:         V1=1 V2=0 for (2) \n \
 5092:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 5093:  output of IMaCh is often meaningless.\n \
 5094:  Exiting.\n",lval,linei, i,line,j);
 5095: 	fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 5096:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 5097:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 5098:  For example, for multinomial values like 1, 2 and 3,\n \
 5099:  build V1=0 V2=0 for the reference value (1),\n \
 5100:         V1=1 V2=0 for (2) \n \
 5101:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 5102:  output of IMaCh is often meaningless.\n \
 5103:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
 5104: 	return 1;
 5105:       }
 5106:       covar[j][i]=(double)(lval);
 5107:       strcpy(line,stra);
 5108:     }  
 5109:     lstra=strlen(stra);
 5110:      
 5111:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
 5112:       stratrunc = &(stra[lstra-9]);
 5113:       num[i]=atol(stratrunc);
 5114:     }
 5115:     else
 5116:       num[i]=atol(stra);
 5117:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
 5118:       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;}*/
 5119:     
 5120:     i=i+1;
 5121:   } /* End loop reading  data */
 5122: 
 5123:   *imax=i-1; /* Number of individuals */
 5124:   fclose(fic);
 5125:  
 5126:   return (0);
 5127:   /* endread: */
 5128:     printf("Exiting readdata: ");
 5129:     fclose(fic);
 5130:     return (1);
 5131: 
 5132: 
 5133: 
 5134: }
 5135: void removespace(char *str) {
 5136:   char *p1 = str, *p2 = str;
 5137:   do
 5138:     while (*p2 == ' ')
 5139:       p2++;
 5140:   while (*p1++ = *p2++);
 5141: }
 5142: 
 5143: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
 5144:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
 5145:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
 5146:    * - cptcovn or number of covariates k of the models excluding age*products =6
 5147:    * - cptcovage number of covariates with age*products =2
 5148:    * - cptcovs number of simple covariates
 5149:    * - Tvar[k] is the id of the kth covariate Tvar[1]@12 {1, 2, 3, 8, 10, 11, 8, 3, 7, 8, 5, 6}, thus Tvar[5=V7*V8]=10
 5150:    *     which is a new column after the 9 (ncovcol) variables. 
 5151:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
 5152:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
 5153:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
 5154:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
 5155:  */
 5156: {
 5157:   int i, j, k, ks;
 5158:   int  j1, k1, k2;
 5159:   char modelsav[80];
 5160:   char stra[80], strb[80], strc[80], strd[80],stre[80];
 5161: 
 5162:   /*removespace(model);*/
 5163:   if (strlen(model) >1){ /* If there is at least 1 covariate */
 5164:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
 5165:     j=nbocc(model,'+'); /**< j=Number of '+' */
 5166:     j1=nbocc(model,'*'); /**< j1=Number of '*' */
 5167:     cptcovs=j+1-j1; /**<  Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2  */
 5168:     cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
 5169:                   /* including age products which are counted in cptcovage.
 5170: 		  /* but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
 5171:     cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
 5172:     cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
 5173:     strcpy(modelsav,model); 
 5174:     if (strstr(model,"AGE") !=0){
 5175:       printf("Error. AGE must be in lower case 'age' model=%s ",model);
 5176:       fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
 5177:       return 1;
 5178:     }
 5179:     if (strstr(model,"v") !=0){
 5180:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
 5181:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
 5182:       return 1;
 5183:     }
 5184:     
 5185:     /*   Design
 5186:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
 5187:      *  <          ncovcol=8                >
 5188:      * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
 5189:      *   k=  1    2      3       4     5       6      7        8
 5190:      *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
 5191:      *  covar[k,i], value of kth covariate if not including age for individual i:
 5192:      *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
 5193:      *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
 5194:      *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
 5195:      *  Tage[++cptcovage]=k
 5196:      *       if products, new covar are created after ncovcol with k1
 5197:      *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
 5198:      *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
 5199:      *  Tvard[k1][1]=m Tvard[k1][2]=m; Tvard[1][1]=5 (V5) Tvard[1][2]=6 Tvard[2][1]=7 (V7) Tvard[2][2]=8
 5200:      *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
 5201:      *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
 5202:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
 5203:      *  <          ncovcol=8                >
 5204:      *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
 5205:      *          k=  1    2      3       4     5       6      7        8    9   10   11  12
 5206:      *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
 5207:      * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 5208:      * p Tprod[1]@2={                         6, 5}
 5209:      *p Tvard[1][1]@4= {7, 8, 5, 6}
 5210:      * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
 5211:      *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 5212:      *How to reorganize?
 5213:      * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
 5214:      * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 5215:      *       {2,   1,     4,      8,    5,      6,     3,       7}
 5216:      * Struct []
 5217:      */
 5218: 
 5219:     /* This loop fills the array Tvar from the string 'model'.*/
 5220:     /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
 5221:     /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
 5222:     /* 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
 5223:     /* 	k=3 V4 Tvar[k=3]= 4 (from V4) */
 5224:     /* 	k=2 V1 Tvar[k=2]= 1 (from V1) */
 5225:     /* 	k=1 Tvar[1]=2 (from V2) */
 5226:     /* 	k=5 Tvar[5] */
 5227:     /* for (k=1; k<=cptcovn;k++) { */
 5228:     /* 	cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
 5229:     /* 	} */
 5230:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 5231:     /*
 5232:      * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
 5233:     for(k=cptcovt; k>=1;k--) /**< Number of covariates */
 5234:         Tvar[k]=0;
 5235:     cptcovage=0;
 5236:     for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
 5237:       cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
 5238: 				     modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
 5239:       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
 5240:       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
 5241:       /*scanf("%d",i);*/
 5242:       if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
 5243: 	cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
 5244: 	if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
 5245: 	  /* covar is not filled and then is empty */
 5246: 	  cptcovprod--;
 5247: 	  cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
 5248: 	  Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
 5249: 	  cptcovage++; /* Sums the number of covariates which include age as a product */
 5250: 	  Tage[cptcovage]=k;  /* Tage[1] = 4 */
 5251: 	  /*printf("stre=%s ", stre);*/
 5252: 	} else if (strcmp(strd,"age")==0) { /* or age*Vn */
 5253: 	  cptcovprod--;
 5254: 	  cutl(stre,strb,strc,'V');
 5255: 	  Tvar[k]=atoi(stre);
 5256: 	  cptcovage++;
 5257: 	  Tage[cptcovage]=k;
 5258: 	} else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
 5259: 	  /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
 5260: 	  cptcovn++;
 5261: 	  cptcovprodnoage++;k1++;
 5262: 	  cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
 5263: 	  Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
 5264: 				  because this model-covariate is a construction we invent a new column
 5265: 				  ncovcol + k1
 5266: 				  If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
 5267: 				  Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
 5268: 	  cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
 5269: 	  Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
 5270: 	  Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
 5271: 	  Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
 5272: 	  k2=k2+2;
 5273: 	  Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
 5274: 	  Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
 5275: 	  for (i=1; i<=lastobs;i++){
 5276: 	    /* Computes the new covariate which is a product of
 5277: 	       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
 5278: 	    covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
 5279: 	  }
 5280: 	} /* End age is not in the model */
 5281:       } /* End if model includes a product */
 5282:       else { /* no more sum */
 5283: 	/*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
 5284:        /*  scanf("%d",i);*/
 5285: 	cutl(strd,strc,strb,'V');
 5286: 	ks++; /**< Number of simple covariates */
 5287: 	cptcovn++;
 5288: 	Tvar[k]=atoi(strd);
 5289:       }
 5290:       strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
 5291:       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
 5292: 	scanf("%d",i);*/
 5293:     } /* end of loop + */
 5294:   } /* end model */
 5295:   
 5296:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
 5297:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
 5298: 
 5299:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
 5300:   printf("cptcovprod=%d ", cptcovprod);
 5301:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
 5302: 
 5303:   scanf("%d ",i);*/
 5304: 
 5305: 
 5306:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
 5307:   /*endread:*/
 5308:     printf("Exiting decodemodel: ");
 5309:     return (1);
 5310: }
 5311: 
 5312: calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
 5313: {
 5314:   int i, m;
 5315: 
 5316:   for (i=1; i<=imx; i++) {
 5317:     for(m=2; (m<= maxwav); m++) {
 5318:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
 5319: 	anint[m][i]=9999;
 5320: 	s[m][i]=-1;
 5321:       }
 5322:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
 5323: 	*nberr++;
 5324: 	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);
 5325: 	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);
 5326: 	s[m][i]=-1;
 5327:       }
 5328:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
 5329: 	*nberr++;
 5330: 	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]); 
 5331: 	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]); 
 5332: 	s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
 5333:       }
 5334:     }
 5335:   }
 5336: 
 5337:   for (i=1; i<=imx; i++)  {
 5338:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
 5339:     for(m=firstpass; (m<= lastpass); m++){
 5340:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
 5341: 	if (s[m][i] >= nlstate+1) {
 5342: 	  if(agedc[i]>0)
 5343: 	    if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
 5344: 	      agev[m][i]=agedc[i];
 5345: 	  /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
 5346: 	    else {
 5347: 	      if ((int)andc[i]!=9999){
 5348: 		nbwarn++;
 5349: 		printf("Warning negative age at death: %ld line:%d\n",num[i],i);
 5350: 		fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
 5351: 		agev[m][i]=-1;
 5352: 	      }
 5353: 	    }
 5354: 	}
 5355: 	else if(s[m][i] !=9){ /* Standard case, age in fractional
 5356: 				 years but with the precision of a month */
 5357: 	  agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
 5358: 	  if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
 5359: 	    agev[m][i]=1;
 5360: 	  else if(agev[m][i] < *agemin){ 
 5361: 	    *agemin=agev[m][i];
 5362: 	    printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
 5363: 	  }
 5364: 	  else if(agev[m][i] >*agemax){
 5365: 	    *agemax=agev[m][i];
 5366: 	    /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
 5367: 	  }
 5368: 	  /*agev[m][i]=anint[m][i]-annais[i];*/
 5369: 	  /*	 agev[m][i] = age[i]+2*m;*/
 5370: 	}
 5371: 	else { /* =9 */
 5372: 	  agev[m][i]=1;
 5373: 	  s[m][i]=-1;
 5374: 	}
 5375:       }
 5376:       else /*= 0 Unknown */
 5377: 	agev[m][i]=1;
 5378:     }
 5379:     
 5380:   }
 5381:   for (i=1; i<=imx; i++)  {
 5382:     for(m=firstpass; (m<=lastpass); m++){
 5383:       if (s[m][i] > (nlstate+ndeath)) {
 5384: 	*nberr++;
 5385: 	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);	
 5386: 	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);	
 5387: 	return 1;
 5388:       }
 5389:     }
 5390:   }
 5391: 
 5392:   /*for (i=1; i<=imx; i++){
 5393:   for (m=firstpass; (m<lastpass); m++){
 5394:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
 5395: }
 5396: 
 5397: }*/
 5398: 
 5399: 
 5400:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
 5401:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
 5402: 
 5403:   return (0);
 5404:  /* endread:*/
 5405:     printf("Exiting calandcheckages: ");
 5406:     return (1);
 5407: }
 5408: 
 5409: 
 5410: /***********************************************/
 5411: /**************** Main Program *****************/
 5412: /***********************************************/
 5413: 
 5414: int main(int argc, char *argv[])
 5415: {
 5416: #ifdef GSL
 5417:   const gsl_multimin_fminimizer_type *T;
 5418:   size_t iteri = 0, it;
 5419:   int rval = GSL_CONTINUE;
 5420:   int status = GSL_SUCCESS;
 5421:   double ssval;
 5422: #endif
 5423:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
 5424:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
 5425: 
 5426:   int jj, ll, li, lj, lk;
 5427:   int numlinepar=0; /* Current linenumber of parameter file */
 5428:   int itimes;
 5429:   int NDIM=2;
 5430:   int vpopbased=0;
 5431: 
 5432:   char ca[32], cb[32];
 5433:   /*  FILE *fichtm; *//* Html File */
 5434:   /* FILE *ficgp;*/ /*Gnuplot File */
 5435:   struct stat info;
 5436:   double agedeb;
 5437:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
 5438: 
 5439: 
 5440:   double dum; /* Dummy variable */
 5441:   double ***p3mat;
 5442:   double ***mobaverage;
 5443: 
 5444:   char line[MAXLINE];
 5445:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
 5446:   char pathr[MAXLINE], pathimach[MAXLINE]; 
 5447:   char *tok, *val; /* pathtot */
 5448:   int firstobs=1, lastobs=10;
 5449:   int c,  h , cpt;
 5450:   int jl;
 5451:   int i1, j1, jk, stepsize;
 5452:   int *tab; 
 5453:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
 5454:   int mobilav=0,popforecast=0;
 5455:   int hstepm, nhstepm;
 5456:   int agemortsup;
 5457:   float  sumlpop=0.;
 5458:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
 5459:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
 5460: 
 5461:   double bage=0, fage=110, age, agelim, agebase;
 5462:   double ftolpl=FTOL;
 5463:   double **prlim;
 5464:   double ***param; /* Matrix of parameters */
 5465:   double  *p;
 5466:   double **matcov; /* Matrix of covariance */
 5467:   double ***delti3; /* Scale */
 5468:   double *delti; /* Scale */
 5469:   double ***eij, ***vareij;
 5470:   double **varpl; /* Variances of prevalence limits by age */
 5471:   double *epj, vepp;
 5472: 
 5473:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
 5474:   double **ximort;
 5475:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
 5476:   int *dcwave;
 5477: 
 5478:   char z[1]="c";
 5479: 
 5480:   /*char  *strt;*/
 5481:   char strtend[80];
 5482: 
 5483: 
 5484: /*   setlocale (LC_ALL, ""); */
 5485: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
 5486: /*   textdomain (PACKAGE); */
 5487: /*   setlocale (LC_CTYPE, ""); */
 5488: /*   setlocale (LC_MESSAGES, ""); */
 5489: 
 5490:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
 5491:   rstart_time = time(NULL);  
 5492:   /*  (void) gettimeofday(&start_time,&tzp);*/
 5493:   start_time = *localtime(&rstart_time);
 5494:   curr_time=start_time;
 5495:   /*tml = *localtime(&start_time.tm_sec);*/
 5496:   /* strcpy(strstart,asctime(&tml)); */
 5497:   strcpy(strstart,asctime(&start_time));
 5498: 
 5499: /*  printf("Localtime (at start)=%s",strstart); */
 5500: /*  tp.tm_sec = tp.tm_sec +86400; */
 5501: /*  tm = *localtime(&start_time.tm_sec); */
 5502: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
 5503: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
 5504: /*   tmg.tm_hour=tmg.tm_hour + 1; */
 5505: /*   tp.tm_sec = mktime(&tmg); */
 5506: /*   strt=asctime(&tmg); */
 5507: /*   printf("Time(after) =%s",strstart);  */
 5508: /*  (void) time (&time_value);
 5509: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
 5510: *  tm = *localtime(&time_value);
 5511: *  strstart=asctime(&tm);
 5512: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
 5513: */
 5514: 
 5515:   nberr=0; /* Number of errors and warnings */
 5516:   nbwarn=0;
 5517:   getcwd(pathcd, size);
 5518: 
 5519:   printf("\n%s\n%s",version,fullversion);
 5520:   if(argc <=1){
 5521:     printf("\nEnter the parameter file name: ");
 5522:     fgets(pathr,FILENAMELENGTH,stdin);
 5523:     i=strlen(pathr);
 5524:     if(pathr[i-1]=='\n')
 5525:       pathr[i-1]='\0';
 5526:     i=strlen(pathr);
 5527:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
 5528:       pathr[i-1]='\0';
 5529:    for (tok = pathr; tok != NULL; ){
 5530:       printf("Pathr |%s|\n",pathr);
 5531:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
 5532:       printf("val= |%s| pathr=%s\n",val,pathr);
 5533:       strcpy (pathtot, val);
 5534:       if(pathr[0] == '\0') break; /* Dirty */
 5535:     }
 5536:   }
 5537:   else{
 5538:     strcpy(pathtot,argv[1]);
 5539:   }
 5540:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
 5541:   /*cygwin_split_path(pathtot,path,optionfile);
 5542:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
 5543:   /* cutv(path,optionfile,pathtot,'\\');*/
 5544: 
 5545:   /* Split argv[0], imach program to get pathimach */
 5546:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
 5547:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 5548:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 5549:  /*   strcpy(pathimach,argv[0]); */
 5550:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
 5551:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
 5552:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
 5553:   chdir(path); /* Can be a relative path */
 5554:   if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
 5555:     printf("Current directory %s!\n",pathcd);
 5556:   strcpy(command,"mkdir ");
 5557:   strcat(command,optionfilefiname);
 5558:   if((outcmd=system(command)) != 0){
 5559:     printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
 5560:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
 5561:     /* fclose(ficlog); */
 5562: /*     exit(1); */
 5563:   }
 5564: /*   if((imk=mkdir(optionfilefiname))<0){ */
 5565: /*     perror("mkdir"); */
 5566: /*   } */
 5567: 
 5568:   /*-------- arguments in the command line --------*/
 5569: 
 5570:   /* Log file */
 5571:   strcat(filelog, optionfilefiname);
 5572:   strcat(filelog,".log");    /* */
 5573:   if((ficlog=fopen(filelog,"w"))==NULL)    {
 5574:     printf("Problem with logfile %s\n",filelog);
 5575:     goto end;
 5576:   }
 5577:   fprintf(ficlog,"Log filename:%s\n",filelog);
 5578:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
 5579:   fprintf(ficlog,"\nEnter the parameter file name: \n");
 5580:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
 5581:  path=%s \n\
 5582:  optionfile=%s\n\
 5583:  optionfilext=%s\n\
 5584:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
 5585: 
 5586:   printf("Local time (at start):%s",strstart);
 5587:   fprintf(ficlog,"Local time (at start): %s",strstart);
 5588:   fflush(ficlog);
 5589: /*   (void) gettimeofday(&curr_time,&tzp); */
 5590: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
 5591: 
 5592:   /* */
 5593:   strcpy(fileres,"r");
 5594:   strcat(fileres, optionfilefiname);
 5595:   strcat(fileres,".txt");    /* Other files have txt extension */
 5596: 
 5597:   /*---------arguments file --------*/
 5598: 
 5599:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
 5600:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 5601:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 5602:     fflush(ficlog);
 5603:     /* goto end; */
 5604:     exit(70); 
 5605:   }
 5606: 
 5607: 
 5608: 
 5609:   strcpy(filereso,"o");
 5610:   strcat(filereso,fileres);
 5611:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
 5612:     printf("Problem with Output resultfile: %s\n", filereso);
 5613:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
 5614:     fflush(ficlog);
 5615:     goto end;
 5616:   }
 5617: 
 5618:   /* Reads comments: lines beginning with '#' */
 5619:   numlinepar=0;
 5620:   while((c=getc(ficpar))=='#' && c!= EOF){
 5621:     ungetc(c,ficpar);
 5622:     fgets(line, MAXLINE, ficpar);
 5623:     numlinepar++;
 5624:     fputs(line,stdout);
 5625:     fputs(line,ficparo);
 5626:     fputs(line,ficlog);
 5627:   }
 5628:   ungetc(c,ficpar);
 5629: 
 5630:   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);
 5631:   numlinepar++;
 5632:   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);
 5633:   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);
 5634:   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);
 5635:   fflush(ficlog);
 5636:   while((c=getc(ficpar))=='#' && c!= EOF){
 5637:     ungetc(c,ficpar);
 5638:     fgets(line, MAXLINE, ficpar);
 5639:     numlinepar++;
 5640:     fputs(line, stdout);
 5641:     //puts(line);
 5642:     fputs(line,ficparo);
 5643:     fputs(line,ficlog);
 5644:   }
 5645:   ungetc(c,ficpar);
 5646: 
 5647:    
 5648:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
 5649:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
 5650:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
 5651:      v1+v2*age+v2*v3 makes cptcovn = 3
 5652:   */
 5653:   if (strlen(model)>1) 
 5654:     ncovmodel=2+nbocc(model,'+')+1; /*Number of variables including intercept and age = cptcovn + intercept + age : v1+v2+v3+v2*v4+v5*age makes 5+2=7*/
 5655:   else
 5656:     ncovmodel=2;
 5657:   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
 5658:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
 5659:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
 5660:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
 5661:     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);
 5662:     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);
 5663:     fflush(stdout);
 5664:     fclose (ficlog);
 5665:     goto end;
 5666:   }
 5667:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 5668:   delti=delti3[1][1];
 5669:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
 5670:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
 5671:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 5672:     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 5673:     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 5674:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 5675:     fclose (ficparo);
 5676:     fclose (ficlog);
 5677:     goto end;
 5678:     exit(0);
 5679:   }
 5680:   else if(mle==-3) {
 5681:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 5682:     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 5683:     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 5684:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 5685:     matcov=matrix(1,npar,1,npar);
 5686:   }
 5687:   else{
 5688:     /* Read guessed parameters */
 5689:     /* Reads comments: lines beginning with '#' */
 5690:     while((c=getc(ficpar))=='#' && c!= EOF){
 5691:       ungetc(c,ficpar);
 5692:       fgets(line, MAXLINE, ficpar);
 5693:       numlinepar++;
 5694:       fputs(line,stdout);
 5695:       fputs(line,ficparo);
 5696:       fputs(line,ficlog);
 5697:     }
 5698:     ungetc(c,ficpar);
 5699:     
 5700:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 5701:     for(i=1; i <=nlstate; i++){
 5702:       j=0;
 5703:       for(jj=1; jj <=nlstate+ndeath; jj++){
 5704: 	if(jj==i) continue;
 5705: 	j++;
 5706: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 5707: 	if ((i1 != i) && (j1 != j)){
 5708: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
 5709: It might be a problem of design; if ncovcol and the model are correct\n \
 5710: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
 5711: 	  exit(1);
 5712: 	}
 5713: 	fprintf(ficparo,"%1d%1d",i1,j1);
 5714: 	if(mle==1)
 5715: 	  printf("%1d%1d",i,j);
 5716: 	fprintf(ficlog,"%1d%1d",i,j);
 5717: 	for(k=1; k<=ncovmodel;k++){
 5718: 	  fscanf(ficpar," %lf",&param[i][j][k]);
 5719: 	  if(mle==1){
 5720: 	    printf(" %lf",param[i][j][k]);
 5721: 	    fprintf(ficlog," %lf",param[i][j][k]);
 5722: 	  }
 5723: 	  else
 5724: 	    fprintf(ficlog," %lf",param[i][j][k]);
 5725: 	  fprintf(ficparo," %lf",param[i][j][k]);
 5726: 	}
 5727: 	fscanf(ficpar,"\n");
 5728: 	numlinepar++;
 5729: 	if(mle==1)
 5730: 	  printf("\n");
 5731: 	fprintf(ficlog,"\n");
 5732: 	fprintf(ficparo,"\n");
 5733:       }
 5734:     }  
 5735:     fflush(ficlog);
 5736: 
 5737:     /* Reads scales values */
 5738:     p=param[1][1];
 5739:     
 5740:     /* Reads comments: lines beginning with '#' */
 5741:     while((c=getc(ficpar))=='#' && c!= EOF){
 5742:       ungetc(c,ficpar);
 5743:       fgets(line, MAXLINE, ficpar);
 5744:       numlinepar++;
 5745:       fputs(line,stdout);
 5746:       fputs(line,ficparo);
 5747:       fputs(line,ficlog);
 5748:     }
 5749:     ungetc(c,ficpar);
 5750: 
 5751:     for(i=1; i <=nlstate; i++){
 5752:       for(j=1; j <=nlstate+ndeath-1; j++){
 5753: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 5754: 	if ( (i1-i) * (j1-j) != 0){
 5755: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
 5756: 	  exit(1);
 5757: 	}
 5758: 	printf("%1d%1d",i,j);
 5759: 	fprintf(ficparo,"%1d%1d",i1,j1);
 5760: 	fprintf(ficlog,"%1d%1d",i1,j1);
 5761: 	for(k=1; k<=ncovmodel;k++){
 5762: 	  fscanf(ficpar,"%le",&delti3[i][j][k]);
 5763: 	  printf(" %le",delti3[i][j][k]);
 5764: 	  fprintf(ficparo," %le",delti3[i][j][k]);
 5765: 	  fprintf(ficlog," %le",delti3[i][j][k]);
 5766: 	}
 5767: 	fscanf(ficpar,"\n");
 5768: 	numlinepar++;
 5769: 	printf("\n");
 5770: 	fprintf(ficparo,"\n");
 5771: 	fprintf(ficlog,"\n");
 5772:       }
 5773:     }
 5774:     fflush(ficlog);
 5775: 
 5776:     /* Reads covariance matrix */
 5777:     delti=delti3[1][1];
 5778: 
 5779: 
 5780:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
 5781:   
 5782:     /* Reads comments: lines beginning with '#' */
 5783:     while((c=getc(ficpar))=='#' && c!= EOF){
 5784:       ungetc(c,ficpar);
 5785:       fgets(line, MAXLINE, ficpar);
 5786:       numlinepar++;
 5787:       fputs(line,stdout);
 5788:       fputs(line,ficparo);
 5789:       fputs(line,ficlog);
 5790:     }
 5791:     ungetc(c,ficpar);
 5792:   
 5793:     matcov=matrix(1,npar,1,npar);
 5794:     for(i=1; i <=npar; i++)
 5795:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
 5796:       
 5797:     for(i=1; i <=npar; i++){
 5798:       fscanf(ficpar,"%s",str);
 5799:       if(mle==1)
 5800: 	printf("%s",str);
 5801:       fprintf(ficlog,"%s",str);
 5802:       fprintf(ficparo,"%s",str);
 5803:       for(j=1; j <=i; j++){
 5804: 	fscanf(ficpar," %le",&matcov[i][j]);
 5805: 	if(mle==1){
 5806: 	  printf(" %.5le",matcov[i][j]);
 5807: 	}
 5808: 	fprintf(ficlog," %.5le",matcov[i][j]);
 5809: 	fprintf(ficparo," %.5le",matcov[i][j]);
 5810:       }
 5811:       fscanf(ficpar,"\n");
 5812:       numlinepar++;
 5813:       if(mle==1)
 5814: 	printf("\n");
 5815:       fprintf(ficlog,"\n");
 5816:       fprintf(ficparo,"\n");
 5817:     }
 5818:     for(i=1; i <=npar; i++)
 5819:       for(j=i+1;j<=npar;j++)
 5820: 	matcov[i][j]=matcov[j][i];
 5821:     
 5822:     if(mle==1)
 5823:       printf("\n");
 5824:     fprintf(ficlog,"\n");
 5825:     
 5826:     fflush(ficlog);
 5827:     
 5828:     /*-------- Rewriting parameter file ----------*/
 5829:     strcpy(rfileres,"r");    /* "Rparameterfile */
 5830:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
 5831:     strcat(rfileres,".");    /* */
 5832:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
 5833:     if((ficres =fopen(rfileres,"w"))==NULL) {
 5834:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
 5835:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
 5836:     }
 5837:     fprintf(ficres,"#%s\n",version);
 5838:   }    /* End of mle != -3 */
 5839: 
 5840: 
 5841:   n= lastobs;
 5842:   num=lvector(1,n);
 5843:   moisnais=vector(1,n);
 5844:   annais=vector(1,n);
 5845:   moisdc=vector(1,n);
 5846:   andc=vector(1,n);
 5847:   agedc=vector(1,n);
 5848:   cod=ivector(1,n);
 5849:   weight=vector(1,n);
 5850:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
 5851:   mint=matrix(1,maxwav,1,n);
 5852:   anint=matrix(1,maxwav,1,n);
 5853:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
 5854:   tab=ivector(1,NCOVMAX);
 5855:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
 5856: 
 5857:   /* Reads data from file datafile */
 5858:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
 5859:     goto end;
 5860: 
 5861:   /* Calculation of the number of parameters from char model */
 5862:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
 5863: 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
 5864: 	k=3 V4 Tvar[k=3]= 4 (from V4)
 5865: 	k=2 V1 Tvar[k=2]= 1 (from V1)
 5866: 	k=1 Tvar[1]=2 (from V2)
 5867:     */
 5868:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
 5869:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
 5870:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
 5871:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
 5872:   */
 5873:   /* For model-covariate k tells which data-covariate to use but
 5874:     because this model-covariate is a construction we invent a new column
 5875:     ncovcol + k1
 5876:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
 5877:     Tvar[3=V1*V4]=4+1 etc */
 5878:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
 5879:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
 5880:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
 5881:   */
 5882:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
 5883:   Tvard=imatrix(1,NCOVMAX,1,2); /* n=Tvard[k1][1]  and m=Tvard[k1][2] gives the couple n,m of the k1 th product Vn*Vm
 5884: 			    * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
 5885: 			    * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
 5886:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
 5887: 			 4 covariates (3 plus signs)
 5888: 			 Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
 5889: 		      */  
 5890: 
 5891:   if(decodemodel(model, lastobs) == 1)
 5892:     goto end;
 5893: 
 5894:   if((double)(lastobs-imx)/(double)imx > 1.10){
 5895:     nbwarn++;
 5896:     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); 
 5897:     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); 
 5898:   }
 5899:     /*  if(mle==1){*/
 5900:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
 5901:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
 5902:   }
 5903: 
 5904:     /*-calculation of age at interview from date of interview and age at death -*/
 5905:   agev=matrix(1,maxwav,1,imx);
 5906: 
 5907:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
 5908:     goto end;
 5909: 
 5910: 
 5911:   agegomp=(int)agemin;
 5912:   free_vector(moisnais,1,n);
 5913:   free_vector(annais,1,n);
 5914:   /* free_matrix(mint,1,maxwav,1,n);
 5915:      free_matrix(anint,1,maxwav,1,n);*/
 5916:   free_vector(moisdc,1,n);
 5917:   free_vector(andc,1,n);
 5918:   /* */
 5919:   
 5920:   wav=ivector(1,imx);
 5921:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
 5922:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
 5923:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
 5924:    
 5925:   /* Concatenates waves */
 5926:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
 5927:   /* */
 5928:  
 5929:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
 5930: 
 5931:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
 5932:   ncodemax[1]=1;
 5933:   Ndum =ivector(-1,NCOVMAX);  
 5934:   if (ncovmodel > 2)
 5935:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
 5936: 
 5937:   codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
 5938:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
 5939:   h=0;
 5940: 
 5941: 
 5942:   /*if (cptcovn > 0) */
 5943:       
 5944:  
 5945:   m=pow(2,cptcoveff);
 5946:  
 5947:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
 5948:     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 */ 
 5949:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
 5950: 	for(cpt=1; cpt <=pow(2,k-1); cpt++){  /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */ 
 5951: 	  h++;
 5952: 	  if (h>m) 
 5953: 	    h=1;
 5954: 	  /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
 5955: 	   *     h     1     2     3     4
 5956: 	   *______________________________  
 5957: 	   *     1 i=1 1 i=1 1 i=1 1 i=1 1
 5958: 	   *     2     2     1     1     1
 5959: 	   *     3 i=2 1     2     1     1
 5960: 	   *     4     2     2     1     1
 5961: 	   *     5 i=3 1 i=2 1     2     1
 5962: 	   *     6     2     1     2     1
 5963: 	   *     7 i=4 1     2     2     1
 5964: 	   *     8     2     2     2     1
 5965: 	   *     9 i=5 1 i=3 1 i=2 1     1
 5966: 	   *    10     2     1     1     1
 5967: 	   *    11 i=6 1     2     1     1
 5968: 	   *    12     2     2     1     1
 5969: 	   *    13 i=7 1 i=4 1     2     1    
 5970: 	   *    14     2     1     2     1
 5971: 	   *    15 i=8 1     2     2     1
 5972: 	   *    16     2     2     2     1
 5973: 	   */
 5974: 	  codtab[h][k]=j;
 5975: 	  /*codtab[h][Tvar[k]]=j;*/
 5976: 	  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]]);
 5977: 	} 
 5978:       }
 5979:     }
 5980:   } 
 5981:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
 5982:      codtab[1][2]=1;codtab[2][2]=2; */
 5983:   /* for(i=1; i <=m ;i++){ 
 5984:      for(k=1; k <=cptcovn; k++){
 5985:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
 5986:      }
 5987:      printf("\n");
 5988:      }
 5989:      scanf("%d",i);*/
 5990: 
 5991:  free_ivector(Ndum,-1,NCOVMAX);
 5992: 
 5993: 
 5994:     
 5995:   /*------------ gnuplot -------------*/
 5996:   strcpy(optionfilegnuplot,optionfilefiname);
 5997:   if(mle==-3)
 5998:     strcat(optionfilegnuplot,"-mort");
 5999:   strcat(optionfilegnuplot,".gp");
 6000: 
 6001:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
 6002:     printf("Problem with file %s",optionfilegnuplot);
 6003:   }
 6004:   else{
 6005:     fprintf(ficgp,"\n# %s\n", version); 
 6006:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
 6007:     //fprintf(ficgp,"set missing 'NaNq'\n");
 6008:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
 6009:   }
 6010:   /*  fclose(ficgp);*/
 6011:   /*--------- index.htm --------*/
 6012: 
 6013:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
 6014:   if(mle==-3)
 6015:     strcat(optionfilehtm,"-mort");
 6016:   strcat(optionfilehtm,".htm");
 6017:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
 6018:     printf("Problem with %s \n",optionfilehtm);
 6019:     exit(0);
 6020:   }
 6021: 
 6022:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
 6023:   strcat(optionfilehtmcov,"-cov.htm");
 6024:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
 6025:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
 6026:   }
 6027:   else{
 6028:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 6029: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 6030: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
 6031: 	  optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 6032:   }
 6033: 
 6034:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 6035: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 6036: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
 6037: \n\
 6038: <hr  size=\"2\" color=\"#EC5E5E\">\
 6039:  <ul><li><h4>Parameter files</h4>\n\
 6040:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
 6041:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
 6042:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
 6043:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
 6044:  - Date and time at start: %s</ul>\n",\
 6045: 	  optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
 6046: 	  optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
 6047: 	  fileres,fileres,\
 6048: 	  filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
 6049:   fflush(fichtm);
 6050: 
 6051:   strcpy(pathr,path);
 6052:   strcat(pathr,optionfilefiname);
 6053:   chdir(optionfilefiname); /* Move to directory named optionfile */
 6054:   
 6055:   /* Calculates basic frequencies. Computes observed prevalence at single age
 6056:      and prints on file fileres'p'. */
 6057:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
 6058: 
 6059:   fprintf(fichtm,"\n");
 6060:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
 6061: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
 6062: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
 6063: 	  imx,agemin,agemax,jmin,jmax,jmean);
 6064:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6065:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6066:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6067:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6068:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
 6069:     
 6070:    
 6071:   /* For Powell, parameters are in a vector p[] starting at p[1]
 6072:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
 6073:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
 6074: 
 6075:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
 6076: 
 6077:   if (mle==-3){
 6078:     ximort=matrix(1,NDIM,1,NDIM); 
 6079: /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
 6080:     cens=ivector(1,n);
 6081:     ageexmed=vector(1,n);
 6082:     agecens=vector(1,n);
 6083:     dcwave=ivector(1,n);
 6084:  
 6085:     for (i=1; i<=imx; i++){
 6086:       dcwave[i]=-1;
 6087:       for (m=firstpass; m<=lastpass; m++)
 6088: 	if (s[m][i]>nlstate) {
 6089: 	  dcwave[i]=m;
 6090: 	  /*	printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
 6091: 	  break;
 6092: 	}
 6093:     }
 6094: 
 6095:     for (i=1; i<=imx; i++) {
 6096:       if (wav[i]>0){
 6097: 	ageexmed[i]=agev[mw[1][i]][i];
 6098: 	j=wav[i];
 6099: 	agecens[i]=1.; 
 6100: 
 6101: 	if (ageexmed[i]> 1 && wav[i] > 0){
 6102: 	  agecens[i]=agev[mw[j][i]][i];
 6103: 	  cens[i]= 1;
 6104: 	}else if (ageexmed[i]< 1) 
 6105: 	  cens[i]= -1;
 6106: 	if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
 6107: 	  cens[i]=0 ;
 6108:       }
 6109:       else cens[i]=-1;
 6110:     }
 6111:     
 6112:     for (i=1;i<=NDIM;i++) {
 6113:       for (j=1;j<=NDIM;j++)
 6114: 	ximort[i][j]=(i == j ? 1.0 : 0.0);
 6115:     }
 6116:     
 6117:     /*p[1]=0.0268; p[NDIM]=0.083;*/
 6118:     /*printf("%lf %lf", p[1], p[2]);*/
 6119:     
 6120:     
 6121: #ifdef GSL
 6122:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
 6123: #else
 6124:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
 6125: #endif
 6126:     strcpy(filerespow,"pow-mort"); 
 6127:     strcat(filerespow,fileres);
 6128:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
 6129:       printf("Problem with resultfile: %s\n", filerespow);
 6130:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 6131:     }
 6132: #ifdef GSL
 6133:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
 6134: #else
 6135:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
 6136: #endif
 6137:     /*  for (i=1;i<=nlstate;i++)
 6138: 	for(j=1;j<=nlstate+ndeath;j++)
 6139: 	if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 6140:     */
 6141:     fprintf(ficrespow,"\n");
 6142: #ifdef GSL
 6143:     /* gsl starts here */ 
 6144:     T = gsl_multimin_fminimizer_nmsimplex;
 6145:     gsl_multimin_fminimizer *sfm = NULL;
 6146:     gsl_vector *ss, *x;
 6147:     gsl_multimin_function minex_func;
 6148: 
 6149:     /* Initial vertex size vector */
 6150:     ss = gsl_vector_alloc (NDIM);
 6151:     
 6152:     if (ss == NULL){
 6153:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
 6154:     }
 6155:     /* Set all step sizes to 1 */
 6156:     gsl_vector_set_all (ss, 0.001);
 6157: 
 6158:     /* Starting point */
 6159:     
 6160:     x = gsl_vector_alloc (NDIM);
 6161:     
 6162:     if (x == NULL){
 6163:       gsl_vector_free(ss);
 6164:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
 6165:     }
 6166:   
 6167:     /* Initialize method and iterate */
 6168:     /*     p[1]=0.0268; p[NDIM]=0.083; */
 6169: /*     gsl_vector_set(x, 0, 0.0268); */
 6170: /*     gsl_vector_set(x, 1, 0.083); */
 6171:     gsl_vector_set(x, 0, p[1]);
 6172:     gsl_vector_set(x, 1, p[2]);
 6173: 
 6174:     minex_func.f = &gompertz_f;
 6175:     minex_func.n = NDIM;
 6176:     minex_func.params = (void *)&p; /* ??? */
 6177:     
 6178:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
 6179:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
 6180:     
 6181:     printf("Iterations beginning .....\n\n");
 6182:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
 6183: 
 6184:     iteri=0;
 6185:     while (rval == GSL_CONTINUE){
 6186:       iteri++;
 6187:       status = gsl_multimin_fminimizer_iterate(sfm);
 6188:       
 6189:       if (status) printf("error: %s\n", gsl_strerror (status));
 6190:       fflush(0);
 6191:       
 6192:       if (status) 
 6193:         break;
 6194:       
 6195:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
 6196:       ssval = gsl_multimin_fminimizer_size (sfm);
 6197:       
 6198:       if (rval == GSL_SUCCESS)
 6199:         printf ("converged to a local maximum at\n");
 6200:       
 6201:       printf("%5d ", iteri);
 6202:       for (it = 0; it < NDIM; it++){
 6203: 	printf ("%10.5f ", gsl_vector_get (sfm->x, it));
 6204:       }
 6205:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
 6206:     }
 6207:     
 6208:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
 6209:     
 6210:     gsl_vector_free(x); /* initial values */
 6211:     gsl_vector_free(ss); /* inital step size */
 6212:     for (it=0; it<NDIM; it++){
 6213:       p[it+1]=gsl_vector_get(sfm->x,it);
 6214:       fprintf(ficrespow," %.12lf", p[it]);
 6215:     }
 6216:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
 6217: #endif
 6218: #ifdef POWELL
 6219:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
 6220: #endif  
 6221:     fclose(ficrespow);
 6222:     
 6223:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
 6224: 
 6225:     for(i=1; i <=NDIM; i++)
 6226:       for(j=i+1;j<=NDIM;j++)
 6227: 	matcov[i][j]=matcov[j][i];
 6228:     
 6229:     printf("\nCovariance matrix\n ");
 6230:     for(i=1; i <=NDIM; i++) {
 6231:       for(j=1;j<=NDIM;j++){ 
 6232: 	printf("%f ",matcov[i][j]);
 6233:       }
 6234:       printf("\n ");
 6235:     }
 6236:     
 6237:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
 6238:     for (i=1;i<=NDIM;i++) 
 6239:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
 6240: 
 6241:     lsurv=vector(1,AGESUP);
 6242:     lpop=vector(1,AGESUP);
 6243:     tpop=vector(1,AGESUP);
 6244:     lsurv[agegomp]=100000;
 6245:     
 6246:     for (k=agegomp;k<=AGESUP;k++) {
 6247:       agemortsup=k;
 6248:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
 6249:     }
 6250:     
 6251:     for (k=agegomp;k<agemortsup;k++)
 6252:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
 6253:     
 6254:     for (k=agegomp;k<agemortsup;k++){
 6255:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
 6256:       sumlpop=sumlpop+lpop[k];
 6257:     }
 6258:     
 6259:     tpop[agegomp]=sumlpop;
 6260:     for (k=agegomp;k<(agemortsup-3);k++){
 6261:       /*  tpop[k+1]=2;*/
 6262:       tpop[k+1]=tpop[k]-lpop[k];
 6263:     }
 6264:     
 6265:     
 6266:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
 6267:     for (k=agegomp;k<(agemortsup-2);k++) 
 6268:       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]);
 6269:     
 6270:     
 6271:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 6272:     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 6273:     
 6274:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
 6275: 		     stepm, weightopt,\
 6276: 		     model,imx,p,matcov,agemortsup);
 6277:     
 6278:     free_vector(lsurv,1,AGESUP);
 6279:     free_vector(lpop,1,AGESUP);
 6280:     free_vector(tpop,1,AGESUP);
 6281: #ifdef GSL
 6282:     free_ivector(cens,1,n);
 6283:     free_vector(agecens,1,n);
 6284:     free_ivector(dcwave,1,n);
 6285:     free_matrix(ximort,1,NDIM,1,NDIM);
 6286: #endif
 6287:   } /* Endof if mle==-3 */
 6288:   
 6289:   else{ /* For mle >=1 */
 6290:     globpr=0;/* debug */
 6291:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 6292:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 6293:     for (k=1; k<=npar;k++)
 6294:       printf(" %d %8.5f",k,p[k]);
 6295:     printf("\n");
 6296:     globpr=1; /* to print the contributions */
 6297:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 6298:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 6299:     for (k=1; k<=npar;k++)
 6300:       printf(" %d %8.5f",k,p[k]);
 6301:     printf("\n");
 6302:     if(mle>=1){ /* Could be 1 or 2 */
 6303:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
 6304:     }
 6305:     
 6306:     /*--------- results files --------------*/
 6307:     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);
 6308:     
 6309:     
 6310:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 6311:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 6312:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 6313:     for(i=1,jk=1; i <=nlstate; i++){
 6314:       for(k=1; k <=(nlstate+ndeath); k++){
 6315: 	if (k != i) {
 6316: 	  printf("%d%d ",i,k);
 6317: 	  fprintf(ficlog,"%d%d ",i,k);
 6318: 	  fprintf(ficres,"%1d%1d ",i,k);
 6319: 	  for(j=1; j <=ncovmodel; j++){
 6320: 	    printf("%lf ",p[jk]);
 6321: 	    fprintf(ficlog,"%lf ",p[jk]);
 6322: 	    fprintf(ficres,"%lf ",p[jk]);
 6323: 	    jk++; 
 6324: 	  }
 6325: 	  printf("\n");
 6326: 	  fprintf(ficlog,"\n");
 6327: 	  fprintf(ficres,"\n");
 6328: 	}
 6329:       }
 6330:     }
 6331:     if(mle!=0){
 6332:       /* Computing hessian and covariance matrix */
 6333:       ftolhess=ftol; /* Usually correct */
 6334:       hesscov(matcov, p, npar, delti, ftolhess, func);
 6335:     }
 6336:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
 6337:     printf("# Scales (for hessian or gradient estimation)\n");
 6338:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
 6339:     for(i=1,jk=1; i <=nlstate; i++){
 6340:       for(j=1; j <=nlstate+ndeath; j++){
 6341: 	if (j!=i) {
 6342: 	  fprintf(ficres,"%1d%1d",i,j);
 6343: 	  printf("%1d%1d",i,j);
 6344: 	  fprintf(ficlog,"%1d%1d",i,j);
 6345: 	  for(k=1; k<=ncovmodel;k++){
 6346: 	    printf(" %.5e",delti[jk]);
 6347: 	    fprintf(ficlog," %.5e",delti[jk]);
 6348: 	    fprintf(ficres," %.5e",delti[jk]);
 6349: 	    jk++;
 6350: 	  }
 6351: 	  printf("\n");
 6352: 	  fprintf(ficlog,"\n");
 6353: 	  fprintf(ficres,"\n");
 6354: 	}
 6355:       }
 6356:     }
 6357:     
 6358:     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");
 6359:     if(mle>=1)
 6360:       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");
 6361:     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");
 6362:     /* # 121 Var(a12)\n\ */
 6363:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
 6364:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 6365:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 6366:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 6367:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 6368:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 6369:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 6370:     
 6371:     
 6372:     /* Just to have a covariance matrix which will be more understandable
 6373:        even is we still don't want to manage dictionary of variables
 6374:     */
 6375:     for(itimes=1;itimes<=2;itimes++){
 6376:       jj=0;
 6377:       for(i=1; i <=nlstate; i++){
 6378: 	for(j=1; j <=nlstate+ndeath; j++){
 6379: 	  if(j==i) continue;
 6380: 	  for(k=1; k<=ncovmodel;k++){
 6381: 	    jj++;
 6382: 	    ca[0]= k+'a'-1;ca[1]='\0';
 6383: 	    if(itimes==1){
 6384: 	      if(mle>=1)
 6385: 		printf("#%1d%1d%d",i,j,k);
 6386: 	      fprintf(ficlog,"#%1d%1d%d",i,j,k);
 6387: 	      fprintf(ficres,"#%1d%1d%d",i,j,k);
 6388: 	    }else{
 6389: 	      if(mle>=1)
 6390: 		printf("%1d%1d%d",i,j,k);
 6391: 	      fprintf(ficlog,"%1d%1d%d",i,j,k);
 6392: 	      fprintf(ficres,"%1d%1d%d",i,j,k);
 6393: 	    }
 6394: 	    ll=0;
 6395: 	    for(li=1;li <=nlstate; li++){
 6396: 	      for(lj=1;lj <=nlstate+ndeath; lj++){
 6397: 		if(lj==li) continue;
 6398: 		for(lk=1;lk<=ncovmodel;lk++){
 6399: 		  ll++;
 6400: 		  if(ll<=jj){
 6401: 		    cb[0]= lk +'a'-1;cb[1]='\0';
 6402: 		    if(ll<jj){
 6403: 		      if(itimes==1){
 6404: 			if(mle>=1)
 6405: 			  printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 6406: 			fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 6407: 			fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 6408: 		      }else{
 6409: 			if(mle>=1)
 6410: 			  printf(" %.5e",matcov[jj][ll]); 
 6411: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 6412: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 6413: 		      }
 6414: 		    }else{
 6415: 		      if(itimes==1){
 6416: 			if(mle>=1)
 6417: 			  printf(" Var(%s%1d%1d)",ca,i,j);
 6418: 			fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
 6419: 			fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
 6420: 		      }else{
 6421: 			if(mle>=1)
 6422: 			  printf(" %.5e",matcov[jj][ll]); 
 6423: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 6424: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 6425: 		      }
 6426: 		    }
 6427: 		  }
 6428: 		} /* end lk */
 6429: 	      } /* end lj */
 6430: 	    } /* end li */
 6431: 	    if(mle>=1)
 6432: 	      printf("\n");
 6433: 	    fprintf(ficlog,"\n");
 6434: 	    fprintf(ficres,"\n");
 6435: 	    numlinepar++;
 6436: 	  } /* end k*/
 6437: 	} /*end j */
 6438:       } /* end i */
 6439:     } /* end itimes */
 6440:     
 6441:     fflush(ficlog);
 6442:     fflush(ficres);
 6443:     
 6444:     while((c=getc(ficpar))=='#' && c!= EOF){
 6445:       ungetc(c,ficpar);
 6446:       fgets(line, MAXLINE, ficpar);
 6447:       fputs(line,stdout);
 6448:       fputs(line,ficparo);
 6449:     }
 6450:     ungetc(c,ficpar);
 6451:     
 6452:     estepm=0;
 6453:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
 6454:     if (estepm==0 || estepm < stepm) estepm=stepm;
 6455:     if (fage <= 2) {
 6456:       bage = ageminpar;
 6457:       fage = agemaxpar;
 6458:     }
 6459:     
 6460:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
 6461:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 6462:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 6463:     
 6464:     while((c=getc(ficpar))=='#' && c!= EOF){
 6465:       ungetc(c,ficpar);
 6466:       fgets(line, MAXLINE, ficpar);
 6467:       fputs(line,stdout);
 6468:       fputs(line,ficparo);
 6469:     }
 6470:     ungetc(c,ficpar);
 6471:     
 6472:     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);
 6473:     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);
 6474:     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);
 6475:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
 6476:     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);
 6477:     
 6478:     while((c=getc(ficpar))=='#' && c!= EOF){
 6479:       ungetc(c,ficpar);
 6480:       fgets(line, MAXLINE, ficpar);
 6481:       fputs(line,stdout);
 6482:       fputs(line,ficparo);
 6483:     }
 6484:     ungetc(c,ficpar);
 6485:     
 6486:     
 6487:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
 6488:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
 6489:     
 6490:     fscanf(ficpar,"pop_based=%d\n",&popbased);
 6491:     fprintf(ficparo,"pop_based=%d\n",popbased);   
 6492:     fprintf(ficres,"pop_based=%d\n",popbased);   
 6493:     
 6494:     while((c=getc(ficpar))=='#' && c!= EOF){
 6495:       ungetc(c,ficpar);
 6496:       fgets(line, MAXLINE, ficpar);
 6497:       fputs(line,stdout);
 6498:       fputs(line,ficparo);
 6499:     }
 6500:     ungetc(c,ficpar);
 6501:     
 6502:     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);
 6503:     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);
 6504:     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);
 6505:     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);
 6506:     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);
 6507:     /* day and month of proj2 are not used but only year anproj2.*/
 6508:     
 6509:     
 6510:     
 6511:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
 6512:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
 6513:     
 6514:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 6515:     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 6516:     
 6517:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
 6518: 		 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
 6519: 		 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
 6520:       
 6521:    /*------------ free_vector  -------------*/
 6522:    /*  chdir(path); */
 6523:  
 6524:     free_ivector(wav,1,imx);
 6525:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
 6526:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
 6527:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
 6528:     free_lvector(num,1,n);
 6529:     free_vector(agedc,1,n);
 6530:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
 6531:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
 6532:     fclose(ficparo);
 6533:     fclose(ficres);
 6534: 
 6535: 
 6536:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 6537: #include "prevlim.h"  /* Use ficrespl, ficlog */
 6538:     fclose(ficrespl);
 6539: 
 6540: #ifdef FREEEXIT2
 6541: #include "freeexit2.h"
 6542: #endif
 6543: 
 6544:     /*------------- h Pij x at various ages ------------*/
 6545: #include "hpijx.h"
 6546:     fclose(ficrespij);
 6547: 
 6548:   /*-------------- Variance of one-step probabilities---*/
 6549:     k=1;
 6550:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
 6551: 
 6552: 
 6553:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6554:     for(i=1;i<=AGESUP;i++)
 6555:       for(j=1;j<=NCOVMAX;j++)
 6556: 	for(k=1;k<=NCOVMAX;k++)
 6557: 	  probs[i][j][k]=0.;
 6558: 
 6559:     /*---------- Forecasting ------------------*/
 6560:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
 6561:     if(prevfcast==1){
 6562:       /*    if(stepm ==1){*/
 6563:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
 6564:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
 6565:       /*      }  */
 6566:       /*      else{ */
 6567:       /*        erreur=108; */
 6568:       /*        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); */
 6569:       /*        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); */
 6570:       /*      } */
 6571:     }
 6572:   
 6573: 
 6574:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
 6575: 
 6576:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 6577:     /*  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",\
 6578: 	ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
 6579:     */
 6580: 
 6581:     if (mobilav!=0) {
 6582:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6583:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 6584: 	fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 6585: 	printf(" Error in movingaverage mobilav=%d\n",mobilav);
 6586:       }
 6587:     }
 6588: 
 6589: 
 6590:     /*---------- Health expectancies, no variances ------------*/
 6591: 
 6592:     strcpy(filerese,"e");
 6593:     strcat(filerese,fileres);
 6594:     if((ficreseij=fopen(filerese,"w"))==NULL) {
 6595:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 6596:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 6597:     }
 6598:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
 6599:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
 6600:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6601:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 6602:           
 6603:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 6604: 	fprintf(ficreseij,"\n#****** ");
 6605: 	for(j=1;j<=cptcoveff;j++) {
 6606: 	  fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6607: 	}
 6608: 	fprintf(ficreseij,"******\n");
 6609: 
 6610: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 6611: 	oldm=oldms;savm=savms;
 6612: 	evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
 6613:       
 6614: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 6615:       /*}*/
 6616:     }
 6617:     fclose(ficreseij);
 6618: 
 6619: 
 6620:     /*---------- Health expectancies and variances ------------*/
 6621: 
 6622: 
 6623:     strcpy(filerest,"t");
 6624:     strcat(filerest,fileres);
 6625:     if((ficrest=fopen(filerest,"w"))==NULL) {
 6626:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
 6627:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
 6628:     }
 6629:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
 6630:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
 6631: 
 6632: 
 6633:     strcpy(fileresstde,"stde");
 6634:     strcat(fileresstde,fileres);
 6635:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
 6636:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 6637:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 6638:     }
 6639:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 6640:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 6641: 
 6642:     strcpy(filerescve,"cve");
 6643:     strcat(filerescve,fileres);
 6644:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
 6645:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 6646:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 6647:     }
 6648:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 6649:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 6650: 
 6651:     strcpy(fileresv,"v");
 6652:     strcat(fileresv,fileres);
 6653:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
 6654:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
 6655:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
 6656:     }
 6657:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 6658:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 6659: 
 6660:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6661:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 6662:           
 6663:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 6664:     	fprintf(ficrest,"\n#****** ");
 6665: 	for(j=1;j<=cptcoveff;j++) 
 6666: 	  fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6667: 	fprintf(ficrest,"******\n");
 6668: 
 6669: 	fprintf(ficresstdeij,"\n#****** ");
 6670: 	fprintf(ficrescveij,"\n#****** ");
 6671: 	for(j=1;j<=cptcoveff;j++) {
 6672: 	  fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6673: 	  fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6674: 	}
 6675: 	fprintf(ficresstdeij,"******\n");
 6676: 	fprintf(ficrescveij,"******\n");
 6677: 
 6678: 	fprintf(ficresvij,"\n#****** ");
 6679: 	for(j=1;j<=cptcoveff;j++) 
 6680: 	  fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6681: 	fprintf(ficresvij,"******\n");
 6682: 
 6683: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 6684: 	oldm=oldms;savm=savms;
 6685: 	cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
 6686: 	/*
 6687: 	 */
 6688: 	/* goto endfree; */
 6689:  
 6690: 	vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 6691: 	pstamp(ficrest);
 6692: 
 6693: 
 6694: 	for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 6695: 	  oldm=oldms;savm=savms; /* Segmentation fault */
 6696: 	  cptcod= 0; /* To be deleted */
 6697: 	  varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); /* cptcod not initialized Intel */
 6698: 	  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 ");
 6699: 	  if(vpopbased==1)
 6700: 	    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);
 6701: 	  else
 6702: 	    fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
 6703: 	  fprintf(ficrest,"# Age e.. (std) ");
 6704: 	  for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
 6705: 	  fprintf(ficrest,"\n");
 6706: 
 6707: 	  epj=vector(1,nlstate+1);
 6708: 	  for(age=bage; age <=fage ;age++){
 6709: 	    prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
 6710: 	    if (vpopbased==1) {
 6711: 	      if(mobilav ==0){
 6712: 		for(i=1; i<=nlstate;i++)
 6713: 		  prlim[i][i]=probs[(int)age][i][k];
 6714: 	      }else{ /* mobilav */ 
 6715: 		for(i=1; i<=nlstate;i++)
 6716: 		  prlim[i][i]=mobaverage[(int)age][i][k];
 6717: 	      }
 6718: 	    }
 6719: 	
 6720: 	    fprintf(ficrest," %4.0f",age);
 6721: 	    for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
 6722: 	      for(i=1, epj[j]=0.;i <=nlstate;i++) {
 6723: 		epj[j] += prlim[i][i]*eij[i][j][(int)age];
 6724: 		/*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
 6725: 	      }
 6726: 	      epj[nlstate+1] +=epj[j];
 6727: 	    }
 6728: 
 6729: 	    for(i=1, vepp=0.;i <=nlstate;i++)
 6730: 	      for(j=1;j <=nlstate;j++)
 6731: 		vepp += vareij[i][j][(int)age];
 6732: 	    fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
 6733: 	    for(j=1;j <=nlstate;j++){
 6734: 	      fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
 6735: 	    }
 6736: 	    fprintf(ficrest,"\n");
 6737: 	  }
 6738: 	}
 6739: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 6740: 	free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 6741: 	free_vector(epj,1,nlstate+1);
 6742:       /*}*/
 6743:     }
 6744:     free_vector(weight,1,n);
 6745:     free_imatrix(Tvard,1,NCOVMAX,1,2);
 6746:     free_imatrix(s,1,maxwav+1,1,n);
 6747:     free_matrix(anint,1,maxwav,1,n); 
 6748:     free_matrix(mint,1,maxwav,1,n);
 6749:     free_ivector(cod,1,n);
 6750:     free_ivector(tab,1,NCOVMAX);
 6751:     fclose(ficresstdeij);
 6752:     fclose(ficrescveij);
 6753:     fclose(ficresvij);
 6754:     fclose(ficrest);
 6755:     fclose(ficpar);
 6756:   
 6757:     /*------- Variance of period (stable) prevalence------*/   
 6758: 
 6759:     strcpy(fileresvpl,"vpl");
 6760:     strcat(fileresvpl,fileres);
 6761:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
 6762:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
 6763:       exit(0);
 6764:     }
 6765:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
 6766: 
 6767:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6768:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 6769:           
 6770:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 6771:     	fprintf(ficresvpl,"\n#****** ");
 6772: 	for(j=1;j<=cptcoveff;j++) 
 6773: 	  fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6774: 	fprintf(ficresvpl,"******\n");
 6775:       
 6776: 	varpl=matrix(1,nlstate,(int) bage, (int) fage);
 6777: 	oldm=oldms;savm=savms;
 6778: 	varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
 6779: 	free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
 6780:       /*}*/
 6781:     }
 6782: 
 6783:     fclose(ficresvpl);
 6784: 
 6785:     /*---------- End : free ----------------*/
 6786:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6787:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6788:   }  /* mle==-3 arrives here for freeing */
 6789:  /* endfree:*/
 6790:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
 6791:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
 6792:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
 6793:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
 6794:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
 6795:     free_matrix(covar,0,NCOVMAX,1,n);
 6796:     free_matrix(matcov,1,npar,1,npar);
 6797:     /*free_vector(delti,1,npar);*/
 6798:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 6799:     free_matrix(agev,1,maxwav,1,imx);
 6800:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
 6801: 
 6802:     free_ivector(ncodemax,1,NCOVMAX);
 6803:     free_ivector(Tvar,1,NCOVMAX);
 6804:     free_ivector(Tprod,1,NCOVMAX);
 6805:     free_ivector(Tvaraff,1,NCOVMAX);
 6806:     free_ivector(Tage,1,NCOVMAX);
 6807: 
 6808:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
 6809:     free_imatrix(codtab,1,100,1,10);
 6810:   fflush(fichtm);
 6811:   fflush(ficgp);
 6812:   
 6813: 
 6814:   if((nberr >0) || (nbwarn>0)){
 6815:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
 6816:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
 6817:   }else{
 6818:     printf("End of Imach\n");
 6819:     fprintf(ficlog,"End of Imach\n");
 6820:   }
 6821:   printf("See log file on %s\n",filelog);
 6822:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
 6823:   /*(void) gettimeofday(&end_time,&tzp);*/
 6824:   rend_time = time(NULL);  
 6825:   end_time = *localtime(&rend_time);
 6826:   /* tml = *localtime(&end_time.tm_sec); */
 6827:   strcpy(strtend,asctime(&end_time));
 6828:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
 6829:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
 6830:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 6831: 
 6832:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 6833:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 6834:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 6835:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
 6836: /*   if(fileappend(fichtm,optionfilehtm)){ */
 6837:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 6838:   fclose(fichtm);
 6839:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 6840:   fclose(fichtmcov);
 6841:   fclose(ficgp);
 6842:   fclose(ficlog);
 6843:   /*------ End -----------*/
 6844: 
 6845: 
 6846:    printf("Before Current directory %s!\n",pathcd);
 6847:    if(chdir(pathcd) != 0)
 6848:     printf("Can't move to directory %s!\n",path);
 6849:   if(getcwd(pathcd,MAXLINE) > 0)
 6850:     printf("Current directory %s!\n",pathcd);
 6851:   /*strcat(plotcmd,CHARSEPARATOR);*/
 6852:   sprintf(plotcmd,"gnuplot");
 6853: #ifdef _WIN32
 6854:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
 6855: #endif
 6856:   if(!stat(plotcmd,&info)){
 6857:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 6858:     if(!stat(getenv("GNUPLOTBIN"),&info)){
 6859:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
 6860:     }else
 6861:       strcpy(pplotcmd,plotcmd);
 6862: #ifdef __unix
 6863:     strcpy(plotcmd,GNUPLOTPROGRAM);
 6864:     if(!stat(plotcmd,&info)){
 6865:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 6866:     }else
 6867:       strcpy(pplotcmd,plotcmd);
 6868: #endif
 6869:   }else
 6870:     strcpy(pplotcmd,plotcmd);
 6871:   
 6872:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
 6873:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
 6874: 
 6875:   if((outcmd=system(plotcmd)) != 0){
 6876:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
 6877:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
 6878:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
 6879:     if((outcmd=system(plotcmd)) != 0)
 6880:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
 6881:   }
 6882:   printf(" Successful, please wait...");
 6883:   while (z[0] != 'q') {
 6884:     /* chdir(path); */
 6885:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
 6886:     scanf("%s",z);
 6887: /*     if (z[0] == 'c') system("./imach"); */
 6888:     if (z[0] == 'e') {
 6889: #ifdef __APPLE__
 6890:       sprintf(pplotcmd, "open %s", optionfilehtm);
 6891: #elif __linux
 6892:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
 6893: #else
 6894:       sprintf(pplotcmd, "%s", optionfilehtm);
 6895: #endif
 6896:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
 6897:       system(pplotcmd);
 6898:     }
 6899:     else if (z[0] == 'g') system(plotcmd);
 6900:     else if (z[0] == 'q') exit(0);
 6901:   }
 6902:   end:
 6903:   while (z[0] != 'q') {
 6904:     printf("\nType  q for exiting: ");
 6905:     scanf("%s",z);
 6906:   }
 6907: }

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