File:  [Local Repository] / imach / src / imach.c
Revision 1.190: download - view: text, annotated - select for diffs
Tue May 5 08:51:13 2015 UTC (9 years, 1 month ago) by brouard
Branches: MAIN
CVS tags: HEAD
Summary: Adding digits in output parameters (7 digits instead of 6)

Fix 1+age+.

    1: /* $Id: imach.c,v 1.190 2015/05/05 08:51:13 brouard Exp $
    2:   $State: Exp $
    3:   $Log: imach.c,v $
    4:   Revision 1.190  2015/05/05 08:51:13  brouard
    5:   Summary: Adding digits in output parameters (7 digits instead of 6)
    6: 
    7:   Fix 1+age+.
    8: 
    9:   Revision 1.189  2015/04/30 14:45:16  brouard
   10:   Summary: 0.98q2
   11: 
   12:   Revision 1.188  2015/04/30 08:27:53  brouard
   13:   *** empty log message ***
   14: 
   15:   Revision 1.187  2015/04/29 09:11:15  brouard
   16:   *** empty log message ***
   17: 
   18:   Revision 1.186  2015/04/23 12:01:52  brouard
   19:   Summary: V1*age is working now, version 0.98q1
   20: 
   21:   Some codes had been disabled in order to simplify and Vn*age was
   22:   working in the optimization phase, ie, giving correct MLE parameters,
   23:   but, as usual, outputs were not correct and program core dumped.
   24: 
   25:   Revision 1.185  2015/03/11 13:26:42  brouard
   26:   Summary: Inclusion of compile and links command line for Intel Compiler
   27: 
   28:   Revision 1.184  2015/03/11 11:52:39  brouard
   29:   Summary: Back from Windows 8. Intel Compiler
   30: 
   31:   Revision 1.183  2015/03/10 20:34:32  brouard
   32:   Summary: 0.98q0, trying with directest, mnbrak fixed
   33: 
   34:   We use directest instead of original Powell test; probably no
   35:   incidence on the results, but better justifications;
   36:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
   37:   wrong results.
   38: 
   39:   Revision 1.182  2015/02/12 08:19:57  brouard
   40:   Summary: Trying to keep directest which seems simpler and more general
   41:   Author: Nicolas Brouard
   42: 
   43:   Revision 1.181  2015/02/11 23:22:24  brouard
   44:   Summary: Comments on Powell added
   45: 
   46:   Author:
   47: 
   48:   Revision 1.180  2015/02/11 17:33:45  brouard
   49:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
   50: 
   51:   Revision 1.179  2015/01/04 09:57:06  brouard
   52:   Summary: back to OS/X
   53: 
   54:   Revision 1.178  2015/01/04 09:35:48  brouard
   55:   *** empty log message ***
   56: 
   57:   Revision 1.177  2015/01/03 18:40:56  brouard
   58:   Summary: Still testing ilc32 on OSX
   59: 
   60:   Revision 1.176  2015/01/03 16:45:04  brouard
   61:   *** empty log message ***
   62: 
   63:   Revision 1.175  2015/01/03 16:33:42  brouard
   64:   *** empty log message ***
   65: 
   66:   Revision 1.174  2015/01/03 16:15:49  brouard
   67:   Summary: Still in cross-compilation
   68: 
   69:   Revision 1.173  2015/01/03 12:06:26  brouard
   70:   Summary: trying to detect cross-compilation
   71: 
   72:   Revision 1.172  2014/12/27 12:07:47  brouard
   73:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
   74: 
   75:   Revision 1.171  2014/12/23 13:26:59  brouard
   76:   Summary: Back from Visual C
   77: 
   78:   Still problem with utsname.h on Windows
   79: 
   80:   Revision 1.170  2014/12/23 11:17:12  brouard
   81:   Summary: Cleaning some \%% back to %%
   82: 
   83:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
   84: 
   85:   Revision 1.169  2014/12/22 23:08:31  brouard
   86:   Summary: 0.98p
   87: 
   88:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
   89: 
   90:   Revision 1.168  2014/12/22 15:17:42  brouard
   91:   Summary: update
   92: 
   93:   Revision 1.167  2014/12/22 13:50:56  brouard
   94:   Summary: Testing uname and compiler version and if compiled 32 or 64
   95: 
   96:   Testing on Linux 64
   97: 
   98:   Revision 1.166  2014/12/22 11:40:47  brouard
   99:   *** empty log message ***
  100: 
  101:   Revision 1.165  2014/12/16 11:20:36  brouard
  102:   Summary: After compiling on Visual C
  103: 
  104:   * imach.c (Module): Merging 1.61 to 1.162
  105: 
  106:   Revision 1.164  2014/12/16 10:52:11  brouard
  107:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
  108: 
  109:   * imach.c (Module): Merging 1.61 to 1.162
  110: 
  111:   Revision 1.163  2014/12/16 10:30:11  brouard
  112:   * imach.c (Module): Merging 1.61 to 1.162
  113: 
  114:   Revision 1.162  2014/09/25 11:43:39  brouard
  115:   Summary: temporary backup 0.99!
  116: 
  117:   Revision 1.1  2014/09/16 11:06:58  brouard
  118:   Summary: With some code (wrong) for nlopt
  119: 
  120:   Author:
  121: 
  122:   Revision 1.161  2014/09/15 20:41:41  brouard
  123:   Summary: Problem with macro SQR on Intel compiler
  124: 
  125:   Revision 1.160  2014/09/02 09:24:05  brouard
  126:   *** empty log message ***
  127: 
  128:   Revision 1.159  2014/09/01 10:34:10  brouard
  129:   Summary: WIN32
  130:   Author: Brouard
  131: 
  132:   Revision 1.158  2014/08/27 17:11:51  brouard
  133:   *** empty log message ***
  134: 
  135:   Revision 1.157  2014/08/27 16:26:55  brouard
  136:   Summary: Preparing windows Visual studio version
  137:   Author: Brouard
  138: 
  139:   In order to compile on Visual studio, time.h is now correct and time_t
  140:   and tm struct should be used. difftime should be used but sometimes I
  141:   just make the differences in raw time format (time(&now).
  142:   Trying to suppress #ifdef LINUX
  143:   Add xdg-open for __linux in order to open default browser.
  144: 
  145:   Revision 1.156  2014/08/25 20:10:10  brouard
  146:   *** empty log message ***
  147: 
  148:   Revision 1.155  2014/08/25 18:32:34  brouard
  149:   Summary: New compile, minor changes
  150:   Author: Brouard
  151: 
  152:   Revision 1.154  2014/06/20 17:32:08  brouard
  153:   Summary: Outputs now all graphs of convergence to period prevalence
  154: 
  155:   Revision 1.153  2014/06/20 16:45:46  brouard
  156:   Summary: If 3 live state, convergence to period prevalence on same graph
  157:   Author: Brouard
  158: 
  159:   Revision 1.152  2014/06/18 17:54:09  brouard
  160:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
  161: 
  162:   Revision 1.151  2014/06/18 16:43:30  brouard
  163:   *** empty log message ***
  164: 
  165:   Revision 1.150  2014/06/18 16:42:35  brouard
  166:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
  167:   Author: brouard
  168: 
  169:   Revision 1.149  2014/06/18 15:51:14  brouard
  170:   Summary: Some fixes in parameter files errors
  171:   Author: Nicolas Brouard
  172: 
  173:   Revision 1.148  2014/06/17 17:38:48  brouard
  174:   Summary: Nothing new
  175:   Author: Brouard
  176: 
  177:   Just a new packaging for OS/X version 0.98nS
  178: 
  179:   Revision 1.147  2014/06/16 10:33:11  brouard
  180:   *** empty log message ***
  181: 
  182:   Revision 1.146  2014/06/16 10:20:28  brouard
  183:   Summary: Merge
  184:   Author: Brouard
  185: 
  186:   Merge, before building revised version.
  187: 
  188:   Revision 1.145  2014/06/10 21:23:15  brouard
  189:   Summary: Debugging with valgrind
  190:   Author: Nicolas Brouard
  191: 
  192:   Lot of changes in order to output the results with some covariates
  193:   After the Edimburgh REVES conference 2014, it seems mandatory to
  194:   improve the code.
  195:   No more memory valgrind error but a lot has to be done in order to
  196:   continue the work of splitting the code into subroutines.
  197:   Also, decodemodel has been improved. Tricode is still not
  198:   optimal. nbcode should be improved. Documentation has been added in
  199:   the source code.
  200: 
  201:   Revision 1.143  2014/01/26 09:45:38  brouard
  202:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
  203: 
  204:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  205:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
  206: 
  207:   Revision 1.142  2014/01/26 03:57:36  brouard
  208:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
  209: 
  210:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  211: 
  212:   Revision 1.141  2014/01/26 02:42:01  brouard
  213:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  214: 
  215:   Revision 1.140  2011/09/02 10:37:54  brouard
  216:   Summary: times.h is ok with mingw32 now.
  217: 
  218:   Revision 1.139  2010/06/14 07:50:17  brouard
  219:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
  220:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
  221: 
  222:   Revision 1.138  2010/04/30 18:19:40  brouard
  223:   *** empty log message ***
  224: 
  225:   Revision 1.137  2010/04/29 18:11:38  brouard
  226:   (Module): Checking covariates for more complex models
  227:   than V1+V2. A lot of change to be done. Unstable.
  228: 
  229:   Revision 1.136  2010/04/26 20:30:53  brouard
  230:   (Module): merging some libgsl code. Fixing computation
  231:   of likelione (using inter/intrapolation if mle = 0) in order to
  232:   get same likelihood as if mle=1.
  233:   Some cleaning of code and comments added.
  234: 
  235:   Revision 1.135  2009/10/29 15:33:14  brouard
  236:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  237: 
  238:   Revision 1.134  2009/10/29 13:18:53  brouard
  239:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  240: 
  241:   Revision 1.133  2009/07/06 10:21:25  brouard
  242:   just nforces
  243: 
  244:   Revision 1.132  2009/07/06 08:22:05  brouard
  245:   Many tings
  246: 
  247:   Revision 1.131  2009/06/20 16:22:47  brouard
  248:   Some dimensions resccaled
  249: 
  250:   Revision 1.130  2009/05/26 06:44:34  brouard
  251:   (Module): Max Covariate is now set to 20 instead of 8. A
  252:   lot of cleaning with variables initialized to 0. Trying to make
  253:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
  254: 
  255:   Revision 1.129  2007/08/31 13:49:27  lievre
  256:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
  257: 
  258:   Revision 1.128  2006/06/30 13:02:05  brouard
  259:   (Module): Clarifications on computing e.j
  260: 
  261:   Revision 1.127  2006/04/28 18:11:50  brouard
  262:   (Module): Yes the sum of survivors was wrong since
  263:   imach-114 because nhstepm was no more computed in the age
  264:   loop. Now we define nhstepma in the age loop.
  265:   (Module): In order to speed up (in case of numerous covariates) we
  266:   compute health expectancies (without variances) in a first step
  267:   and then all the health expectancies with variances or standard
  268:   deviation (needs data from the Hessian matrices) which slows the
  269:   computation.
  270:   In the future we should be able to stop the program is only health
  271:   expectancies and graph are needed without standard deviations.
  272: 
  273:   Revision 1.126  2006/04/28 17:23:28  brouard
  274:   (Module): Yes the sum of survivors was wrong since
  275:   imach-114 because nhstepm was no more computed in the age
  276:   loop. Now we define nhstepma in the age loop.
  277:   Version 0.98h
  278: 
  279:   Revision 1.125  2006/04/04 15:20:31  lievre
  280:   Errors in calculation of health expectancies. Age was not initialized.
  281:   Forecasting file added.
  282: 
  283:   Revision 1.124  2006/03/22 17:13:53  lievre
  284:   Parameters are printed with %lf instead of %f (more numbers after the comma).
  285:   The log-likelihood is printed in the log file
  286: 
  287:   Revision 1.123  2006/03/20 10:52:43  brouard
  288:   * imach.c (Module): <title> changed, corresponds to .htm file
  289:   name. <head> headers where missing.
  290: 
  291:   * imach.c (Module): Weights can have a decimal point as for
  292:   English (a comma might work with a correct LC_NUMERIC environment,
  293:   otherwise the weight is truncated).
  294:   Modification of warning when the covariates values are not 0 or
  295:   1.
  296:   Version 0.98g
  297: 
  298:   Revision 1.122  2006/03/20 09:45:41  brouard
  299:   (Module): Weights can have a decimal point as for
  300:   English (a comma might work with a correct LC_NUMERIC environment,
  301:   otherwise the weight is truncated).
  302:   Modification of warning when the covariates values are not 0 or
  303:   1.
  304:   Version 0.98g
  305: 
  306:   Revision 1.121  2006/03/16 17:45:01  lievre
  307:   * imach.c (Module): Comments concerning covariates added
  308: 
  309:   * imach.c (Module): refinements in the computation of lli if
  310:   status=-2 in order to have more reliable computation if stepm is
  311:   not 1 month. Version 0.98f
  312: 
  313:   Revision 1.120  2006/03/16 15:10:38  lievre
  314:   (Module): refinements in the computation of lli if
  315:   status=-2 in order to have more reliable computation if stepm is
  316:   not 1 month. Version 0.98f
  317: 
  318:   Revision 1.119  2006/03/15 17:42:26  brouard
  319:   (Module): Bug if status = -2, the loglikelihood was
  320:   computed as likelihood omitting the logarithm. Version O.98e
  321: 
  322:   Revision 1.118  2006/03/14 18:20:07  brouard
  323:   (Module): varevsij Comments added explaining the second
  324:   table of variances if popbased=1 .
  325:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  326:   (Module): Function pstamp added
  327:   (Module): Version 0.98d
  328: 
  329:   Revision 1.117  2006/03/14 17:16:22  brouard
  330:   (Module): varevsij Comments added explaining the second
  331:   table of variances if popbased=1 .
  332:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  333:   (Module): Function pstamp added
  334:   (Module): Version 0.98d
  335: 
  336:   Revision 1.116  2006/03/06 10:29:27  brouard
  337:   (Module): Variance-covariance wrong links and
  338:   varian-covariance of ej. is needed (Saito).
  339: 
  340:   Revision 1.115  2006/02/27 12:17:45  brouard
  341:   (Module): One freematrix added in mlikeli! 0.98c
  342: 
  343:   Revision 1.114  2006/02/26 12:57:58  brouard
  344:   (Module): Some improvements in processing parameter
  345:   filename with strsep.
  346: 
  347:   Revision 1.113  2006/02/24 14:20:24  brouard
  348:   (Module): Memory leaks checks with valgrind and:
  349:   datafile was not closed, some imatrix were not freed and on matrix
  350:   allocation too.
  351: 
  352:   Revision 1.112  2006/01/30 09:55:26  brouard
  353:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
  354: 
  355:   Revision 1.111  2006/01/25 20:38:18  brouard
  356:   (Module): Lots of cleaning and bugs added (Gompertz)
  357:   (Module): Comments can be added in data file. Missing date values
  358:   can be a simple dot '.'.
  359: 
  360:   Revision 1.110  2006/01/25 00:51:50  brouard
  361:   (Module): Lots of cleaning and bugs added (Gompertz)
  362: 
  363:   Revision 1.109  2006/01/24 19:37:15  brouard
  364:   (Module): Comments (lines starting with a #) are allowed in data.
  365: 
  366:   Revision 1.108  2006/01/19 18:05:42  lievre
  367:   Gnuplot problem appeared...
  368:   To be fixed
  369: 
  370:   Revision 1.107  2006/01/19 16:20:37  brouard
  371:   Test existence of gnuplot in imach path
  372: 
  373:   Revision 1.106  2006/01/19 13:24:36  brouard
  374:   Some cleaning and links added in html output
  375: 
  376:   Revision 1.105  2006/01/05 20:23:19  lievre
  377:   *** empty log message ***
  378: 
  379:   Revision 1.104  2005/09/30 16:11:43  lievre
  380:   (Module): sump fixed, loop imx fixed, and simplifications.
  381:   (Module): If the status is missing at the last wave but we know
  382:   that the person is alive, then we can code his/her status as -2
  383:   (instead of missing=-1 in earlier versions) and his/her
  384:   contributions to the likelihood is 1 - Prob of dying from last
  385:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
  386:   the healthy state at last known wave). Version is 0.98
  387: 
  388:   Revision 1.103  2005/09/30 15:54:49  lievre
  389:   (Module): sump fixed, loop imx fixed, and simplifications.
  390: 
  391:   Revision 1.102  2004/09/15 17:31:30  brouard
  392:   Add the possibility to read data file including tab characters.
  393: 
  394:   Revision 1.101  2004/09/15 10:38:38  brouard
  395:   Fix on curr_time
  396: 
  397:   Revision 1.100  2004/07/12 18:29:06  brouard
  398:   Add version for Mac OS X. Just define UNIX in Makefile
  399: 
  400:   Revision 1.99  2004/06/05 08:57:40  brouard
  401:   *** empty log message ***
  402: 
  403:   Revision 1.98  2004/05/16 15:05:56  brouard
  404:   New version 0.97 . First attempt to estimate force of mortality
  405:   directly from the data i.e. without the need of knowing the health
  406:   state at each age, but using a Gompertz model: log u =a + b*age .
  407:   This is the basic analysis of mortality and should be done before any
  408:   other analysis, in order to test if the mortality estimated from the
  409:   cross-longitudinal survey is different from the mortality estimated
  410:   from other sources like vital statistic data.
  411: 
  412:   The same imach parameter file can be used but the option for mle should be -3.
  413: 
  414:   Agnès, who wrote this part of the code, tried to keep most of the
  415:   former routines in order to include the new code within the former code.
  416: 
  417:   The output is very simple: only an estimate of the intercept and of
  418:   the slope with 95% confident intervals.
  419: 
  420:   Current limitations:
  421:   A) Even if you enter covariates, i.e. with the
  422:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
  423:   B) There is no computation of Life Expectancy nor Life Table.
  424: 
  425:   Revision 1.97  2004/02/20 13:25:42  lievre
  426:   Version 0.96d. Population forecasting command line is (temporarily)
  427:   suppressed.
  428: 
  429:   Revision 1.96  2003/07/15 15:38:55  brouard
  430:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
  431:   rewritten within the same printf. Workaround: many printfs.
  432: 
  433:   Revision 1.95  2003/07/08 07:54:34  brouard
  434:   * imach.c (Repository):
  435:   (Repository): Using imachwizard code to output a more meaningful covariance
  436:   matrix (cov(a12,c31) instead of numbers.
  437: 
  438:   Revision 1.94  2003/06/27 13:00:02  brouard
  439:   Just cleaning
  440: 
  441:   Revision 1.93  2003/06/25 16:33:55  brouard
  442:   (Module): On windows (cygwin) function asctime_r doesn't
  443:   exist so I changed back to asctime which exists.
  444:   (Module): Version 0.96b
  445: 
  446:   Revision 1.92  2003/06/25 16:30:45  brouard
  447:   (Module): On windows (cygwin) function asctime_r doesn't
  448:   exist so I changed back to asctime which exists.
  449: 
  450:   Revision 1.91  2003/06/25 15:30:29  brouard
  451:   * imach.c (Repository): Duplicated warning errors corrected.
  452:   (Repository): Elapsed time after each iteration is now output. It
  453:   helps to forecast when convergence will be reached. Elapsed time
  454:   is stamped in powell.  We created a new html file for the graphs
  455:   concerning matrix of covariance. It has extension -cov.htm.
  456: 
  457:   Revision 1.90  2003/06/24 12:34:15  brouard
  458:   (Module): Some bugs corrected for windows. Also, when
  459:   mle=-1 a template is output in file "or"mypar.txt with the design
  460:   of the covariance matrix to be input.
  461: 
  462:   Revision 1.89  2003/06/24 12:30:52  brouard
  463:   (Module): Some bugs corrected for windows. Also, when
  464:   mle=-1 a template is output in file "or"mypar.txt with the design
  465:   of the covariance matrix to be input.
  466: 
  467:   Revision 1.88  2003/06/23 17:54:56  brouard
  468:   * 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.
  469: 
  470:   Revision 1.87  2003/06/18 12:26:01  brouard
  471:   Version 0.96
  472: 
  473:   Revision 1.86  2003/06/17 20:04:08  brouard
  474:   (Module): Change position of html and gnuplot routines and added
  475:   routine fileappend.
  476: 
  477:   Revision 1.85  2003/06/17 13:12:43  brouard
  478:   * imach.c (Repository): Check when date of death was earlier that
  479:   current date of interview. It may happen when the death was just
  480:   prior to the death. In this case, dh was negative and likelihood
  481:   was wrong (infinity). We still send an "Error" but patch by
  482:   assuming that the date of death was just one stepm after the
  483:   interview.
  484:   (Repository): Because some people have very long ID (first column)
  485:   we changed int to long in num[] and we added a new lvector for
  486:   memory allocation. But we also truncated to 8 characters (left
  487:   truncation)
  488:   (Repository): No more line truncation errors.
  489: 
  490:   Revision 1.84  2003/06/13 21:44:43  brouard
  491:   * imach.c (Repository): Replace "freqsummary" at a correct
  492:   place. It differs from routine "prevalence" which may be called
  493:   many times. Probs is memory consuming and must be used with
  494:   parcimony.
  495:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
  496: 
  497:   Revision 1.83  2003/06/10 13:39:11  lievre
  498:   *** empty log message ***
  499: 
  500:   Revision 1.82  2003/06/05 15:57:20  brouard
  501:   Add log in  imach.c and  fullversion number is now printed.
  502: 
  503: */
  504: /*
  505:    Interpolated Markov Chain
  506: 
  507:   Short summary of the programme:
  508:   
  509:   This program computes Healthy Life Expectancies from
  510:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
  511:   first survey ("cross") where individuals from different ages are
  512:   interviewed on their health status or degree of disability (in the
  513:   case of a health survey which is our main interest) -2- at least a
  514:   second wave of interviews ("longitudinal") which measure each change
  515:   (if any) in individual health status.  Health expectancies are
  516:   computed from the time spent in each health state according to a
  517:   model. More health states you consider, more time is necessary to reach the
  518:   Maximum Likelihood of the parameters involved in the model.  The
  519:   simplest model is the multinomial logistic model where pij is the
  520:   probability to be observed in state j at the second wave
  521:   conditional to be observed in state i at the first wave. Therefore
  522:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
  523:   'age' is age and 'sex' is a covariate. If you want to have a more
  524:   complex model than "constant and age", you should modify the program
  525:   where the markup *Covariates have to be included here again* invites
  526:   you to do it.  More covariates you add, slower the
  527:   convergence.
  528: 
  529:   The advantage of this computer programme, compared to a simple
  530:   multinomial logistic model, is clear when the delay between waves is not
  531:   identical for each individual. Also, if a individual missed an
  532:   intermediate interview, the information is lost, but taken into
  533:   account using an interpolation or extrapolation.  
  534: 
  535:   hPijx is the probability to be observed in state i at age x+h
  536:   conditional to the observed state i at age x. The delay 'h' can be
  537:   split into an exact number (nh*stepm) of unobserved intermediate
  538:   states. This elementary transition (by month, quarter,
  539:   semester or year) is modelled as a multinomial logistic.  The hPx
  540:   matrix is simply the matrix product of nh*stepm elementary matrices
  541:   and the contribution of each individual to the likelihood is simply
  542:   hPijx.
  543: 
  544:   Also this programme outputs the covariance matrix of the parameters but also
  545:   of the life expectancies. It also computes the period (stable) prevalence. 
  546:   
  547:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
  548:            Institut national d'études démographiques, Paris.
  549:   This software have been partly granted by Euro-REVES, a concerted action
  550:   from the European Union.
  551:   It is copyrighted identically to a GNU software product, ie programme and
  552:   software can be distributed freely for non commercial use. Latest version
  553:   can be accessed at http://euroreves.ined.fr/imach .
  554: 
  555:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
  556:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
  557:   
  558:   **********************************************************************/
  559: /*
  560:   main
  561:   read parameterfile
  562:   read datafile
  563:   concatwav
  564:   freqsummary
  565:   if (mle >= 1)
  566:     mlikeli
  567:   print results files
  568:   if mle==1 
  569:      computes hessian
  570:   read end of parameter file: agemin, agemax, bage, fage, estepm
  571:       begin-prev-date,...
  572:   open gnuplot file
  573:   open html file
  574:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
  575:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
  576:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
  577:     freexexit2 possible for memory heap.
  578: 
  579:   h Pij x                         | pij_nom  ficrestpij
  580:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
  581:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
  582:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
  583: 
  584:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
  585:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
  586:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
  587:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
  588:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
  589: 
  590:   forecasting if prevfcast==1 prevforecast call prevalence()
  591:   health expectancies
  592:   Variance-covariance of DFLE
  593:   prevalence()
  594:    movingaverage()
  595:   varevsij() 
  596:   if popbased==1 varevsij(,popbased)
  597:   total life expectancies
  598:   Variance of period (stable) prevalence
  599:  end
  600: */
  601: 
  602: /* #define DEBUG */
  603: /* #define DEBUGBRENT */
  604: #define POWELL /* Instead of NLOPT */
  605: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
  606: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
  607: 
  608: #include <math.h>
  609: #include <stdio.h>
  610: #include <stdlib.h>
  611: #include <string.h>
  612: 
  613: #ifdef _WIN32
  614: #include <io.h>
  615: #include <windows.h>
  616: #include <tchar.h>
  617: #else
  618: #include <unistd.h>
  619: #endif
  620: 
  621: #include <limits.h>
  622: #include <sys/types.h>
  623: 
  624: #if defined(__GNUC__)
  625: #include <sys/utsname.h> /* Doesn't work on Windows */
  626: #endif
  627: 
  628: #include <sys/stat.h>
  629: #include <errno.h>
  630: /* extern int errno; */
  631: 
  632: /* #ifdef LINUX */
  633: /* #include <time.h> */
  634: /* #include "timeval.h" */
  635: /* #else */
  636: /* #include <sys/time.h> */
  637: /* #endif */
  638: 
  639: #include <time.h>
  640: 
  641: #ifdef GSL
  642: #include <gsl/gsl_errno.h>
  643: #include <gsl/gsl_multimin.h>
  644: #endif
  645: 
  646: 
  647: #ifdef NLOPT
  648: #include <nlopt.h>
  649: typedef struct {
  650:   double (* function)(double [] );
  651: } myfunc_data ;
  652: #endif
  653: 
  654: /* #include <libintl.h> */
  655: /* #define _(String) gettext (String) */
  656: 
  657: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
  658: 
  659: #define GNUPLOTPROGRAM "gnuplot"
  660: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
  661: #define FILENAMELENGTH 132
  662: 
  663: #define	GLOCK_ERROR_NOPATH		-1	/* empty path */
  664: #define	GLOCK_ERROR_GETCWD		-2	/* cannot get cwd */
  665: 
  666: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
  667: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
  668: 
  669: #define NINTERVMAX 8
  670: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
  671: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
  672: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
  673: #define codtabm(h,k)  1 & (h-1) >> (k-1) ;
  674: #define MAXN 20000
  675: #define YEARM 12. /**< Number of months per year */
  676: #define AGESUP 130
  677: #define AGEBASE 40
  678: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
  679: #ifdef _WIN32
  680: #define DIRSEPARATOR '\\'
  681: #define CHARSEPARATOR "\\"
  682: #define ODIRSEPARATOR '/'
  683: #else
  684: #define DIRSEPARATOR '/'
  685: #define CHARSEPARATOR "/"
  686: #define ODIRSEPARATOR '\\'
  687: #endif
  688: 
  689: /* $Id: imach.c,v 1.190 2015/05/05 08:51:13 brouard Exp $ */
  690: /* $State: Exp $ */
  691: 
  692: char version[]="Imach version 0.98q2, April 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
  693: char fullversion[]="$Revision: 1.190 $ $Date: 2015/05/05 08:51:13 $"; 
  694: char strstart[80];
  695: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
  696: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
  697: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
  698: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
  699: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
  700: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
  701: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
  702: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
  703: int cptcovprodnoage=0; /**< Number of covariate products without age */   
  704: int cptcoveff=0; /* Total number of covariates to vary for printing results */
  705: int cptcov=0; /* Working variable */
  706: int npar=NPARMAX;
  707: int nlstate=2; /* Number of live states */
  708: int ndeath=1; /* Number of dead states */
  709: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
  710: int popbased=0;
  711: 
  712: int *wav; /* Number of waves for this individuual 0 is possible */
  713: int maxwav=0; /* Maxim number of waves */
  714: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
  715: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
  716: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
  717: 		   to the likelihood and the sum of weights (done by funcone)*/
  718: int mle=1, weightopt=0;
  719: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
  720: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
  721: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
  722: 	   * wave mi and wave mi+1 is not an exact multiple of stepm. */
  723: int countcallfunc=0;  /* Count the number of calls to func */
  724: double jmean=1; /* Mean space between 2 waves */
  725: double **matprod2(); /* test */
  726: double **oldm, **newm, **savm; /* Working pointers to matrices */
  727: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
  728: /*FILE *fic ; */ /* Used in readdata only */
  729: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
  730: FILE *ficlog, *ficrespow;
  731: int globpr=0; /* Global variable for printing or not */
  732: double fretone; /* Only one call to likelihood */
  733: long ipmx=0; /* Number of contributions */
  734: double sw; /* Sum of weights */
  735: char filerespow[FILENAMELENGTH];
  736: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
  737: FILE *ficresilk;
  738: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
  739: FILE *ficresprobmorprev;
  740: FILE *fichtm, *fichtmcov; /* Html File */
  741: FILE *ficreseij;
  742: char filerese[FILENAMELENGTH];
  743: FILE *ficresstdeij;
  744: char fileresstde[FILENAMELENGTH];
  745: FILE *ficrescveij;
  746: char filerescve[FILENAMELENGTH];
  747: FILE  *ficresvij;
  748: char fileresv[FILENAMELENGTH];
  749: FILE  *ficresvpl;
  750: char fileresvpl[FILENAMELENGTH];
  751: char title[MAXLINE];
  752: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
  753: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
  754: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
  755: char command[FILENAMELENGTH];
  756: int  outcmd=0;
  757: 
  758: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
  759: 
  760: char filelog[FILENAMELENGTH]; /* Log file */
  761: char filerest[FILENAMELENGTH];
  762: char fileregp[FILENAMELENGTH];
  763: char popfile[FILENAMELENGTH];
  764: 
  765: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
  766: 
  767: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
  768: /* struct timezone tzp; */
  769: /* extern int gettimeofday(); */
  770: struct tm tml, *gmtime(), *localtime();
  771: 
  772: extern time_t time();
  773: 
  774: struct tm start_time, end_time, curr_time, last_time, forecast_time;
  775: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
  776: struct tm tm;
  777: 
  778: char strcurr[80], strfor[80];
  779: 
  780: char *endptr;
  781: long lval;
  782: double dval;
  783: 
  784: #define NR_END 1
  785: #define FREE_ARG char*
  786: #define FTOL 1.0e-10
  787: 
  788: #define NRANSI 
  789: #define ITMAX 200 
  790: 
  791: #define TOL 2.0e-4 
  792: 
  793: #define CGOLD 0.3819660 
  794: #define ZEPS 1.0e-10 
  795: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
  796: 
  797: #define GOLD 1.618034 
  798: #define GLIMIT 100.0 
  799: #define TINY 1.0e-20 
  800: 
  801: static double maxarg1,maxarg2;
  802: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
  803: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
  804:   
  805: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
  806: #define rint(a) floor(a+0.5)
  807: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
  808: #define mytinydouble 1.0e-16
  809: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
  810: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
  811: /* static double dsqrarg; */
  812: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
  813: static double sqrarg;
  814: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
  815: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
  816: int agegomp= AGEGOMP;
  817: 
  818: int imx; 
  819: int stepm=1;
  820: /* Stepm, step in month: minimum step interpolation*/
  821: 
  822: int estepm;
  823: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
  824: 
  825: int m,nb;
  826: long *num;
  827: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
  828: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
  829: double **pmmij, ***probs;
  830: double *ageexmed,*agecens;
  831: double dateintmean=0;
  832: 
  833: double *weight;
  834: int **s; /* Status */
  835: double *agedc;
  836: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
  837: 		  * covar=matrix(0,NCOVMAX,1,n); 
  838: 		  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
  839: double  idx; 
  840: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
  841: int *Ndum; /** Freq of modality (tricode */
  842: int **codtab; /**< codtab=imatrix(1,100,1,10); */
  843: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
  844: double *lsurv, *lpop, *tpop;
  845: 
  846: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
  847: double ftolhess; /**< Tolerance for computing hessian */
  848: 
  849: /**************** split *************************/
  850: static	int split( char *path, char *dirc, char *name, char *ext, char *finame )
  851: {
  852:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
  853:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
  854:   */ 
  855:   char	*ss;				/* pointer */
  856:   int	l1=0, l2=0;				/* length counters */
  857: 
  858:   l1 = strlen(path );			/* length of path */
  859:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
  860:   ss= strrchr( path, DIRSEPARATOR );		/* find last / */
  861:   if ( ss == NULL ) {			/* no directory, so determine current directory */
  862:     strcpy( name, path );		/* we got the fullname name because no directory */
  863:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
  864:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
  865:     /* get current working directory */
  866:     /*    extern  char* getcwd ( char *buf , int len);*/
  867: #ifdef WIN32
  868:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
  869: #else
  870: 	if (getcwd(dirc, FILENAME_MAX) == NULL) {
  871: #endif
  872:       return( GLOCK_ERROR_GETCWD );
  873:     }
  874:     /* got dirc from getcwd*/
  875:     printf(" DIRC = %s \n",dirc);
  876:   } else {				/* strip direcotry from path */
  877:     ss++;				/* after this, the filename */
  878:     l2 = strlen( ss );			/* length of filename */
  879:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
  880:     strcpy( name, ss );		/* save file name */
  881:     strncpy( dirc, path, l1 - l2 );	/* now the directory */
  882:     dirc[l1-l2] = '\0';			/* add zero */
  883:     printf(" DIRC2 = %s \n",dirc);
  884:   }
  885:   /* We add a separator at the end of dirc if not exists */
  886:   l1 = strlen( dirc );			/* length of directory */
  887:   if( dirc[l1-1] != DIRSEPARATOR ){
  888:     dirc[l1] =  DIRSEPARATOR;
  889:     dirc[l1+1] = 0; 
  890:     printf(" DIRC3 = %s \n",dirc);
  891:   }
  892:   ss = strrchr( name, '.' );		/* find last / */
  893:   if (ss >0){
  894:     ss++;
  895:     strcpy(ext,ss);			/* save extension */
  896:     l1= strlen( name);
  897:     l2= strlen(ss)+1;
  898:     strncpy( finame, name, l1-l2);
  899:     finame[l1-l2]= 0;
  900:   }
  901: 
  902:   return( 0 );				/* we're done */
  903: }
  904: 
  905: 
  906: /******************************************/
  907: 
  908: void replace_back_to_slash(char *s, char*t)
  909: {
  910:   int i;
  911:   int lg=0;
  912:   i=0;
  913:   lg=strlen(t);
  914:   for(i=0; i<= lg; i++) {
  915:     (s[i] = t[i]);
  916:     if (t[i]== '\\') s[i]='/';
  917:   }
  918: }
  919: 
  920: char *trimbb(char *out, char *in)
  921: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
  922:   char *s;
  923:   s=out;
  924:   while (*in != '\0'){
  925:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
  926:       in++;
  927:     }
  928:     *out++ = *in++;
  929:   }
  930:   *out='\0';
  931:   return s;
  932: }
  933: 
  934: /* char *substrchaine(char *out, char *in, char *chain) */
  935: /* { */
  936: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
  937: /*   char *s, *t; */
  938: /*   t=in;s=out; */
  939: /*   while ((*in != *chain) && (*in != '\0')){ */
  940: /*     *out++ = *in++; */
  941: /*   } */
  942: 
  943: /*   /\* *in matches *chain *\/ */
  944: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
  945: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
  946: /*   } */
  947: /*   in--; chain--; */
  948: /*   while ( (*in != '\0')){ */
  949: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
  950: /*     *out++ = *in++; */
  951: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
  952: /*   } */
  953: /*   *out='\0'; */
  954: /*   out=s; */
  955: /*   return out; */
  956: /* } */
  957: char *substrchaine(char *out, char *in, char *chain)
  958: {
  959:   /* Substract chain 'chain' from 'in', return and output 'out' */
  960:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
  961: 
  962:   char *strloc;
  963: 
  964:   strcpy (out, in); 
  965:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
  966:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
  967:   if(strloc != NULL){ 
  968:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
  969:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
  970:     /* strcpy (strloc, strloc +strlen(chain));*/
  971:   }
  972:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
  973:   return out;
  974: }
  975: 
  976: 
  977: char *cutl(char *blocc, char *alocc, char *in, char occ)
  978: {
  979:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
  980:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
  981:      gives blocc="abcdef" and alocc="ghi2j".
  982:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
  983:   */
  984:   char *s, *t;
  985:   t=in;s=in;
  986:   while ((*in != occ) && (*in != '\0')){
  987:     *alocc++ = *in++;
  988:   }
  989:   if( *in == occ){
  990:     *(alocc)='\0';
  991:     s=++in;
  992:   }
  993:  
  994:   if (s == t) {/* occ not found */
  995:     *(alocc-(in-s))='\0';
  996:     in=s;
  997:   }
  998:   while ( *in != '\0'){
  999:     *blocc++ = *in++;
 1000:   }
 1001: 
 1002:   *blocc='\0';
 1003:   return t;
 1004: }
 1005: char *cutv(char *blocc, char *alocc, char *in, char occ)
 1006: {
 1007:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
 1008:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
 1009:      gives blocc="abcdef2ghi" and alocc="j".
 1010:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
 1011:   */
 1012:   char *s, *t;
 1013:   t=in;s=in;
 1014:   while (*in != '\0'){
 1015:     while( *in == occ){
 1016:       *blocc++ = *in++;
 1017:       s=in;
 1018:     }
 1019:     *blocc++ = *in++;
 1020:   }
 1021:   if (s == t) /* occ not found */
 1022:     *(blocc-(in-s))='\0';
 1023:   else
 1024:     *(blocc-(in-s)-1)='\0';
 1025:   in=s;
 1026:   while ( *in != '\0'){
 1027:     *alocc++ = *in++;
 1028:   }
 1029: 
 1030:   *alocc='\0';
 1031:   return s;
 1032: }
 1033: 
 1034: int nbocc(char *s, char occ)
 1035: {
 1036:   int i,j=0;
 1037:   int lg=20;
 1038:   i=0;
 1039:   lg=strlen(s);
 1040:   for(i=0; i<= lg; i++) {
 1041:   if  (s[i] == occ ) j++;
 1042:   }
 1043:   return j;
 1044: }
 1045: 
 1046: /* void cutv(char *u,char *v, char*t, char occ) */
 1047: /* { */
 1048: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
 1049: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
 1050: /*      gives u="abcdef2ghi" and v="j" *\/ */
 1051: /*   int i,lg,j,p=0; */
 1052: /*   i=0; */
 1053: /*   lg=strlen(t); */
 1054: /*   for(j=0; j<=lg-1; j++) { */
 1055: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
 1056: /*   } */
 1057: 
 1058: /*   for(j=0; j<p; j++) { */
 1059: /*     (u[j] = t[j]); */
 1060: /*   } */
 1061: /*      u[p]='\0'; */
 1062: 
 1063: /*    for(j=0; j<= lg; j++) { */
 1064: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
 1065: /*   } */
 1066: /* } */
 1067: 
 1068: #ifdef _WIN32
 1069: char * strsep(char **pp, const char *delim)
 1070: {
 1071:   char *p, *q;
 1072:          
 1073:   if ((p = *pp) == NULL)
 1074:     return 0;
 1075:   if ((q = strpbrk (p, delim)) != NULL)
 1076:   {
 1077:     *pp = q + 1;
 1078:     *q = '\0';
 1079:   }
 1080:   else
 1081:     *pp = 0;
 1082:   return p;
 1083: }
 1084: #endif
 1085: 
 1086: /********************** nrerror ********************/
 1087: 
 1088: void nrerror(char error_text[])
 1089: {
 1090:   fprintf(stderr,"ERREUR ...\n");
 1091:   fprintf(stderr,"%s\n",error_text);
 1092:   exit(EXIT_FAILURE);
 1093: }
 1094: /*********************** vector *******************/
 1095: double *vector(int nl, int nh)
 1096: {
 1097:   double *v;
 1098:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
 1099:   if (!v) nrerror("allocation failure in vector");
 1100:   return v-nl+NR_END;
 1101: }
 1102: 
 1103: /************************ free vector ******************/
 1104: void free_vector(double*v, int nl, int nh)
 1105: {
 1106:   free((FREE_ARG)(v+nl-NR_END));
 1107: }
 1108: 
 1109: /************************ivector *******************************/
 1110: int *ivector(long nl,long nh)
 1111: {
 1112:   int *v;
 1113:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
 1114:   if (!v) nrerror("allocation failure in ivector");
 1115:   return v-nl+NR_END;
 1116: }
 1117: 
 1118: /******************free ivector **************************/
 1119: void free_ivector(int *v, long nl, long nh)
 1120: {
 1121:   free((FREE_ARG)(v+nl-NR_END));
 1122: }
 1123: 
 1124: /************************lvector *******************************/
 1125: long *lvector(long nl,long nh)
 1126: {
 1127:   long *v;
 1128:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
 1129:   if (!v) nrerror("allocation failure in ivector");
 1130:   return v-nl+NR_END;
 1131: }
 1132: 
 1133: /******************free lvector **************************/
 1134: void free_lvector(long *v, long nl, long nh)
 1135: {
 1136:   free((FREE_ARG)(v+nl-NR_END));
 1137: }
 1138: 
 1139: /******************* imatrix *******************************/
 1140: int **imatrix(long nrl, long nrh, long ncl, long nch) 
 1141:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
 1142: { 
 1143:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
 1144:   int **m; 
 1145:   
 1146:   /* allocate pointers to rows */ 
 1147:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
 1148:   if (!m) nrerror("allocation failure 1 in matrix()"); 
 1149:   m += NR_END; 
 1150:   m -= nrl; 
 1151:   
 1152:   
 1153:   /* allocate rows and set pointers to them */ 
 1154:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
 1155:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
 1156:   m[nrl] += NR_END; 
 1157:   m[nrl] -= ncl; 
 1158:   
 1159:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
 1160:   
 1161:   /* return pointer to array of pointers to rows */ 
 1162:   return m; 
 1163: } 
 1164: 
 1165: /****************** free_imatrix *************************/
 1166: void free_imatrix(m,nrl,nrh,ncl,nch)
 1167:       int **m;
 1168:       long nch,ncl,nrh,nrl; 
 1169:      /* free an int matrix allocated by imatrix() */ 
 1170: { 
 1171:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
 1172:   free((FREE_ARG) (m+nrl-NR_END)); 
 1173: } 
 1174: 
 1175: /******************* matrix *******************************/
 1176: double **matrix(long nrl, long nrh, long ncl, long nch)
 1177: {
 1178:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
 1179:   double **m;
 1180: 
 1181:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1182:   if (!m) nrerror("allocation failure 1 in matrix()");
 1183:   m += NR_END;
 1184:   m -= nrl;
 1185: 
 1186:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1187:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1188:   m[nrl] += NR_END;
 1189:   m[nrl] -= ncl;
 1190: 
 1191:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1192:   return m;
 1193:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
 1194: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
 1195: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
 1196:    */
 1197: }
 1198: 
 1199: /*************************free matrix ************************/
 1200: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
 1201: {
 1202:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1203:   free((FREE_ARG)(m+nrl-NR_END));
 1204: }
 1205: 
 1206: /******************* ma3x *******************************/
 1207: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
 1208: {
 1209:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
 1210:   double ***m;
 1211: 
 1212:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1213:   if (!m) nrerror("allocation failure 1 in matrix()");
 1214:   m += NR_END;
 1215:   m -= nrl;
 1216: 
 1217:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1218:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1219:   m[nrl] += NR_END;
 1220:   m[nrl] -= ncl;
 1221: 
 1222:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1223: 
 1224:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
 1225:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
 1226:   m[nrl][ncl] += NR_END;
 1227:   m[nrl][ncl] -= nll;
 1228:   for (j=ncl+1; j<=nch; j++) 
 1229:     m[nrl][j]=m[nrl][j-1]+nlay;
 1230:   
 1231:   for (i=nrl+1; i<=nrh; i++) {
 1232:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
 1233:     for (j=ncl+1; j<=nch; j++) 
 1234:       m[i][j]=m[i][j-1]+nlay;
 1235:   }
 1236:   return m; 
 1237:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
 1238:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
 1239:   */
 1240: }
 1241: 
 1242: /*************************free ma3x ************************/
 1243: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
 1244: {
 1245:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
 1246:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1247:   free((FREE_ARG)(m+nrl-NR_END));
 1248: }
 1249: 
 1250: /*************** function subdirf ***********/
 1251: char *subdirf(char fileres[])
 1252: {
 1253:   /* Caution optionfilefiname is hidden */
 1254:   strcpy(tmpout,optionfilefiname);
 1255:   strcat(tmpout,"/"); /* Add to the right */
 1256:   strcat(tmpout,fileres);
 1257:   return tmpout;
 1258: }
 1259: 
 1260: /*************** function subdirf2 ***********/
 1261: char *subdirf2(char fileres[], char *preop)
 1262: {
 1263:   
 1264:   /* Caution optionfilefiname is hidden */
 1265:   strcpy(tmpout,optionfilefiname);
 1266:   strcat(tmpout,"/");
 1267:   strcat(tmpout,preop);
 1268:   strcat(tmpout,fileres);
 1269:   return tmpout;
 1270: }
 1271: 
 1272: /*************** function subdirf3 ***********/
 1273: char *subdirf3(char fileres[], char *preop, char *preop2)
 1274: {
 1275:   
 1276:   /* Caution optionfilefiname is hidden */
 1277:   strcpy(tmpout,optionfilefiname);
 1278:   strcat(tmpout,"/");
 1279:   strcat(tmpout,preop);
 1280:   strcat(tmpout,preop2);
 1281:   strcat(tmpout,fileres);
 1282:   return tmpout;
 1283: }
 1284: 
 1285: char *asc_diff_time(long time_sec, char ascdiff[])
 1286: {
 1287:   long sec_left, days, hours, minutes;
 1288:   days = (time_sec) / (60*60*24);
 1289:   sec_left = (time_sec) % (60*60*24);
 1290:   hours = (sec_left) / (60*60) ;
 1291:   sec_left = (sec_left) %(60*60);
 1292:   minutes = (sec_left) /60;
 1293:   sec_left = (sec_left) % (60);
 1294:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
 1295:   return ascdiff;
 1296: }
 1297: 
 1298: /***************** f1dim *************************/
 1299: extern int ncom; 
 1300: extern double *pcom,*xicom;
 1301: extern double (*nrfunc)(double []); 
 1302:  
 1303: double f1dim(double x) 
 1304: { 
 1305:   int j; 
 1306:   double f;
 1307:   double *xt; 
 1308:  
 1309:   xt=vector(1,ncom); 
 1310:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
 1311:   f=(*nrfunc)(xt); 
 1312:   free_vector(xt,1,ncom); 
 1313:   return f; 
 1314: } 
 1315: 
 1316: /*****************brent *************************/
 1317: double brent(double ax, double bx, double cx, double (*f)(double), double tol, 	double *xmin) 
 1318: {
 1319:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
 1320:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
 1321:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
 1322:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
 1323:    * returned function value. 
 1324:   */
 1325:   int iter; 
 1326:   double a,b,d,etemp;
 1327:   double fu=0,fv,fw,fx;
 1328:   double ftemp=0.;
 1329:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
 1330:   double e=0.0; 
 1331:  
 1332:   a=(ax < cx ? ax : cx); 
 1333:   b=(ax > cx ? ax : cx); 
 1334:   x=w=v=bx; 
 1335:   fw=fv=fx=(*f)(x); 
 1336:   for (iter=1;iter<=ITMAX;iter++) { 
 1337:     xm=0.5*(a+b); 
 1338:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
 1339:     /*		if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
 1340:     printf(".");fflush(stdout);
 1341:     fprintf(ficlog,".");fflush(ficlog);
 1342: #ifdef DEBUGBRENT
 1343:     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);
 1344:     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);
 1345:     /*		if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
 1346: #endif
 1347:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
 1348:       *xmin=x; 
 1349:       return fx; 
 1350:     } 
 1351:     ftemp=fu;
 1352:     if (fabs(e) > tol1) { 
 1353:       r=(x-w)*(fx-fv); 
 1354:       q=(x-v)*(fx-fw); 
 1355:       p=(x-v)*q-(x-w)*r; 
 1356:       q=2.0*(q-r); 
 1357:       if (q > 0.0) p = -p; 
 1358:       q=fabs(q); 
 1359:       etemp=e; 
 1360:       e=d; 
 1361:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
 1362: 	d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1363:       else { 
 1364: 	d=p/q; 
 1365: 	u=x+d; 
 1366: 	if (u-a < tol2 || b-u < tol2) 
 1367: 	  d=SIGN(tol1,xm-x); 
 1368:       } 
 1369:     } else { 
 1370:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1371:     } 
 1372:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
 1373:     fu=(*f)(u); 
 1374:     if (fu <= fx) { 
 1375:       if (u >= x) a=x; else b=x; 
 1376:       SHFT(v,w,x,u) 
 1377:       SHFT(fv,fw,fx,fu) 
 1378:     } else { 
 1379:       if (u < x) a=u; else b=u; 
 1380:       if (fu <= fw || w == x) { 
 1381: 	v=w; 
 1382: 	w=u; 
 1383: 	fv=fw; 
 1384: 	fw=fu; 
 1385:       } else if (fu <= fv || v == x || v == w) { 
 1386: 	v=u; 
 1387: 	fv=fu; 
 1388:       } 
 1389:     } 
 1390:   } 
 1391:   nrerror("Too many iterations in brent"); 
 1392:   *xmin=x; 
 1393:   return fx; 
 1394: } 
 1395: 
 1396: /****************** mnbrak ***********************/
 1397: 
 1398: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
 1399: 	    double (*func)(double)) 
 1400: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
 1401: the downhill direction (defined by the function as evaluated at the initial points) and returns
 1402: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
 1403: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
 1404:    */
 1405:   double ulim,u,r,q, dum;
 1406:   double fu; 
 1407: 
 1408:   double scale=10.;
 1409:   int iterscale=0;
 1410: 
 1411:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
 1412:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
 1413: 
 1414: 
 1415:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
 1416:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
 1417:   /*   *bx = *ax - (*ax - *bx)/scale; */
 1418:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
 1419:   /* } */
 1420: 
 1421:   if (*fb > *fa) { 
 1422:     SHFT(dum,*ax,*bx,dum) 
 1423:     SHFT(dum,*fb,*fa,dum) 
 1424:   } 
 1425:   *cx=(*bx)+GOLD*(*bx-*ax); 
 1426:   *fc=(*func)(*cx); 
 1427: #ifdef DEBUG
 1428:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
 1429:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
 1430: #endif
 1431:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
 1432:     r=(*bx-*ax)*(*fb-*fc); 
 1433:     q=(*bx-*cx)*(*fb-*fa); 
 1434:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
 1435:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
 1436:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
 1437:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
 1438:       fu=(*func)(u); 
 1439: #ifdef DEBUG
 1440:       /* f(x)=A(x-u)**2+f(u) */
 1441:       double A, fparabu; 
 1442:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 1443:       fparabu= *fa - A*(*ax-u)*(*ax-u);
 1444:       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);
 1445:       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);
 1446:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
 1447:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
 1448:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
 1449:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
 1450: #endif 
 1451: #ifdef MNBRAKORIGINAL
 1452: #else
 1453:       if (fu > *fc) {
 1454: #ifdef DEBUG
 1455:       printf("mnbrak4  fu > fc \n");
 1456:       fprintf(ficlog, "mnbrak4 fu > fc\n");
 1457: #endif
 1458: 	/* SHFT(u,*cx,*cx,u) /\* ie a=c, c=u and u=c; in that case, next SHFT(a,b,c,u) will give a=b=b, b=c=u, c=u=c and *\/  */
 1459: 	/* SHFT(*fa,*fc,fu,*fc) /\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\/ */
 1460: 	dum=u; /* Shifting c and u */
 1461: 	u = *cx;
 1462: 	*cx = dum;
 1463: 	dum = fu;
 1464: 	fu = *fc;
 1465: 	*fc =dum;
 1466:       } else { /* end */
 1467: #ifdef DEBUG
 1468:       printf("mnbrak3  fu < fc \n");
 1469:       fprintf(ficlog, "mnbrak3 fu < fc\n");
 1470: #endif
 1471: 	dum=u; /* Shifting c and u */
 1472: 	u = *cx;
 1473: 	*cx = dum;
 1474: 	dum = fu;
 1475: 	fu = *fc;
 1476: 	*fc =dum;
 1477:       }
 1478: #endif
 1479:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
 1480: #ifdef DEBUG
 1481:       printf("mnbrak2  u after c but before ulim\n");
 1482:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
 1483: #endif
 1484:       fu=(*func)(u); 
 1485:       if (fu < *fc) { 
 1486: #ifdef DEBUG
 1487:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
 1488:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
 1489: #endif
 1490: 	SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
 1491: 	SHFT(*fb,*fc,fu,(*func)(u)) 
 1492:       } 
 1493:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
 1494: #ifdef DEBUG
 1495:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
 1496:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
 1497: #endif
 1498:       u=ulim; 
 1499:       fu=(*func)(u); 
 1500:     } else { /* u could be left to b (if r > q parabola has a maximum) */
 1501: #ifdef DEBUG
 1502:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
 1503:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
 1504: #endif
 1505:       u=(*cx)+GOLD*(*cx-*bx); 
 1506:       fu=(*func)(u); 
 1507:     } /* end tests */
 1508:     SHFT(*ax,*bx,*cx,u) 
 1509:     SHFT(*fa,*fb,*fc,fu) 
 1510: #ifdef DEBUG
 1511:       printf("mnbrak2 (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu);
 1512:       fprintf(ficlog, "mnbrak2 (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu);
 1513: #endif
 1514:   } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
 1515: } 
 1516: 
 1517: /*************** linmin ************************/
 1518: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
 1519: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
 1520: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
 1521: the value of func at the returned location p . This is actually all accomplished by calling the
 1522: routines mnbrak and brent .*/
 1523: int ncom; 
 1524: double *pcom,*xicom;
 1525: double (*nrfunc)(double []); 
 1526:  
 1527: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
 1528: { 
 1529:   double brent(double ax, double bx, double cx, 
 1530: 	       double (*f)(double), double tol, double *xmin); 
 1531:   double f1dim(double x); 
 1532:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
 1533: 	      double *fc, double (*func)(double)); 
 1534:   int j; 
 1535:   double xx,xmin,bx,ax; 
 1536:   double fx,fb,fa;
 1537: 
 1538:   double scale=10., axs, xxs, xxss; /* Scale added for infinity */
 1539:  
 1540:   ncom=n; 
 1541:   pcom=vector(1,n); 
 1542:   xicom=vector(1,n); 
 1543:   nrfunc=func; 
 1544:   for (j=1;j<=n;j++) { 
 1545:     pcom[j]=p[j]; 
 1546:     xicom[j]=xi[j]; 
 1547:   } 
 1548: 
 1549:   axs=0.0;
 1550:   xxss=1; /* 1 and using scale */
 1551:   xxs=1;
 1552:   do{
 1553:     ax=0.;
 1554:     xx= xxs;
 1555:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
 1556:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
 1557:     /* xt[x,j]=pcom[j]+x*xicom[j]  f(ax) = f(xt(a,j=1,n)) = f(p(j) + 0 * xi(j)) and  f(xx) = f(xt(x, j=1,n)) = f(p(j) + 1 * xi(j))   */
 1558:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
 1559:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
 1560:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
 1561:     /* Find a bracket a,x,b in direction n=xi ie xicom, order may change. Scale is [0:xxs*xi[j]] et non plus  [0:xi[j]]*/
 1562:     if (fx != fx){
 1563: 	xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
 1564: 	printf("\nLinmin NAN : input [axs=%lf:xxs=%lf], mnbrak outputs fx=%lf <(fb=%lf and fa=%lf) with xx=%lf in [ax=%lf:bx=%lf] \n",  axs, xxs, fx,fb, fa, xx, ax, bx);
 1565:     }
 1566:   }while(fx != fx);
 1567: 
 1568:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
 1569:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
 1570:   /* fmin = f(p[j] + xmin * xi[j]) */
 1571:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
 1572:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
 1573: #ifdef DEBUG
 1574:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1575:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1576: #endif
 1577:   /* printf("linmin end "); */
 1578:   for (j=1;j<=n;j++) { 
 1579:     /* printf(" before xi[%d]=%12.8f", j,xi[j]); */
 1580:     xi[j] *= xmin; /* xi rescaled by xmin: if xmin=-1.237 and xi=(1,0,...,0) xi=(-1.237,0,...,0) */
 1581:     /* if(xxs <1.0) */
 1582:     /*   printf(" after xi[%d]=%12.8f, xmin=%12.8f, ax=%12.8f, xx=%12.8f, bx=%12.8f, xxs=%12.8f", j,xi[j], xmin, ax, xx, bx,xxs ); */
 1583:     p[j] += xi[j]; /* Parameters values are updated accordingly */
 1584:   } 
 1585:   /* printf("\n"); */
 1586:   /* printf("Comparing last *frec(xmin)=%12.8f from Brent and frec(0.)=%12.8f \n", *fret, (*func)(p)); */
 1587:   free_vector(xicom,1,n); 
 1588:   free_vector(pcom,1,n); 
 1589: } 
 1590: 
 1591: 
 1592: /*************** powell ************************/
 1593: /*
 1594: Minimization of a function func of n variables. Input consists of an initial starting point
 1595: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
 1596: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
 1597: such that failure to decrease by more than this amount on one iteration signals doneness. On
 1598: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
 1599: function value at p , and iter is the number of iterations taken. The routine linmin is used.
 1600:  */
 1601: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
 1602: 	    double (*func)(double [])) 
 1603: { 
 1604:   void linmin(double p[], double xi[], int n, double *fret, 
 1605: 	      double (*func)(double [])); 
 1606:   int i,ibig,j; 
 1607:   double del,t,*pt,*ptt,*xit;
 1608:   double directest;
 1609:   double fp,fptt;
 1610:   double *xits;
 1611:   int niterf, itmp;
 1612: 
 1613:   pt=vector(1,n); 
 1614:   ptt=vector(1,n); 
 1615:   xit=vector(1,n); 
 1616:   xits=vector(1,n); 
 1617:   *fret=(*func)(p); 
 1618:   for (j=1;j<=n;j++) pt[j]=p[j]; 
 1619:     rcurr_time = time(NULL);  
 1620:   for (*iter=1;;++(*iter)) { 
 1621:     fp=(*fret); /* From former iteration or initial value */
 1622:     ibig=0; 
 1623:     del=0.0; 
 1624:     rlast_time=rcurr_time;
 1625:     /* (void) gettimeofday(&curr_time,&tzp); */
 1626:     rcurr_time = time(NULL);  
 1627:     curr_time = *localtime(&rcurr_time);
 1628:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
 1629:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
 1630: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
 1631:    for (i=1;i<=n;i++) {
 1632:       printf(" %d %.12f",i, p[i]);
 1633:       fprintf(ficlog," %d %.12lf",i, p[i]);
 1634:       fprintf(ficrespow," %.12lf", p[i]);
 1635:     }
 1636:     printf("\n");
 1637:     fprintf(ficlog,"\n");
 1638:     fprintf(ficrespow,"\n");fflush(ficrespow);
 1639:     if(*iter <=3){
 1640:       tml = *localtime(&rcurr_time);
 1641:       strcpy(strcurr,asctime(&tml));
 1642:       rforecast_time=rcurr_time; 
 1643:       itmp = strlen(strcurr);
 1644:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
 1645: 	strcurr[itmp-1]='\0';
 1646:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1647:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1648:       for(niterf=10;niterf<=30;niterf+=10){
 1649: 	rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
 1650: 	forecast_time = *localtime(&rforecast_time);
 1651: 	strcpy(strfor,asctime(&forecast_time));
 1652: 	itmp = strlen(strfor);
 1653: 	if(strfor[itmp-1]=='\n')
 1654: 	strfor[itmp-1]='\0';
 1655: 	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);
 1656: 	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);
 1657:       }
 1658:     }
 1659:     for (i=1;i<=n;i++) { /* For each direction i */
 1660:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
 1661:       fptt=(*fret); 
 1662: #ifdef DEBUG
 1663: 	  printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1664: 	  fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1665: #endif
 1666: 	  printf("%d",i);fflush(stdout); /* print direction (parameter) i */
 1667:       fprintf(ficlog,"%d",i);fflush(ficlog);
 1668:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
 1669: 				    /* Outputs are fret(new point p) p is updated and xit rescaled */
 1670:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
 1671: 	/* because that direction will be replaced unless the gain del is small */
 1672: 	/* in comparison with the 'probable' gain, mu^2, with the last average direction. */
 1673: 	/* Unless the n directions are conjugate some gain in the determinant may be obtained */
 1674: 	/* with the new direction. */
 1675: 	del=fabs(fptt-(*fret)); 
 1676: 	ibig=i; 
 1677:       } 
 1678: #ifdef DEBUG
 1679:       printf("%d %.12e",i,(*fret));
 1680:       fprintf(ficlog,"%d %.12e",i,(*fret));
 1681:       for (j=1;j<=n;j++) {
 1682: 	xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
 1683: 	printf(" x(%d)=%.12e",j,xit[j]);
 1684: 	fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
 1685:       }
 1686:       for(j=1;j<=n;j++) {
 1687: 	printf(" p(%d)=%.12e",j,p[j]);
 1688: 	fprintf(ficlog," p(%d)=%.12e",j,p[j]);
 1689:       }
 1690:       printf("\n");
 1691:       fprintf(ficlog,"\n");
 1692: #endif
 1693:     } /* end loop on each direction i */
 1694:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
 1695:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
 1696:     /* New value of last point Pn is not computed, P(n-1) */
 1697:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
 1698:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
 1699:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
 1700:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
 1701:       /* decreased of more than 3.84  */
 1702:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
 1703:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
 1704:       /* By adding 10 parameters more the gain should be 18.31 */
 1705: 
 1706:       /* Starting the program with initial values given by a former maximization will simply change */
 1707:       /* the scales of the directions and the directions, because the are reset to canonical directions */
 1708:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
 1709:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
 1710: #ifdef DEBUG
 1711:       int k[2],l;
 1712:       k[0]=1;
 1713:       k[1]=-1;
 1714:       printf("Max: %.12e",(*func)(p));
 1715:       fprintf(ficlog,"Max: %.12e",(*func)(p));
 1716:       for (j=1;j<=n;j++) {
 1717: 	printf(" %.12e",p[j]);
 1718: 	fprintf(ficlog," %.12e",p[j]);
 1719:       }
 1720:       printf("\n");
 1721:       fprintf(ficlog,"\n");
 1722:       for(l=0;l<=1;l++) {
 1723: 	for (j=1;j<=n;j++) {
 1724: 	  ptt[j]=p[j]+(p[j]-pt[j])*k[l];
 1725: 	  printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1726: 	  fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1727: 	}
 1728: 	printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1729: 	fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1730:       }
 1731: #endif
 1732: 
 1733: 
 1734:       free_vector(xit,1,n); 
 1735:       free_vector(xits,1,n); 
 1736:       free_vector(ptt,1,n); 
 1737:       free_vector(pt,1,n); 
 1738:       return; 
 1739:     } 
 1740:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
 1741:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
 1742:       ptt[j]=2.0*p[j]-pt[j]; 
 1743:       xit[j]=p[j]-pt[j]; 
 1744:       pt[j]=p[j]; 
 1745:     } 
 1746:     fptt=(*func)(ptt); /* f_3 */
 1747:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
 1748:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
 1749:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
 1750:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
 1751:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
 1752:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
 1753:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
 1754:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
 1755: #ifdef NRCORIGINAL
 1756:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
 1757: #else
 1758:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
 1759:       t= t- del*SQR(fp-fptt);
 1760: #endif
 1761:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If del was big enough we change it for a new direction */
 1762: #ifdef DEBUG
 1763:       printf("t1= %.12lf, t2= %.12lf, t=%.12lf  directest=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t,directest);
 1764:       fprintf(ficlog,"t1= %.12lf, t2= %.12lf, t=%.12lf directest=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t,directest);
 1765:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 1766: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 1767:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 1768: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 1769:       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);
 1770:       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);
 1771: #endif
 1772: #ifdef POWELLORIGINAL
 1773:       if (t < 0.0) { /* Then we use it for new direction */
 1774: #else
 1775:       if (directest*t < 0.0) { /* Contradiction between both tests */
 1776:       printf("directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
 1777:       printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 1778:       fprintf(ficlog,"directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
 1779:       fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 1780:     } 
 1781:       if (directest < 0.0) { /* Then we use it for new direction */
 1782: #endif
 1783: 	linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
 1784: 	for (j=1;j<=n;j++) { 
 1785: 	  xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
 1786: 	  xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
 1787: 	}
 1788: 	printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 1789: 	fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 1790: 
 1791: #ifdef DEBUG
 1792: 	printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1793: 	fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1794: 	for(j=1;j<=n;j++){
 1795: 	  printf(" %.12e",xit[j]);
 1796: 	  fprintf(ficlog," %.12e",xit[j]);
 1797: 	}
 1798: 	printf("\n");
 1799: 	fprintf(ficlog,"\n");
 1800: #endif
 1801:       } /* end of t negative */
 1802:     } /* end if (fptt < fp)  */
 1803:   } 
 1804: } 
 1805: 
 1806: /**** Prevalence limit (stable or period prevalence)  ****************/
 1807: 
 1808: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
 1809: {
 1810:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
 1811:      matrix by transitions matrix until convergence is reached */
 1812:   
 1813:   int i, ii,j,k;
 1814:   double min, max, maxmin, maxmax,sumnew=0.;
 1815:   /* double **matprod2(); */ /* test */
 1816:   double **out, cov[NCOVMAX+1], **pmij();
 1817:   double **newm;
 1818:   double agefin, delaymax=50 ; /* Max number of years to converge */
 1819:   
 1820:   for (ii=1;ii<=nlstate+ndeath;ii++)
 1821:     for (j=1;j<=nlstate+ndeath;j++){
 1822:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1823:     }
 1824:   
 1825:   cov[1]=1.;
 1826:   
 1827:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 1828:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
 1829:     newm=savm;
 1830:     /* Covariates have to be included here again */
 1831:     cov[2]=agefin;
 1832:     if(nagesqr==1)
 1833:       cov[3]= agefin*agefin;;
 1834:     for (k=1; k<=cptcovn;k++) {
 1835:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 1836:       /*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]]);*/
 1837:     }
 1838:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 1839:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]*cov[2];
 1840:     for (k=1; k<=cptcovprod;k++) /* Useless */
 1841:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 1842:     
 1843:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 1844:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 1845:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 1846:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 1847:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 1848:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
 1849:     
 1850:     savm=oldm;
 1851:     oldm=newm;
 1852:     maxmax=0.;
 1853:     for(j=1;j<=nlstate;j++){
 1854:       min=1.;
 1855:       max=0.;
 1856:       for(i=1; i<=nlstate; i++) {
 1857: 	sumnew=0;
 1858: 	for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
 1859: 	prlim[i][j]= newm[i][j]/(1-sumnew);
 1860:         /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
 1861: 	max=FMAX(max,prlim[i][j]);
 1862: 	min=FMIN(min,prlim[i][j]);
 1863:       }
 1864:       maxmin=max-min;
 1865:       maxmax=FMAX(maxmax,maxmin);
 1866:     } /* j loop */
 1867:     if(maxmax < ftolpl){
 1868:       return prlim;
 1869:     }
 1870:   } /* age loop */
 1871:   return prlim; /* should not reach here */
 1872: }
 1873: 
 1874: /*************** transition probabilities ***************/ 
 1875: 
 1876: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 1877: {
 1878:   /* According to parameters values stored in x and the covariate's values stored in cov,
 1879:      computes the probability to be observed in state j being in state i by appying the
 1880:      model to the ncovmodel covariates (including constant and age).
 1881:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 1882:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 1883:      ncth covariate in the global vector x is given by the formula:
 1884:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 1885:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 1886:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 1887:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 1888:      Outputs ps[i][j] the probability to be observed in j being in j according to
 1889:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 1890:   */
 1891:   double s1, lnpijopii;
 1892:   /*double t34;*/
 1893:   int i,j, nc, ii, jj;
 1894: 
 1895:     for(i=1; i<= nlstate; i++){
 1896:       for(j=1; j<i;j++){
 1897: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 1898: 	  /*lnpijopii += param[i][j][nc]*cov[nc];*/
 1899: 	  lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 1900: /* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 1901: 	}
 1902: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 1903: /* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 1904:       }
 1905:       for(j=i+1; j<=nlstate+ndeath;j++){
 1906: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 1907: 	  /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 1908: 	  lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 1909: /* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 1910: 	}
 1911: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 1912:       }
 1913:     }
 1914:     
 1915:     for(i=1; i<= nlstate; i++){
 1916:       s1=0;
 1917:       for(j=1; j<i; j++){
 1918: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 1919: 	/*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 1920:       }
 1921:       for(j=i+1; j<=nlstate+ndeath; j++){
 1922: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 1923: 	/*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 1924:       }
 1925:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 1926:       ps[i][i]=1./(s1+1.);
 1927:       /* Computing other pijs */
 1928:       for(j=1; j<i; j++)
 1929: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 1930:       for(j=i+1; j<=nlstate+ndeath; j++)
 1931: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 1932:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 1933:     } /* end i */
 1934:     
 1935:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 1936:       for(jj=1; jj<= nlstate+ndeath; jj++){
 1937: 	ps[ii][jj]=0;
 1938: 	ps[ii][ii]=1;
 1939:       }
 1940:     }
 1941:     
 1942:     
 1943:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 1944:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 1945:     /* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 1946:     /*   } */
 1947:     /*   printf("\n "); */
 1948:     /* } */
 1949:     /* printf("\n ");printf("%lf ",cov[2]);*/
 1950:     /*
 1951:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
 1952:       goto end;*/
 1953:     return ps;
 1954: }
 1955: 
 1956: /**************** Product of 2 matrices ******************/
 1957: 
 1958: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
 1959: {
 1960:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
 1961:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
 1962:   /* in, b, out are matrice of pointers which should have been initialized 
 1963:      before: only the contents of out is modified. The function returns
 1964:      a pointer to pointers identical to out */
 1965:   int i, j, k;
 1966:   for(i=nrl; i<= nrh; i++)
 1967:     for(k=ncolol; k<=ncoloh; k++){
 1968:       out[i][k]=0.;
 1969:       for(j=ncl; j<=nch; j++)
 1970:   	out[i][k] +=in[i][j]*b[j][k];
 1971:     }
 1972:   return out;
 1973: }
 1974: 
 1975: 
 1976: /************* Higher Matrix Product ***************/
 1977: 
 1978: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
 1979: {
 1980:   /* Computes the transition matrix starting at age 'age' over 
 1981:      'nhstepm*hstepm*stepm' months (i.e. until
 1982:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
 1983:      nhstepm*hstepm matrices. 
 1984:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
 1985:      (typically every 2 years instead of every month which is too big 
 1986:      for the memory).
 1987:      Model is determined by parameters x and covariates have to be 
 1988:      included manually here. 
 1989: 
 1990:      */
 1991: 
 1992:   int i, j, d, h, k;
 1993:   double **out, cov[NCOVMAX+1];
 1994:   double **newm;
 1995:   double agexact;
 1996: 
 1997:   /* Hstepm could be zero and should return the unit matrix */
 1998:   for (i=1;i<=nlstate+ndeath;i++)
 1999:     for (j=1;j<=nlstate+ndeath;j++){
 2000:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 2001:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 2002:     }
 2003:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2004:   for(h=1; h <=nhstepm; h++){
 2005:     for(d=1; d <=hstepm; d++){
 2006:       newm=savm;
 2007:       /* Covariates have to be included here again */
 2008:       cov[1]=1.;
 2009:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
 2010:       cov[2]=agexact;
 2011:       if(nagesqr==1)
 2012: 	cov[3]= agexact*agexact;
 2013:       for (k=1; k<=cptcovn;k++) 
 2014: 	cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 2015:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
 2016: 	/* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2017: 	cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
 2018:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
 2019: 	cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 2020: 
 2021: 
 2022:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 2023:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 2024:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
 2025: 		   pmij(pmmij,cov,ncovmodel,x,nlstate));
 2026:       savm=oldm;
 2027:       oldm=newm;
 2028:     }
 2029:     for(i=1; i<=nlstate+ndeath; i++)
 2030:       for(j=1;j<=nlstate+ndeath;j++) {
 2031: 	po[i][j][h]=newm[i][j];
 2032: 	/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 2033:       }
 2034:     /*printf("h=%d ",h);*/
 2035:   } /* end h */
 2036: /*     printf("\n H=%d \n",h); */
 2037:   return po;
 2038: }
 2039: 
 2040: #ifdef NLOPT
 2041:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
 2042:   double fret;
 2043:   double *xt;
 2044:   int j;
 2045:   myfunc_data *d2 = (myfunc_data *) pd;
 2046: /* xt = (p1-1); */
 2047:   xt=vector(1,n); 
 2048:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
 2049: 
 2050:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
 2051:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
 2052:   printf("Function = %.12lf ",fret);
 2053:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
 2054:   printf("\n");
 2055:  free_vector(xt,1,n);
 2056:   return fret;
 2057: }
 2058: #endif
 2059: 
 2060: /*************** log-likelihood *************/
 2061: double func( double *x)
 2062: {
 2063:   int i, ii, j, k, mi, d, kk;
 2064:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 2065:   double **out;
 2066:   double sw; /* Sum of weights */
 2067:   double lli; /* Individual log likelihood */
 2068:   int s1, s2;
 2069:   double bbh, survp;
 2070:   long ipmx;
 2071:   double agexact;
 2072:   /*extern weight */
 2073:   /* We are differentiating ll according to initial status */
 2074:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 2075:   /*for(i=1;i<imx;i++) 
 2076:     printf(" %d\n",s[4][i]);
 2077:   */
 2078: 
 2079:   ++countcallfunc;
 2080: 
 2081:   cov[1]=1.;
 2082: 
 2083:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 2084: 
 2085:   if(mle==1){
 2086:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2087:       /* Computes the values of the ncovmodel covariates of the model
 2088: 	 depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
 2089: 	 Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
 2090: 	 to be observed in j being in i according to the model.
 2091:        */
 2092:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
 2093: 	  cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2094:       }
 2095:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
 2096: 	 is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
 2097: 	 has been calculated etc */
 2098:       for(mi=1; mi<= wav[i]-1; mi++){
 2099: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2100: 	  for (j=1;j<=nlstate+ndeath;j++){
 2101: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2102: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2103: 	  }
 2104: 	for(d=0; d<dh[mi][i]; d++){
 2105: 	  newm=savm;
 2106: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2107: 	  cov[2]=agexact;
 2108: 	  if(nagesqr==1)
 2109: 	    cov[3]= agexact*agexact;
 2110: 	  for (kk=1; kk<=cptcovage;kk++) {
 2111: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
 2112: 	  }
 2113: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2114: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2115: 	  savm=oldm;
 2116: 	  oldm=newm;
 2117: 	} /* end mult */
 2118:       
 2119: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 2120: 	/* But now since version 0.9 we anticipate for bias at large stepm.
 2121: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 2122: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
 2123: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
 2124: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 2125: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
 2126: 	 * probability in order to take into account the bias as a fraction of the way
 2127: 	 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
 2128: 	 * -stepm/2 to stepm/2 .
 2129: 	 * For stepm=1 the results are the same as for previous versions of Imach.
 2130: 	 * For stepm > 1 the results are less biased than in previous versions. 
 2131: 	 */
 2132: 	s1=s[mw[mi][i]][i];
 2133: 	s2=s[mw[mi+1][i]][i];
 2134: 	bbh=(double)bh[mi][i]/(double)stepm; 
 2135: 	/* bias bh is positive if real duration
 2136: 	 * is higher than the multiple of stepm and negative otherwise.
 2137: 	 */
 2138: 	/* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
 2139: 	if( s2 > nlstate){ 
 2140: 	  /* i.e. if s2 is a death state and if the date of death is known 
 2141: 	     then the contribution to the likelihood is the probability to 
 2142: 	     die between last step unit time and current  step unit time, 
 2143: 	     which is also equal to probability to die before dh 
 2144: 	     minus probability to die before dh-stepm . 
 2145: 	     In version up to 0.92 likelihood was computed
 2146: 	as if date of death was unknown. Death was treated as any other
 2147: 	health state: the date of the interview describes the actual state
 2148: 	and not the date of a change in health state. The former idea was
 2149: 	to consider that at each interview the state was recorded
 2150: 	(healthy, disable or death) and IMaCh was corrected; but when we
 2151: 	introduced the exact date of death then we should have modified
 2152: 	the contribution of an exact death to the likelihood. This new
 2153: 	contribution is smaller and very dependent of the step unit
 2154: 	stepm. It is no more the probability to die between last interview
 2155: 	and month of death but the probability to survive from last
 2156: 	interview up to one month before death multiplied by the
 2157: 	probability to die within a month. Thanks to Chris
 2158: 	Jackson for correcting this bug.  Former versions increased
 2159: 	mortality artificially. The bad side is that we add another loop
 2160: 	which slows down the processing. The difference can be up to 10%
 2161: 	lower mortality.
 2162: 	  */
 2163: 	/* If, at the beginning of the maximization mostly, the
 2164: 	   cumulative probability or probability to be dead is
 2165: 	   constant (ie = 1) over time d, the difference is equal to
 2166: 	   0.  out[s1][3] = savm[s1][3]: probability, being at state
 2167: 	   s1 at precedent wave, to be dead a month before current
 2168: 	   wave is equal to probability, being at state s1 at
 2169: 	   precedent wave, to be dead at mont of the current
 2170: 	   wave. Then the observed probability (that this person died)
 2171: 	   is null according to current estimated parameter. In fact,
 2172: 	   it should be very low but not zero otherwise the log go to
 2173: 	   infinity.
 2174: 	*/
 2175: /* #ifdef INFINITYORIGINAL */
 2176: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 2177: /* #else */
 2178: /* 	  if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
 2179: /* 	    lli=log(mytinydouble); */
 2180: /* 	  else */
 2181: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 2182: /* #endif */
 2183: 	    lli=log(out[s1][s2] - savm[s1][s2]);
 2184: 
 2185: 	} else if  (s2==-2) {
 2186: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 2187: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2188: 	  /*survp += out[s1][j]; */
 2189: 	  lli= log(survp);
 2190: 	}
 2191: 	
 2192:  	else if  (s2==-4) { 
 2193: 	  for (j=3,survp=0. ; j<=nlstate; j++)  
 2194: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2195:  	  lli= log(survp); 
 2196:  	} 
 2197: 
 2198:  	else if  (s2==-5) { 
 2199:  	  for (j=1,survp=0. ; j<=2; j++)  
 2200: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2201:  	  lli= log(survp); 
 2202:  	} 
 2203: 	
 2204: 	else{
 2205: 	  lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2206: 	  /*  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 */
 2207: 	} 
 2208: 	/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 2209: 	/*if(lli ==000.0)*/
 2210: 	/*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); */
 2211:   	ipmx +=1;
 2212: 	sw += weight[i];
 2213: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2214: 	/* if (lli < log(mytinydouble)){ */
 2215: 	/*   printf("Close to inf lli = %.10lf <  %.10lf i= %d mi= %d, s[%d][i]=%d s1=%d s2=%d\n", lli,log(mytinydouble), i, mi,mw[mi][i], s[mw[mi][i]][i], s1,s2); */
 2216: 	/*   fprintf(ficlog,"Close to inf lli = %.10lf i= %d mi= %d, s[mw[mi][i]][i]=%d\n", lli, i, mi,s[mw[mi][i]][i]); */
 2217: 	/* } */
 2218:       } /* end of wave */
 2219:     } /* end of individual */
 2220:   }  else if(mle==2){
 2221:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2222:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2223:       for(mi=1; mi<= wav[i]-1; mi++){
 2224: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2225: 	  for (j=1;j<=nlstate+ndeath;j++){
 2226: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2227: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2228: 	  }
 2229: 	for(d=0; d<=dh[mi][i]; d++){
 2230: 	  newm=savm;
 2231: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2232: 	  cov[2]=agexact;
 2233: 	  if(nagesqr==1)
 2234: 	    cov[3]= agexact*agexact;
 2235: 	  for (kk=1; kk<=cptcovage;kk++) {
 2236: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2237: 	  }
 2238: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2239: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2240: 	  savm=oldm;
 2241: 	  oldm=newm;
 2242: 	} /* end mult */
 2243:       
 2244: 	s1=s[mw[mi][i]][i];
 2245: 	s2=s[mw[mi+1][i]][i];
 2246: 	bbh=(double)bh[mi][i]/(double)stepm; 
 2247: 	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 */
 2248: 	ipmx +=1;
 2249: 	sw += weight[i];
 2250: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2251:       } /* end of wave */
 2252:     } /* end of individual */
 2253:   }  else if(mle==3){  /* exponential inter-extrapolation */
 2254:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2255:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2256:       for(mi=1; mi<= wav[i]-1; mi++){
 2257: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2258: 	  for (j=1;j<=nlstate+ndeath;j++){
 2259: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2260: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2261: 	  }
 2262: 	for(d=0; d<dh[mi][i]; d++){
 2263: 	  newm=savm;
 2264: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2265: 	  cov[2]=agexact;
 2266: 	  if(nagesqr==1)
 2267: 	    cov[3]= agexact*agexact;
 2268: 	  for (kk=1; kk<=cptcovage;kk++) {
 2269: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2270: 	  }
 2271: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2272: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2273: 	  savm=oldm;
 2274: 	  oldm=newm;
 2275: 	} /* end mult */
 2276:       
 2277: 	s1=s[mw[mi][i]][i];
 2278: 	s2=s[mw[mi+1][i]][i];
 2279: 	bbh=(double)bh[mi][i]/(double)stepm; 
 2280: 	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 */
 2281: 	ipmx +=1;
 2282: 	sw += weight[i];
 2283: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2284:       } /* end of wave */
 2285:     } /* end of individual */
 2286:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
 2287:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2288:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2289:       for(mi=1; mi<= wav[i]-1; mi++){
 2290: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2291: 	  for (j=1;j<=nlstate+ndeath;j++){
 2292: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2293: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2294: 	  }
 2295: 	for(d=0; d<dh[mi][i]; d++){
 2296: 	  newm=savm;
 2297: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2298: 	  cov[2]=agexact;
 2299: 	  if(nagesqr==1)
 2300: 	    cov[3]= agexact*agexact;
 2301: 	  for (kk=1; kk<=cptcovage;kk++) {
 2302: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2303: 	  }
 2304: 	
 2305: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2306: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2307: 	  savm=oldm;
 2308: 	  oldm=newm;
 2309: 	} /* end mult */
 2310:       
 2311: 	s1=s[mw[mi][i]][i];
 2312: 	s2=s[mw[mi+1][i]][i];
 2313: 	if( s2 > nlstate){ 
 2314: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 2315: 	}else{
 2316: 	  lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 2317: 	}
 2318: 	ipmx +=1;
 2319: 	sw += weight[i];
 2320: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2321: /* 	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]); */
 2322:       } /* end of wave */
 2323:     } /* end of individual */
 2324:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
 2325:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2326:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2327:       for(mi=1; mi<= wav[i]-1; mi++){
 2328: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2329: 	  for (j=1;j<=nlstate+ndeath;j++){
 2330: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2331: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2332: 	  }
 2333: 	for(d=0; d<dh[mi][i]; d++){
 2334: 	  newm=savm;
 2335: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2336: 	  cov[2]=agexact;
 2337: 	  if(nagesqr==1)
 2338: 	    cov[3]= agexact*agexact;
 2339: 	  for (kk=1; kk<=cptcovage;kk++) {
 2340: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2341: 	  }
 2342: 	
 2343: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2344: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2345: 	  savm=oldm;
 2346: 	  oldm=newm;
 2347: 	} /* end mult */
 2348:       
 2349: 	s1=s[mw[mi][i]][i];
 2350: 	s2=s[mw[mi+1][i]][i];
 2351: 	lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 2352: 	ipmx +=1;
 2353: 	sw += weight[i];
 2354: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2355: 	/*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]);*/
 2356:       } /* end of wave */
 2357:     } /* end of individual */
 2358:   } /* End of if */
 2359:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 2360:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 2361:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 2362:   return -l;
 2363: }
 2364: 
 2365: /*************** log-likelihood *************/
 2366: double funcone( double *x)
 2367: {
 2368:   /* Same as likeli but slower because of a lot of printf and if */
 2369:   int i, ii, j, k, mi, d, kk;
 2370:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 2371:   double **out;
 2372:   double lli; /* Individual log likelihood */
 2373:   double llt;
 2374:   int s1, s2;
 2375:   double bbh, survp;
 2376:   double agexact;
 2377:   /*extern weight */
 2378:   /* We are differentiating ll according to initial status */
 2379:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 2380:   /*for(i=1;i<imx;i++) 
 2381:     printf(" %d\n",s[4][i]);
 2382:   */
 2383:   cov[1]=1.;
 2384: 
 2385:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 2386: 
 2387:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2388:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2389:     for(mi=1; mi<= wav[i]-1; mi++){
 2390:       for (ii=1;ii<=nlstate+ndeath;ii++)
 2391: 	for (j=1;j<=nlstate+ndeath;j++){
 2392: 	  oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2393: 	  savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2394: 	}
 2395:       for(d=0; d<dh[mi][i]; d++){
 2396: 	newm=savm;
 2397: 	agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2398: 	cov[2]=agexact;
 2399: 	if(nagesqr==1)
 2400: 	  cov[3]= agexact*agexact;
 2401: 	for (kk=1; kk<=cptcovage;kk++) {
 2402: 	  cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2403: 	}
 2404: 
 2405: 	/* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2406: 	out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2407: 		     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2408: 	/* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
 2409: 	/* 	     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
 2410: 	savm=oldm;
 2411: 	oldm=newm;
 2412:       } /* end mult */
 2413:       
 2414:       s1=s[mw[mi][i]][i];
 2415:       s2=s[mw[mi+1][i]][i];
 2416:       bbh=(double)bh[mi][i]/(double)stepm; 
 2417:       /* bias is positive if real duration
 2418:        * is higher than the multiple of stepm and negative otherwise.
 2419:        */
 2420:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
 2421: 	lli=log(out[s1][s2] - savm[s1][s2]);
 2422:       } else if  (s2==-2) {
 2423: 	for (j=1,survp=0. ; j<=nlstate; j++) 
 2424: 	  survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2425: 	lli= log(survp);
 2426:       }else if (mle==1){
 2427: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2428:       } else if(mle==2){
 2429: 	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 */
 2430:       } else if(mle==3){  /* exponential inter-extrapolation */
 2431: 	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 */
 2432:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
 2433: 	lli=log(out[s1][s2]); /* Original formula */
 2434:       } else{  /* mle=0 back to 1 */
 2435: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2436: 	/*lli=log(out[s1][s2]); */ /* Original formula */
 2437:       } /* End of if */
 2438:       ipmx +=1;
 2439:       sw += weight[i];
 2440:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2441:       /*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]); */
 2442:       if(globpr){
 2443: 	fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
 2444:  %11.6f %11.6f %11.6f ", \
 2445: 		num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
 2446: 		2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
 2447: 	for(k=1,llt=0.,l=0.; k<=nlstate; k++){
 2448: 	  llt +=ll[k]*gipmx/gsw;
 2449: 	  fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
 2450: 	}
 2451: 	fprintf(ficresilk," %10.6f\n", -llt);
 2452:       }
 2453:     } /* end of wave */
 2454:   } /* end of individual */
 2455:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 2456:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 2457:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 2458:   if(globpr==0){ /* First time we count the contributions and weights */
 2459:     gipmx=ipmx;
 2460:     gsw=sw;
 2461:   }
 2462:   return -l;
 2463: }
 2464: 
 2465: 
 2466: /*************** function likelione ***********/
 2467: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
 2468: {
 2469:   /* This routine should help understanding what is done with 
 2470:      the selection of individuals/waves and
 2471:      to check the exact contribution to the likelihood.
 2472:      Plotting could be done.
 2473:    */
 2474:   int k;
 2475: 
 2476:   if(*globpri !=0){ /* Just counts and sums, no printings */
 2477:     strcpy(fileresilk,"ilk"); 
 2478:     strcat(fileresilk,fileres);
 2479:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
 2480:       printf("Problem with resultfile: %s\n", fileresilk);
 2481:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
 2482:     }
 2483:     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");
 2484:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
 2485:     /* 	i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
 2486:     for(k=1; k<=nlstate; k++) 
 2487:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
 2488:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
 2489:   }
 2490: 
 2491:   *fretone=(*funcone)(p);
 2492:   if(*globpri !=0){
 2493:     fclose(ficresilk);
 2494:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
 2495:     fflush(fichtm); 
 2496:   } 
 2497:   return;
 2498: }
 2499: 
 2500: 
 2501: /*********** Maximum Likelihood Estimation ***************/
 2502: 
 2503: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
 2504: {
 2505:   int i,j, iter=0;
 2506:   double **xi;
 2507:   double fret;
 2508:   double fretone; /* Only one call to likelihood */
 2509:   /*  char filerespow[FILENAMELENGTH];*/
 2510: 
 2511: #ifdef NLOPT
 2512:   int creturn;
 2513:   nlopt_opt opt;
 2514:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
 2515:   double *lb;
 2516:   double minf; /* the minimum objective value, upon return */
 2517:   double * p1; /* Shifted parameters from 0 instead of 1 */
 2518:   myfunc_data dinst, *d = &dinst;
 2519: #endif
 2520: 
 2521: 
 2522:   xi=matrix(1,npar,1,npar);
 2523:   for (i=1;i<=npar;i++)
 2524:     for (j=1;j<=npar;j++)
 2525:       xi[i][j]=(i==j ? 1.0 : 0.0);
 2526:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
 2527:   strcpy(filerespow,"pow"); 
 2528:   strcat(filerespow,fileres);
 2529:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
 2530:     printf("Problem with resultfile: %s\n", filerespow);
 2531:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 2532:   }
 2533:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
 2534:   for (i=1;i<=nlstate;i++)
 2535:     for(j=1;j<=nlstate+ndeath;j++)
 2536:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 2537:   fprintf(ficrespow,"\n");
 2538: #ifdef POWELL
 2539:   powell(p,xi,npar,ftol,&iter,&fret,func);
 2540: #endif
 2541: 
 2542: #ifdef NLOPT
 2543: #ifdef NEWUOA
 2544:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
 2545: #else
 2546:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
 2547: #endif
 2548:   lb=vector(0,npar-1);
 2549:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
 2550:   nlopt_set_lower_bounds(opt, lb);
 2551:   nlopt_set_initial_step1(opt, 0.1);
 2552:   
 2553:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
 2554:   d->function = func;
 2555:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
 2556:   nlopt_set_min_objective(opt, myfunc, d);
 2557:   nlopt_set_xtol_rel(opt, ftol);
 2558:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
 2559:     printf("nlopt failed! %d\n",creturn); 
 2560:   }
 2561:   else {
 2562:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
 2563:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
 2564:     iter=1; /* not equal */
 2565:   }
 2566:   nlopt_destroy(opt);
 2567: #endif
 2568:   free_matrix(xi,1,npar,1,npar);
 2569:   fclose(ficrespow);
 2570:   printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2571:   fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2572:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2573: 
 2574: }
 2575: 
 2576: /**** Computes Hessian and covariance matrix ***/
 2577: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
 2578: {
 2579:   double  **a,**y,*x,pd;
 2580:   double **hess;
 2581:   int i, j;
 2582:   int *indx;
 2583: 
 2584:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
 2585:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
 2586:   void lubksb(double **a, int npar, int *indx, double b[]) ;
 2587:   void ludcmp(double **a, int npar, int *indx, double *d) ;
 2588:   double gompertz(double p[]);
 2589:   hess=matrix(1,npar,1,npar);
 2590: 
 2591:   printf("\nCalculation of the hessian matrix. Wait...\n");
 2592:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
 2593:   for (i=1;i<=npar;i++){
 2594:     printf("%d",i);fflush(stdout);
 2595:     fprintf(ficlog,"%d",i);fflush(ficlog);
 2596:    
 2597:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
 2598:     
 2599:     /*  printf(" %f ",p[i]);
 2600: 	printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
 2601:   }
 2602:   
 2603:   for (i=1;i<=npar;i++) {
 2604:     for (j=1;j<=npar;j++)  {
 2605:       if (j>i) { 
 2606: 	printf(".%d%d",i,j);fflush(stdout);
 2607: 	fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
 2608: 	hess[i][j]=hessij(p,delti,i,j,func,npar);
 2609: 	
 2610: 	hess[j][i]=hess[i][j];    
 2611: 	/*printf(" %lf ",hess[i][j]);*/
 2612:       }
 2613:     }
 2614:   }
 2615:   printf("\n");
 2616:   fprintf(ficlog,"\n");
 2617: 
 2618:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
 2619:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
 2620:   
 2621:   a=matrix(1,npar,1,npar);
 2622:   y=matrix(1,npar,1,npar);
 2623:   x=vector(1,npar);
 2624:   indx=ivector(1,npar);
 2625:   for (i=1;i<=npar;i++)
 2626:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
 2627:   ludcmp(a,npar,indx,&pd);
 2628: 
 2629:   for (j=1;j<=npar;j++) {
 2630:     for (i=1;i<=npar;i++) x[i]=0;
 2631:     x[j]=1;
 2632:     lubksb(a,npar,indx,x);
 2633:     for (i=1;i<=npar;i++){ 
 2634:       matcov[i][j]=x[i];
 2635:     }
 2636:   }
 2637: 
 2638:   printf("\n#Hessian matrix#\n");
 2639:   fprintf(ficlog,"\n#Hessian matrix#\n");
 2640:   for (i=1;i<=npar;i++) { 
 2641:     for (j=1;j<=npar;j++) { 
 2642:       printf("%.3e ",hess[i][j]);
 2643:       fprintf(ficlog,"%.3e ",hess[i][j]);
 2644:     }
 2645:     printf("\n");
 2646:     fprintf(ficlog,"\n");
 2647:   }
 2648: 
 2649:   /* Recompute Inverse */
 2650:   for (i=1;i<=npar;i++)
 2651:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
 2652:   ludcmp(a,npar,indx,&pd);
 2653: 
 2654:   /*  printf("\n#Hessian matrix recomputed#\n");
 2655: 
 2656:   for (j=1;j<=npar;j++) {
 2657:     for (i=1;i<=npar;i++) x[i]=0;
 2658:     x[j]=1;
 2659:     lubksb(a,npar,indx,x);
 2660:     for (i=1;i<=npar;i++){ 
 2661:       y[i][j]=x[i];
 2662:       printf("%.3e ",y[i][j]);
 2663:       fprintf(ficlog,"%.3e ",y[i][j]);
 2664:     }
 2665:     printf("\n");
 2666:     fprintf(ficlog,"\n");
 2667:   }
 2668:   */
 2669: 
 2670:   free_matrix(a,1,npar,1,npar);
 2671:   free_matrix(y,1,npar,1,npar);
 2672:   free_vector(x,1,npar);
 2673:   free_ivector(indx,1,npar);
 2674:   free_matrix(hess,1,npar,1,npar);
 2675: 
 2676: 
 2677: }
 2678: 
 2679: /*************** hessian matrix ****************/
 2680: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
 2681: {
 2682:   int i;
 2683:   int l=1, lmax=20;
 2684:   double k1,k2;
 2685:   double p2[MAXPARM+1]; /* identical to x */
 2686:   double res;
 2687:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 2688:   double fx;
 2689:   int k=0,kmax=10;
 2690:   double l1;
 2691: 
 2692:   fx=func(x);
 2693:   for (i=1;i<=npar;i++) p2[i]=x[i];
 2694:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
 2695:     l1=pow(10,l);
 2696:     delts=delt;
 2697:     for(k=1 ; k <kmax; k=k+1){
 2698:       delt = delta*(l1*k);
 2699:       p2[theta]=x[theta] +delt;
 2700:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
 2701:       p2[theta]=x[theta]-delt;
 2702:       k2=func(p2)-fx;
 2703:       /*res= (k1-2.0*fx+k2)/delt/delt; */
 2704:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
 2705:       
 2706: #ifdef DEBUGHESS
 2707:       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);
 2708:       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);
 2709: #endif
 2710:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
 2711:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 2712: 	k=kmax;
 2713:       }
 2714:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
 2715: 	k=kmax; l=lmax*10;
 2716:       }
 2717:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
 2718: 	delts=delt;
 2719:       }
 2720:     }
 2721:   }
 2722:   delti[theta]=delts;
 2723:   return res; 
 2724:   
 2725: }
 2726: 
 2727: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
 2728: {
 2729:   int i;
 2730:   int l=1, lmax=20;
 2731:   double k1,k2,k3,k4,res,fx;
 2732:   double p2[MAXPARM+1];
 2733:   int k;
 2734: 
 2735:   fx=func(x);
 2736:   for (k=1; k<=2; k++) {
 2737:     for (i=1;i<=npar;i++) p2[i]=x[i];
 2738:     p2[thetai]=x[thetai]+delti[thetai]/k;
 2739:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 2740:     k1=func(p2)-fx;
 2741:   
 2742:     p2[thetai]=x[thetai]+delti[thetai]/k;
 2743:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 2744:     k2=func(p2)-fx;
 2745:   
 2746:     p2[thetai]=x[thetai]-delti[thetai]/k;
 2747:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 2748:     k3=func(p2)-fx;
 2749:   
 2750:     p2[thetai]=x[thetai]-delti[thetai]/k;
 2751:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 2752:     k4=func(p2)-fx;
 2753:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
 2754: #ifdef DEBUG
 2755:     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);
 2756:     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);
 2757: #endif
 2758:   }
 2759:   return res;
 2760: }
 2761: 
 2762: /************** Inverse of matrix **************/
 2763: void ludcmp(double **a, int n, int *indx, double *d) 
 2764: { 
 2765:   int i,imax,j,k; 
 2766:   double big,dum,sum,temp; 
 2767:   double *vv; 
 2768:  
 2769:   vv=vector(1,n); 
 2770:   *d=1.0; 
 2771:   for (i=1;i<=n;i++) { 
 2772:     big=0.0; 
 2773:     for (j=1;j<=n;j++) 
 2774:       if ((temp=fabs(a[i][j])) > big) big=temp; 
 2775:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
 2776:     vv[i]=1.0/big; 
 2777:   } 
 2778:   for (j=1;j<=n;j++) { 
 2779:     for (i=1;i<j;i++) { 
 2780:       sum=a[i][j]; 
 2781:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
 2782:       a[i][j]=sum; 
 2783:     } 
 2784:     big=0.0; 
 2785:     for (i=j;i<=n;i++) { 
 2786:       sum=a[i][j]; 
 2787:       for (k=1;k<j;k++) 
 2788: 	sum -= a[i][k]*a[k][j]; 
 2789:       a[i][j]=sum; 
 2790:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
 2791: 	big=dum; 
 2792: 	imax=i; 
 2793:       } 
 2794:     } 
 2795:     if (j != imax) { 
 2796:       for (k=1;k<=n;k++) { 
 2797: 	dum=a[imax][k]; 
 2798: 	a[imax][k]=a[j][k]; 
 2799: 	a[j][k]=dum; 
 2800:       } 
 2801:       *d = -(*d); 
 2802:       vv[imax]=vv[j]; 
 2803:     } 
 2804:     indx[j]=imax; 
 2805:     if (a[j][j] == 0.0) a[j][j]=TINY; 
 2806:     if (j != n) { 
 2807:       dum=1.0/(a[j][j]); 
 2808:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
 2809:     } 
 2810:   } 
 2811:   free_vector(vv,1,n);  /* Doesn't work */
 2812: ;
 2813: } 
 2814: 
 2815: void lubksb(double **a, int n, int *indx, double b[]) 
 2816: { 
 2817:   int i,ii=0,ip,j; 
 2818:   double sum; 
 2819:  
 2820:   for (i=1;i<=n;i++) { 
 2821:     ip=indx[i]; 
 2822:     sum=b[ip]; 
 2823:     b[ip]=b[i]; 
 2824:     if (ii) 
 2825:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
 2826:     else if (sum) ii=i; 
 2827:     b[i]=sum; 
 2828:   } 
 2829:   for (i=n;i>=1;i--) { 
 2830:     sum=b[i]; 
 2831:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
 2832:     b[i]=sum/a[i][i]; 
 2833:   } 
 2834: } 
 2835: 
 2836: void pstamp(FILE *fichier)
 2837: {
 2838:   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
 2839: }
 2840: 
 2841: /************ Frequencies ********************/
 2842: 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[])
 2843: {  /* Some frequencies */
 2844:   
 2845:   int i, m, jk, j1, bool, z1,j;
 2846:   int first;
 2847:   double ***freq; /* Frequencies */
 2848:   double *pp, **prop;
 2849:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
 2850:   char fileresp[FILENAMELENGTH];
 2851:   
 2852:   pp=vector(1,nlstate);
 2853:   prop=matrix(1,nlstate,iagemin,iagemax+3);
 2854:   strcpy(fileresp,"p");
 2855:   strcat(fileresp,fileres);
 2856:   if((ficresp=fopen(fileresp,"w"))==NULL) {
 2857:     printf("Problem with prevalence resultfile: %s\n", fileresp);
 2858:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
 2859:     exit(0);
 2860:   }
 2861:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
 2862:   j1=0;
 2863:   
 2864:   j=cptcoveff;
 2865:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 2866: 
 2867:   first=1;
 2868: 
 2869:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
 2870:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
 2871:   /*    j1++; */
 2872:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
 2873:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
 2874: 	scanf("%d", i);*/
 2875:       for (i=-5; i<=nlstate+ndeath; i++)  
 2876: 	for (jk=-5; jk<=nlstate+ndeath; jk++)  
 2877: 	  for(m=iagemin; m <= iagemax+3; m++)
 2878: 	    freq[i][jk][m]=0;
 2879:       
 2880:       for (i=1; i<=nlstate; i++)  
 2881: 	for(m=iagemin; m <= iagemax+3; m++)
 2882: 	  prop[i][m]=0;
 2883:       
 2884:       dateintsum=0;
 2885:       k2cpt=0;
 2886:       for (i=1; i<=imx; i++) {
 2887: 	bool=1;
 2888: 	if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
 2889: 	  for (z1=1; z1<=cptcoveff; z1++)       
 2890:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
 2891:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
 2892:               bool=0;
 2893:               /* 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", 
 2894:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
 2895:                 j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
 2896:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
 2897:             } 
 2898: 	}
 2899:  
 2900: 	if (bool==1){
 2901: 	  for(m=firstpass; m<=lastpass; m++){
 2902: 	    k2=anint[m][i]+(mint[m][i]/12.);
 2903: 	    /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
 2904: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 2905: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 2906: 	      if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
 2907: 	      if (m<lastpass) {
 2908: 		freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
 2909: 		freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
 2910: 	      }
 2911: 	      
 2912: 	      if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
 2913: 		dateintsum=dateintsum+k2;
 2914: 		k2cpt++;
 2915: 	      }
 2916: 	      /*}*/
 2917: 	  }
 2918: 	}
 2919:       } /* end i */
 2920:        
 2921:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 2922:       pstamp(ficresp);
 2923:       if  (cptcovn>0) {
 2924: 	fprintf(ficresp, "\n#********** Variable "); 
 2925: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2926: 	fprintf(ficresp, "**********\n#");
 2927: 	fprintf(ficlog, "\n#********** Variable "); 
 2928: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2929: 	fprintf(ficlog, "**********\n#");
 2930:       }
 2931:       for(i=1; i<=nlstate;i++) 
 2932: 	fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
 2933:       fprintf(ficresp, "\n");
 2934:       
 2935:       for(i=iagemin; i <= iagemax+3; i++){
 2936: 	if(i==iagemax+3){
 2937: 	  fprintf(ficlog,"Total");
 2938: 	}else{
 2939: 	  if(first==1){
 2940: 	    first=0;
 2941: 	    printf("See log file for details...\n");
 2942: 	  }
 2943: 	  fprintf(ficlog,"Age %d", i);
 2944: 	}
 2945: 	for(jk=1; jk <=nlstate ; jk++){
 2946: 	  for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
 2947: 	    pp[jk] += freq[jk][m][i]; 
 2948: 	}
 2949: 	for(jk=1; jk <=nlstate ; jk++){
 2950: 	  for(m=-1, pos=0; m <=0 ; m++)
 2951: 	    pos += freq[jk][m][i];
 2952: 	  if(pp[jk]>=1.e-10){
 2953: 	    if(first==1){
 2954: 	      printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 2955: 	    }
 2956: 	    fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 2957: 	  }else{
 2958: 	    if(first==1)
 2959: 	      printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 2960: 	    fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 2961: 	  }
 2962: 	}
 2963: 
 2964: 	for(jk=1; jk <=nlstate ; jk++){
 2965: 	  for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
 2966: 	    pp[jk] += freq[jk][m][i];
 2967: 	}	
 2968: 	for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
 2969: 	  pos += pp[jk];
 2970: 	  posprop += prop[jk][i];
 2971: 	}
 2972: 	for(jk=1; jk <=nlstate ; jk++){
 2973: 	  if(pos>=1.e-5){
 2974: 	    if(first==1)
 2975: 	      printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 2976: 	    fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 2977: 	  }else{
 2978: 	    if(first==1)
 2979: 	      printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 2980: 	    fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 2981: 	  }
 2982: 	  if( i <= iagemax){
 2983: 	    if(pos>=1.e-5){
 2984: 	      fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
 2985: 	      /*probs[i][jk][j1]= pp[jk]/pos;*/
 2986: 	      /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
 2987: 	    }
 2988: 	    else
 2989: 	      fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
 2990: 	  }
 2991: 	}
 2992: 	
 2993: 	for(jk=-1; jk <=nlstate+ndeath; jk++)
 2994: 	  for(m=-1; m <=nlstate+ndeath; m++)
 2995: 	    if(freq[jk][m][i] !=0 ) {
 2996: 	    if(first==1)
 2997: 	      printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
 2998: 	      fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
 2999: 	    }
 3000: 	if(i <= iagemax)
 3001: 	  fprintf(ficresp,"\n");
 3002: 	if(first==1)
 3003: 	  printf("Others in log...\n");
 3004: 	fprintf(ficlog,"\n");
 3005:       }
 3006:       /*}*/
 3007:   }
 3008:   dateintmean=dateintsum/k2cpt; 
 3009:  
 3010:   fclose(ficresp);
 3011:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
 3012:   free_vector(pp,1,nlstate);
 3013:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
 3014:   /* End of Freq */
 3015: }
 3016: 
 3017: /************ Prevalence ********************/
 3018: 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)
 3019: {  
 3020:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 3021:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 3022:      We still use firstpass and lastpass as another selection.
 3023:   */
 3024:  
 3025:   int i, m, jk, j1, bool, z1,j;
 3026: 
 3027:   double **prop;
 3028:   double posprop; 
 3029:   double  y2; /* in fractional years */
 3030:   int iagemin, iagemax;
 3031:   int first; /** to stop verbosity which is redirected to log file */
 3032: 
 3033:   iagemin= (int) agemin;
 3034:   iagemax= (int) agemax;
 3035:   /*pp=vector(1,nlstate);*/
 3036:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
 3037:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
 3038:   j1=0;
 3039:   
 3040:   /*j=cptcoveff;*/
 3041:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 3042:   
 3043:   first=1;
 3044:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
 3045:     /*for(i1=1; i1<=ncodemax[k1];i1++){
 3046:       j1++;*/
 3047:       
 3048:       for (i=1; i<=nlstate; i++)  
 3049: 	for(m=iagemin; m <= iagemax+3; m++)
 3050: 	  prop[i][m]=0.0;
 3051:      
 3052:       for (i=1; i<=imx; i++) { /* Each individual */
 3053: 	bool=1;
 3054: 	if  (cptcovn>0) {
 3055: 	  for (z1=1; z1<=cptcoveff; z1++) 
 3056: 	    if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
 3057: 	      bool=0;
 3058: 	} 
 3059: 	if (bool==1) { 
 3060: 	  for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
 3061: 	    y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
 3062: 	    if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
 3063: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 3064: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 3065: 	      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); 
 3066:  	      if (s[m][i]>0 && s[m][i]<=nlstate) { 
 3067: 		/*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]]);*/
 3068:  		prop[s[m][i]][(int)agev[m][i]] += weight[i];
 3069:  		prop[s[m][i]][iagemax+3] += weight[i]; 
 3070:  	      } 
 3071: 	    }
 3072: 	  } /* end selection of waves */
 3073: 	}
 3074:       }
 3075:       for(i=iagemin; i <= iagemax+3; i++){  
 3076:  	for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
 3077:  	  posprop += prop[jk][i]; 
 3078:  	} 
 3079: 	
 3080:  	for(jk=1; jk <=nlstate ; jk++){	    
 3081:  	  if( i <=  iagemax){ 
 3082:  	    if(posprop>=1.e-5){ 
 3083:  	      probs[i][jk][j1]= prop[jk][i]/posprop;
 3084:  	    } else{
 3085: 	      if(first==1){
 3086: 		first=0;
 3087: 		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]);
 3088: 	      }
 3089: 	    }
 3090:  	  } 
 3091:  	}/* end jk */ 
 3092:       }/* end i */ 
 3093:     /*} *//* end i1 */
 3094:   } /* end j1 */
 3095:   
 3096:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
 3097:   /*free_vector(pp,1,nlstate);*/
 3098:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
 3099: }  /* End of prevalence */
 3100: 
 3101: /************* Waves Concatenation ***************/
 3102: 
 3103: 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)
 3104: {
 3105:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 3106:      Death is a valid wave (if date is known).
 3107:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
 3108:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 3109:      and mw[mi+1][i]. dh depends on stepm.
 3110:      */
 3111: 
 3112:   int i, mi, m;
 3113:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
 3114:      double sum=0., jmean=0.;*/
 3115:   int first;
 3116:   int j, k=0,jk, ju, jl;
 3117:   double sum=0.;
 3118:   first=0;
 3119:   jmin=100000;
 3120:   jmax=-1;
 3121:   jmean=0.;
 3122:   for(i=1; i<=imx; i++){
 3123:     mi=0;
 3124:     m=firstpass;
 3125:     while(s[m][i] <= nlstate){
 3126:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
 3127: 	mw[++mi][i]=m;
 3128:       if(m >=lastpass)
 3129: 	break;
 3130:       else
 3131: 	m++;
 3132:     }/* end while */
 3133:     if (s[m][i] > nlstate){
 3134:       mi++;	/* Death is another wave */
 3135:       /* if(mi==0)  never been interviewed correctly before death */
 3136: 	 /* Only death is a correct wave */
 3137:       mw[mi][i]=m;
 3138:     }
 3139: 
 3140:     wav[i]=mi;
 3141:     if(mi==0){
 3142:       nbwarn++;
 3143:       if(first==0){
 3144: 	printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
 3145: 	first=1;
 3146:       }
 3147:       if(first==1){
 3148: 	fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
 3149:       }
 3150:     } /* end mi==0 */
 3151:   } /* End individuals */
 3152: 
 3153:   for(i=1; i<=imx; i++){
 3154:     for(mi=1; mi<wav[i];mi++){
 3155:       if (stepm <=0)
 3156: 	dh[mi][i]=1;
 3157:       else{
 3158: 	if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
 3159: 	  if (agedc[i] < 2*AGESUP) {
 3160: 	    j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
 3161: 	    if(j==0) j=1;  /* Survives at least one month after exam */
 3162: 	    else if(j<0){
 3163: 	      nberr++;
 3164: 	      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]);
 3165: 	      j=1; /* Temporary Dangerous patch */
 3166: 	      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);
 3167: 	      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]);
 3168: 	      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);
 3169: 	    }
 3170: 	    k=k+1;
 3171: 	    if (j >= jmax){
 3172: 	      jmax=j;
 3173: 	      ijmax=i;
 3174: 	    }
 3175: 	    if (j <= jmin){
 3176: 	      jmin=j;
 3177: 	      ijmin=i;
 3178: 	    }
 3179: 	    sum=sum+j;
 3180: 	    /*if (j<0) printf("j=%d num=%d \n",j,i);*/
 3181: 	    /*	  printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
 3182: 	  }
 3183: 	}
 3184: 	else{
 3185: 	  j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 3186: /* 	  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]); */
 3187: 
 3188: 	  k=k+1;
 3189: 	  if (j >= jmax) {
 3190: 	    jmax=j;
 3191: 	    ijmax=i;
 3192: 	  }
 3193: 	  else if (j <= jmin){
 3194: 	    jmin=j;
 3195: 	    ijmin=i;
 3196: 	  }
 3197: 	  /*	    if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
 3198: 	  /*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]);*/
 3199: 	  if(j<0){
 3200: 	    nberr++;
 3201: 	    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]);
 3202: 	    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]);
 3203: 	  }
 3204: 	  sum=sum+j;
 3205: 	}
 3206: 	jk= j/stepm;
 3207: 	jl= j -jk*stepm;
 3208: 	ju= j -(jk+1)*stepm;
 3209: 	if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
 3210: 	  if(jl==0){
 3211: 	    dh[mi][i]=jk;
 3212: 	    bh[mi][i]=0;
 3213: 	  }else{ /* We want a negative bias in order to only have interpolation ie
 3214: 		  * to avoid the price of an extra matrix product in likelihood */
 3215: 	    dh[mi][i]=jk+1;
 3216: 	    bh[mi][i]=ju;
 3217: 	  }
 3218: 	}else{
 3219: 	  if(jl <= -ju){
 3220: 	    dh[mi][i]=jk;
 3221: 	    bh[mi][i]=jl;	/* bias is positive if real duration
 3222: 				 * is higher than the multiple of stepm and negative otherwise.
 3223: 				 */
 3224: 	  }
 3225: 	  else{
 3226: 	    dh[mi][i]=jk+1;
 3227: 	    bh[mi][i]=ju;
 3228: 	  }
 3229: 	  if(dh[mi][i]==0){
 3230: 	    dh[mi][i]=1; /* At least one step */
 3231: 	    bh[mi][i]=ju; /* At least one step */
 3232: 	    /*  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);*/
 3233: 	  }
 3234: 	} /* end if mle */
 3235:       }
 3236:     } /* end wave */
 3237:   }
 3238:   jmean=sum/k;
 3239:   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);
 3240:   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);
 3241:  }
 3242: 
 3243: /*********** Tricode ****************************/
 3244: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
 3245: {
 3246:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
 3247:   /*	  Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
 3248:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
 3249:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
 3250:    * nbcode[Tvar[j]][1]= 
 3251:   */
 3252: 
 3253:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
 3254:   int modmaxcovj=0; /* Modality max of covariates j */
 3255:   int cptcode=0; /* Modality max of covariates j */
 3256:   int modmincovj=0; /* Modality min of covariates j */
 3257: 
 3258: 
 3259:   cptcoveff=0; 
 3260:  
 3261:   for (k=-1; k < maxncov; k++) Ndum[k]=0;
 3262:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
 3263: 
 3264:   /* Loop on covariates without age and products */
 3265:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
 3266:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
 3267: 			       modality of this covariate Vj*/ 
 3268:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
 3269: 				    * If product of Vn*Vm, still boolean *:
 3270: 				    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
 3271: 				    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
 3272:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
 3273: 				      modality of the nth covariate of individual i. */
 3274:       if (ij > modmaxcovj)
 3275:         modmaxcovj=ij; 
 3276:       else if (ij < modmincovj) 
 3277: 	modmincovj=ij; 
 3278:       if ((ij < -1) && (ij > NCOVMAX)){
 3279: 	printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
 3280: 	exit(1);
 3281:       }else
 3282:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
 3283:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
 3284:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
 3285:       /* getting the maximum value of the modality of the covariate
 3286: 	 (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
 3287: 	 female is 1, then modmaxcovj=1.*/
 3288:     } /* end for loop on individuals */
 3289:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
 3290:     cptcode=modmaxcovj;
 3291:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
 3292:    /*for (i=0; i<=cptcode; i++) {*/
 3293:     for (i=modmincovj;  i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
 3294:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], i, Ndum[i]);
 3295:       if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
 3296: 	ncodemax[j]++;  /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
 3297:       }
 3298:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
 3299: 	 historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
 3300:     } /* Ndum[-1] number of undefined modalities */
 3301: 
 3302:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
 3303:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
 3304:        If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
 3305:        modmincovj=3; modmaxcovj = 7;
 3306:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
 3307:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
 3308:        defining two dummy variables: variables V1_1 and V1_2.
 3309:        nbcode[Tvar[j]][ij]=k;
 3310:        nbcode[Tvar[j]][1]=0;
 3311:        nbcode[Tvar[j]][2]=1;
 3312:        nbcode[Tvar[j]][3]=2;
 3313:     */
 3314:     ij=1; /* ij is similar to i but can jumps over null modalities */
 3315:     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
 3316:       for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
 3317: 	/*recode from 0 */
 3318: 	if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
 3319: 	  nbcode[Tvar[j]][ij]=k;  /* stores the modality k in an array nbcode. 
 3320: 				     k is a modality. If we have model=V1+V1*sex 
 3321: 				     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
 3322: 	  ij++;
 3323: 	}
 3324: 	if (ij > ncodemax[j]) break; 
 3325:       }  /* end of loop on */
 3326:     } /* end of loop on modality */ 
 3327:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
 3328:   
 3329:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
 3330:   
 3331:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
 3332:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
 3333:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
 3334:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
 3335:  } 
 3336: 
 3337:  ij=1;
 3338:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
 3339:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
 3340:    if((Ndum[i]!=0) && (i<=ncovcol)){
 3341:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
 3342:      Tvaraff[ij]=i; /*For printing (unclear) */
 3343:      ij++;
 3344:    }else
 3345:        Tvaraff[ij]=0;
 3346:  }
 3347:  ij--;
 3348:  cptcoveff=ij; /*Number of total covariates*/
 3349: 
 3350: }
 3351: 
 3352: 
 3353: /*********** Health Expectancies ****************/
 3354: 
 3355: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
 3356: 
 3357: {
 3358:   /* Health expectancies, no variances */
 3359:   int i, j, nhstepm, hstepm, h, nstepm;
 3360:   int nhstepma, nstepma; /* Decreasing with age */
 3361:   double age, agelim, hf;
 3362:   double ***p3mat;
 3363:   double eip;
 3364: 
 3365:   pstamp(ficreseij);
 3366:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
 3367:   fprintf(ficreseij,"# Age");
 3368:   for(i=1; i<=nlstate;i++){
 3369:     for(j=1; j<=nlstate;j++){
 3370:       fprintf(ficreseij," e%1d%1d ",i,j);
 3371:     }
 3372:     fprintf(ficreseij," e%1d. ",i);
 3373:   }
 3374:   fprintf(ficreseij,"\n");
 3375: 
 3376:   
 3377:   if(estepm < stepm){
 3378:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3379:   }
 3380:   else  hstepm=estepm;   
 3381:   /* We compute the life expectancy from trapezoids spaced every estepm months
 3382:    * This is mainly to measure the difference between two models: for example
 3383:    * if stepm=24 months pijx are given only every 2 years and by summing them
 3384:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 3385:    * progression in between and thus overestimating or underestimating according
 3386:    * to the curvature of the survival function. If, for the same date, we 
 3387:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 3388:    * to compare the new estimate of Life expectancy with the same linear 
 3389:    * hypothesis. A more precise result, taking into account a more precise
 3390:    * curvature will be obtained if estepm is as small as stepm. */
 3391: 
 3392:   /* For example we decided to compute the life expectancy with the smallest unit */
 3393:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3394:      nhstepm is the number of hstepm from age to agelim 
 3395:      nstepm is the number of stepm from age to agelin. 
 3396:      Look at hpijx to understand the reason of that which relies in memory size
 3397:      and note for a fixed period like estepm months */
 3398:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3399:      survival function given by stepm (the optimization length). Unfortunately it
 3400:      means that if the survival funtion is printed only each two years of age and if
 3401:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3402:      results. So we changed our mind and took the option of the best precision.
 3403:   */
 3404:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3405: 
 3406:   agelim=AGESUP;
 3407:   /* If stepm=6 months */
 3408:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
 3409:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 3410:     
 3411: /* nhstepm age range expressed in number of stepm */
 3412:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3413:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3414:   /* if (stepm >= YEARM) hstepm=1;*/
 3415:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3416:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3417: 
 3418:   for (age=bage; age<=fage; age ++){ 
 3419:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3420:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3421:     /* if (stepm >= YEARM) hstepm=1;*/
 3422:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 3423: 
 3424:     /* If stepm=6 months */
 3425:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 3426:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 3427:     
 3428:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 3429:     
 3430:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3431:     
 3432:     printf("%d|",(int)age);fflush(stdout);
 3433:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 3434:     
 3435:     /* Computing expectancies */
 3436:     for(i=1; i<=nlstate;i++)
 3437:       for(j=1; j<=nlstate;j++)
 3438: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 3439: 	  eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
 3440: 	  
 3441: 	  /* 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]);*/
 3442: 
 3443: 	}
 3444: 
 3445:     fprintf(ficreseij,"%3.0f",age );
 3446:     for(i=1; i<=nlstate;i++){
 3447:       eip=0;
 3448:       for(j=1; j<=nlstate;j++){
 3449: 	eip +=eij[i][j][(int)age];
 3450: 	fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
 3451:       }
 3452:       fprintf(ficreseij,"%9.4f", eip );
 3453:     }
 3454:     fprintf(ficreseij,"\n");
 3455:     
 3456:   }
 3457:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3458:   printf("\n");
 3459:   fprintf(ficlog,"\n");
 3460:   
 3461: }
 3462: 
 3463: 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[] )
 3464: 
 3465: {
 3466:   /* Covariances of health expectancies eij and of total life expectancies according
 3467:    to initial status i, ei. .
 3468:   */
 3469:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
 3470:   int nhstepma, nstepma; /* Decreasing with age */
 3471:   double age, agelim, hf;
 3472:   double ***p3matp, ***p3matm, ***varhe;
 3473:   double **dnewm,**doldm;
 3474:   double *xp, *xm;
 3475:   double **gp, **gm;
 3476:   double ***gradg, ***trgradg;
 3477:   int theta;
 3478: 
 3479:   double eip, vip;
 3480: 
 3481:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
 3482:   xp=vector(1,npar);
 3483:   xm=vector(1,npar);
 3484:   dnewm=matrix(1,nlstate*nlstate,1,npar);
 3485:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
 3486:   
 3487:   pstamp(ficresstdeij);
 3488:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
 3489:   fprintf(ficresstdeij,"# Age");
 3490:   for(i=1; i<=nlstate;i++){
 3491:     for(j=1; j<=nlstate;j++)
 3492:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
 3493:     fprintf(ficresstdeij," e%1d. ",i);
 3494:   }
 3495:   fprintf(ficresstdeij,"\n");
 3496: 
 3497:   pstamp(ficrescveij);
 3498:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
 3499:   fprintf(ficrescveij,"# Age");
 3500:   for(i=1; i<=nlstate;i++)
 3501:     for(j=1; j<=nlstate;j++){
 3502:       cptj= (j-1)*nlstate+i;
 3503:       for(i2=1; i2<=nlstate;i2++)
 3504: 	for(j2=1; j2<=nlstate;j2++){
 3505: 	  cptj2= (j2-1)*nlstate+i2;
 3506: 	  if(cptj2 <= cptj)
 3507: 	    fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
 3508: 	}
 3509:     }
 3510:   fprintf(ficrescveij,"\n");
 3511:   
 3512:   if(estepm < stepm){
 3513:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3514:   }
 3515:   else  hstepm=estepm;   
 3516:   /* We compute the life expectancy from trapezoids spaced every estepm months
 3517:    * This is mainly to measure the difference between two models: for example
 3518:    * if stepm=24 months pijx are given only every 2 years and by summing them
 3519:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 3520:    * progression in between and thus overestimating or underestimating according
 3521:    * to the curvature of the survival function. If, for the same date, we 
 3522:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 3523:    * to compare the new estimate of Life expectancy with the same linear 
 3524:    * hypothesis. A more precise result, taking into account a more precise
 3525:    * curvature will be obtained if estepm is as small as stepm. */
 3526: 
 3527:   /* For example we decided to compute the life expectancy with the smallest unit */
 3528:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3529:      nhstepm is the number of hstepm from age to agelim 
 3530:      nstepm is the number of stepm from age to agelin. 
 3531:      Look at hpijx to understand the reason of that which relies in memory size
 3532:      and note for a fixed period like estepm months */
 3533:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3534:      survival function given by stepm (the optimization length). Unfortunately it
 3535:      means that if the survival funtion is printed only each two years of age and if
 3536:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3537:      results. So we changed our mind and took the option of the best precision.
 3538:   */
 3539:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3540: 
 3541:   /* If stepm=6 months */
 3542:   /* nhstepm age range expressed in number of stepm */
 3543:   agelim=AGESUP;
 3544:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
 3545:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3546:   /* if (stepm >= YEARM) hstepm=1;*/
 3547:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3548:   
 3549:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3550:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3551:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
 3552:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
 3553:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
 3554:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
 3555: 
 3556:   for (age=bage; age<=fage; age ++){ 
 3557:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3558:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3559:     /* if (stepm >= YEARM) hstepm=1;*/
 3560:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 3561: 
 3562:     /* If stepm=6 months */
 3563:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 3564:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 3565:     
 3566:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3567: 
 3568:     /* Computing  Variances of health expectancies */
 3569:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
 3570:        decrease memory allocation */
 3571:     for(theta=1; theta <=npar; theta++){
 3572:       for(i=1; i<=npar; i++){ 
 3573: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3574: 	xm[i] = x[i] - (i==theta ?delti[theta]:0);
 3575:       }
 3576:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
 3577:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
 3578:   
 3579:       for(j=1; j<= nlstate; j++){
 3580: 	for(i=1; i<=nlstate; i++){
 3581: 	  for(h=0; h<=nhstepm-1; h++){
 3582: 	    gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
 3583: 	    gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
 3584: 	  }
 3585: 	}
 3586:       }
 3587:      
 3588:       for(ij=1; ij<= nlstate*nlstate; ij++)
 3589: 	for(h=0; h<=nhstepm-1; h++){
 3590: 	  gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
 3591: 	}
 3592:     }/* End theta */
 3593:     
 3594:     
 3595:     for(h=0; h<=nhstepm-1; h++)
 3596:       for(j=1; j<=nlstate*nlstate;j++)
 3597: 	for(theta=1; theta <=npar; theta++)
 3598: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 3599:     
 3600: 
 3601:      for(ij=1;ij<=nlstate*nlstate;ij++)
 3602:       for(ji=1;ji<=nlstate*nlstate;ji++)
 3603: 	varhe[ij][ji][(int)age] =0.;
 3604: 
 3605:      printf("%d|",(int)age);fflush(stdout);
 3606:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 3607:      for(h=0;h<=nhstepm-1;h++){
 3608:       for(k=0;k<=nhstepm-1;k++){
 3609: 	matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
 3610: 	matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
 3611: 	for(ij=1;ij<=nlstate*nlstate;ij++)
 3612: 	  for(ji=1;ji<=nlstate*nlstate;ji++)
 3613: 	    varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
 3614:       }
 3615:     }
 3616: 
 3617:     /* Computing expectancies */
 3618:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 3619:     for(i=1; i<=nlstate;i++)
 3620:       for(j=1; j<=nlstate;j++)
 3621: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 3622: 	  eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
 3623: 	  
 3624: 	  /* 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]);*/
 3625: 
 3626: 	}
 3627: 
 3628:     fprintf(ficresstdeij,"%3.0f",age );
 3629:     for(i=1; i<=nlstate;i++){
 3630:       eip=0.;
 3631:       vip=0.;
 3632:       for(j=1; j<=nlstate;j++){
 3633: 	eip += eij[i][j][(int)age];
 3634: 	for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
 3635: 	  vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
 3636: 	fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
 3637:       }
 3638:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
 3639:     }
 3640:     fprintf(ficresstdeij,"\n");
 3641: 
 3642:     fprintf(ficrescveij,"%3.0f",age );
 3643:     for(i=1; i<=nlstate;i++)
 3644:       for(j=1; j<=nlstate;j++){
 3645: 	cptj= (j-1)*nlstate+i;
 3646: 	for(i2=1; i2<=nlstate;i2++)
 3647: 	  for(j2=1; j2<=nlstate;j2++){
 3648: 	    cptj2= (j2-1)*nlstate+i2;
 3649: 	    if(cptj2 <= cptj)
 3650: 	      fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
 3651: 	  }
 3652:       }
 3653:     fprintf(ficrescveij,"\n");
 3654:    
 3655:   }
 3656:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
 3657:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
 3658:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
 3659:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
 3660:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3661:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3662:   printf("\n");
 3663:   fprintf(ficlog,"\n");
 3664: 
 3665:   free_vector(xm,1,npar);
 3666:   free_vector(xp,1,npar);
 3667:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
 3668:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
 3669:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
 3670: }
 3671: 
 3672: /************ Variance ******************/
 3673: 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[])
 3674: {
 3675:   /* Variance of health expectancies */
 3676:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
 3677:   /* double **newm;*/
 3678:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
 3679:   
 3680:   int movingaverage();
 3681:   double **dnewm,**doldm;
 3682:   double **dnewmp,**doldmp;
 3683:   int i, j, nhstepm, hstepm, h, nstepm ;
 3684:   int k;
 3685:   double *xp;
 3686:   double **gp, **gm;  /* for var eij */
 3687:   double ***gradg, ***trgradg; /*for var eij */
 3688:   double **gradgp, **trgradgp; /* for var p point j */
 3689:   double *gpp, *gmp; /* for var p point j */
 3690:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
 3691:   double ***p3mat;
 3692:   double age,agelim, hf;
 3693:   double ***mobaverage;
 3694:   int theta;
 3695:   char digit[4];
 3696:   char digitp[25];
 3697: 
 3698:   char fileresprobmorprev[FILENAMELENGTH];
 3699: 
 3700:   if(popbased==1){
 3701:     if(mobilav!=0)
 3702:       strcpy(digitp,"-populbased-mobilav-");
 3703:     else strcpy(digitp,"-populbased-nomobil-");
 3704:   }
 3705:   else 
 3706:     strcpy(digitp,"-stablbased-");
 3707: 
 3708:   if (mobilav!=0) {
 3709:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3710:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 3711:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 3712:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 3713:     }
 3714:   }
 3715: 
 3716:   strcpy(fileresprobmorprev,"prmorprev"); 
 3717:   sprintf(digit,"%-d",ij);
 3718:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
 3719:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
 3720:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
 3721:   strcat(fileresprobmorprev,fileres);
 3722:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
 3723:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
 3724:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
 3725:   }
 3726:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 3727:  
 3728:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 3729:   pstamp(ficresprobmorprev);
 3730:   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);
 3731:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
 3732:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 3733:     fprintf(ficresprobmorprev," p.%-d SE",j);
 3734:     for(i=1; i<=nlstate;i++)
 3735:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 3736:   }  
 3737:   fprintf(ficresprobmorprev,"\n");
 3738:   fprintf(ficgp,"\n# Routine varevsij");
 3739:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
 3740:   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");
 3741:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
 3742: /*   } */
 3743:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3744:   pstamp(ficresvij);
 3745:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
 3746:   if(popbased==1)
 3747:     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);
 3748:   else
 3749:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
 3750:   fprintf(ficresvij,"# Age");
 3751:   for(i=1; i<=nlstate;i++)
 3752:     for(j=1; j<=nlstate;j++)
 3753:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
 3754:   fprintf(ficresvij,"\n");
 3755: 
 3756:   xp=vector(1,npar);
 3757:   dnewm=matrix(1,nlstate,1,npar);
 3758:   doldm=matrix(1,nlstate,1,nlstate);
 3759:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
 3760:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3761: 
 3762:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
 3763:   gpp=vector(nlstate+1,nlstate+ndeath);
 3764:   gmp=vector(nlstate+1,nlstate+ndeath);
 3765:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 3766:   
 3767:   if(estepm < stepm){
 3768:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3769:   }
 3770:   else  hstepm=estepm;   
 3771:   /* For example we decided to compute the life expectancy with the smallest unit */
 3772:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3773:      nhstepm is the number of hstepm from age to agelim 
 3774:      nstepm is the number of stepm from age to agelin. 
 3775:      Look at function hpijx to understand why (it is linked to memory size questions) */
 3776:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3777:      survival function given by stepm (the optimization length). Unfortunately it
 3778:      means that if the survival funtion is printed every two years of age and if
 3779:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3780:      results. So we changed our mind and took the option of the best precision.
 3781:   */
 3782:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3783:   agelim = AGESUP;
 3784:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 3785:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 3786:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3787:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3788:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
 3789:     gp=matrix(0,nhstepm,1,nlstate);
 3790:     gm=matrix(0,nhstepm,1,nlstate);
 3791: 
 3792: 
 3793:     for(theta=1; theta <=npar; theta++){
 3794:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
 3795: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3796:       }
 3797:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 3798:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3799: 
 3800:       if (popbased==1) {
 3801: 	if(mobilav ==0){
 3802: 	  for(i=1; i<=nlstate;i++)
 3803: 	    prlim[i][i]=probs[(int)age][i][ij];
 3804: 	}else{ /* mobilav */ 
 3805: 	  for(i=1; i<=nlstate;i++)
 3806: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 3807: 	}
 3808:       }
 3809:   
 3810:       for(j=1; j<= nlstate; j++){
 3811: 	for(h=0; h<=nhstepm; h++){
 3812: 	  for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 3813: 	    gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 3814: 	}
 3815:       }
 3816:       /* This for computing probability of death (h=1 means
 3817:          computed over hstepm matrices product = hstepm*stepm months) 
 3818:          as a weighted average of prlim.
 3819:       */
 3820:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3821: 	for(i=1,gpp[j]=0.; i<= nlstate; i++)
 3822: 	  gpp[j] += prlim[i][i]*p3mat[i][j][1];
 3823:       }    
 3824:       /* end probability of death */
 3825: 
 3826:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
 3827: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 3828:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 3829:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3830:  
 3831:       if (popbased==1) {
 3832: 	if(mobilav ==0){
 3833: 	  for(i=1; i<=nlstate;i++)
 3834: 	    prlim[i][i]=probs[(int)age][i][ij];
 3835: 	}else{ /* mobilav */ 
 3836: 	  for(i=1; i<=nlstate;i++)
 3837: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 3838: 	}
 3839:       }
 3840: 
 3841:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
 3842: 	for(h=0; h<=nhstepm; h++){
 3843: 	  for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 3844: 	    gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 3845: 	}
 3846:       }
 3847:       /* This for computing probability of death (h=1 means
 3848:          computed over hstepm matrices product = hstepm*stepm months) 
 3849:          as a weighted average of prlim.
 3850:       */
 3851:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3852: 	for(i=1,gmp[j]=0.; i<= nlstate; i++)
 3853:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
 3854:       }    
 3855:       /* end probability of death */
 3856: 
 3857:       for(j=1; j<= nlstate; j++) /* vareij */
 3858: 	for(h=0; h<=nhstepm; h++){
 3859: 	  gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 3860: 	}
 3861: 
 3862:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
 3863: 	gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
 3864:       }
 3865: 
 3866:     } /* End theta */
 3867: 
 3868:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
 3869: 
 3870:     for(h=0; h<=nhstepm; h++) /* veij */
 3871:       for(j=1; j<=nlstate;j++)
 3872: 	for(theta=1; theta <=npar; theta++)
 3873: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 3874: 
 3875:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
 3876:       for(theta=1; theta <=npar; theta++)
 3877: 	trgradgp[j][theta]=gradgp[theta][j];
 3878:   
 3879: 
 3880:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3881:     for(i=1;i<=nlstate;i++)
 3882:       for(j=1;j<=nlstate;j++)
 3883: 	vareij[i][j][(int)age] =0.;
 3884: 
 3885:     for(h=0;h<=nhstepm;h++){
 3886:       for(k=0;k<=nhstepm;k++){
 3887: 	matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 3888: 	matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
 3889: 	for(i=1;i<=nlstate;i++)
 3890: 	  for(j=1;j<=nlstate;j++)
 3891: 	    vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
 3892:       }
 3893:     }
 3894:   
 3895:     /* pptj */
 3896:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
 3897:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
 3898:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
 3899:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
 3900: 	varppt[j][i]=doldmp[j][i];
 3901:     /* end ppptj */
 3902:     /*  x centered again */
 3903:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
 3904:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
 3905:  
 3906:     if (popbased==1) {
 3907:       if(mobilav ==0){
 3908: 	for(i=1; i<=nlstate;i++)
 3909: 	  prlim[i][i]=probs[(int)age][i][ij];
 3910:       }else{ /* mobilav */ 
 3911: 	for(i=1; i<=nlstate;i++)
 3912: 	  prlim[i][i]=mobaverage[(int)age][i][ij];
 3913:       }
 3914:     }
 3915:              
 3916:     /* This for computing probability of death (h=1 means
 3917:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
 3918:        as a weighted average of prlim.
 3919:     */
 3920:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3921:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
 3922: 	gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
 3923:     }    
 3924:     /* end probability of death */
 3925: 
 3926:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
 3927:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 3928:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
 3929:       for(i=1; i<=nlstate;i++){
 3930: 	fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 3931:       }
 3932:     } 
 3933:     fprintf(ficresprobmorprev,"\n");
 3934: 
 3935:     fprintf(ficresvij,"%.0f ",age );
 3936:     for(i=1; i<=nlstate;i++)
 3937:       for(j=1; j<=nlstate;j++){
 3938: 	fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
 3939:       }
 3940:     fprintf(ficresvij,"\n");
 3941:     free_matrix(gp,0,nhstepm,1,nlstate);
 3942:     free_matrix(gm,0,nhstepm,1,nlstate);
 3943:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 3944:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 3945:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3946:   } /* End age */
 3947:   free_vector(gpp,nlstate+1,nlstate+ndeath);
 3948:   free_vector(gmp,nlstate+1,nlstate+ndeath);
 3949:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
 3950:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 3951:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
 3952:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
 3953:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
 3954: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
 3955: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
 3956: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
 3957:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
 3958:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
 3959:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
 3960:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
 3961:   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);
 3962:   /*  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);
 3963: */
 3964: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
 3965:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
 3966: 
 3967:   free_vector(xp,1,npar);
 3968:   free_matrix(doldm,1,nlstate,1,nlstate);
 3969:   free_matrix(dnewm,1,nlstate,1,npar);
 3970:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3971:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
 3972:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3973:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3974:   fclose(ficresprobmorprev);
 3975:   fflush(ficgp);
 3976:   fflush(fichtm); 
 3977: }  /* end varevsij */
 3978: 
 3979: /************ Variance of prevlim ******************/
 3980: 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[])
 3981: {
 3982:   /* Variance of prevalence limit */
 3983:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 3984: 
 3985:   double **dnewm,**doldm;
 3986:   int i, j, nhstepm, hstepm;
 3987:   double *xp;
 3988:   double *gp, *gm;
 3989:   double **gradg, **trgradg;
 3990:   double age,agelim;
 3991:   int theta;
 3992:   
 3993:   pstamp(ficresvpl);
 3994:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
 3995:   fprintf(ficresvpl,"# Age");
 3996:   for(i=1; i<=nlstate;i++)
 3997:       fprintf(ficresvpl," %1d-%1d",i,i);
 3998:   fprintf(ficresvpl,"\n");
 3999: 
 4000:   xp=vector(1,npar);
 4001:   dnewm=matrix(1,nlstate,1,npar);
 4002:   doldm=matrix(1,nlstate,1,nlstate);
 4003:   
 4004:   hstepm=1*YEARM; /* Every year of age */
 4005:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 4006:   agelim = AGESUP;
 4007:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 4008:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 4009:     if (stepm >= YEARM) hstepm=1;
 4010:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 4011:     gradg=matrix(1,npar,1,nlstate);
 4012:     gp=vector(1,nlstate);
 4013:     gm=vector(1,nlstate);
 4014: 
 4015:     for(theta=1; theta <=npar; theta++){
 4016:       for(i=1; i<=npar; i++){ /* Computes gradient */
 4017: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 4018:       }
 4019:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 4020:       for(i=1;i<=nlstate;i++)
 4021: 	gp[i] = prlim[i][i];
 4022:     
 4023:       for(i=1; i<=npar; i++) /* Computes gradient */
 4024: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 4025:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 4026:       for(i=1;i<=nlstate;i++)
 4027: 	gm[i] = prlim[i][i];
 4028: 
 4029:       for(i=1;i<=nlstate;i++)
 4030: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 4031:     } /* End theta */
 4032: 
 4033:     trgradg =matrix(1,nlstate,1,npar);
 4034: 
 4035:     for(j=1; j<=nlstate;j++)
 4036:       for(theta=1; theta <=npar; theta++)
 4037: 	trgradg[j][theta]=gradg[theta][j];
 4038: 
 4039:     for(i=1;i<=nlstate;i++)
 4040:       varpl[i][(int)age] =0.;
 4041:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 4042:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 4043:     for(i=1;i<=nlstate;i++)
 4044:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 4045: 
 4046:     fprintf(ficresvpl,"%.0f ",age );
 4047:     for(i=1; i<=nlstate;i++)
 4048:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
 4049:     fprintf(ficresvpl,"\n");
 4050:     free_vector(gp,1,nlstate);
 4051:     free_vector(gm,1,nlstate);
 4052:     free_matrix(gradg,1,npar,1,nlstate);
 4053:     free_matrix(trgradg,1,nlstate,1,npar);
 4054:   } /* End age */
 4055: 
 4056:   free_vector(xp,1,npar);
 4057:   free_matrix(doldm,1,nlstate,1,npar);
 4058:   free_matrix(dnewm,1,nlstate,1,nlstate);
 4059: 
 4060: }
 4061: 
 4062: /************ Variance of one-step probabilities  ******************/
 4063: 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[])
 4064: {
 4065:   int i, j=0,  k1, l1, tj;
 4066:   int k2, l2, j1,  z1;
 4067:   int k=0, l;
 4068:   int first=1, first1, first2;
 4069:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
 4070:   double **dnewm,**doldm;
 4071:   double *xp;
 4072:   double *gp, *gm;
 4073:   double **gradg, **trgradg;
 4074:   double **mu;
 4075:   double age, cov[NCOVMAX+1];
 4076:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
 4077:   int theta;
 4078:   char fileresprob[FILENAMELENGTH];
 4079:   char fileresprobcov[FILENAMELENGTH];
 4080:   char fileresprobcor[FILENAMELENGTH];
 4081:   double ***varpij;
 4082: 
 4083:   strcpy(fileresprob,"prob"); 
 4084:   strcat(fileresprob,fileres);
 4085:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
 4086:     printf("Problem with resultfile: %s\n", fileresprob);
 4087:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
 4088:   }
 4089:   strcpy(fileresprobcov,"probcov"); 
 4090:   strcat(fileresprobcov,fileres);
 4091:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
 4092:     printf("Problem with resultfile: %s\n", fileresprobcov);
 4093:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 4094:   }
 4095:   strcpy(fileresprobcor,"probcor"); 
 4096:   strcat(fileresprobcor,fileres);
 4097:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 4098:     printf("Problem with resultfile: %s\n", fileresprobcor);
 4099:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 4100:   }
 4101:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 4102:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 4103:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 4104:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 4105:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 4106:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 4107:   pstamp(ficresprob);
 4108:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
 4109:   fprintf(ficresprob,"# Age");
 4110:   pstamp(ficresprobcov);
 4111:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
 4112:   fprintf(ficresprobcov,"# Age");
 4113:   pstamp(ficresprobcor);
 4114:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 4115:   fprintf(ficresprobcor,"# Age");
 4116: 
 4117: 
 4118:   for(i=1; i<=nlstate;i++)
 4119:     for(j=1; j<=(nlstate+ndeath);j++){
 4120:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
 4121:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
 4122:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
 4123:     }  
 4124:  /* fprintf(ficresprob,"\n");
 4125:   fprintf(ficresprobcov,"\n");
 4126:   fprintf(ficresprobcor,"\n");
 4127:  */
 4128:   xp=vector(1,npar);
 4129:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 4130:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 4131:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
 4132:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 4133:   first=1;
 4134:   fprintf(ficgp,"\n# Routine varprob");
 4135:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
 4136:   fprintf(fichtm,"\n");
 4137: 
 4138:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
 4139:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
 4140:   file %s<br>\n",optionfilehtmcov);
 4141:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
 4142: and drawn. It helps understanding how is the covariance between two incidences.\
 4143:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
 4144:   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. \
 4145: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
 4146: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
 4147: standard deviations wide on each axis. <br>\
 4148:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
 4149:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 4150: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
 4151: 
 4152:   cov[1]=1;
 4153:   /* tj=cptcoveff; */
 4154:   tj = (int) pow(2,cptcoveff);
 4155:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
 4156:   j1=0;
 4157:   for(j1=1; j1<=tj;j1++){
 4158:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
 4159:     /*j1++;*/
 4160:       if  (cptcovn>0) {
 4161: 	fprintf(ficresprob, "\n#********** Variable "); 
 4162: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 4163: 	fprintf(ficresprob, "**********\n#\n");
 4164: 	fprintf(ficresprobcov, "\n#********** Variable "); 
 4165: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 4166: 	fprintf(ficresprobcov, "**********\n#\n");
 4167: 	
 4168: 	fprintf(ficgp, "\n#********** Variable "); 
 4169: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 4170: 	fprintf(ficgp, "**********\n#\n");
 4171: 	
 4172: 	
 4173: 	fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
 4174: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 4175: 	fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
 4176: 	
 4177: 	fprintf(ficresprobcor, "\n#********** Variable ");    
 4178: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 4179: 	fprintf(ficresprobcor, "**********\n#");    
 4180:       }
 4181:       
 4182:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
 4183:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 4184:       gp=vector(1,(nlstate)*(nlstate+ndeath));
 4185:       gm=vector(1,(nlstate)*(nlstate+ndeath));
 4186:       for (age=bage; age<=fage; age ++){ 
 4187: 	cov[2]=age;
 4188: 	if(nagesqr==1)
 4189: 	  cov[3]= age*age;
 4190: 	for (k=1; k<=cptcovn;k++) {
 4191: 	  cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
 4192: 							 * 1  1 1 1 1
 4193: 							 * 2  2 1 1 1
 4194: 							 * 3  1 2 1 1
 4195: 							 */
 4196: 	  /* nbcode[1][1]=0 nbcode[1][2]=1;*/
 4197: 	}
 4198: 	/* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 4199: 	for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
 4200: 	for (k=1; k<=cptcovprod;k++)
 4201: 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 4202: 	
 4203:     
 4204: 	for(theta=1; theta <=npar; theta++){
 4205: 	  for(i=1; i<=npar; i++)
 4206: 	    xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
 4207: 	  
 4208: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 4209: 	  
 4210: 	  k=0;
 4211: 	  for(i=1; i<= (nlstate); i++){
 4212: 	    for(j=1; j<=(nlstate+ndeath);j++){
 4213: 	      k=k+1;
 4214: 	      gp[k]=pmmij[i][j];
 4215: 	    }
 4216: 	  }
 4217: 	  
 4218: 	  for(i=1; i<=npar; i++)
 4219: 	    xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
 4220:     
 4221: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 4222: 	  k=0;
 4223: 	  for(i=1; i<=(nlstate); i++){
 4224: 	    for(j=1; j<=(nlstate+ndeath);j++){
 4225: 	      k=k+1;
 4226: 	      gm[k]=pmmij[i][j];
 4227: 	    }
 4228: 	  }
 4229:      
 4230: 	  for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
 4231: 	    gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
 4232: 	}
 4233: 
 4234: 	for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
 4235: 	  for(theta=1; theta <=npar; theta++)
 4236: 	    trgradg[j][theta]=gradg[theta][j];
 4237: 	
 4238: 	matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
 4239: 	matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
 4240: 
 4241: 	pmij(pmmij,cov,ncovmodel,x,nlstate);
 4242: 	
 4243: 	k=0;
 4244: 	for(i=1; i<=(nlstate); i++){
 4245: 	  for(j=1; j<=(nlstate+ndeath);j++){
 4246: 	    k=k+1;
 4247: 	    mu[k][(int) age]=pmmij[i][j];
 4248: 	  }
 4249: 	}
 4250:      	for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 4251: 	  for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 4252: 	    varpij[i][j][(int)age] = doldm[i][j];
 4253: 
 4254: 	/*printf("\n%d ",(int)age);
 4255: 	  for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 4256: 	  printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 4257: 	  fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 4258: 	  }*/
 4259: 
 4260: 	fprintf(ficresprob,"\n%d ",(int)age);
 4261: 	fprintf(ficresprobcov,"\n%d ",(int)age);
 4262: 	fprintf(ficresprobcor,"\n%d ",(int)age);
 4263: 
 4264: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
 4265: 	  fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
 4266: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 4267: 	  fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
 4268: 	  fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
 4269: 	}
 4270: 	i=0;
 4271: 	for (k=1; k<=(nlstate);k++){
 4272:  	  for (l=1; l<=(nlstate+ndeath);l++){ 
 4273:  	    i++;
 4274: 	    fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 4275: 	    fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
 4276: 	    for (j=1; j<=i;j++){
 4277: 	      /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
 4278: 	      fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
 4279: 	      fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
 4280: 	    }
 4281: 	  }
 4282: 	}/* end of loop for state */
 4283:       } /* end of loop for age */
 4284:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
 4285:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 4286:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 4287:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 4288:       
 4289:       /* Confidence intervalle of pij  */
 4290:       /*
 4291: 	fprintf(ficgp,"\nunset parametric;unset label");
 4292: 	fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
 4293: 	fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 4294: 	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);
 4295: 	fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
 4296: 	fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
 4297: 	fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
 4298:       */
 4299: 
 4300:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
 4301:       first1=1;first2=2;
 4302:       for (k2=1; k2<=(nlstate);k2++){
 4303: 	for (l2=1; l2<=(nlstate+ndeath);l2++){ 
 4304: 	  if(l2==k2) continue;
 4305: 	  j=(k2-1)*(nlstate+ndeath)+l2;
 4306: 	  for (k1=1; k1<=(nlstate);k1++){
 4307: 	    for (l1=1; l1<=(nlstate+ndeath);l1++){ 
 4308: 	      if(l1==k1) continue;
 4309: 	      i=(k1-1)*(nlstate+ndeath)+l1;
 4310: 	      if(i<=j) continue;
 4311: 	      for (age=bage; age<=fage; age ++){ 
 4312: 		if ((int)age %5==0){
 4313: 		  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
 4314: 		  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
 4315: 		  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
 4316: 		  mu1=mu[i][(int) age]/stepm*YEARM ;
 4317: 		  mu2=mu[j][(int) age]/stepm*YEARM;
 4318: 		  c12=cv12/sqrt(v1*v2);
 4319: 		  /* Computing eigen value of matrix of covariance */
 4320: 		  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 4321: 		  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 4322: 		  if ((lc2 <0) || (lc1 <0) ){
 4323: 		    if(first2==1){
 4324: 		      first1=0;
 4325: 		    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);
 4326: 		    }
 4327: 		    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);
 4328: 		    /* lc1=fabs(lc1); */ /* If we want to have them positive */
 4329: 		    /* lc2=fabs(lc2); */
 4330: 		  }
 4331: 
 4332: 		  /* Eigen vectors */
 4333: 		  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
 4334: 		  /*v21=sqrt(1.-v11*v11); *//* error */
 4335: 		  v21=(lc1-v1)/cv12*v11;
 4336: 		  v12=-v21;
 4337: 		  v22=v11;
 4338: 		  tnalp=v21/v11;
 4339: 		  if(first1==1){
 4340: 		    first1=0;
 4341: 		    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);
 4342: 		  }
 4343: 		  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);
 4344: 		  /*printf(fignu*/
 4345: 		  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
 4346: 		  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
 4347: 		  if(first==1){
 4348: 		    first=0;
 4349:  		    fprintf(ficgp,"\nset parametric;unset label");
 4350: 		    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);
 4351: 		    fprintf(ficgp,"\nset ter png small size 320, 240");
 4352: 		    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
 4353:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
 4354: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
 4355: 			    subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
 4356: 			    subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4357: 		    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4358: 		    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
 4359: 		    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4360: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 4361: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 4362: 		    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",\
 4363: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 4364: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 4365: 		  }else{
 4366: 		    first=0;
 4367: 		    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
 4368: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 4369: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 4370: 		    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",\
 4371: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 4372: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 4373: 		  }/* if first */
 4374: 		} /* age mod 5 */
 4375: 	      } /* end loop age */
 4376: 	      fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4377: 	      first=1;
 4378: 	    } /*l12 */
 4379: 	  } /* k12 */
 4380: 	} /*l1 */
 4381:       }/* k1 */
 4382:       /* } */ /* loop covariates */
 4383:   }
 4384:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 4385:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
 4386:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 4387:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
 4388:   free_vector(xp,1,npar);
 4389:   fclose(ficresprob);
 4390:   fclose(ficresprobcov);
 4391:   fclose(ficresprobcor);
 4392:   fflush(ficgp);
 4393:   fflush(fichtmcov);
 4394: }
 4395: 
 4396: 
 4397: /******************* Printing html file ***********/
 4398: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
 4399: 		  int lastpass, int stepm, int weightopt, char model[],\
 4400: 		  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 4401: 		  int popforecast, int estepm ,\
 4402: 		  double jprev1, double mprev1,double anprev1, \
 4403: 		  double jprev2, double mprev2,double anprev2){
 4404:   int jj1, k1, i1, cpt;
 4405: 
 4406:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
 4407:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
 4408: </ul>");
 4409:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
 4410:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
 4411: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
 4412:    fprintf(fichtm,"\
 4413:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 4414: 	   stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
 4415:    fprintf(fichtm,"\
 4416:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 4417: 	   subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
 4418:    fprintf(fichtm,"\
 4419:  - (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): \
 4420:    <a href=\"%s\">%s</a> <br>\n",
 4421: 	   estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
 4422:    fprintf(fichtm,"\
 4423:  - Population projections by age and states: \
 4424:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
 4425: 
 4426: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
 4427: 
 4428:  m=pow(2,cptcoveff);
 4429:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 4430: 
 4431:  jj1=0;
 4432:  for(k1=1; k1<=m;k1++){
 4433:    for(i1=1; i1<=ncodemax[k1];i1++){
 4434:      jj1++;
 4435:      if (cptcovn > 0) {
 4436:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 4437:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 4438: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 4439:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 4440:      }
 4441:      /* Pij */
 4442:      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> \
 4443: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
 4444:      /* Quasi-incidences */
 4445:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
 4446:  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> \
 4447: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
 4448:        /* Period (stable) prevalence in each health state */
 4449:        for(cpt=1; cpt<=nlstate;cpt++){
 4450: 	 fprintf(fichtm,"<br>- Convergence to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.png\">%s%d_%d.png</a><br> \
 4451: <img src=\"%s%d_%d.png\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
 4452:        }
 4453:      for(cpt=1; cpt<=nlstate;cpt++) {
 4454:         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> \
 4455: <img src=\"%s%d%d.png\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
 4456:      }
 4457:    } /* end i1 */
 4458:  }/* End k1 */
 4459:  fprintf(fichtm,"</ul>");
 4460: 
 4461: 
 4462:  fprintf(fichtm,"\
 4463: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
 4464:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
 4465: 
 4466:  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4467: 	 subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
 4468:  fprintf(fichtm,"\
 4469:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4470: 	 subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
 4471: 
 4472:  fprintf(fichtm,"\
 4473:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4474: 	 subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
 4475:  fprintf(fichtm,"\
 4476:  - 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): \
 4477:    <a href=\"%s\">%s</a> <br>\n</li>",
 4478: 	   estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
 4479:  fprintf(fichtm,"\
 4480:  - (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): \
 4481:    <a href=\"%s\">%s</a> <br>\n</li>",
 4482: 	   estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
 4483:  fprintf(fichtm,"\
 4484:  - 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",
 4485: 	 estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
 4486:  fprintf(fichtm,"\
 4487:  - 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",
 4488: 	 estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
 4489:  fprintf(fichtm,"\
 4490:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
 4491: 	 subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
 4492: 
 4493: /*  if(popforecast==1) fprintf(fichtm,"\n */
 4494: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
 4495: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
 4496: /* 	<br>",fileres,fileres,fileres,fileres); */
 4497: /*  else  */
 4498: /*    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); */
 4499:  fflush(fichtm);
 4500:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
 4501: 
 4502:  m=pow(2,cptcoveff);
 4503:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 4504: 
 4505:  jj1=0;
 4506:  for(k1=1; k1<=m;k1++){
 4507:    for(i1=1; i1<=ncodemax[k1];i1++){
 4508:      jj1++;
 4509:      if (cptcovn > 0) {
 4510:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 4511:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 4512: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 4513:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 4514:      }
 4515:      for(cpt=1; cpt<=nlstate;cpt++) {
 4516:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
 4517: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
 4518: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
 4519:      }
 4520:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
 4521: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
 4522: true period expectancies (those weighted with period prevalences are also\
 4523:  drawn in addition to the population based expectancies computed using\
 4524:  observed and cahotic prevalences: %s%d.png<br>\
 4525: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
 4526:    } /* end i1 */
 4527:  }/* End k1 */
 4528:  fprintf(fichtm,"</ul>");
 4529:  fflush(fichtm);
 4530: }
 4531: 
 4532: /******************* Gnuplot file **************/
 4533: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 4534: 
 4535:   char dirfileres[132],optfileres[132];
 4536:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
 4537:   int ng=0;
 4538: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
 4539: /*     printf("Problem with file %s",optionfilegnuplot); */
 4540: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
 4541: /*   } */
 4542: 
 4543:   /*#ifdef windows */
 4544:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 4545:     /*#endif */
 4546:   m=pow(2,cptcoveff);
 4547: 
 4548:   strcpy(dirfileres,optionfilefiname);
 4549:   strcpy(optfileres,"vpl");
 4550:  /* 1eme*/
 4551:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
 4552:   for (cpt=1; cpt<= nlstate ; cpt ++) {
 4553:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
 4554:      fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
 4555:      fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
 4556:      fprintf(ficgp,"set xlabel \"Age\" \n\
 4557: set ylabel \"Probability\" \n\
 4558: set ter png small size 320, 240\n\
 4559: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
 4560: 
 4561:      for (i=1; i<= nlstate ; i ++) {
 4562:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 4563:        else        fprintf(ficgp," %%*lf (%%*lf)");
 4564:      }
 4565:      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);
 4566:      for (i=1; i<= nlstate ; i ++) {
 4567:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 4568:        else fprintf(ficgp," %%*lf (%%*lf)");
 4569:      } 
 4570:      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); 
 4571:      for (i=1; i<= nlstate ; i ++) {
 4572:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 4573:        else fprintf(ficgp," %%*lf (%%*lf)");
 4574:      }  
 4575:      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));
 4576:    }
 4577:   }
 4578:   /*2 eme*/
 4579:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
 4580:   for (k1=1; k1<= m ; k1 ++) { 
 4581:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
 4582:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
 4583:     
 4584:     for (i=1; i<= nlstate+1 ; i ++) {
 4585:       k=2*i;
 4586:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4587:       for (j=1; j<= nlstate+1 ; j ++) {
 4588: 	if (j==i) fprintf(ficgp," %%lf (%%lf)");
 4589: 	else fprintf(ficgp," %%*lf (%%*lf)");
 4590:       }   
 4591:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
 4592:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
 4593:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4594:       for (j=1; j<= nlstate+1 ; j ++) {
 4595: 	if (j==i) fprintf(ficgp," %%lf (%%lf)");
 4596: 	else fprintf(ficgp," %%*lf (%%*lf)");
 4597:       }   
 4598:       fprintf(ficgp,"\" t\"\" w l lt 0,");
 4599:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4600:       for (j=1; j<= nlstate+1 ; j ++) {
 4601: 	if (j==i) fprintf(ficgp," %%lf (%%lf)");
 4602: 	else fprintf(ficgp," %%*lf (%%*lf)");
 4603:       }   
 4604:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
 4605:       else fprintf(ficgp,"\" t\"\" w l lt 0,");
 4606:     }
 4607:   }
 4608:   
 4609:   /*3eme*/
 4610:   
 4611:   for (k1=1; k1<= m ; k1 ++) { 
 4612:     for (cpt=1; cpt<= nlstate ; cpt ++) {
 4613:       /*       k=2+nlstate*(2*cpt-2); */
 4614:       k=2+(nlstate+1)*(cpt-1);
 4615:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
 4616:       fprintf(ficgp,"set ter png small size 320, 240\n\
 4617: 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);
 4618:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 4619: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 4620: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 4621: 	fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 4622: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 4623: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 4624: 	
 4625:       */
 4626:       for (i=1; i< nlstate ; i ++) {
 4627: 	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);
 4628: 	/*	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);*/
 4629: 	
 4630:       } 
 4631:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
 4632:     }
 4633:   }
 4634:   
 4635:   /* CV preval stable (period) */
 4636:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
 4637:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 4638:       k=3;
 4639:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
 4640:       fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
 4641:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 4642: set ter png small size 320, 240\n\
 4643: unset log y\n\
 4644: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 4645:       for (i=1; i<= nlstate ; i ++){
 4646: 	if(i==1)
 4647: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
 4648: 	else
 4649: 	  fprintf(ficgp,", '' ");
 4650: 	l=(nlstate+ndeath)*(i-1)+1;
 4651: 	fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 4652: 	for (j=1; j<= (nlstate-1) ; j ++)
 4653: 	  fprintf(ficgp,"+$%d",k+l+j);
 4654: 	fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
 4655:       } /* nlstate */
 4656:       fprintf(ficgp,"\n");
 4657:     } /* end cpt state*/ 
 4658:   } /* end covariate */  
 4659:   
 4660:   /* proba elementaires */
 4661:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
 4662:   for(i=1,jk=1; i <=nlstate; i++){
 4663:     fprintf(ficgp,"# initial state %d\n",i);
 4664:     for(k=1; k <=(nlstate+ndeath); k++){
 4665:       if (k != i) {
 4666: 	fprintf(ficgp,"#   current state %d\n",k);
 4667: 	for(j=1; j <=ncovmodel; j++){
 4668: 	  fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
 4669: 	  jk++; 
 4670: 	}
 4671: 	fprintf(ficgp,"\n");
 4672:       }
 4673:     }
 4674:    }
 4675:   fprintf(ficgp,"##############\n#\n");
 4676: 
 4677:   /*goto avoid;*/
 4678:   fprintf(ficgp,"\n##############\n#Graphics of of probabilities or incidences\n#############\n");
 4679:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
 4680:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
 4681:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
 4682:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
 4683:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 4684:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 4685:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 4686:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 4687:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
 4688:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 4689:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
 4690:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
 4691:   fprintf(ficgp,"#\n");
 4692:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
 4693:      fprintf(ficgp,"# ng=%d\n",ng);
 4694:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
 4695:      for(jk=1; jk <=m; jk++) {
 4696:        fprintf(ficgp,"#    jk=%d\n",jk);
 4697:        fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
 4698:        if (ng==2)
 4699: 	 fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
 4700:        else
 4701: 	 fprintf(ficgp,"\nset title \"Probability\"\n");
 4702:        fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
 4703:        i=1;
 4704:        for(k2=1; k2<=nlstate; k2++) {
 4705: 	 k3=i;
 4706: 	 for(k=1; k<=(nlstate+ndeath); k++) {
 4707: 	   if (k != k2){
 4708: 	     if(ng==2)
 4709: 	       if(nagesqr==0)
 4710: 		 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
 4711: 	       else /* nagesqr =1 */
 4712: 		 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
 4713: 	     else
 4714: 	       if(nagesqr==0)
 4715: 		 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
 4716: 	       else /* nagesqr =1 */
 4717: 		 fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
 4718: 	     ij=1;/* To be checked else nbcode[0][0] wrong */
 4719: 	     for(j=3; j <=ncovmodel-nagesqr; j++) {
 4720: 	       if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /* Bug valgrind */
 4721: 	       	 fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
 4722: 	       	 ij++;
 4723: 	       }
 4724: 	       else
 4725: 		 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 4726: 	     }
 4727: 	     fprintf(ficgp,")/(1");
 4728: 	     
 4729: 	     for(k1=1; k1 <=nlstate; k1++){ 
 4730: 	       if(nagesqr==0)
 4731: 		 fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
 4732: 	       else /* nagesqr =1 */
 4733: 		 fprintf(ficgp,"+exp(p%d+p%d*x+p%d*x*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1,k3+(k1-1)*ncovmodel+1+nagesqr);
 4734:   
 4735: 	       ij=1;
 4736: 	       for(j=3; j <=ncovmodel-nagesqr; j++){
 4737: 		 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
 4738: 		   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
 4739: 		   ij++;
 4740: 		 }
 4741: 		 else
 4742: 		   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 4743: 	       }
 4744: 	       fprintf(ficgp,")");
 4745: 	     }
 4746: 	     fprintf(ficgp,") t \"p%d%d\" ", k2,k);
 4747: 	     if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
 4748: 	     i=i+ncovmodel;
 4749: 	   }
 4750: 	 } /* end k */
 4751:        } /* end k2 */
 4752:      } /* end jk */
 4753:    } /* end ng */
 4754:  /* avoid: */
 4755:    fflush(ficgp); 
 4756: }  /* end gnuplot */
 4757: 
 4758: 
 4759: /*************** Moving average **************/
 4760: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
 4761: 
 4762:   int i, cpt, cptcod;
 4763:   int modcovmax =1;
 4764:   int mobilavrange, mob;
 4765:   double age;
 4766: 
 4767:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
 4768: 			   a covariate has 2 modalities */
 4769:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
 4770: 
 4771:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
 4772:     if(mobilav==1) mobilavrange=5; /* default */
 4773:     else mobilavrange=mobilav;
 4774:     for (age=bage; age<=fage; age++)
 4775:       for (i=1; i<=nlstate;i++)
 4776: 	for (cptcod=1;cptcod<=modcovmax;cptcod++)
 4777: 	  mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 4778:     /* We keep the original values on the extreme ages bage, fage and for 
 4779:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
 4780:        we use a 5 terms etc. until the borders are no more concerned. 
 4781:     */ 
 4782:     for (mob=3;mob <=mobilavrange;mob=mob+2){
 4783:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
 4784: 	for (i=1; i<=nlstate;i++){
 4785: 	  for (cptcod=1;cptcod<=modcovmax;cptcod++){
 4786: 	    mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
 4787: 	      for (cpt=1;cpt<=(mob-1)/2;cpt++){
 4788: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
 4789: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
 4790: 	      }
 4791: 	    mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
 4792: 	  }
 4793: 	}
 4794:       }/* end age */
 4795:     }/* end mob */
 4796:   }else return -1;
 4797:   return 0;
 4798: }/* End movingaverage */
 4799: 
 4800: 
 4801: /************** Forecasting ******************/
 4802: void 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){
 4803:   /* proj1, year, month, day of starting projection 
 4804:      agemin, agemax range of age
 4805:      dateprev1 dateprev2 range of dates during which prevalence is computed
 4806:      anproj2 year of en of projection (same day and month as proj1).
 4807:   */
 4808:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
 4809:   double agec; /* generic age */
 4810:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
 4811:   double *popeffectif,*popcount;
 4812:   double ***p3mat;
 4813:   double ***mobaverage;
 4814:   char fileresf[FILENAMELENGTH];
 4815: 
 4816:   agelim=AGESUP;
 4817:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 4818:  
 4819:   strcpy(fileresf,"f"); 
 4820:   strcat(fileresf,fileres);
 4821:   if((ficresf=fopen(fileresf,"w"))==NULL) {
 4822:     printf("Problem with forecast resultfile: %s\n", fileresf);
 4823:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
 4824:   }
 4825:   printf("Computing forecasting: result on file '%s' \n", fileresf);
 4826:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
 4827: 
 4828:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 4829: 
 4830:   if (mobilav!=0) {
 4831:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4832:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 4833:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 4834:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 4835:     }
 4836:   }
 4837: 
 4838:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 4839:   if (stepm<=12) stepsize=1;
 4840:   if(estepm < stepm){
 4841:     printf ("Problem %d lower than %d\n",estepm, stepm);
 4842:   }
 4843:   else  hstepm=estepm;   
 4844: 
 4845:   hstepm=hstepm/stepm; 
 4846:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
 4847:                                fractional in yp1 */
 4848:   anprojmean=yp;
 4849:   yp2=modf((yp1*12),&yp);
 4850:   mprojmean=yp;
 4851:   yp1=modf((yp2*30.5),&yp);
 4852:   jprojmean=yp;
 4853:   if(jprojmean==0) jprojmean=1;
 4854:   if(mprojmean==0) jprojmean=1;
 4855: 
 4856:   i1=cptcoveff;
 4857:   if (cptcovn < 1){i1=1;}
 4858:   
 4859:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
 4860:   
 4861:   fprintf(ficresf,"#****** Routine prevforecast **\n");
 4862: 
 4863: /* 	      if (h==(int)(YEARM*yearp)){ */
 4864:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
 4865:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 4866:       k=k+1;
 4867:       fprintf(ficresf,"\n#******");
 4868:       for(j=1;j<=cptcoveff;j++) {
 4869: 	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]]);
 4870:       }
 4871:       fprintf(ficresf,"******\n");
 4872:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
 4873:       for(j=1; j<=nlstate+ndeath;j++){ 
 4874: 	for(i=1; i<=nlstate;i++) 	      
 4875:           fprintf(ficresf," p%d%d",i,j);
 4876: 	fprintf(ficresf," p.%d",j);
 4877:       }
 4878:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
 4879: 	fprintf(ficresf,"\n");
 4880: 	fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
 4881: 
 4882:      	for (agec=fage; agec>=(ageminpar-1); agec--){ 
 4883: 	  nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
 4884: 	  nhstepm = nhstepm/hstepm; 
 4885: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4886: 	  oldm=oldms;savm=savms;
 4887: 	  hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4888: 	
 4889: 	  for (h=0; h<=nhstepm; h++){
 4890: 	    if (h*hstepm/YEARM*stepm ==yearp) {
 4891:               fprintf(ficresf,"\n");
 4892:               for(j=1;j<=cptcoveff;j++) 
 4893:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4894: 	      fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
 4895: 	    } 
 4896: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4897: 	      ppij=0.;
 4898: 	      for(i=1; i<=nlstate;i++) {
 4899: 		if (mobilav==1) 
 4900: 		  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
 4901: 		else {
 4902: 		  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
 4903: 		}
 4904: 		if (h*hstepm/YEARM*stepm== yearp) {
 4905: 		  fprintf(ficresf," %.3f", p3mat[i][j][h]);
 4906: 		}
 4907: 	      } /* end i */
 4908: 	      if (h*hstepm/YEARM*stepm==yearp) {
 4909: 		fprintf(ficresf," %.3f", ppij);
 4910: 	      }
 4911: 	    }/* end j */
 4912: 	  } /* end h */
 4913: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4914: 	} /* end agec */
 4915:       } /* end yearp */
 4916:     } /* end cptcod */
 4917:   } /* end  cptcov */
 4918:        
 4919:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4920: 
 4921:   fclose(ficresf);
 4922: }
 4923: 
 4924: /************** Forecasting *****not tested NB*************/
 4925: void 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){
 4926:   
 4927:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
 4928:   int *popage;
 4929:   double calagedatem, agelim, kk1, kk2;
 4930:   double *popeffectif,*popcount;
 4931:   double ***p3mat,***tabpop,***tabpopprev;
 4932:   double ***mobaverage;
 4933:   char filerespop[FILENAMELENGTH];
 4934: 
 4935:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4936:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4937:   agelim=AGESUP;
 4938:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
 4939:   
 4940:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 4941:   
 4942:   
 4943:   strcpy(filerespop,"pop"); 
 4944:   strcat(filerespop,fileres);
 4945:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
 4946:     printf("Problem with forecast resultfile: %s\n", filerespop);
 4947:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
 4948:   }
 4949:   printf("Computing forecasting: result on file '%s' \n", filerespop);
 4950:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
 4951: 
 4952:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 4953: 
 4954:   if (mobilav!=0) {
 4955:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4956:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 4957:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 4958:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 4959:     }
 4960:   }
 4961: 
 4962:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 4963:   if (stepm<=12) stepsize=1;
 4964:   
 4965:   agelim=AGESUP;
 4966:   
 4967:   hstepm=1;
 4968:   hstepm=hstepm/stepm; 
 4969:   
 4970:   if (popforecast==1) {
 4971:     if((ficpop=fopen(popfile,"r"))==NULL) {
 4972:       printf("Problem with population file : %s\n",popfile);exit(0);
 4973:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
 4974:     } 
 4975:     popage=ivector(0,AGESUP);
 4976:     popeffectif=vector(0,AGESUP);
 4977:     popcount=vector(0,AGESUP);
 4978:     
 4979:     i=1;   
 4980:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
 4981:    
 4982:     imx=i;
 4983:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
 4984:   }
 4985: 
 4986:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
 4987:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 4988:       k=k+1;
 4989:       fprintf(ficrespop,"\n#******");
 4990:       for(j=1;j<=cptcoveff;j++) {
 4991: 	fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4992:       }
 4993:       fprintf(ficrespop,"******\n");
 4994:       fprintf(ficrespop,"# Age");
 4995:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
 4996:       if (popforecast==1)  fprintf(ficrespop," [Population]");
 4997:       
 4998:       for (cpt=0; cpt<=0;cpt++) { 
 4999: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 5000: 	
 5001:      	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 5002: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 5003: 	  nhstepm = nhstepm/hstepm; 
 5004: 	  
 5005: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5006: 	  oldm=oldms;savm=savms;
 5007: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 5008: 	
 5009: 	  for (h=0; h<=nhstepm; h++){
 5010: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 5011: 	      fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 5012: 	    } 
 5013: 	    for(j=1; j<=nlstate+ndeath;j++) {
 5014: 	      kk1=0.;kk2=0;
 5015: 	      for(i=1; i<=nlstate;i++) {	      
 5016: 		if (mobilav==1) 
 5017: 		  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
 5018: 		else {
 5019: 		  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
 5020: 		}
 5021: 	      }
 5022: 	      if (h==(int)(calagedatem+12*cpt)){
 5023: 		tabpop[(int)(agedeb)][j][cptcod]=kk1;
 5024: 		  /*fprintf(ficrespop," %.3f", kk1);
 5025: 		    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
 5026: 	      }
 5027: 	    }
 5028: 	    for(i=1; i<=nlstate;i++){
 5029: 	      kk1=0.;
 5030: 		for(j=1; j<=nlstate;j++){
 5031: 		  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
 5032: 		}
 5033: 		  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
 5034: 	    }
 5035: 
 5036: 	    if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
 5037: 	      fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
 5038: 	  }
 5039: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5040: 	}
 5041:       }
 5042:  
 5043:   /******/
 5044: 
 5045:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
 5046: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 5047: 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 5048: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 5049: 	  nhstepm = nhstepm/hstepm; 
 5050: 	  
 5051: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5052: 	  oldm=oldms;savm=savms;
 5053: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 5054: 	  for (h=0; h<=nhstepm; h++){
 5055: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 5056: 	      fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 5057: 	    } 
 5058: 	    for(j=1; j<=nlstate+ndeath;j++) {
 5059: 	      kk1=0.;kk2=0;
 5060: 	      for(i=1; i<=nlstate;i++) {	      
 5061: 		kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];	
 5062: 	      }
 5063: 	      if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);	
 5064: 	    }
 5065: 	  }
 5066: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5067: 	}
 5068:       }
 5069:    } 
 5070:   }
 5071:  
 5072:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 5073: 
 5074:   if (popforecast==1) {
 5075:     free_ivector(popage,0,AGESUP);
 5076:     free_vector(popeffectif,0,AGESUP);
 5077:     free_vector(popcount,0,AGESUP);
 5078:   }
 5079:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 5080:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 5081:   fclose(ficrespop);
 5082: } /* End of popforecast */
 5083: 
 5084: int fileappend(FILE *fichier, char *optionfich)
 5085: {
 5086:   if((fichier=fopen(optionfich,"a"))==NULL) {
 5087:     printf("Problem with file: %s\n", optionfich);
 5088:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
 5089:     return (0);
 5090:   }
 5091:   fflush(fichier);
 5092:   return (1);
 5093: }
 5094: 
 5095: 
 5096: /**************** function prwizard **********************/
 5097: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
 5098: {
 5099: 
 5100:   /* Wizard to print covariance matrix template */
 5101: 
 5102:   char ca[32], cb[32];
 5103:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
 5104:   int numlinepar;
 5105: 
 5106:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 5107:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 5108:   for(i=1; i <=nlstate; i++){
 5109:     jj=0;
 5110:     for(j=1; j <=nlstate+ndeath; j++){
 5111:       if(j==i) continue;
 5112:       jj++;
 5113:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
 5114:       printf("%1d%1d",i,j);
 5115:       fprintf(ficparo,"%1d%1d",i,j);
 5116:       for(k=1; k<=ncovmodel;k++){
 5117: 	/* 	  printf(" %lf",param[i][j][k]); */
 5118: 	/* 	  fprintf(ficparo," %lf",param[i][j][k]); */
 5119: 	printf(" 0.");
 5120: 	fprintf(ficparo," 0.");
 5121:       }
 5122:       printf("\n");
 5123:       fprintf(ficparo,"\n");
 5124:     }
 5125:   }
 5126:   printf("# Scales (for hessian or gradient estimation)\n");
 5127:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
 5128:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
 5129:   for(i=1; i <=nlstate; i++){
 5130:     jj=0;
 5131:     for(j=1; j <=nlstate+ndeath; j++){
 5132:       if(j==i) continue;
 5133:       jj++;
 5134:       fprintf(ficparo,"%1d%1d",i,j);
 5135:       printf("%1d%1d",i,j);
 5136:       fflush(stdout);
 5137:       for(k=1; k<=ncovmodel;k++){
 5138: 	/* 	printf(" %le",delti3[i][j][k]); */
 5139: 	/* 	fprintf(ficparo," %le",delti3[i][j][k]); */
 5140: 	printf(" 0.");
 5141: 	fprintf(ficparo," 0.");
 5142:       }
 5143:       numlinepar++;
 5144:       printf("\n");
 5145:       fprintf(ficparo,"\n");
 5146:     }
 5147:   }
 5148:   printf("# Covariance matrix\n");
 5149: /* # 121 Var(a12)\n\ */
 5150: /* # 122 Cov(b12,a12) Var(b12)\n\ */
 5151: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 5152: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 5153: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 5154: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 5155: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 5156: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 5157:   fflush(stdout);
 5158:   fprintf(ficparo,"# Covariance matrix\n");
 5159:   /* # 121 Var(a12)\n\ */
 5160:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
 5161:   /* #   ...\n\ */
 5162:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
 5163:   
 5164:   for(itimes=1;itimes<=2;itimes++){
 5165:     jj=0;
 5166:     for(i=1; i <=nlstate; i++){
 5167:       for(j=1; j <=nlstate+ndeath; j++){
 5168: 	if(j==i) continue;
 5169: 	for(k=1; k<=ncovmodel;k++){
 5170: 	  jj++;
 5171: 	  ca[0]= k+'a'-1;ca[1]='\0';
 5172: 	  if(itimes==1){
 5173: 	    printf("#%1d%1d%d",i,j,k);
 5174: 	    fprintf(ficparo,"#%1d%1d%d",i,j,k);
 5175: 	  }else{
 5176: 	    printf("%1d%1d%d",i,j,k);
 5177: 	    fprintf(ficparo,"%1d%1d%d",i,j,k);
 5178: 	    /* 	printf(" %.5le",matcov[i][j]); */
 5179: 	  }
 5180: 	  ll=0;
 5181: 	  for(li=1;li <=nlstate; li++){
 5182: 	    for(lj=1;lj <=nlstate+ndeath; lj++){
 5183: 	      if(lj==li) continue;
 5184: 	      for(lk=1;lk<=ncovmodel;lk++){
 5185: 		ll++;
 5186: 		if(ll<=jj){
 5187: 		  cb[0]= lk +'a'-1;cb[1]='\0';
 5188: 		  if(ll<jj){
 5189: 		    if(itimes==1){
 5190: 		      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 5191: 		      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 5192: 		    }else{
 5193: 		      printf(" 0.");
 5194: 		      fprintf(ficparo," 0.");
 5195: 		    }
 5196: 		  }else{
 5197: 		    if(itimes==1){
 5198: 		      printf(" Var(%s%1d%1d)",ca,i,j);
 5199: 		      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
 5200: 		    }else{
 5201: 		      printf(" 0.");
 5202: 		      fprintf(ficparo," 0.");
 5203: 		    }
 5204: 		  }
 5205: 		}
 5206: 	      } /* end lk */
 5207: 	    } /* end lj */
 5208: 	  } /* end li */
 5209: 	  printf("\n");
 5210: 	  fprintf(ficparo,"\n");
 5211: 	  numlinepar++;
 5212: 	} /* end k*/
 5213:       } /*end j */
 5214:     } /* end i */
 5215:   } /* end itimes */
 5216: 
 5217: } /* end of prwizard */
 5218: /******************* Gompertz Likelihood ******************************/
 5219: double gompertz(double x[])
 5220: { 
 5221:   double A,B,L=0.0,sump=0.,num=0.;
 5222:   int i,n=0; /* n is the size of the sample */
 5223: 
 5224:   for (i=0;i<=imx-1 ; i++) {
 5225:     sump=sump+weight[i];
 5226:     /*    sump=sump+1;*/
 5227:     num=num+1;
 5228:   }
 5229:  
 5230:  
 5231:   /* for (i=0; i<=imx; i++) 
 5232:      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]);*/
 5233: 
 5234:   for (i=1;i<=imx ; i++)
 5235:     {
 5236:       if (cens[i] == 1 && wav[i]>1)
 5237: 	A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
 5238:       
 5239:       if (cens[i] == 0 && wav[i]>1)
 5240: 	A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
 5241: 	     +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
 5242:       
 5243:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 5244:       if (wav[i] > 1 ) { /* ??? */
 5245: 	L=L+A*weight[i];
 5246: 	/* 	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]);*/
 5247:       }
 5248:     }
 5249: 
 5250:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 5251:  
 5252:   return -2*L*num/sump;
 5253: }
 5254: 
 5255: #ifdef GSL
 5256: /******************* Gompertz_f Likelihood ******************************/
 5257: double gompertz_f(const gsl_vector *v, void *params)
 5258: { 
 5259:   double A,B,LL=0.0,sump=0.,num=0.;
 5260:   double *x= (double *) v->data;
 5261:   int i,n=0; /* n is the size of the sample */
 5262: 
 5263:   for (i=0;i<=imx-1 ; i++) {
 5264:     sump=sump+weight[i];
 5265:     /*    sump=sump+1;*/
 5266:     num=num+1;
 5267:   }
 5268:  
 5269:  
 5270:   /* for (i=0; i<=imx; i++) 
 5271:      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]);*/
 5272:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
 5273:   for (i=1;i<=imx ; i++)
 5274:     {
 5275:       if (cens[i] == 1 && wav[i]>1)
 5276: 	A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
 5277:       
 5278:       if (cens[i] == 0 && wav[i]>1)
 5279: 	A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
 5280: 	     +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
 5281:       
 5282:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 5283:       if (wav[i] > 1 ) { /* ??? */
 5284: 	LL=LL+A*weight[i];
 5285: 	/* 	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]);*/
 5286:       }
 5287:     }
 5288: 
 5289:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 5290:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
 5291:  
 5292:   return -2*LL*num/sump;
 5293: }
 5294: #endif
 5295: 
 5296: /******************* Printing html file ***********/
 5297: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
 5298: 		  int lastpass, int stepm, int weightopt, char model[],\
 5299: 		  int imx,  double p[],double **matcov,double agemortsup){
 5300:   int i,k;
 5301: 
 5302:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
 5303:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
 5304:   for (i=1;i<=2;i++) 
 5305:     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]));
 5306:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
 5307:   fprintf(fichtm,"</ul>");
 5308: 
 5309: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
 5310: 
 5311:  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>");
 5312: 
 5313:  for (k=agegomp;k<(agemortsup-2);k++) 
 5314:    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]);
 5315: 
 5316:  
 5317:   fflush(fichtm);
 5318: }
 5319: 
 5320: /******************* Gnuplot file **************/
 5321: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 5322: 
 5323:   char dirfileres[132],optfileres[132];
 5324: 
 5325:   int ng;
 5326: 
 5327: 
 5328:   /*#ifdef windows */
 5329:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 5330:     /*#endif */
 5331: 
 5332: 
 5333:   strcpy(dirfileres,optionfilefiname);
 5334:   strcpy(optfileres,"vpl");
 5335:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
 5336:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
 5337:   fprintf(ficgp, "set ter png small size 320, 240\n set log y\n"); 
 5338:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
 5339:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
 5340: 
 5341: } 
 5342: 
 5343: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
 5344: {
 5345: 
 5346:   /*-------- data file ----------*/
 5347:   FILE *fic;
 5348:   char dummy[]="                         ";
 5349:   int i=0, j=0, n=0;
 5350:   int linei, month, year,iout;
 5351:   char line[MAXLINE], linetmp[MAXLINE];
 5352:   char stra[MAXLINE], strb[MAXLINE];
 5353:   char *stratrunc;
 5354:   int lstra;
 5355: 
 5356: 
 5357:   if((fic=fopen(datafile,"r"))==NULL)    {
 5358:     printf("Problem while opening datafile: %s\n", datafile);return 1;
 5359:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
 5360:   }
 5361: 
 5362:   i=1;
 5363:   linei=0;
 5364:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
 5365:     linei=linei+1;
 5366:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
 5367:       if(line[j] == '\t')
 5368: 	line[j] = ' ';
 5369:     }
 5370:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
 5371:       ;
 5372:     };
 5373:     line[j+1]=0;  /* Trims blanks at end of line */
 5374:     if(line[0]=='#'){
 5375:       fprintf(ficlog,"Comment line\n%s\n",line);
 5376:       printf("Comment line\n%s\n",line);
 5377:       continue;
 5378:     }
 5379:     trimbb(linetmp,line); /* Trims multiple blanks in line */
 5380:     strcpy(line, linetmp);
 5381:   
 5382: 
 5383:     for (j=maxwav;j>=1;j--){
 5384:       cutv(stra, strb, line, ' '); 
 5385:       if(strb[0]=='.') { /* Missing status */
 5386: 	lval=-1;
 5387:       }else{
 5388: 	errno=0;
 5389: 	lval=strtol(strb,&endptr,10); 
 5390:       /*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
 5391: 	if( strb[0]=='\0' || (*endptr != '\0')){
 5392: 	  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);
 5393: 	  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);
 5394: 	  return 1;
 5395: 	}
 5396:       }
 5397:       s[j][i]=lval;
 5398:       
 5399:       strcpy(line,stra);
 5400:       cutv(stra, strb,line,' ');
 5401:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 5402:       }
 5403:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 5404: 	month=99;
 5405: 	year=9999;
 5406:       }else{
 5407: 	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);
 5408: 	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);
 5409: 	return 1;
 5410:       }
 5411:       anint[j][i]= (double) year; 
 5412:       mint[j][i]= (double)month; 
 5413:       strcpy(line,stra);
 5414:     } /* ENd Waves */
 5415:     
 5416:     cutv(stra, strb,line,' '); 
 5417:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 5418:     }
 5419:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 5420:       month=99;
 5421:       year=9999;
 5422:     }else{
 5423:       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);
 5424: 	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);
 5425: 	return 1;
 5426:     }
 5427:     andc[i]=(double) year; 
 5428:     moisdc[i]=(double) month; 
 5429:     strcpy(line,stra);
 5430:     
 5431:     cutv(stra, strb,line,' '); 
 5432:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 5433:     }
 5434:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
 5435:       month=99;
 5436:       year=9999;
 5437:     }else{
 5438:       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);
 5439:       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);
 5440: 	return 1;
 5441:     }
 5442:     if (year==9999) {
 5443:       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);
 5444:       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);
 5445: 	return 1;
 5446: 
 5447:     }
 5448:     annais[i]=(double)(year);
 5449:     moisnais[i]=(double)(month); 
 5450:     strcpy(line,stra);
 5451:     
 5452:     cutv(stra, strb,line,' '); 
 5453:     errno=0;
 5454:     dval=strtod(strb,&endptr); 
 5455:     if( strb[0]=='\0' || (*endptr != '\0')){
 5456:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
 5457:       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);
 5458:       fflush(ficlog);
 5459:       return 1;
 5460:     }
 5461:     weight[i]=dval; 
 5462:     strcpy(line,stra);
 5463:     
 5464:     for (j=ncovcol;j>=1;j--){
 5465:       cutv(stra, strb,line,' '); 
 5466:       if(strb[0]=='.') { /* Missing status */
 5467: 	lval=-1;
 5468:       }else{
 5469: 	errno=0;
 5470: 	lval=strtol(strb,&endptr,10); 
 5471: 	if( strb[0]=='\0' || (*endptr != '\0')){
 5472: 	  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);
 5473: 	  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);
 5474: 	  return 1;
 5475: 	}
 5476:       }
 5477:       if(lval <-1 || lval >1){
 5478: 	printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 5479:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 5480:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 5481:  For example, for multinomial values like 1, 2 and 3,\n \
 5482:  build V1=0 V2=0 for the reference value (1),\n \
 5483:         V1=1 V2=0 for (2) \n \
 5484:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 5485:  output of IMaCh is often meaningless.\n \
 5486:  Exiting.\n",lval,linei, i,line,j);
 5487: 	fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 5488:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 5489:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 5490:  For example, for multinomial values like 1, 2 and 3,\n \
 5491:  build V1=0 V2=0 for the reference value (1),\n \
 5492:         V1=1 V2=0 for (2) \n \
 5493:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 5494:  output of IMaCh is often meaningless.\n \
 5495:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
 5496: 	return 1;
 5497:       }
 5498:       covar[j][i]=(double)(lval);
 5499:       strcpy(line,stra);
 5500:     }  
 5501:     lstra=strlen(stra);
 5502:      
 5503:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
 5504:       stratrunc = &(stra[lstra-9]);
 5505:       num[i]=atol(stratrunc);
 5506:     }
 5507:     else
 5508:       num[i]=atol(stra);
 5509:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
 5510:       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;}*/
 5511:     
 5512:     i=i+1;
 5513:   } /* End loop reading  data */
 5514: 
 5515:   *imax=i-1; /* Number of individuals */
 5516:   fclose(fic);
 5517:  
 5518:   return (0);
 5519:   /* endread: */
 5520:     printf("Exiting readdata: ");
 5521:     fclose(fic);
 5522:     return (1);
 5523: 
 5524: 
 5525: 
 5526: }
 5527: void removespace(char *str) {
 5528:   char *p1 = str, *p2 = str;
 5529:   do
 5530:     while (*p2 == ' ')
 5531:       p2++;
 5532:   while (*p1++ == *p2++);
 5533: }
 5534: 
 5535: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
 5536:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
 5537:    * - nagesqr = 1 if age*age in the model, otherwise 0.
 5538:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
 5539:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
 5540:    * - cptcovage number of covariates with age*products =2
 5541:    * - cptcovs number of simple covariates
 5542:    * - 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
 5543:    *     which is a new column after the 9 (ncovcol) variables. 
 5544:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
 5545:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
 5546:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
 5547:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
 5548:  */
 5549: {
 5550:   int i, j, k, ks;
 5551:   int  j1, k1, k2;
 5552:   char modelsav[80];
 5553:   char stra[80], strb[80], strc[80], strd[80],stre[80];
 5554:   char *strpt;
 5555: 
 5556:   /*removespace(model);*/
 5557:   if (strlen(model) >1){ /* If there is at least 1 covariate */
 5558:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
 5559:     if (strstr(model,"AGE") !=0){
 5560:       printf("Error. AGE must be in lower case 'age' model=1+age+%s ",model);
 5561:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s ",model);fflush(ficlog);
 5562:       return 1;
 5563:     }
 5564:     if (strstr(model,"v") !=0){
 5565:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
 5566:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
 5567:       return 1;
 5568:     }
 5569:     strcpy(modelsav,model); 
 5570:     if ((strpt=strstr(model,"age*age")) !=0){
 5571:       printf(" strpt=%s, model=%s\n",strpt, model);
 5572:       if(strpt != model){
 5573:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
 5574:  'model=1+age+age*age+V1' or 'model=1+age+age*age+V1+V1*age', please swap as well as \n \
 5575:  corresponding column of parameters.\n",model);
 5576:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
 5577:  'model=1+age+age*age+V1' or 'model=1+age+age*age+V1+V1*age', please swap as well as \n \
 5578:  corresponding column of parameters.\n",model); fflush(ficlog);
 5579:       return 1;
 5580:     }
 5581: 
 5582:       nagesqr=1;
 5583:       if (strstr(model,"+age*age") !=0)
 5584: 	substrchaine(modelsav, model, "+age*age");
 5585:       else if (strstr(model,"age*age+") !=0)
 5586: 	substrchaine(modelsav, model, "age*age+");
 5587:       else 
 5588: 	substrchaine(modelsav, model, "age*age");
 5589:     }else
 5590:       nagesqr=0;
 5591:     if (strlen(modelsav) >1){
 5592:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
 5593:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
 5594:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
 5595:       cptcovt= j+1; /* Number of total covariates in the model, not including
 5596: 		   * cst, age and age*age 
 5597: 		   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
 5598:                   /* including age products which are counted in cptcovage.
 5599: 		  * but the covariates which are products must be treated 
 5600: 		  * separately: ncovn=4- 2=2 (V1+V3). */
 5601:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
 5602:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
 5603: 
 5604:     
 5605:       /*   Design
 5606:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
 5607:        *  <          ncovcol=8                >
 5608:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
 5609:        *   k=  1    2      3       4     5       6      7        8
 5610:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
 5611:        *  covar[k,i], value of kth covariate if not including age for individual i:
 5612:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
 5613:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
 5614:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
 5615:        *  Tage[++cptcovage]=k
 5616:        *       if products, new covar are created after ncovcol with k1
 5617:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
 5618:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
 5619:        *  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
 5620:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
 5621:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
 5622:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
 5623:        *  <          ncovcol=8                >
 5624:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
 5625:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
 5626:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
 5627:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 5628:        * p Tprod[1]@2={                         6, 5}
 5629:        *p Tvard[1][1]@4= {7, 8, 5, 6}
 5630:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
 5631:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 5632:        *How to reorganize?
 5633:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
 5634:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 5635:        *       {2,   1,     4,      8,    5,      6,     3,       7}
 5636:        * Struct []
 5637:        */
 5638: 
 5639:       /* This loop fills the array Tvar from the string 'model'.*/
 5640:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
 5641:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
 5642:       /* 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
 5643:       /* 	k=3 V4 Tvar[k=3]= 4 (from V4) */
 5644:       /* 	k=2 V1 Tvar[k=2]= 1 (from V1) */
 5645:       /* 	k=1 Tvar[1]=2 (from V2) */
 5646:       /* 	k=5 Tvar[5] */
 5647:       /* for (k=1; k<=cptcovn;k++) { */
 5648:       /* 	cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
 5649:       /* 	} */
 5650:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2]; */
 5651:       /*
 5652:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
 5653:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
 5654:         Tvar[k]=0;
 5655:       cptcovage=0;
 5656:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
 5657: 	cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
 5658: 					 modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
 5659: 	if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
 5660: 	/*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
 5661: 	/*scanf("%d",i);*/
 5662: 	if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
 5663: 	  cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
 5664: 	  if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
 5665: 	    /* covar is not filled and then is empty */
 5666: 	    cptcovprod--;
 5667: 	    cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
 5668: 	    Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
 5669: 	    cptcovage++; /* Sums the number of covariates which include age as a product */
 5670: 	    Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
 5671: 	    /*printf("stre=%s ", stre);*/
 5672: 	  } else if (strcmp(strd,"age")==0) { /* or age*Vn */
 5673: 	    cptcovprod--;
 5674: 	    cutl(stre,strb,strc,'V');
 5675: 	    Tvar[k]=atoi(stre);
 5676: 	    cptcovage++;
 5677: 	    Tage[cptcovage]=k;
 5678: 	  } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
 5679: 	    /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
 5680: 	    cptcovn++;
 5681: 	    cptcovprodnoage++;k1++;
 5682: 	    cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
 5683: 	    Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
 5684: 				   because this model-covariate is a construction we invent a new column
 5685: 				   ncovcol + k1
 5686: 				   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
 5687: 				   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
 5688: 	    cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
 5689: 	    Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
 5690: 	    Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
 5691: 	    Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
 5692: 	    k2=k2+2;
 5693: 	    Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
 5694: 	    Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
 5695: 	    for (i=1; i<=lastobs;i++){
 5696: 	      /* Computes the new covariate which is a product of
 5697: 		 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
 5698: 	      covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
 5699: 	    }
 5700: 	  } /* End age is not in the model */
 5701: 	} /* End if model includes a product */
 5702: 	else { /* no more sum */
 5703: 	  /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
 5704: 	  /*  scanf("%d",i);*/
 5705: 	  cutl(strd,strc,strb,'V');
 5706: 	  ks++; /**< Number of simple covariates */
 5707: 	  cptcovn++;
 5708: 	  Tvar[k]=atoi(strd);
 5709: 	}
 5710: 	strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
 5711: 	/*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
 5712: 	  scanf("%d",i);*/
 5713:       } /* end of loop + on total covariates */
 5714:     } /* end if strlen(modelsave == 0) age*age might exist */
 5715:   } /* end if strlen(model == 0) */
 5716:   
 5717:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
 5718:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
 5719: 
 5720:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
 5721:   printf("cptcovprod=%d ", cptcovprod);
 5722:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
 5723: 
 5724:   scanf("%d ",i);*/
 5725: 
 5726: 
 5727:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
 5728:   /*endread:*/
 5729:     printf("Exiting decodemodel: ");
 5730:     return (1);
 5731: }
 5732: 
 5733: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
 5734: {
 5735:   int i, m;
 5736: 
 5737:   for (i=1; i<=imx; i++) {
 5738:     for(m=2; (m<= maxwav); m++) {
 5739:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
 5740: 	anint[m][i]=9999;
 5741: 	s[m][i]=-1;
 5742:       }
 5743:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
 5744: 	*nberr = *nberr + 1;
 5745: 	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 (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
 5746: 	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 (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
 5747: 	s[m][i]=-1;
 5748:       }
 5749:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
 5750: 	(*nberr)++;
 5751: 	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]); 
 5752: 	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]); 
 5753: 	s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
 5754:       }
 5755:     }
 5756:   }
 5757: 
 5758:   for (i=1; i<=imx; i++)  {
 5759:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
 5760:     for(m=firstpass; (m<= lastpass); m++){
 5761:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
 5762: 	if (s[m][i] >= nlstate+1) {
 5763: 	  if(agedc[i]>0){
 5764: 	    if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
 5765: 	      agev[m][i]=agedc[i];
 5766: 	  /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
 5767: 	    }else {
 5768: 	      if ((int)andc[i]!=9999){
 5769: 		nbwarn++;
 5770: 		printf("Warning negative age at death: %ld line:%d\n",num[i],i);
 5771: 		fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
 5772: 		agev[m][i]=-1;
 5773: 	      }
 5774: 	    }
 5775: 	  } /* agedc > 0 */
 5776: 	}
 5777: 	else if(s[m][i] !=9){ /* Standard case, age in fractional
 5778: 				 years but with the precision of a month */
 5779: 	  agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
 5780: 	  if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
 5781: 	    agev[m][i]=1;
 5782: 	  else if(agev[m][i] < *agemin){ 
 5783: 	    *agemin=agev[m][i];
 5784: 	    printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
 5785: 	  }
 5786: 	  else if(agev[m][i] >*agemax){
 5787: 	    *agemax=agev[m][i];
 5788: 	    /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
 5789: 	  }
 5790: 	  /*agev[m][i]=anint[m][i]-annais[i];*/
 5791: 	  /*	 agev[m][i] = age[i]+2*m;*/
 5792: 	}
 5793: 	else { /* =9 */
 5794: 	  agev[m][i]=1;
 5795: 	  s[m][i]=-1;
 5796: 	}
 5797:       }
 5798:       else /*= 0 Unknown */
 5799: 	agev[m][i]=1;
 5800:     }
 5801:     
 5802:   }
 5803:   for (i=1; i<=imx; i++)  {
 5804:     for(m=firstpass; (m<=lastpass); m++){
 5805:       if (s[m][i] > (nlstate+ndeath)) {
 5806: 	(*nberr)++;
 5807: 	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);	
 5808: 	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);	
 5809: 	return 1;
 5810:       }
 5811:     }
 5812:   }
 5813: 
 5814:   /*for (i=1; i<=imx; i++){
 5815:   for (m=firstpass; (m<lastpass); m++){
 5816:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
 5817: }
 5818: 
 5819: }*/
 5820: 
 5821: 
 5822:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
 5823:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
 5824: 
 5825:   return (0);
 5826:  /* endread:*/
 5827:     printf("Exiting calandcheckages: ");
 5828:     return (1);
 5829: }
 5830: 
 5831: #if defined(_MSC_VER)
 5832: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 5833: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 5834: //#include "stdafx.h"
 5835: //#include <stdio.h>
 5836: //#include <tchar.h>
 5837: //#include <windows.h>
 5838: //#include <iostream>
 5839: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
 5840: 
 5841: LPFN_ISWOW64PROCESS fnIsWow64Process;
 5842: 
 5843: BOOL IsWow64()
 5844: {
 5845: 	BOOL bIsWow64 = FALSE;
 5846: 
 5847: 	//typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
 5848: 	//  (HANDLE, PBOOL);
 5849: 
 5850: 	//LPFN_ISWOW64PROCESS fnIsWow64Process;
 5851: 
 5852: 	HMODULE module = GetModuleHandle(_T("kernel32"));
 5853: 	const char funcName[] = "IsWow64Process";
 5854: 	fnIsWow64Process = (LPFN_ISWOW64PROCESS)
 5855: 		GetProcAddress(module, funcName);
 5856: 
 5857: 	if (NULL != fnIsWow64Process)
 5858: 	{
 5859: 		if (!fnIsWow64Process(GetCurrentProcess(),
 5860: 			&bIsWow64))
 5861: 			//throw std::exception("Unknown error");
 5862: 			printf("Unknown error\n");
 5863: 	}
 5864: 	return bIsWow64 != FALSE;
 5865: }
 5866: #endif
 5867: 
 5868: void syscompilerinfo()
 5869:  {
 5870:    /* #include "syscompilerinfo.h"*/
 5871:    /* command line Intel compiler 32bit windows, XP compatible:*/
 5872:    /* /GS /W3 /Gy
 5873:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
 5874:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
 5875:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
 5876:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
 5877:    */ 
 5878:    /* 64 bits */
 5879:    /*
 5880:      /GS /W3 /Gy
 5881:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
 5882:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
 5883:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
 5884:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
 5885:    /* Optimization are useless and O3 is slower than O2 */
 5886:    /*
 5887:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
 5888:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
 5889:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
 5890:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
 5891:    */
 5892:    /* Link is */ /* /OUT:"visual studio
 5893:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
 5894:       /PDB:"visual studio
 5895:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
 5896:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
 5897:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
 5898:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
 5899:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
 5900:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
 5901:       uiAccess='false'"
 5902:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
 5903:       /NOLOGO /TLBID:1
 5904:    */
 5905: #if defined __INTEL_COMPILER
 5906: #if defined(__GNUC__)
 5907: 	struct utsname sysInfo;  /* For Intel on Linux and OS/X */
 5908: #endif
 5909: #elif defined(__GNUC__) 
 5910: #ifndef  __APPLE__
 5911: #include <gnu/libc-version.h>  /* Only on gnu */
 5912: #endif
 5913:    struct utsname sysInfo;
 5914:    int cross = CROSS;
 5915:    if (cross){
 5916: 	   printf("Cross-");
 5917: 	   fprintf(ficlog, "Cross-");
 5918:    }
 5919: #endif
 5920: 
 5921: #include <stdint.h>
 5922: 
 5923:    printf("Compiled with:");fprintf(ficlog,"Compiled with:");
 5924: #if defined(__clang__)
 5925:    printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM");	/* Clang/LLVM. ---------------------------------------------- */
 5926: #endif
 5927: #if defined(__ICC) || defined(__INTEL_COMPILER)
 5928:    printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
 5929: #endif
 5930: #if defined(__GNUC__) || defined(__GNUG__)
 5931:    printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
 5932: #endif
 5933: #if defined(__HP_cc) || defined(__HP_aCC)
 5934:    printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
 5935: #endif
 5936: #if defined(__IBMC__) || defined(__IBMCPP__)
 5937:    printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
 5938: #endif
 5939: #if defined(_MSC_VER)
 5940:    printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
 5941: #endif
 5942: #if defined(__PGI)
 5943:    printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
 5944: #endif
 5945: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
 5946:    printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
 5947: #endif
 5948:    printf(" for ");fprintf(ficlog," for ");
 5949:    
 5950: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
 5951: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
 5952:     // Windows (x64 and x86)
 5953:    printf("Windows (x64 and x86) ");fprintf(ficlog,"Windows (x64 and x86) ");
 5954: #elif __unix__ // all unices, not all compilers
 5955:     // Unix
 5956:    printf("Unix ");fprintf(ficlog,"Unix ");
 5957: #elif __linux__
 5958:     // linux
 5959:    printf("linux ");fprintf(ficlog,"linux ");
 5960: #elif __APPLE__
 5961:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
 5962:    printf("Mac OS ");fprintf(ficlog,"Mac OS ");
 5963: #endif
 5964: 
 5965: /*  __MINGW32__	  */
 5966: /*  __CYGWIN__	 */
 5967: /* __MINGW64__  */
 5968: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
 5969: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
 5970: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
 5971: /* _WIN64  // Defined for applications for Win64. */
 5972: /* _M_X64 // Defined for compilations that target x64 processors. */
 5973: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
 5974: 
 5975: #if UINTPTR_MAX == 0xffffffff
 5976:    printf(" 32-bit"); fprintf(ficlog," 32-bit");/* 32-bit */
 5977: #elif UINTPTR_MAX == 0xffffffffffffffff
 5978:    printf(" 64-bit"); fprintf(ficlog," 64-bit");/* 64-bit */
 5979: #else
 5980:    printf(" wtf-bit"); fprintf(ficlog," wtf-bit");/* wtf */
 5981: #endif
 5982: 
 5983: #if defined(__GNUC__)
 5984: # if defined(__GNUC_PATCHLEVEL__)
 5985: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 5986:                             + __GNUC_MINOR__ * 100 \
 5987:                             + __GNUC_PATCHLEVEL__)
 5988: # else
 5989: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 5990:                             + __GNUC_MINOR__ * 100)
 5991: # endif
 5992:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
 5993:    fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
 5994: 
 5995:    if (uname(&sysInfo) != -1) {
 5996:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 5997:      fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 5998:    }
 5999:    else
 6000:       perror("uname() error");
 6001:    //#ifndef __INTEL_COMPILER 
 6002: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
 6003:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
 6004:    fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
 6005: #endif
 6006: #endif
 6007: 
 6008:    //   void main()
 6009:    //   {
 6010: #if defined(_MSC_VER)
 6011:    if (IsWow64()){
 6012: 	   printf("The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 6013: 	   fprintf(ficlog, "The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 6014:    }
 6015:    else{
 6016: 	   printf("The process is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 6017: 	   fprintf(ficlog,"The programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 6018:    }
 6019:    //	   printf("\nPress Enter to continue...");
 6020:    //	   getchar();
 6021:    //   }
 6022: 
 6023: #endif
 6024:    
 6025: 
 6026:  }
 6027: 
 6028: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
 6029:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 6030:   int i, j, k, i1 ;
 6031:   double ftolpl = 1.e-10;
 6032:   double age, agebase, agelim;
 6033: 
 6034:     strcpy(filerespl,"pl");
 6035:     strcat(filerespl,fileres);
 6036:     if((ficrespl=fopen(filerespl,"w"))==NULL) {
 6037:       printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
 6038:       fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
 6039:     }
 6040:     printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
 6041:     fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
 6042:     pstamp(ficrespl);
 6043:     fprintf(ficrespl,"# Period (stable) prevalence \n");
 6044:     fprintf(ficrespl,"#Age ");
 6045:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
 6046:     fprintf(ficrespl,"\n");
 6047:   
 6048:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
 6049: 
 6050:     agebase=ageminpar;
 6051:     agelim=agemaxpar;
 6052: 
 6053:     i1=pow(2,cptcoveff);
 6054:     if (cptcovn < 1){i1=1;}
 6055: 
 6056:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6057:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
 6058:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 6059: 	k=k+1;
 6060: 	/* to clean */
 6061: 	//printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
 6062: 	fprintf(ficrespl,"\n#******");
 6063: 	printf("\n#******");
 6064: 	fprintf(ficlog,"\n#******");
 6065: 	for(j=1;j<=cptcoveff;j++) {
 6066: 	  fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6067: 	  printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6068: 	  fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6069: 	}
 6070: 	fprintf(ficrespl,"******\n");
 6071: 	printf("******\n");
 6072: 	fprintf(ficlog,"******\n");
 6073: 
 6074: 	fprintf(ficrespl,"#Age ");
 6075: 	for(j=1;j<=cptcoveff;j++) {
 6076: 	  fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6077: 	}
 6078: 	for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
 6079: 	fprintf(ficrespl,"\n");
 6080: 	
 6081: 	for (age=agebase; age<=agelim; age++){
 6082: 	/* for (age=agebase; age<=agebase; age++){ */
 6083: 	  prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
 6084: 	  fprintf(ficrespl,"%.0f ",age );
 6085: 	  for(j=1;j<=cptcoveff;j++)
 6086: 	    fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6087: 	  for(i=1; i<=nlstate;i++)
 6088: 	    fprintf(ficrespl," %.5f", prlim[i][i]);
 6089: 	  fprintf(ficrespl,"\n");
 6090: 	} /* Age */
 6091: 	/* was end of cptcod */
 6092:     } /* cptcov */
 6093: 	return 0;
 6094: }
 6095: 
 6096: int hPijx(double *p, int bage, int fage){
 6097:     /*------------- h Pij x at various ages ------------*/
 6098: 
 6099:   int stepsize;
 6100:   int agelim;
 6101:   int hstepm;
 6102:   int nhstepm;
 6103:   int h, i, i1, j, k;
 6104: 
 6105:   double agedeb;
 6106:   double ***p3mat;
 6107: 
 6108:     strcpy(filerespij,"pij");  strcat(filerespij,fileres);
 6109:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
 6110:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
 6111:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
 6112:     }
 6113:     printf("Computing pij: result on file '%s' \n", filerespij);
 6114:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
 6115:   
 6116:     stepsize=(int) (stepm+YEARM-1)/YEARM;
 6117:     /*if (stepm<=24) stepsize=2;*/
 6118: 
 6119:     agelim=AGESUP;
 6120:     hstepm=stepsize*YEARM; /* Every year of age */
 6121:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
 6122: 
 6123:     /* hstepm=1;   aff par mois*/
 6124:     pstamp(ficrespij);
 6125:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
 6126:     i1= pow(2,cptcoveff);
 6127:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 6128:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
 6129:    /*  	k=k+1;  */
 6130:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 6131:       fprintf(ficrespij,"\n#****** ");
 6132:       for(j=1;j<=cptcoveff;j++) 
 6133: 	fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6134:       fprintf(ficrespij,"******\n");
 6135:       
 6136:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
 6137: 	nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 6138: 	nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 6139: 	
 6140: 	/*	  nhstepm=nhstepm*YEARM; aff par mois*/
 6141: 	
 6142: 	p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6143: 	oldm=oldms;savm=savms;
 6144: 	hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 6145: 	fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
 6146: 	for(i=1; i<=nlstate;i++)
 6147: 	  for(j=1; j<=nlstate+ndeath;j++)
 6148: 	    fprintf(ficrespij," %1d-%1d",i,j);
 6149: 	fprintf(ficrespij,"\n");
 6150: 	for (h=0; h<=nhstepm; h++){
 6151: 	  /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
 6152: 	  fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
 6153: 	  for(i=1; i<=nlstate;i++)
 6154: 	    for(j=1; j<=nlstate+ndeath;j++)
 6155: 	      fprintf(ficrespij," %.5f", p3mat[i][j][h]);
 6156: 	  fprintf(ficrespij,"\n");
 6157: 	}
 6158: 	free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6159: 	fprintf(ficrespij,"\n");
 6160:       }
 6161:       /*}*/
 6162:     }
 6163: 	return 0;
 6164: }
 6165: 
 6166: 
 6167: /***********************************************/
 6168: /**************** Main Program *****************/
 6169: /***********************************************/
 6170: 
 6171: int main(int argc, char *argv[])
 6172: {
 6173: #ifdef GSL
 6174:   const gsl_multimin_fminimizer_type *T;
 6175:   size_t iteri = 0, it;
 6176:   int rval = GSL_CONTINUE;
 6177:   int status = GSL_SUCCESS;
 6178:   double ssval;
 6179: #endif
 6180:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
 6181:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
 6182: 
 6183:   int jj, ll, li, lj, lk;
 6184:   int numlinepar=0; /* Current linenumber of parameter file */
 6185:   int itimes;
 6186:   int NDIM=2;
 6187:   int vpopbased=0;
 6188: 
 6189:   char ca[32], cb[32];
 6190:   /*  FILE *fichtm; *//* Html File */
 6191:   /* FILE *ficgp;*/ /*Gnuplot File */
 6192:   struct stat info;
 6193:   double agedeb;
 6194:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
 6195: 
 6196:   double fret;
 6197:   double dum; /* Dummy variable */
 6198:   double ***p3mat;
 6199:   double ***mobaverage;
 6200: 
 6201:   char line[MAXLINE];
 6202:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
 6203:   char pathr[MAXLINE], pathimach[MAXLINE]; 
 6204:   char *tok, *val; /* pathtot */
 6205:   int firstobs=1, lastobs=10;
 6206:   int c,  h , cpt;
 6207:   int jl;
 6208:   int i1, j1, jk, stepsize;
 6209:   int *tab; 
 6210:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
 6211:   int mobilav=0,popforecast=0;
 6212:   int hstepm, nhstepm;
 6213:   int agemortsup;
 6214:   float  sumlpop=0.;
 6215:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
 6216:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
 6217: 
 6218:   double bage=0, fage=110, age, agelim, agebase;
 6219:   double ftolpl=FTOL;
 6220:   double **prlim;
 6221:   double ***param; /* Matrix of parameters */
 6222:   double  *p;
 6223:   double **matcov; /* Matrix of covariance */
 6224:   double ***delti3; /* Scale */
 6225:   double *delti; /* Scale */
 6226:   double ***eij, ***vareij;
 6227:   double **varpl; /* Variances of prevalence limits by age */
 6228:   double *epj, vepp;
 6229: 
 6230:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
 6231:   double **ximort;
 6232:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
 6233:   int *dcwave;
 6234: 
 6235:   char z[1]="c";
 6236: 
 6237:   /*char  *strt;*/
 6238:   char strtend[80];
 6239: 
 6240: 
 6241: /*   setlocale (LC_ALL, ""); */
 6242: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
 6243: /*   textdomain (PACKAGE); */
 6244: /*   setlocale (LC_CTYPE, ""); */
 6245: /*   setlocale (LC_MESSAGES, ""); */
 6246: 
 6247:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
 6248:   rstart_time = time(NULL);  
 6249:   /*  (void) gettimeofday(&start_time,&tzp);*/
 6250:   start_time = *localtime(&rstart_time);
 6251:   curr_time=start_time;
 6252:   /*tml = *localtime(&start_time.tm_sec);*/
 6253:   /* strcpy(strstart,asctime(&tml)); */
 6254:   strcpy(strstart,asctime(&start_time));
 6255: 
 6256: /*  printf("Localtime (at start)=%s",strstart); */
 6257: /*  tp.tm_sec = tp.tm_sec +86400; */
 6258: /*  tm = *localtime(&start_time.tm_sec); */
 6259: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
 6260: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
 6261: /*   tmg.tm_hour=tmg.tm_hour + 1; */
 6262: /*   tp.tm_sec = mktime(&tmg); */
 6263: /*   strt=asctime(&tmg); */
 6264: /*   printf("Time(after) =%s",strstart);  */
 6265: /*  (void) time (&time_value);
 6266: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
 6267: *  tm = *localtime(&time_value);
 6268: *  strstart=asctime(&tm);
 6269: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
 6270: */
 6271: 
 6272:   nberr=0; /* Number of errors and warnings */
 6273:   nbwarn=0;
 6274: #ifdef WIN32
 6275:   _getcwd(pathcd, size);
 6276: #else
 6277:   getcwd(pathcd, size);
 6278: #endif
 6279: 
 6280:   printf("\n%s\n%s",version,fullversion);
 6281:   if(argc <=1){
 6282:     printf("\nEnter the parameter file name: ");
 6283:     fgets(pathr,FILENAMELENGTH,stdin);
 6284:     i=strlen(pathr);
 6285:     if(pathr[i-1]=='\n')
 6286:       pathr[i-1]='\0';
 6287:     i=strlen(pathr);
 6288:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
 6289:       pathr[i-1]='\0';
 6290:    for (tok = pathr; tok != NULL; ){
 6291:       printf("Pathr |%s|\n",pathr);
 6292:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
 6293:       printf("val= |%s| pathr=%s\n",val,pathr);
 6294:       strcpy (pathtot, val);
 6295:       if(pathr[0] == '\0') break; /* Dirty */
 6296:     }
 6297:   }
 6298:   else{
 6299:     strcpy(pathtot,argv[1]);
 6300:   }
 6301:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
 6302:   /*cygwin_split_path(pathtot,path,optionfile);
 6303:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
 6304:   /* cutv(path,optionfile,pathtot,'\\');*/
 6305: 
 6306:   /* Split argv[0], imach program to get pathimach */
 6307:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
 6308:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 6309:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 6310:  /*   strcpy(pathimach,argv[0]); */
 6311:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
 6312:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
 6313:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
 6314: #ifdef WIN32
 6315:   _chdir(path); /* Can be a relative path */
 6316:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
 6317: #else
 6318:   chdir(path); /* Can be a relative path */
 6319:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
 6320: #endif
 6321:   printf("Current directory %s!\n",pathcd);
 6322:   strcpy(command,"mkdir ");
 6323:   strcat(command,optionfilefiname);
 6324:   if((outcmd=system(command)) != 0){
 6325:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
 6326:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
 6327:     /* fclose(ficlog); */
 6328: /*     exit(1); */
 6329:   }
 6330: /*   if((imk=mkdir(optionfilefiname))<0){ */
 6331: /*     perror("mkdir"); */
 6332: /*   } */
 6333: 
 6334:   /*-------- arguments in the command line --------*/
 6335: 
 6336:   /* Main Log file */
 6337:   strcat(filelog, optionfilefiname);
 6338:   strcat(filelog,".log");    /* */
 6339:   if((ficlog=fopen(filelog,"w"))==NULL)    {
 6340:     printf("Problem with logfile %s\n",filelog);
 6341:     goto end;
 6342:   }
 6343:   fprintf(ficlog,"Log filename:%s\n",filelog);
 6344:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
 6345:   fprintf(ficlog,"\nEnter the parameter file name: \n");
 6346:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
 6347:  path=%s \n\
 6348:  optionfile=%s\n\
 6349:  optionfilext=%s\n\
 6350:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
 6351: 
 6352:   syscompilerinfo();
 6353: 
 6354:   printf("Local time (at start):%s",strstart);
 6355:   fprintf(ficlog,"Local time (at start): %s",strstart);
 6356:   fflush(ficlog);
 6357: /*   (void) gettimeofday(&curr_time,&tzp); */
 6358: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
 6359: 
 6360:   /* */
 6361:   strcpy(fileres,"r");
 6362:   strcat(fileres, optionfilefiname);
 6363:   strcat(fileres,".txt");    /* Other files have txt extension */
 6364: 
 6365:   /* Main ---------arguments file --------*/
 6366: 
 6367:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
 6368:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 6369:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 6370:     fflush(ficlog);
 6371:     /* goto end; */
 6372:     exit(70); 
 6373:   }
 6374: 
 6375: 
 6376: 
 6377:   strcpy(filereso,"o");
 6378:   strcat(filereso,fileres);
 6379:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
 6380:     printf("Problem with Output resultfile: %s\n", filereso);
 6381:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
 6382:     fflush(ficlog);
 6383:     goto end;
 6384:   }
 6385: 
 6386:   /* Reads comments: lines beginning with '#' */
 6387:   numlinepar=0;
 6388:   while((c=getc(ficpar))=='#' && c!= EOF){
 6389:     ungetc(c,ficpar);
 6390:     fgets(line, MAXLINE, ficpar);
 6391:     numlinepar++;
 6392:     fputs(line,stdout);
 6393:     fputs(line,ficparo);
 6394:     fputs(line,ficlog);
 6395:   }
 6396:   ungetc(c,ficpar);
 6397: 
 6398:   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=1+age+%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model);
 6399:   numlinepar++;
 6400:   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=1+age+%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model);
 6401:   if(model[strlen(model)-1]=='.') /* Suppressing leading dot in the model */
 6402:     model[strlen(model)-1]='\0';
 6403:   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=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
 6404:   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=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
 6405:   fflush(ficlog);
 6406:   /* if(model[0]=='#'|| model[0]== '\0'){ */
 6407:   if(model[0]=='#'){
 6408:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
 6409:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
 6410:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");		\
 6411:     if(mle != -1){
 6412:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
 6413:       exit(1);
 6414:     }
 6415:   }
 6416:   while((c=getc(ficpar))=='#' && c!= EOF){
 6417:     ungetc(c,ficpar);
 6418:     fgets(line, MAXLINE, ficpar);
 6419:     numlinepar++;
 6420:     fputs(line, stdout);
 6421:     //puts(line);
 6422:     fputs(line,ficparo);
 6423:     fputs(line,ficlog);
 6424:   }
 6425:   ungetc(c,ficpar);
 6426: 
 6427:    
 6428:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
 6429:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
 6430:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
 6431:      v1+v2*age+v2*v3 makes cptcovn = 3
 6432:   */
 6433:   if (strlen(model)>1) 
 6434:     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,age*age makes 3*/
 6435:   else
 6436:     ncovmodel=2; /* Constant and age */
 6437:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
 6438:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
 6439:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
 6440:     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);
 6441:     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);
 6442:     fflush(stdout);
 6443:     fclose (ficlog);
 6444:     goto end;
 6445:   }
 6446:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 6447:   delti=delti3[1][1];
 6448:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
 6449:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
 6450:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 6451:     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 6452:     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 6453:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 6454:     fclose (ficparo);
 6455:     fclose (ficlog);
 6456:     goto end;
 6457:     exit(0);
 6458:   }
 6459:   else if(mle==-3) { /* Main Wizard */
 6460:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 6461:     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 6462:     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 6463:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 6464:     matcov=matrix(1,npar,1,npar);
 6465:   }
 6466:   else{
 6467:     /* Read guessed parameters */
 6468:     /* Reads comments: lines beginning with '#' */
 6469:     while((c=getc(ficpar))=='#' && c!= EOF){
 6470:       ungetc(c,ficpar);
 6471:       fgets(line, MAXLINE, ficpar);
 6472:       numlinepar++;
 6473:       fputs(line,stdout);
 6474:       fputs(line,ficparo);
 6475:       fputs(line,ficlog);
 6476:     }
 6477:     ungetc(c,ficpar);
 6478:     
 6479:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 6480:     for(i=1; i <=nlstate; i++){
 6481:       j=0;
 6482:       for(jj=1; jj <=nlstate+ndeath; jj++){
 6483: 	if(jj==i) continue;
 6484: 	j++;
 6485: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 6486: 	if ((i1 != i) && (j1 != j)){
 6487: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
 6488: It might be a problem of design; if ncovcol and the model are correct\n \
 6489: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
 6490: 	  exit(1);
 6491: 	}
 6492: 	fprintf(ficparo,"%1d%1d",i1,j1);
 6493: 	if(mle==1)
 6494: 	  printf("%1d%1d",i,j);
 6495: 	fprintf(ficlog,"%1d%1d",i,j);
 6496: 	for(k=1; k<=ncovmodel;k++){
 6497: 	  fscanf(ficpar," %lf",&param[i][j][k]);
 6498: 	  if(mle==1){
 6499: 	    printf(" %lf",param[i][j][k]);
 6500: 	    fprintf(ficlog," %lf",param[i][j][k]);
 6501: 	  }
 6502: 	  else
 6503: 	    fprintf(ficlog," %lf",param[i][j][k]);
 6504: 	  fprintf(ficparo," %lf",param[i][j][k]);
 6505: 	}
 6506: 	fscanf(ficpar,"\n");
 6507: 	numlinepar++;
 6508: 	if(mle==1)
 6509: 	  printf("\n");
 6510: 	fprintf(ficlog,"\n");
 6511: 	fprintf(ficparo,"\n");
 6512:       }
 6513:     }  
 6514:     fflush(ficlog);
 6515: 
 6516:     /* Reads scales values */
 6517:     p=param[1][1];
 6518:     
 6519:     /* Reads comments: lines beginning with '#' */
 6520:     while((c=getc(ficpar))=='#' && c!= EOF){
 6521:       ungetc(c,ficpar);
 6522:       fgets(line, MAXLINE, ficpar);
 6523:       numlinepar++;
 6524:       fputs(line,stdout);
 6525:       fputs(line,ficparo);
 6526:       fputs(line,ficlog);
 6527:     }
 6528:     ungetc(c,ficpar);
 6529: 
 6530:     for(i=1; i <=nlstate; i++){
 6531:       for(j=1; j <=nlstate+ndeath-1; j++){
 6532: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 6533: 	if ( (i1-i) * (j1-j) != 0){
 6534: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
 6535: 	  exit(1);
 6536: 	}
 6537: 	printf("%1d%1d",i,j);
 6538: 	fprintf(ficparo,"%1d%1d",i1,j1);
 6539: 	fprintf(ficlog,"%1d%1d",i1,j1);
 6540: 	for(k=1; k<=ncovmodel;k++){
 6541: 	  fscanf(ficpar,"%le",&delti3[i][j][k]);
 6542: 	  printf(" %le",delti3[i][j][k]);
 6543: 	  fprintf(ficparo," %le",delti3[i][j][k]);
 6544: 	  fprintf(ficlog," %le",delti3[i][j][k]);
 6545: 	}
 6546: 	fscanf(ficpar,"\n");
 6547: 	numlinepar++;
 6548: 	printf("\n");
 6549: 	fprintf(ficparo,"\n");
 6550: 	fprintf(ficlog,"\n");
 6551:       }
 6552:     }
 6553:     fflush(ficlog);
 6554: 
 6555:     /* Reads covariance matrix */
 6556:     delti=delti3[1][1];
 6557: 
 6558: 
 6559:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
 6560:   
 6561:     /* Reads comments: lines beginning with '#' */
 6562:     while((c=getc(ficpar))=='#' && c!= EOF){
 6563:       ungetc(c,ficpar);
 6564:       fgets(line, MAXLINE, ficpar);
 6565:       numlinepar++;
 6566:       fputs(line,stdout);
 6567:       fputs(line,ficparo);
 6568:       fputs(line,ficlog);
 6569:     }
 6570:     ungetc(c,ficpar);
 6571:   
 6572:     matcov=matrix(1,npar,1,npar);
 6573:     for(i=1; i <=npar; i++)
 6574:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
 6575:       
 6576:     for(i=1; i <=npar; i++){
 6577:       fscanf(ficpar,"%s",str);
 6578:       if(mle==1)
 6579: 	printf("%s",str);
 6580:       fprintf(ficlog,"%s",str);
 6581:       fprintf(ficparo,"%s",str);
 6582:       for(j=1; j <=i; j++){
 6583: 	fscanf(ficpar," %le",&matcov[i][j]);
 6584: 	if(mle==1){
 6585: 	  printf(" %.5le",matcov[i][j]);
 6586: 	}
 6587: 	fprintf(ficlog," %.5le",matcov[i][j]);
 6588: 	fprintf(ficparo," %.5le",matcov[i][j]);
 6589:       }
 6590:       fscanf(ficpar,"\n");
 6591:       numlinepar++;
 6592:       if(mle==1)
 6593: 	printf("\n");
 6594:       fprintf(ficlog,"\n");
 6595:       fprintf(ficparo,"\n");
 6596:     }
 6597:     for(i=1; i <=npar; i++)
 6598:       for(j=i+1;j<=npar;j++)
 6599: 	matcov[i][j]=matcov[j][i];
 6600:     
 6601:     if(mle==1)
 6602:       printf("\n");
 6603:     fprintf(ficlog,"\n");
 6604:     
 6605:     fflush(ficlog);
 6606:     
 6607:     /*-------- Rewriting parameter file ----------*/
 6608:     strcpy(rfileres,"r");    /* "Rparameterfile */
 6609:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
 6610:     strcat(rfileres,".");    /* */
 6611:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
 6612:     if((ficres =fopen(rfileres,"w"))==NULL) {
 6613:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
 6614:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
 6615:     }
 6616:     fprintf(ficres,"#%s\n",version);
 6617:   }    /* End of mle != -3 */
 6618: 
 6619:   /*  Main data
 6620:    */
 6621:   n= lastobs;
 6622:   num=lvector(1,n);
 6623:   moisnais=vector(1,n);
 6624:   annais=vector(1,n);
 6625:   moisdc=vector(1,n);
 6626:   andc=vector(1,n);
 6627:   agedc=vector(1,n);
 6628:   cod=ivector(1,n);
 6629:   weight=vector(1,n);
 6630:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
 6631:   mint=matrix(1,maxwav,1,n);
 6632:   anint=matrix(1,maxwav,1,n);
 6633:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
 6634:   tab=ivector(1,NCOVMAX);
 6635:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
 6636: 
 6637:   /* Reads data from file datafile */
 6638:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
 6639:     goto end;
 6640: 
 6641:   /* Calculation of the number of parameters from char model */
 6642:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
 6643: 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
 6644: 	k=3 V4 Tvar[k=3]= 4 (from V4)
 6645: 	k=2 V1 Tvar[k=2]= 1 (from V1)
 6646: 	k=1 Tvar[1]=2 (from V2)
 6647:     */
 6648:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
 6649:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
 6650:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
 6651:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
 6652:   */
 6653:   /* For model-covariate k tells which data-covariate to use but
 6654:     because this model-covariate is a construction we invent a new column
 6655:     ncovcol + k1
 6656:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
 6657:     Tvar[3=V1*V4]=4+1 etc */
 6658:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
 6659:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
 6660:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
 6661:   */
 6662:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
 6663:   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
 6664: 			    * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
 6665: 			    * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
 6666:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
 6667: 			 4 covariates (3 plus signs)
 6668: 			 Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
 6669: 		      */  
 6670: 
 6671: /* Main decodemodel */
 6672: 
 6673: 
 6674:   if(decodemodel(model, lastobs) == 1)
 6675:     goto end;
 6676: 
 6677:   if((double)(lastobs-imx)/(double)imx > 1.10){
 6678:     nbwarn++;
 6679:     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); 
 6680:     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); 
 6681:   }
 6682:     /*  if(mle==1){*/
 6683:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
 6684:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
 6685:   }
 6686: 
 6687:     /*-calculation of age at interview from date of interview and age at death -*/
 6688:   agev=matrix(1,maxwav,1,imx);
 6689: 
 6690:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
 6691:     goto end;
 6692: 
 6693: 
 6694:   agegomp=(int)agemin;
 6695:   free_vector(moisnais,1,n);
 6696:   free_vector(annais,1,n);
 6697:   /* free_matrix(mint,1,maxwav,1,n);
 6698:      free_matrix(anint,1,maxwav,1,n);*/
 6699:   free_vector(moisdc,1,n);
 6700:   free_vector(andc,1,n);
 6701:   /* */
 6702:   
 6703:   wav=ivector(1,imx);
 6704:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
 6705:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
 6706:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
 6707:    
 6708:   /* Concatenates waves */
 6709:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
 6710:   /* */
 6711:  
 6712:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
 6713: 
 6714:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
 6715:   ncodemax[1]=1;
 6716:   Ndum =ivector(-1,NCOVMAX);  
 6717:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
 6718:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
 6719:   /* Nbcode gives the value of the lth modality of jth covariate, in
 6720:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
 6721:   /* 1 to ncodemax[j] is the maximum value of this jth covariate */
 6722: 
 6723:   codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
 6724:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
 6725:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
 6726:   h=0;
 6727: 
 6728: 
 6729:   /*if (cptcovn > 0) */
 6730:       
 6731:  
 6732:   m=pow(2,cptcoveff);
 6733:  
 6734:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
 6735:     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 */ 
 6736:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
 6737: 	for(cpt=1; cpt <=pow(2,k-1); cpt++){  /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */ 
 6738: 	  h++;
 6739: 	  if (h>m) 
 6740: 	    h=1;
 6741: 	  /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
 6742: 	   * For k=4 covariates, h goes from 1 to 2**k
 6743: 	   * codtabm(h,k)=  1 & (h-1) >> (k-1) ;
 6744: 	   *     h\k   1     2     3     4
 6745: 	   *______________________________  
 6746: 	   *     1 i=1 1 i=1 1 i=1 1 i=1 1
 6747: 	   *     2     2     1     1     1
 6748: 	   *     3 i=2 1     2     1     1
 6749: 	   *     4     2     2     1     1
 6750: 	   *     5 i=3 1 i=2 1     2     1
 6751: 	   *     6     2     1     2     1
 6752: 	   *     7 i=4 1     2     2     1
 6753: 	   *     8     2     2     2     1
 6754: 	   *     9 i=5 1 i=3 1 i=2 1     1
 6755: 	   *    10     2     1     1     1
 6756: 	   *    11 i=6 1     2     1     1
 6757: 	   *    12     2     2     1     1
 6758: 	   *    13 i=7 1 i=4 1     2     1    
 6759: 	   *    14     2     1     2     1
 6760: 	   *    15 i=8 1     2     2     1
 6761: 	   *    16     2     2     2     1
 6762: 	   */
 6763: 	  codtab[h][k]=j;
 6764: 	  /* codtab[12][3]=1; */
 6765: 	  /*codtab[h][Tvar[k]]=j;*/
 6766: 	  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]]);
 6767: 	} 
 6768:       }
 6769:     }
 6770:   } 
 6771:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
 6772:      codtab[1][2]=1;codtab[2][2]=2; */
 6773:   /* for(i=1; i <=m ;i++){ 
 6774:      for(k=1; k <=cptcovn; k++){
 6775:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
 6776:      }
 6777:      printf("\n");
 6778:      }
 6779:      scanf("%d",i);*/
 6780: 
 6781:  free_ivector(Ndum,-1,NCOVMAX);
 6782: 
 6783: 
 6784:     
 6785:   /* Initialisation of ----------- gnuplot -------------*/
 6786:   strcpy(optionfilegnuplot,optionfilefiname);
 6787:   if(mle==-3)
 6788:     strcat(optionfilegnuplot,"-mort");
 6789:   strcat(optionfilegnuplot,".gp");
 6790: 
 6791:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
 6792:     printf("Problem with file %s",optionfilegnuplot);
 6793:   }
 6794:   else{
 6795:     fprintf(ficgp,"\n# %s\n", version); 
 6796:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
 6797:     //fprintf(ficgp,"set missing 'NaNq'\n");
 6798:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
 6799:   }
 6800:   /*  fclose(ficgp);*/
 6801: 
 6802: 
 6803:   /* Initialisation of --------- index.htm --------*/
 6804: 
 6805:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
 6806:   if(mle==-3)
 6807:     strcat(optionfilehtm,"-mort");
 6808:   strcat(optionfilehtm,".htm");
 6809:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
 6810:     printf("Problem with %s \n",optionfilehtm);
 6811:     exit(0);
 6812:   }
 6813: 
 6814:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
 6815:   strcat(optionfilehtmcov,"-cov.htm");
 6816:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
 6817:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
 6818:   }
 6819:   else{
 6820:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 6821: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 6822: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
 6823: 	  optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 6824:   }
 6825: 
 6826:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 6827: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 6828: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
 6829: \n\
 6830: <hr  size=\"2\" color=\"#EC5E5E\">\
 6831:  <ul><li><h4>Parameter files</h4>\n\
 6832:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
 6833:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
 6834:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
 6835:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
 6836:  - Date and time at start: %s</ul>\n",\
 6837: 	  optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
 6838: 	  optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
 6839: 	  fileres,fileres,\
 6840: 	  filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
 6841:   fflush(fichtm);
 6842: 
 6843:   strcpy(pathr,path);
 6844:   strcat(pathr,optionfilefiname);
 6845: #ifdef WIN32
 6846:   _chdir(optionfilefiname); /* Move to directory named optionfile */
 6847: #else
 6848:   chdir(optionfilefiname); /* Move to directory named optionfile */
 6849: #endif
 6850: 	  
 6851:   
 6852:   /* Calculates basic frequencies. Computes observed prevalence at single age
 6853:      and prints on file fileres'p'. */
 6854:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
 6855: 
 6856:   fprintf(fichtm,"\n");
 6857:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
 6858: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
 6859: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
 6860: 	  imx,agemin,agemax,jmin,jmax,jmean);
 6861:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6862:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6863:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6864:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6865:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
 6866:     
 6867:    
 6868:   /* For Powell, parameters are in a vector p[] starting at p[1]
 6869:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
 6870:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
 6871: 
 6872:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
 6873:   /* For mortality only */
 6874:   if (mle==-3){
 6875:     ximort=matrix(1,NDIM,1,NDIM); 
 6876:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
 6877:     cens=ivector(1,n);
 6878:     ageexmed=vector(1,n);
 6879:     agecens=vector(1,n);
 6880:     dcwave=ivector(1,n);
 6881:  
 6882:     for (i=1; i<=imx; i++){
 6883:       dcwave[i]=-1;
 6884:       for (m=firstpass; m<=lastpass; m++)
 6885: 	if (s[m][i]>nlstate) {
 6886: 	  dcwave[i]=m;
 6887: 	  /*	printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
 6888: 	  break;
 6889: 	}
 6890:     }
 6891: 
 6892:     for (i=1; i<=imx; i++) {
 6893:       if (wav[i]>0){
 6894: 	ageexmed[i]=agev[mw[1][i]][i];
 6895: 	j=wav[i];
 6896: 	agecens[i]=1.; 
 6897: 
 6898: 	if (ageexmed[i]> 1 && wav[i] > 0){
 6899: 	  agecens[i]=agev[mw[j][i]][i];
 6900: 	  cens[i]= 1;
 6901: 	}else if (ageexmed[i]< 1) 
 6902: 	  cens[i]= -1;
 6903: 	if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
 6904: 	  cens[i]=0 ;
 6905:       }
 6906:       else cens[i]=-1;
 6907:     }
 6908:     
 6909:     for (i=1;i<=NDIM;i++) {
 6910:       for (j=1;j<=NDIM;j++)
 6911: 	ximort[i][j]=(i == j ? 1.0 : 0.0);
 6912:     }
 6913:     
 6914:     /*p[1]=0.0268; p[NDIM]=0.083;*/
 6915:     /*printf("%lf %lf", p[1], p[2]);*/
 6916:     
 6917:     
 6918: #ifdef GSL
 6919:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
 6920: #else
 6921:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
 6922: #endif
 6923:     strcpy(filerespow,"pow-mort"); 
 6924:     strcat(filerespow,fileres);
 6925:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
 6926:       printf("Problem with resultfile: %s\n", filerespow);
 6927:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 6928:     }
 6929: #ifdef GSL
 6930:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
 6931: #else
 6932:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
 6933: #endif
 6934:     /*  for (i=1;i<=nlstate;i++)
 6935: 	for(j=1;j<=nlstate+ndeath;j++)
 6936: 	if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 6937:     */
 6938:     fprintf(ficrespow,"\n");
 6939: #ifdef GSL
 6940:     /* gsl starts here */ 
 6941:     T = gsl_multimin_fminimizer_nmsimplex;
 6942:     gsl_multimin_fminimizer *sfm = NULL;
 6943:     gsl_vector *ss, *x;
 6944:     gsl_multimin_function minex_func;
 6945: 
 6946:     /* Initial vertex size vector */
 6947:     ss = gsl_vector_alloc (NDIM);
 6948:     
 6949:     if (ss == NULL){
 6950:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
 6951:     }
 6952:     /* Set all step sizes to 1 */
 6953:     gsl_vector_set_all (ss, 0.001);
 6954: 
 6955:     /* Starting point */
 6956:     
 6957:     x = gsl_vector_alloc (NDIM);
 6958:     
 6959:     if (x == NULL){
 6960:       gsl_vector_free(ss);
 6961:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
 6962:     }
 6963:   
 6964:     /* Initialize method and iterate */
 6965:     /*     p[1]=0.0268; p[NDIM]=0.083; */
 6966:     /*     gsl_vector_set(x, 0, 0.0268); */
 6967:     /*     gsl_vector_set(x, 1, 0.083); */
 6968:     gsl_vector_set(x, 0, p[1]);
 6969:     gsl_vector_set(x, 1, p[2]);
 6970: 
 6971:     minex_func.f = &gompertz_f;
 6972:     minex_func.n = NDIM;
 6973:     minex_func.params = (void *)&p; /* ??? */
 6974:     
 6975:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
 6976:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
 6977:     
 6978:     printf("Iterations beginning .....\n\n");
 6979:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
 6980: 
 6981:     iteri=0;
 6982:     while (rval == GSL_CONTINUE){
 6983:       iteri++;
 6984:       status = gsl_multimin_fminimizer_iterate(sfm);
 6985:       
 6986:       if (status) printf("error: %s\n", gsl_strerror (status));
 6987:       fflush(0);
 6988:       
 6989:       if (status) 
 6990:         break;
 6991:       
 6992:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
 6993:       ssval = gsl_multimin_fminimizer_size (sfm);
 6994:       
 6995:       if (rval == GSL_SUCCESS)
 6996:         printf ("converged to a local maximum at\n");
 6997:       
 6998:       printf("%5d ", iteri);
 6999:       for (it = 0; it < NDIM; it++){
 7000: 	printf ("%10.5f ", gsl_vector_get (sfm->x, it));
 7001:       }
 7002:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
 7003:     }
 7004:     
 7005:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
 7006:     
 7007:     gsl_vector_free(x); /* initial values */
 7008:     gsl_vector_free(ss); /* inital step size */
 7009:     for (it=0; it<NDIM; it++){
 7010:       p[it+1]=gsl_vector_get(sfm->x,it);
 7011:       fprintf(ficrespow," %.12lf", p[it]);
 7012:     }
 7013:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
 7014: #endif
 7015: #ifdef POWELL
 7016:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
 7017: #endif  
 7018:     fclose(ficrespow);
 7019:     
 7020:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
 7021: 
 7022:     for(i=1; i <=NDIM; i++)
 7023:       for(j=i+1;j<=NDIM;j++)
 7024: 	matcov[i][j]=matcov[j][i];
 7025:     
 7026:     printf("\nCovariance matrix\n ");
 7027:     for(i=1; i <=NDIM; i++) {
 7028:       for(j=1;j<=NDIM;j++){ 
 7029: 	printf("%f ",matcov[i][j]);
 7030:       }
 7031:       printf("\n ");
 7032:     }
 7033:     
 7034:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
 7035:     for (i=1;i<=NDIM;i++) 
 7036:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
 7037: 
 7038:     lsurv=vector(1,AGESUP);
 7039:     lpop=vector(1,AGESUP);
 7040:     tpop=vector(1,AGESUP);
 7041:     lsurv[agegomp]=100000;
 7042:     
 7043:     for (k=agegomp;k<=AGESUP;k++) {
 7044:       agemortsup=k;
 7045:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
 7046:     }
 7047:     
 7048:     for (k=agegomp;k<agemortsup;k++)
 7049:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
 7050:     
 7051:     for (k=agegomp;k<agemortsup;k++){
 7052:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
 7053:       sumlpop=sumlpop+lpop[k];
 7054:     }
 7055:     
 7056:     tpop[agegomp]=sumlpop;
 7057:     for (k=agegomp;k<(agemortsup-3);k++){
 7058:       /*  tpop[k+1]=2;*/
 7059:       tpop[k+1]=tpop[k]-lpop[k];
 7060:     }
 7061:     
 7062:     
 7063:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
 7064:     for (k=agegomp;k<(agemortsup-2);k++) 
 7065:       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]);
 7066:     
 7067:     
 7068:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 7069:     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 7070:     
 7071:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
 7072: 		     stepm, weightopt,\
 7073: 		     model,imx,p,matcov,agemortsup);
 7074:     
 7075:     free_vector(lsurv,1,AGESUP);
 7076:     free_vector(lpop,1,AGESUP);
 7077:     free_vector(tpop,1,AGESUP);
 7078: #ifdef GSL
 7079:     free_ivector(cens,1,n);
 7080:     free_vector(agecens,1,n);
 7081:     free_ivector(dcwave,1,n);
 7082:     free_matrix(ximort,1,NDIM,1,NDIM);
 7083: #endif
 7084:   } /* Endof if mle==-3 mortality only */
 7085:   /* Standard maximisation */
 7086:   else{ /* For mle >=1 */
 7087:     globpr=0;/* debug */
 7088:     /* Computes likelihood for initial parameters */
 7089:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 7090:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 7091:     for (k=1; k<=npar;k++)
 7092:       printf(" %d %8.5f",k,p[k]);
 7093:     printf("\n");
 7094:     globpr=1; /* again, to print the contributions */
 7095:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 7096:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 7097:     for (k=1; k<=npar;k++)
 7098:       printf(" %d %8.5f",k,p[k]);
 7099:     printf("\n");
 7100:     if(mle>=1){ /* Could be 1 or 2, Real Maximisation */
 7101:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
 7102:     }
 7103:     
 7104:     /*--------- results files --------------*/
 7105:     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=1+age+%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate, ndeath, maxwav, weightopt,model);
 7106:     
 7107:     
 7108:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 7109:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 7110:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 7111:     for(i=1,jk=1; i <=nlstate; i++){
 7112:       for(k=1; k <=(nlstate+ndeath); k++){
 7113: 	if (k != i) {
 7114: 	  printf("%d%d ",i,k);
 7115: 	  fprintf(ficlog,"%d%d ",i,k);
 7116: 	  fprintf(ficres,"%1d%1d ",i,k);
 7117: 	  for(j=1; j <=ncovmodel; j++){
 7118: 	    printf("%12.7f ",p[jk]);
 7119: 	    fprintf(ficlog,"%12.7f ",p[jk]);
 7120: 	    fprintf(ficres,"%12.7f ",p[jk]);
 7121: 	    jk++; 
 7122: 	  }
 7123: 	  printf("\n");
 7124: 	  fprintf(ficlog,"\n");
 7125: 	  fprintf(ficres,"\n");
 7126: 	}
 7127:       }
 7128:     }
 7129:     if(mle!=0){
 7130:       /* Computing hessian and covariance matrix */
 7131:       ftolhess=ftol; /* Usually correct */
 7132:       hesscov(matcov, p, npar, delti, ftolhess, func);
 7133:     }
 7134:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
 7135:     printf("# Scales (for hessian or gradient estimation)\n");
 7136:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
 7137:     for(i=1,jk=1; i <=nlstate; i++){
 7138:       for(j=1; j <=nlstate+ndeath; j++){
 7139: 	if (j!=i) {
 7140: 	  fprintf(ficres,"%1d%1d",i,j);
 7141: 	  printf("%1d%1d",i,j);
 7142: 	  fprintf(ficlog,"%1d%1d",i,j);
 7143: 	  for(k=1; k<=ncovmodel;k++){
 7144: 	    printf(" %.5e",delti[jk]);
 7145: 	    fprintf(ficlog," %.5e",delti[jk]);
 7146: 	    fprintf(ficres," %.5e",delti[jk]);
 7147: 	    jk++;
 7148: 	  }
 7149: 	  printf("\n");
 7150: 	  fprintf(ficlog,"\n");
 7151: 	  fprintf(ficres,"\n");
 7152: 	}
 7153:       }
 7154:     }
 7155:     
 7156:     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");
 7157:     if(mle>=1)
 7158:       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");
 7159:     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");
 7160:     /* # 121 Var(a12)\n\ */
 7161:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
 7162:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 7163:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 7164:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 7165:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 7166:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 7167:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 7168:     
 7169:     
 7170:     /* Just to have a covariance matrix which will be more understandable
 7171:        even is we still don't want to manage dictionary of variables
 7172:     */
 7173:     for(itimes=1;itimes<=2;itimes++){
 7174:       jj=0;
 7175:       for(i=1; i <=nlstate; i++){
 7176: 	for(j=1; j <=nlstate+ndeath; j++){
 7177: 	  if(j==i) continue;
 7178: 	  for(k=1; k<=ncovmodel;k++){
 7179: 	    jj++;
 7180: 	    ca[0]= k+'a'-1;ca[1]='\0';
 7181: 	    if(itimes==1){
 7182: 	      if(mle>=1)
 7183: 		printf("#%1d%1d%d",i,j,k);
 7184: 	      fprintf(ficlog,"#%1d%1d%d",i,j,k);
 7185: 	      fprintf(ficres,"#%1d%1d%d",i,j,k);
 7186: 	    }else{
 7187: 	      if(mle>=1)
 7188: 		printf("%1d%1d%d",i,j,k);
 7189: 	      fprintf(ficlog,"%1d%1d%d",i,j,k);
 7190: 	      fprintf(ficres,"%1d%1d%d",i,j,k);
 7191: 	    }
 7192: 	    ll=0;
 7193: 	    for(li=1;li <=nlstate; li++){
 7194: 	      for(lj=1;lj <=nlstate+ndeath; lj++){
 7195: 		if(lj==li) continue;
 7196: 		for(lk=1;lk<=ncovmodel;lk++){
 7197: 		  ll++;
 7198: 		  if(ll<=jj){
 7199: 		    cb[0]= lk +'a'-1;cb[1]='\0';
 7200: 		    if(ll<jj){
 7201: 		      if(itimes==1){
 7202: 			if(mle>=1)
 7203: 			  printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 7204: 			fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 7205: 			fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 7206: 		      }else{
 7207: 			if(mle>=1)
 7208: 			  printf(" %.5e",matcov[jj][ll]); 
 7209: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 7210: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 7211: 		      }
 7212: 		    }else{
 7213: 		      if(itimes==1){
 7214: 			if(mle>=1)
 7215: 			  printf(" Var(%s%1d%1d)",ca,i,j);
 7216: 			fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
 7217: 			fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
 7218: 		      }else{
 7219: 			if(mle>=1)
 7220: 			  printf(" %.5e",matcov[jj][ll]); 
 7221: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 7222: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 7223: 		      }
 7224: 		    }
 7225: 		  }
 7226: 		} /* end lk */
 7227: 	      } /* end lj */
 7228: 	    } /* end li */
 7229: 	    if(mle>=1)
 7230: 	      printf("\n");
 7231: 	    fprintf(ficlog,"\n");
 7232: 	    fprintf(ficres,"\n");
 7233: 	    numlinepar++;
 7234: 	  } /* end k*/
 7235: 	} /*end j */
 7236:       } /* end i */
 7237:     } /* end itimes */
 7238:     
 7239:     fflush(ficlog);
 7240:     fflush(ficres);
 7241:     
 7242:     while((c=getc(ficpar))=='#' && c!= EOF){
 7243:       ungetc(c,ficpar);
 7244:       fgets(line, MAXLINE, ficpar);
 7245:       fputs(line,stdout);
 7246:       fputs(line,ficparo);
 7247:     }
 7248:     ungetc(c,ficpar);
 7249:     
 7250:     estepm=0;
 7251:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
 7252:     if (estepm==0 || estepm < stepm) estepm=stepm;
 7253:     if (fage <= 2) {
 7254:       bage = ageminpar;
 7255:       fage = agemaxpar;
 7256:     }
 7257:     
 7258:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
 7259:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 7260:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 7261: 
 7262:     /* Other stuffs, more or less useful */    
 7263:     while((c=getc(ficpar))=='#' && c!= EOF){
 7264:       ungetc(c,ficpar);
 7265:       fgets(line, MAXLINE, ficpar);
 7266:       fputs(line,stdout);
 7267:       fputs(line,ficparo);
 7268:     }
 7269:     ungetc(c,ficpar);
 7270:     
 7271:     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);
 7272:     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);
 7273:     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);
 7274:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
 7275:     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);
 7276:     
 7277:     while((c=getc(ficpar))=='#' && c!= EOF){
 7278:       ungetc(c,ficpar);
 7279:       fgets(line, MAXLINE, ficpar);
 7280:       fputs(line,stdout);
 7281:       fputs(line,ficparo);
 7282:     }
 7283:     ungetc(c,ficpar);
 7284:     
 7285:     
 7286:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
 7287:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
 7288:     
 7289:     fscanf(ficpar,"pop_based=%d\n",&popbased);
 7290:     fprintf(ficparo,"pop_based=%d\n",popbased);   
 7291:     fprintf(ficres,"pop_based=%d\n",popbased);   
 7292:     
 7293:     while((c=getc(ficpar))=='#' && c!= EOF){
 7294:       ungetc(c,ficpar);
 7295:       fgets(line, MAXLINE, ficpar);
 7296:       fputs(line,stdout);
 7297:       fputs(line,ficparo);
 7298:     }
 7299:     ungetc(c,ficpar);
 7300:     
 7301:     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);
 7302:     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);
 7303:     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);
 7304:     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);
 7305:     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);
 7306:     /* day and month of proj2 are not used but only year anproj2.*/
 7307:     
 7308:     
 7309:     
 7310:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
 7311:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
 7312:     
 7313:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 7314:     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 7315:     
 7316:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
 7317: 		 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
 7318: 		 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
 7319:       
 7320:    /*------------ free_vector  -------------*/
 7321:    /*  chdir(path); */
 7322:  
 7323:     free_ivector(wav,1,imx);
 7324:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
 7325:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
 7326:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
 7327:     free_lvector(num,1,n);
 7328:     free_vector(agedc,1,n);
 7329:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
 7330:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
 7331:     fclose(ficparo);
 7332:     fclose(ficres);
 7333: 
 7334: 
 7335:     /* Other results (useful)*/
 7336: 
 7337: 
 7338:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 7339:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
 7340:     prlim=matrix(1,nlstate,1,nlstate);
 7341:     prevalence_limit(p, prlim,  ageminpar, agemaxpar);
 7342:     fclose(ficrespl);
 7343: 
 7344: #ifdef FREEEXIT2
 7345: #include "freeexit2.h"
 7346: #endif
 7347: 
 7348:     /*------------- h Pij x at various ages ------------*/
 7349:     /*#include "hpijx.h"*/
 7350:     hPijx(p, bage, fage);
 7351:     fclose(ficrespij);
 7352: 
 7353:   /*-------------- Variance of one-step probabilities---*/
 7354:     k=1;
 7355:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
 7356: 
 7357: 
 7358:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 7359:     for(i=1;i<=AGESUP;i++)
 7360:       for(j=1;j<=NCOVMAX;j++)
 7361: 	for(k=1;k<=NCOVMAX;k++)
 7362: 	  probs[i][j][k]=0.;
 7363: 
 7364:     /*---------- Forecasting ------------------*/
 7365:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
 7366:     if(prevfcast==1){
 7367:       /*    if(stepm ==1){*/
 7368:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
 7369:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
 7370:       /*      }  */
 7371:       /*      else{ */
 7372:       /*        erreur=108; */
 7373:       /*        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); */
 7374:       /*        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); */
 7375:       /*      } */
 7376:     }
 7377:  
 7378:     /* ------ Other prevalence ratios------------ */
 7379: 
 7380:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
 7381: 
 7382:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 7383:     /*  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",\
 7384: 	ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
 7385:     */
 7386: 
 7387:     if (mobilav!=0) {
 7388:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 7389:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 7390: 	fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 7391: 	printf(" Error in movingaverage mobilav=%d\n",mobilav);
 7392:       }
 7393:     }
 7394: 
 7395: 
 7396:     /*---------- Health expectancies, no variances ------------*/
 7397: 
 7398:     strcpy(filerese,"e");
 7399:     strcat(filerese,fileres);
 7400:     if((ficreseij=fopen(filerese,"w"))==NULL) {
 7401:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 7402:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 7403:     }
 7404:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
 7405:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
 7406:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 7407:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 7408:           
 7409:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 7410: 	fprintf(ficreseij,"\n#****** ");
 7411: 	for(j=1;j<=cptcoveff;j++) {
 7412: 	  fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7413: 	}
 7414: 	fprintf(ficreseij,"******\n");
 7415: 
 7416: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 7417: 	oldm=oldms;savm=savms;
 7418: 	evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
 7419:       
 7420: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 7421:       /*}*/
 7422:     }
 7423:     fclose(ficreseij);
 7424: 
 7425: 
 7426:     /*---------- Health expectancies and variances ------------*/
 7427: 
 7428: 
 7429:     strcpy(filerest,"t");
 7430:     strcat(filerest,fileres);
 7431:     if((ficrest=fopen(filerest,"w"))==NULL) {
 7432:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
 7433:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
 7434:     }
 7435:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
 7436:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
 7437: 
 7438: 
 7439:     strcpy(fileresstde,"stde");
 7440:     strcat(fileresstde,fileres);
 7441:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
 7442:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 7443:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 7444:     }
 7445:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 7446:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 7447: 
 7448:     strcpy(filerescve,"cve");
 7449:     strcat(filerescve,fileres);
 7450:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
 7451:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 7452:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 7453:     }
 7454:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 7455:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 7456: 
 7457:     strcpy(fileresv,"v");
 7458:     strcat(fileresv,fileres);
 7459:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
 7460:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
 7461:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
 7462:     }
 7463:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 7464:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 7465: 
 7466:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 7467:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 7468:           
 7469:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 7470:     	fprintf(ficrest,"\n#****** ");
 7471: 	for(j=1;j<=cptcoveff;j++) 
 7472: 	  fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7473: 	fprintf(ficrest,"******\n");
 7474: 
 7475: 	fprintf(ficresstdeij,"\n#****** ");
 7476: 	fprintf(ficrescveij,"\n#****** ");
 7477: 	for(j=1;j<=cptcoveff;j++) {
 7478: 	  fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7479: 	  fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7480: 	}
 7481: 	fprintf(ficresstdeij,"******\n");
 7482: 	fprintf(ficrescveij,"******\n");
 7483: 
 7484: 	fprintf(ficresvij,"\n#****** ");
 7485: 	for(j=1;j<=cptcoveff;j++) 
 7486: 	  fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7487: 	fprintf(ficresvij,"******\n");
 7488: 
 7489: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 7490: 	oldm=oldms;savm=savms;
 7491: 	cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
 7492: 	/*
 7493: 	 */
 7494: 	/* goto endfree; */
 7495:  
 7496: 	vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 7497: 	pstamp(ficrest);
 7498: 
 7499: 
 7500: 	for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 7501: 	  oldm=oldms;savm=savms; /* Segmentation fault */
 7502: 	  cptcod= 0; /* To be deleted */
 7503: 	  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 */
 7504: 	  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 ");
 7505: 	  if(vpopbased==1)
 7506: 	    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);
 7507: 	  else
 7508: 	    fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
 7509: 	  fprintf(ficrest,"# Age e.. (std) ");
 7510: 	  for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
 7511: 	  fprintf(ficrest,"\n");
 7512: 
 7513: 	  epj=vector(1,nlstate+1);
 7514: 	  for(age=bage; age <=fage ;age++){
 7515: 	    prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
 7516: 	    if (vpopbased==1) {
 7517: 	      if(mobilav ==0){
 7518: 		for(i=1; i<=nlstate;i++)
 7519: 		  prlim[i][i]=probs[(int)age][i][k];
 7520: 	      }else{ /* mobilav */ 
 7521: 		for(i=1; i<=nlstate;i++)
 7522: 		  prlim[i][i]=mobaverage[(int)age][i][k];
 7523: 	      }
 7524: 	    }
 7525: 	
 7526: 	    fprintf(ficrest," %4.0f",age);
 7527: 	    for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
 7528: 	      for(i=1, epj[j]=0.;i <=nlstate;i++) {
 7529: 		epj[j] += prlim[i][i]*eij[i][j][(int)age];
 7530: 		/*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
 7531: 	      }
 7532: 	      epj[nlstate+1] +=epj[j];
 7533: 	    }
 7534: 
 7535: 	    for(i=1, vepp=0.;i <=nlstate;i++)
 7536: 	      for(j=1;j <=nlstate;j++)
 7537: 		vepp += vareij[i][j][(int)age];
 7538: 	    fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
 7539: 	    for(j=1;j <=nlstate;j++){
 7540: 	      fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
 7541: 	    }
 7542: 	    fprintf(ficrest,"\n");
 7543: 	  }
 7544: 	}
 7545: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 7546: 	free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 7547: 	free_vector(epj,1,nlstate+1);
 7548:       /*}*/
 7549:     }
 7550:     free_vector(weight,1,n);
 7551:     free_imatrix(Tvard,1,NCOVMAX,1,2);
 7552:     free_imatrix(s,1,maxwav+1,1,n);
 7553:     free_matrix(anint,1,maxwav,1,n); 
 7554:     free_matrix(mint,1,maxwav,1,n);
 7555:     free_ivector(cod,1,n);
 7556:     free_ivector(tab,1,NCOVMAX);
 7557:     fclose(ficresstdeij);
 7558:     fclose(ficrescveij);
 7559:     fclose(ficresvij);
 7560:     fclose(ficrest);
 7561:     fclose(ficpar);
 7562:   
 7563:     /*------- Variance of period (stable) prevalence------*/   
 7564: 
 7565:     strcpy(fileresvpl,"vpl");
 7566:     strcat(fileresvpl,fileres);
 7567:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
 7568:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
 7569:       exit(0);
 7570:     }
 7571:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
 7572: 
 7573:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 7574:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 7575:           
 7576:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 7577:     	fprintf(ficresvpl,"\n#****** ");
 7578: 	for(j=1;j<=cptcoveff;j++) 
 7579: 	  fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7580: 	fprintf(ficresvpl,"******\n");
 7581:       
 7582: 	varpl=matrix(1,nlstate,(int) bage, (int) fage);
 7583: 	oldm=oldms;savm=savms;
 7584: 	varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
 7585: 	free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
 7586:       /*}*/
 7587:     }
 7588: 
 7589:     fclose(ficresvpl);
 7590: 
 7591:     /*---------- End : free ----------------*/
 7592:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 7593:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 7594:   }  /* mle==-3 arrives here for freeing */
 7595:  /* endfree:*/
 7596:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
 7597:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
 7598:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
 7599:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
 7600:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
 7601:     free_matrix(covar,0,NCOVMAX,1,n);
 7602:     free_matrix(matcov,1,npar,1,npar);
 7603:     /*free_vector(delti,1,npar);*/
 7604:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 7605:     free_matrix(agev,1,maxwav,1,imx);
 7606:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
 7607: 
 7608:     free_ivector(ncodemax,1,NCOVMAX);
 7609:     free_ivector(Tvar,1,NCOVMAX);
 7610:     free_ivector(Tprod,1,NCOVMAX);
 7611:     free_ivector(Tvaraff,1,NCOVMAX);
 7612:     free_ivector(Tage,1,NCOVMAX);
 7613: 
 7614:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
 7615:     free_imatrix(codtab,1,100,1,10);
 7616:   fflush(fichtm);
 7617:   fflush(ficgp);
 7618:   
 7619: 
 7620:   if((nberr >0) || (nbwarn>0)){
 7621:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
 7622:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
 7623:   }else{
 7624:     printf("End of Imach\n");
 7625:     fprintf(ficlog,"End of Imach\n");
 7626:   }
 7627:   printf("See log file on %s\n",filelog);
 7628:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
 7629:   /*(void) gettimeofday(&end_time,&tzp);*/
 7630:   rend_time = time(NULL);  
 7631:   end_time = *localtime(&rend_time);
 7632:   /* tml = *localtime(&end_time.tm_sec); */
 7633:   strcpy(strtend,asctime(&end_time));
 7634:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
 7635:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
 7636:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 7637: 
 7638:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 7639:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 7640:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 7641:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
 7642: /*   if(fileappend(fichtm,optionfilehtm)){ */
 7643:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 7644:   fclose(fichtm);
 7645:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 7646:   fclose(fichtmcov);
 7647:   fclose(ficgp);
 7648:   fclose(ficlog);
 7649:   /*------ End -----------*/
 7650: 
 7651: 
 7652:    printf("Before Current directory %s!\n",pathcd);
 7653: #ifdef WIN32
 7654:    if (_chdir(pathcd) != 0)
 7655: 	   printf("Can't move to directory %s!\n",path);
 7656:    if(_getcwd(pathcd,MAXLINE) > 0)
 7657: #else
 7658:    if(chdir(pathcd) != 0)
 7659: 	   printf("Can't move to directory %s!\n", path);
 7660:    if (getcwd(pathcd, MAXLINE) > 0)
 7661: #endif 
 7662:     printf("Current directory %s!\n",pathcd);
 7663:   /*strcat(plotcmd,CHARSEPARATOR);*/
 7664:   sprintf(plotcmd,"gnuplot");
 7665: #ifdef _WIN32
 7666:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
 7667: #endif
 7668:   if(!stat(plotcmd,&info)){
 7669:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 7670:     if(!stat(getenv("GNUPLOTBIN"),&info)){
 7671:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
 7672:     }else
 7673:       strcpy(pplotcmd,plotcmd);
 7674: #ifdef __unix
 7675:     strcpy(plotcmd,GNUPLOTPROGRAM);
 7676:     if(!stat(plotcmd,&info)){
 7677:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 7678:     }else
 7679:       strcpy(pplotcmd,plotcmd);
 7680: #endif
 7681:   }else
 7682:     strcpy(pplotcmd,plotcmd);
 7683:   
 7684:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
 7685:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
 7686: 
 7687:   if((outcmd=system(plotcmd)) != 0){
 7688:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
 7689:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
 7690:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
 7691:     if((outcmd=system(plotcmd)) != 0)
 7692:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
 7693:   }
 7694:   printf(" Successful, please wait...");
 7695:   while (z[0] != 'q') {
 7696:     /* chdir(path); */
 7697:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
 7698:     scanf("%s",z);
 7699: /*     if (z[0] == 'c') system("./imach"); */
 7700:     if (z[0] == 'e') {
 7701: #ifdef __APPLE__
 7702:       sprintf(pplotcmd, "open %s", optionfilehtm);
 7703: #elif __linux
 7704:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
 7705: #else
 7706:       sprintf(pplotcmd, "%s", optionfilehtm);
 7707: #endif
 7708:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
 7709:       system(pplotcmd);
 7710:     }
 7711:     else if (z[0] == 'g') system(plotcmd);
 7712:     else if (z[0] == 'q') exit(0);
 7713:   }
 7714:   end:
 7715:   while (z[0] != 'q') {
 7716:     printf("\nType  q for exiting: ");
 7717:     scanf("%s",z);
 7718:   }
 7719: }

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