File:  [Local Repository] / imach / src / imach.c
Revision 1.212: download - view: text, annotated - select for diffs
Sat Nov 21 12:47:24 2015 UTC (8 years, 6 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
Summary: minor typo

    1: /* $Id: imach.c,v 1.212 2015/11/21 12:47:24 brouard Exp $
    2:   $State: Exp $
    3:   $Log: imach.c,v $
    4:   Revision 1.212  2015/11/21 12:47:24  brouard
    5:   Summary: minor typo
    6: 
    7:   Revision 1.211  2015/11/21 12:41:11  brouard
    8:   Summary: 0.98r3 with some graph of projected cross-sectional
    9: 
   10:   Author: Nicolas Brouard
   11: 
   12:   Revision 1.210  2015/11/18 17:41:20  brouard
   13:   Summary: Start working on projected prevalences
   14: 
   15:   Revision 1.209  2015/11/17 22:12:03  brouard
   16:   Summary: Adding ftolpl parameter
   17:   Author: N Brouard
   18: 
   19:   We had difficulties to get smoothed confidence intervals. It was due
   20:   to the period prevalence which wasn't computed accurately. The inner
   21:   parameter ftolpl is now an outer parameter of the .imach parameter
   22:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
   23:   computation are long.
   24: 
   25:   Revision 1.208  2015/11/17 14:31:57  brouard
   26:   Summary: temporary
   27: 
   28:   Revision 1.207  2015/10/27 17:36:57  brouard
   29:   *** empty log message ***
   30: 
   31:   Revision 1.206  2015/10/24 07:14:11  brouard
   32:   *** empty log message ***
   33: 
   34:   Revision 1.205  2015/10/23 15:50:53  brouard
   35:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
   36: 
   37:   Revision 1.204  2015/10/01 16:20:26  brouard
   38:   Summary: Some new graphs of contribution to likelihood
   39: 
   40:   Revision 1.203  2015/09/30 17:45:14  brouard
   41:   Summary: looking at better estimation of the hessian
   42: 
   43:   Also a better criteria for convergence to the period prevalence And
   44:   therefore adding the number of years needed to converge. (The
   45:   prevalence in any alive state shold sum to one
   46: 
   47:   Revision 1.202  2015/09/22 19:45:16  brouard
   48:   Summary: Adding some overall graph on contribution to likelihood. Might change
   49: 
   50:   Revision 1.201  2015/09/15 17:34:58  brouard
   51:   Summary: 0.98r0
   52: 
   53:   - Some new graphs like suvival functions
   54:   - Some bugs fixed like model=1+age+V2.
   55: 
   56:   Revision 1.200  2015/09/09 16:53:55  brouard
   57:   Summary: Big bug thanks to Flavia
   58: 
   59:   Even model=1+age+V2. did not work anymore
   60: 
   61:   Revision 1.199  2015/09/07 14:09:23  brouard
   62:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
   63: 
   64:   Revision 1.198  2015/09/03 07:14:39  brouard
   65:   Summary: 0.98q5 Flavia
   66: 
   67:   Revision 1.197  2015/09/01 18:24:39  brouard
   68:   *** empty log message ***
   69: 
   70:   Revision 1.196  2015/08/18 23:17:52  brouard
   71:   Summary: 0.98q5
   72: 
   73:   Revision 1.195  2015/08/18 16:28:39  brouard
   74:   Summary: Adding a hack for testing purpose
   75: 
   76:   After reading the title, ftol and model lines, if the comment line has
   77:   a q, starting with #q, the answer at the end of the run is quit. It
   78:   permits to run test files in batch with ctest. The former workaround was
   79:   $ echo q | imach foo.imach
   80: 
   81:   Revision 1.194  2015/08/18 13:32:00  brouard
   82:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
   83: 
   84:   Revision 1.193  2015/08/04 07:17:42  brouard
   85:   Summary: 0.98q4
   86: 
   87:   Revision 1.192  2015/07/16 16:49:02  brouard
   88:   Summary: Fixing some outputs
   89: 
   90:   Revision 1.191  2015/07/14 10:00:33  brouard
   91:   Summary: Some fixes
   92: 
   93:   Revision 1.190  2015/05/05 08:51:13  brouard
   94:   Summary: Adding digits in output parameters (7 digits instead of 6)
   95: 
   96:   Fix 1+age+.
   97: 
   98:   Revision 1.189  2015/04/30 14:45:16  brouard
   99:   Summary: 0.98q2
  100: 
  101:   Revision 1.188  2015/04/30 08:27:53  brouard
  102:   *** empty log message ***
  103: 
  104:   Revision 1.187  2015/04/29 09:11:15  brouard
  105:   *** empty log message ***
  106: 
  107:   Revision 1.186  2015/04/23 12:01:52  brouard
  108:   Summary: V1*age is working now, version 0.98q1
  109: 
  110:   Some codes had been disabled in order to simplify and Vn*age was
  111:   working in the optimization phase, ie, giving correct MLE parameters,
  112:   but, as usual, outputs were not correct and program core dumped.
  113: 
  114:   Revision 1.185  2015/03/11 13:26:42  brouard
  115:   Summary: Inclusion of compile and links command line for Intel Compiler
  116: 
  117:   Revision 1.184  2015/03/11 11:52:39  brouard
  118:   Summary: Back from Windows 8. Intel Compiler
  119: 
  120:   Revision 1.183  2015/03/10 20:34:32  brouard
  121:   Summary: 0.98q0, trying with directest, mnbrak fixed
  122: 
  123:   We use directest instead of original Powell test; probably no
  124:   incidence on the results, but better justifications;
  125:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
  126:   wrong results.
  127: 
  128:   Revision 1.182  2015/02/12 08:19:57  brouard
  129:   Summary: Trying to keep directest which seems simpler and more general
  130:   Author: Nicolas Brouard
  131: 
  132:   Revision 1.181  2015/02/11 23:22:24  brouard
  133:   Summary: Comments on Powell added
  134: 
  135:   Author:
  136: 
  137:   Revision 1.180  2015/02/11 17:33:45  brouard
  138:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
  139: 
  140:   Revision 1.179  2015/01/04 09:57:06  brouard
  141:   Summary: back to OS/X
  142: 
  143:   Revision 1.178  2015/01/04 09:35:48  brouard
  144:   *** empty log message ***
  145: 
  146:   Revision 1.177  2015/01/03 18:40:56  brouard
  147:   Summary: Still testing ilc32 on OSX
  148: 
  149:   Revision 1.176  2015/01/03 16:45:04  brouard
  150:   *** empty log message ***
  151: 
  152:   Revision 1.175  2015/01/03 16:33:42  brouard
  153:   *** empty log message ***
  154: 
  155:   Revision 1.174  2015/01/03 16:15:49  brouard
  156:   Summary: Still in cross-compilation
  157: 
  158:   Revision 1.173  2015/01/03 12:06:26  brouard
  159:   Summary: trying to detect cross-compilation
  160: 
  161:   Revision 1.172  2014/12/27 12:07:47  brouard
  162:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
  163: 
  164:   Revision 1.171  2014/12/23 13:26:59  brouard
  165:   Summary: Back from Visual C
  166: 
  167:   Still problem with utsname.h on Windows
  168: 
  169:   Revision 1.170  2014/12/23 11:17:12  brouard
  170:   Summary: Cleaning some \%% back to %%
  171: 
  172:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
  173: 
  174:   Revision 1.169  2014/12/22 23:08:31  brouard
  175:   Summary: 0.98p
  176: 
  177:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
  178: 
  179:   Revision 1.168  2014/12/22 15:17:42  brouard
  180:   Summary: update
  181: 
  182:   Revision 1.167  2014/12/22 13:50:56  brouard
  183:   Summary: Testing uname and compiler version and if compiled 32 or 64
  184: 
  185:   Testing on Linux 64
  186: 
  187:   Revision 1.166  2014/12/22 11:40:47  brouard
  188:   *** empty log message ***
  189: 
  190:   Revision 1.165  2014/12/16 11:20:36  brouard
  191:   Summary: After compiling on Visual C
  192: 
  193:   * imach.c (Module): Merging 1.61 to 1.162
  194: 
  195:   Revision 1.164  2014/12/16 10:52:11  brouard
  196:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
  197: 
  198:   * imach.c (Module): Merging 1.61 to 1.162
  199: 
  200:   Revision 1.163  2014/12/16 10:30:11  brouard
  201:   * imach.c (Module): Merging 1.61 to 1.162
  202: 
  203:   Revision 1.162  2014/09/25 11:43:39  brouard
  204:   Summary: temporary backup 0.99!
  205: 
  206:   Revision 1.1  2014/09/16 11:06:58  brouard
  207:   Summary: With some code (wrong) for nlopt
  208: 
  209:   Author:
  210: 
  211:   Revision 1.161  2014/09/15 20:41:41  brouard
  212:   Summary: Problem with macro SQR on Intel compiler
  213: 
  214:   Revision 1.160  2014/09/02 09:24:05  brouard
  215:   *** empty log message ***
  216: 
  217:   Revision 1.159  2014/09/01 10:34:10  brouard
  218:   Summary: WIN32
  219:   Author: Brouard
  220: 
  221:   Revision 1.158  2014/08/27 17:11:51  brouard
  222:   *** empty log message ***
  223: 
  224:   Revision 1.157  2014/08/27 16:26:55  brouard
  225:   Summary: Preparing windows Visual studio version
  226:   Author: Brouard
  227: 
  228:   In order to compile on Visual studio, time.h is now correct and time_t
  229:   and tm struct should be used. difftime should be used but sometimes I
  230:   just make the differences in raw time format (time(&now).
  231:   Trying to suppress #ifdef LINUX
  232:   Add xdg-open for __linux in order to open default browser.
  233: 
  234:   Revision 1.156  2014/08/25 20:10:10  brouard
  235:   *** empty log message ***
  236: 
  237:   Revision 1.155  2014/08/25 18:32:34  brouard
  238:   Summary: New compile, minor changes
  239:   Author: Brouard
  240: 
  241:   Revision 1.154  2014/06/20 17:32:08  brouard
  242:   Summary: Outputs now all graphs of convergence to period prevalence
  243: 
  244:   Revision 1.153  2014/06/20 16:45:46  brouard
  245:   Summary: If 3 live state, convergence to period prevalence on same graph
  246:   Author: Brouard
  247: 
  248:   Revision 1.152  2014/06/18 17:54:09  brouard
  249:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
  250: 
  251:   Revision 1.151  2014/06/18 16:43:30  brouard
  252:   *** empty log message ***
  253: 
  254:   Revision 1.150  2014/06/18 16:42:35  brouard
  255:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
  256:   Author: brouard
  257: 
  258:   Revision 1.149  2014/06/18 15:51:14  brouard
  259:   Summary: Some fixes in parameter files errors
  260:   Author: Nicolas Brouard
  261: 
  262:   Revision 1.148  2014/06/17 17:38:48  brouard
  263:   Summary: Nothing new
  264:   Author: Brouard
  265: 
  266:   Just a new packaging for OS/X version 0.98nS
  267: 
  268:   Revision 1.147  2014/06/16 10:33:11  brouard
  269:   *** empty log message ***
  270: 
  271:   Revision 1.146  2014/06/16 10:20:28  brouard
  272:   Summary: Merge
  273:   Author: Brouard
  274: 
  275:   Merge, before building revised version.
  276: 
  277:   Revision 1.145  2014/06/10 21:23:15  brouard
  278:   Summary: Debugging with valgrind
  279:   Author: Nicolas Brouard
  280: 
  281:   Lot of changes in order to output the results with some covariates
  282:   After the Edimburgh REVES conference 2014, it seems mandatory to
  283:   improve the code.
  284:   No more memory valgrind error but a lot has to be done in order to
  285:   continue the work of splitting the code into subroutines.
  286:   Also, decodemodel has been improved. Tricode is still not
  287:   optimal. nbcode should be improved. Documentation has been added in
  288:   the source code.
  289: 
  290:   Revision 1.143  2014/01/26 09:45:38  brouard
  291:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
  292: 
  293:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  294:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
  295: 
  296:   Revision 1.142  2014/01/26 03:57:36  brouard
  297:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
  298: 
  299:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  300: 
  301:   Revision 1.141  2014/01/26 02:42:01  brouard
  302:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  303: 
  304:   Revision 1.140  2011/09/02 10:37:54  brouard
  305:   Summary: times.h is ok with mingw32 now.
  306: 
  307:   Revision 1.139  2010/06/14 07:50:17  brouard
  308:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
  309:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
  310: 
  311:   Revision 1.138  2010/04/30 18:19:40  brouard
  312:   *** empty log message ***
  313: 
  314:   Revision 1.137  2010/04/29 18:11:38  brouard
  315:   (Module): Checking covariates for more complex models
  316:   than V1+V2. A lot of change to be done. Unstable.
  317: 
  318:   Revision 1.136  2010/04/26 20:30:53  brouard
  319:   (Module): merging some libgsl code. Fixing computation
  320:   of likelione (using inter/intrapolation if mle = 0) in order to
  321:   get same likelihood as if mle=1.
  322:   Some cleaning of code and comments added.
  323: 
  324:   Revision 1.135  2009/10/29 15:33:14  brouard
  325:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  326: 
  327:   Revision 1.134  2009/10/29 13:18:53  brouard
  328:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  329: 
  330:   Revision 1.133  2009/07/06 10:21:25  brouard
  331:   just nforces
  332: 
  333:   Revision 1.132  2009/07/06 08:22:05  brouard
  334:   Many tings
  335: 
  336:   Revision 1.131  2009/06/20 16:22:47  brouard
  337:   Some dimensions resccaled
  338: 
  339:   Revision 1.130  2009/05/26 06:44:34  brouard
  340:   (Module): Max Covariate is now set to 20 instead of 8. A
  341:   lot of cleaning with variables initialized to 0. Trying to make
  342:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
  343: 
  344:   Revision 1.129  2007/08/31 13:49:27  lievre
  345:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
  346: 
  347:   Revision 1.128  2006/06/30 13:02:05  brouard
  348:   (Module): Clarifications on computing e.j
  349: 
  350:   Revision 1.127  2006/04/28 18:11:50  brouard
  351:   (Module): Yes the sum of survivors was wrong since
  352:   imach-114 because nhstepm was no more computed in the age
  353:   loop. Now we define nhstepma in the age loop.
  354:   (Module): In order to speed up (in case of numerous covariates) we
  355:   compute health expectancies (without variances) in a first step
  356:   and then all the health expectancies with variances or standard
  357:   deviation (needs data from the Hessian matrices) which slows the
  358:   computation.
  359:   In the future we should be able to stop the program is only health
  360:   expectancies and graph are needed without standard deviations.
  361: 
  362:   Revision 1.126  2006/04/28 17:23:28  brouard
  363:   (Module): Yes the sum of survivors was wrong since
  364:   imach-114 because nhstepm was no more computed in the age
  365:   loop. Now we define nhstepma in the age loop.
  366:   Version 0.98h
  367: 
  368:   Revision 1.125  2006/04/04 15:20:31  lievre
  369:   Errors in calculation of health expectancies. Age was not initialized.
  370:   Forecasting file added.
  371: 
  372:   Revision 1.124  2006/03/22 17:13:53  lievre
  373:   Parameters are printed with %lf instead of %f (more numbers after the comma).
  374:   The log-likelihood is printed in the log file
  375: 
  376:   Revision 1.123  2006/03/20 10:52:43  brouard
  377:   * imach.c (Module): <title> changed, corresponds to .htm file
  378:   name. <head> headers where missing.
  379: 
  380:   * imach.c (Module): Weights can have a decimal point as for
  381:   English (a comma might work with a correct LC_NUMERIC environment,
  382:   otherwise the weight is truncated).
  383:   Modification of warning when the covariates values are not 0 or
  384:   1.
  385:   Version 0.98g
  386: 
  387:   Revision 1.122  2006/03/20 09:45:41  brouard
  388:   (Module): Weights can have a decimal point as for
  389:   English (a comma might work with a correct LC_NUMERIC environment,
  390:   otherwise the weight is truncated).
  391:   Modification of warning when the covariates values are not 0 or
  392:   1.
  393:   Version 0.98g
  394: 
  395:   Revision 1.121  2006/03/16 17:45:01  lievre
  396:   * imach.c (Module): Comments concerning covariates added
  397: 
  398:   * imach.c (Module): refinements in the computation of lli if
  399:   status=-2 in order to have more reliable computation if stepm is
  400:   not 1 month. Version 0.98f
  401: 
  402:   Revision 1.120  2006/03/16 15:10:38  lievre
  403:   (Module): refinements in the computation of lli if
  404:   status=-2 in order to have more reliable computation if stepm is
  405:   not 1 month. Version 0.98f
  406: 
  407:   Revision 1.119  2006/03/15 17:42:26  brouard
  408:   (Module): Bug if status = -2, the loglikelihood was
  409:   computed as likelihood omitting the logarithm. Version O.98e
  410: 
  411:   Revision 1.118  2006/03/14 18:20:07  brouard
  412:   (Module): varevsij Comments added explaining the second
  413:   table of variances if popbased=1 .
  414:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  415:   (Module): Function pstamp added
  416:   (Module): Version 0.98d
  417: 
  418:   Revision 1.117  2006/03/14 17:16:22  brouard
  419:   (Module): varevsij Comments added explaining the second
  420:   table of variances if popbased=1 .
  421:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  422:   (Module): Function pstamp added
  423:   (Module): Version 0.98d
  424: 
  425:   Revision 1.116  2006/03/06 10:29:27  brouard
  426:   (Module): Variance-covariance wrong links and
  427:   varian-covariance of ej. is needed (Saito).
  428: 
  429:   Revision 1.115  2006/02/27 12:17:45  brouard
  430:   (Module): One freematrix added in mlikeli! 0.98c
  431: 
  432:   Revision 1.114  2006/02/26 12:57:58  brouard
  433:   (Module): Some improvements in processing parameter
  434:   filename with strsep.
  435: 
  436:   Revision 1.113  2006/02/24 14:20:24  brouard
  437:   (Module): Memory leaks checks with valgrind and:
  438:   datafile was not closed, some imatrix were not freed and on matrix
  439:   allocation too.
  440: 
  441:   Revision 1.112  2006/01/30 09:55:26  brouard
  442:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
  443: 
  444:   Revision 1.111  2006/01/25 20:38:18  brouard
  445:   (Module): Lots of cleaning and bugs added (Gompertz)
  446:   (Module): Comments can be added in data file. Missing date values
  447:   can be a simple dot '.'.
  448: 
  449:   Revision 1.110  2006/01/25 00:51:50  brouard
  450:   (Module): Lots of cleaning and bugs added (Gompertz)
  451: 
  452:   Revision 1.109  2006/01/24 19:37:15  brouard
  453:   (Module): Comments (lines starting with a #) are allowed in data.
  454: 
  455:   Revision 1.108  2006/01/19 18:05:42  lievre
  456:   Gnuplot problem appeared...
  457:   To be fixed
  458: 
  459:   Revision 1.107  2006/01/19 16:20:37  brouard
  460:   Test existence of gnuplot in imach path
  461: 
  462:   Revision 1.106  2006/01/19 13:24:36  brouard
  463:   Some cleaning and links added in html output
  464: 
  465:   Revision 1.105  2006/01/05 20:23:19  lievre
  466:   *** empty log message ***
  467: 
  468:   Revision 1.104  2005/09/30 16:11:43  lievre
  469:   (Module): sump fixed, loop imx fixed, and simplifications.
  470:   (Module): If the status is missing at the last wave but we know
  471:   that the person is alive, then we can code his/her status as -2
  472:   (instead of missing=-1 in earlier versions) and his/her
  473:   contributions to the likelihood is 1 - Prob of dying from last
  474:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
  475:   the healthy state at last known wave). Version is 0.98
  476: 
  477:   Revision 1.103  2005/09/30 15:54:49  lievre
  478:   (Module): sump fixed, loop imx fixed, and simplifications.
  479: 
  480:   Revision 1.102  2004/09/15 17:31:30  brouard
  481:   Add the possibility to read data file including tab characters.
  482: 
  483:   Revision 1.101  2004/09/15 10:38:38  brouard
  484:   Fix on curr_time
  485: 
  486:   Revision 1.100  2004/07/12 18:29:06  brouard
  487:   Add version for Mac OS X. Just define UNIX in Makefile
  488: 
  489:   Revision 1.99  2004/06/05 08:57:40  brouard
  490:   *** empty log message ***
  491: 
  492:   Revision 1.98  2004/05/16 15:05:56  brouard
  493:   New version 0.97 . First attempt to estimate force of mortality
  494:   directly from the data i.e. without the need of knowing the health
  495:   state at each age, but using a Gompertz model: log u =a + b*age .
  496:   This is the basic analysis of mortality and should be done before any
  497:   other analysis, in order to test if the mortality estimated from the
  498:   cross-longitudinal survey is different from the mortality estimated
  499:   from other sources like vital statistic data.
  500: 
  501:   The same imach parameter file can be used but the option for mle should be -3.
  502: 
  503:   Agnès, who wrote this part of the code, tried to keep most of the
  504:   former routines in order to include the new code within the former code.
  505: 
  506:   The output is very simple: only an estimate of the intercept and of
  507:   the slope with 95% confident intervals.
  508: 
  509:   Current limitations:
  510:   A) Even if you enter covariates, i.e. with the
  511:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
  512:   B) There is no computation of Life Expectancy nor Life Table.
  513: 
  514:   Revision 1.97  2004/02/20 13:25:42  lievre
  515:   Version 0.96d. Population forecasting command line is (temporarily)
  516:   suppressed.
  517: 
  518:   Revision 1.96  2003/07/15 15:38:55  brouard
  519:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
  520:   rewritten within the same printf. Workaround: many printfs.
  521: 
  522:   Revision 1.95  2003/07/08 07:54:34  brouard
  523:   * imach.c (Repository):
  524:   (Repository): Using imachwizard code to output a more meaningful covariance
  525:   matrix (cov(a12,c31) instead of numbers.
  526: 
  527:   Revision 1.94  2003/06/27 13:00:02  brouard
  528:   Just cleaning
  529: 
  530:   Revision 1.93  2003/06/25 16:33:55  brouard
  531:   (Module): On windows (cygwin) function asctime_r doesn't
  532:   exist so I changed back to asctime which exists.
  533:   (Module): Version 0.96b
  534: 
  535:   Revision 1.92  2003/06/25 16:30:45  brouard
  536:   (Module): On windows (cygwin) function asctime_r doesn't
  537:   exist so I changed back to asctime which exists.
  538: 
  539:   Revision 1.91  2003/06/25 15:30:29  brouard
  540:   * imach.c (Repository): Duplicated warning errors corrected.
  541:   (Repository): Elapsed time after each iteration is now output. It
  542:   helps to forecast when convergence will be reached. Elapsed time
  543:   is stamped in powell.  We created a new html file for the graphs
  544:   concerning matrix of covariance. It has extension -cov.htm.
  545: 
  546:   Revision 1.90  2003/06/24 12:34:15  brouard
  547:   (Module): Some bugs corrected for windows. Also, when
  548:   mle=-1 a template is output in file "or"mypar.txt with the design
  549:   of the covariance matrix to be input.
  550: 
  551:   Revision 1.89  2003/06/24 12:30:52  brouard
  552:   (Module): Some bugs corrected for windows. Also, when
  553:   mle=-1 a template is output in file "or"mypar.txt with the design
  554:   of the covariance matrix to be input.
  555: 
  556:   Revision 1.88  2003/06/23 17:54:56  brouard
  557:   * 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.
  558: 
  559:   Revision 1.87  2003/06/18 12:26:01  brouard
  560:   Version 0.96
  561: 
  562:   Revision 1.86  2003/06/17 20:04:08  brouard
  563:   (Module): Change position of html and gnuplot routines and added
  564:   routine fileappend.
  565: 
  566:   Revision 1.85  2003/06/17 13:12:43  brouard
  567:   * imach.c (Repository): Check when date of death was earlier that
  568:   current date of interview. It may happen when the death was just
  569:   prior to the death. In this case, dh was negative and likelihood
  570:   was wrong (infinity). We still send an "Error" but patch by
  571:   assuming that the date of death was just one stepm after the
  572:   interview.
  573:   (Repository): Because some people have very long ID (first column)
  574:   we changed int to long in num[] and we added a new lvector for
  575:   memory allocation. But we also truncated to 8 characters (left
  576:   truncation)
  577:   (Repository): No more line truncation errors.
  578: 
  579:   Revision 1.84  2003/06/13 21:44:43  brouard
  580:   * imach.c (Repository): Replace "freqsummary" at a correct
  581:   place. It differs from routine "prevalence" which may be called
  582:   many times. Probs is memory consuming and must be used with
  583:   parcimony.
  584:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
  585: 
  586:   Revision 1.83  2003/06/10 13:39:11  lievre
  587:   *** empty log message ***
  588: 
  589:   Revision 1.82  2003/06/05 15:57:20  brouard
  590:   Add log in  imach.c and  fullversion number is now printed.
  591: 
  592: */
  593: /*
  594:    Interpolated Markov Chain
  595: 
  596:   Short summary of the programme:
  597:   
  598:   This program computes Healthy Life Expectancies from
  599:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
  600:   first survey ("cross") where individuals from different ages are
  601:   interviewed on their health status or degree of disability (in the
  602:   case of a health survey which is our main interest) -2- at least a
  603:   second wave of interviews ("longitudinal") which measure each change
  604:   (if any) in individual health status.  Health expectancies are
  605:   computed from the time spent in each health state according to a
  606:   model. More health states you consider, more time is necessary to reach the
  607:   Maximum Likelihood of the parameters involved in the model.  The
  608:   simplest model is the multinomial logistic model where pij is the
  609:   probability to be observed in state j at the second wave
  610:   conditional to be observed in state i at the first wave. Therefore
  611:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
  612:   'age' is age and 'sex' is a covariate. If you want to have a more
  613:   complex model than "constant and age", you should modify the program
  614:   where the markup *Covariates have to be included here again* invites
  615:   you to do it.  More covariates you add, slower the
  616:   convergence.
  617: 
  618:   The advantage of this computer programme, compared to a simple
  619:   multinomial logistic model, is clear when the delay between waves is not
  620:   identical for each individual. Also, if a individual missed an
  621:   intermediate interview, the information is lost, but taken into
  622:   account using an interpolation or extrapolation.  
  623: 
  624:   hPijx is the probability to be observed in state i at age x+h
  625:   conditional to the observed state i at age x. The delay 'h' can be
  626:   split into an exact number (nh*stepm) of unobserved intermediate
  627:   states. This elementary transition (by month, quarter,
  628:   semester or year) is modelled as a multinomial logistic.  The hPx
  629:   matrix is simply the matrix product of nh*stepm elementary matrices
  630:   and the contribution of each individual to the likelihood is simply
  631:   hPijx.
  632: 
  633:   Also this programme outputs the covariance matrix of the parameters but also
  634:   of the life expectancies. It also computes the period (stable) prevalence. 
  635:   
  636:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
  637:            Institut national d'études démographiques, Paris.
  638:   This software have been partly granted by Euro-REVES, a concerted action
  639:   from the European Union.
  640:   It is copyrighted identically to a GNU software product, ie programme and
  641:   software can be distributed freely for non commercial use. Latest version
  642:   can be accessed at http://euroreves.ined.fr/imach .
  643: 
  644:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
  645:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
  646:   
  647:   **********************************************************************/
  648: /*
  649:   main
  650:   read parameterfile
  651:   read datafile
  652:   concatwav
  653:   freqsummary
  654:   if (mle >= 1)
  655:     mlikeli
  656:   print results files
  657:   if mle==1 
  658:      computes hessian
  659:   read end of parameter file: agemin, agemax, bage, fage, estepm
  660:       begin-prev-date,...
  661:   open gnuplot file
  662:   open html file
  663:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
  664:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
  665:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
  666:     freexexit2 possible for memory heap.
  667: 
  668:   h Pij x                         | pij_nom  ficrestpij
  669:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
  670:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
  671:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
  672: 
  673:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
  674:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
  675:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
  676:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
  677:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
  678: 
  679:   forecasting if prevfcast==1 prevforecast call prevalence()
  680:   health expectancies
  681:   Variance-covariance of DFLE
  682:   prevalence()
  683:    movingaverage()
  684:   varevsij() 
  685:   if popbased==1 varevsij(,popbased)
  686:   total life expectancies
  687:   Variance of period (stable) prevalence
  688:  end
  689: */
  690: 
  691: /* #define DEBUG */
  692: /* #define DEBUGBRENT */
  693: /* #define DEBUGLINMIN */
  694: /* #define DEBUGHESS */
  695: #define DEBUGHESSIJ
  696: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan)*\/ */
  697: #define POWELL /* Instead of NLOPT */
  698: #define POWELLF1F3 /* Skip test */
  699: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
  700: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
  701: 
  702: #include <math.h>
  703: #include <stdio.h>
  704: #include <stdlib.h>
  705: #include <string.h>
  706: 
  707: #ifdef _WIN32
  708: #include <io.h>
  709: #include <windows.h>
  710: #include <tchar.h>
  711: #else
  712: #include <unistd.h>
  713: #endif
  714: 
  715: #include <limits.h>
  716: #include <sys/types.h>
  717: 
  718: #if defined(__GNUC__)
  719: #include <sys/utsname.h> /* Doesn't work on Windows */
  720: #endif
  721: 
  722: #include <sys/stat.h>
  723: #include <errno.h>
  724: /* extern int errno; */
  725: 
  726: /* #ifdef LINUX */
  727: /* #include <time.h> */
  728: /* #include "timeval.h" */
  729: /* #else */
  730: /* #include <sys/time.h> */
  731: /* #endif */
  732: 
  733: #include <time.h>
  734: 
  735: #ifdef GSL
  736: #include <gsl/gsl_errno.h>
  737: #include <gsl/gsl_multimin.h>
  738: #endif
  739: 
  740: 
  741: #ifdef NLOPT
  742: #include <nlopt.h>
  743: typedef struct {
  744:   double (* function)(double [] );
  745: } myfunc_data ;
  746: #endif
  747: 
  748: /* #include <libintl.h> */
  749: /* #define _(String) gettext (String) */
  750: 
  751: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
  752: 
  753: #define GNUPLOTPROGRAM "gnuplot"
  754: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
  755: #define FILENAMELENGTH 132
  756: 
  757: #define	GLOCK_ERROR_NOPATH		-1	/* empty path */
  758: #define	GLOCK_ERROR_GETCWD		-2	/* cannot get cwd */
  759: 
  760: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
  761: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
  762: 
  763: #define NINTERVMAX 8
  764: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
  765: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
  766: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
  767: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
  768: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
  769: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
  770: #define MAXN 20000
  771: #define YEARM 12. /**< Number of months per year */
  772: #define AGESUP 130
  773: #define AGEBASE 40
  774: #define AGEOVERFLOW 1.e20
  775: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
  776: #ifdef _WIN32
  777: #define DIRSEPARATOR '\\'
  778: #define CHARSEPARATOR "\\"
  779: #define ODIRSEPARATOR '/'
  780: #else
  781: #define DIRSEPARATOR '/'
  782: #define CHARSEPARATOR "/"
  783: #define ODIRSEPARATOR '\\'
  784: #endif
  785: 
  786: /* $Id: imach.c,v 1.212 2015/11/21 12:47:24 brouard Exp $ */
  787: /* $State: Exp $ */
  788: #include "version.h"
  789: char version[]=__IMACH_VERSION__;
  790: char copyright[]="October 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
  791: char fullversion[]="$Revision: 1.212 $ $Date: 2015/11/21 12:47:24 $"; 
  792: char strstart[80];
  793: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
  794: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
  795: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
  796: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
  797: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
  798: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
  799: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
  800: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
  801: int cptcovprodnoage=0; /**< Number of covariate products without age */   
  802: int cptcoveff=0; /* Total number of covariates to vary for printing results */
  803: int cptcov=0; /* Working variable */
  804: int npar=NPARMAX;
  805: int nlstate=2; /* Number of live states */
  806: int ndeath=1; /* Number of dead states */
  807: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
  808: int popbased=0;
  809: 
  810: int *wav; /* Number of waves for this individuual 0 is possible */
  811: int maxwav=0; /* Maxim number of waves */
  812: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
  813: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
  814: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
  815: 		   to the likelihood and the sum of weights (done by funcone)*/
  816: int mle=1, weightopt=0;
  817: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
  818: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
  819: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
  820: 	   * wave mi and wave mi+1 is not an exact multiple of stepm. */
  821: int countcallfunc=0;  /* Count the number of calls to func */
  822: double jmean=1; /* Mean space between 2 waves */
  823: double **matprod2(); /* test */
  824: double **oldm, **newm, **savm; /* Working pointers to matrices */
  825: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
  826: /*FILE *fic ; */ /* Used in readdata only */
  827: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
  828: FILE *ficlog, *ficrespow;
  829: int globpr=0; /* Global variable for printing or not */
  830: double fretone; /* Only one call to likelihood */
  831: long ipmx=0; /* Number of contributions */
  832: double sw; /* Sum of weights */
  833: char filerespow[FILENAMELENGTH];
  834: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
  835: FILE *ficresilk;
  836: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
  837: FILE *ficresprobmorprev;
  838: FILE *fichtm, *fichtmcov; /* Html File */
  839: FILE *ficreseij;
  840: char filerese[FILENAMELENGTH];
  841: FILE *ficresstdeij;
  842: char fileresstde[FILENAMELENGTH];
  843: FILE *ficrescveij;
  844: char filerescve[FILENAMELENGTH];
  845: FILE  *ficresvij;
  846: char fileresv[FILENAMELENGTH];
  847: FILE  *ficresvpl;
  848: char fileresvpl[FILENAMELENGTH];
  849: char title[MAXLINE];
  850: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
  851: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
  852: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
  853: char command[FILENAMELENGTH];
  854: int  outcmd=0;
  855: 
  856: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
  857: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
  858: char filelog[FILENAMELENGTH]; /* Log file */
  859: char filerest[FILENAMELENGTH];
  860: char fileregp[FILENAMELENGTH];
  861: char popfile[FILENAMELENGTH];
  862: 
  863: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
  864: 
  865: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
  866: /* struct timezone tzp; */
  867: /* extern int gettimeofday(); */
  868: struct tm tml, *gmtime(), *localtime();
  869: 
  870: extern time_t time();
  871: 
  872: struct tm start_time, end_time, curr_time, last_time, forecast_time;
  873: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
  874: struct tm tm;
  875: 
  876: char strcurr[80], strfor[80];
  877: 
  878: char *endptr;
  879: long lval;
  880: double dval;
  881: 
  882: #define NR_END 1
  883: #define FREE_ARG char*
  884: #define FTOL 1.0e-10
  885: 
  886: #define NRANSI 
  887: #define ITMAX 200 
  888: 
  889: #define TOL 2.0e-4 
  890: 
  891: #define CGOLD 0.3819660 
  892: #define ZEPS 1.0e-10 
  893: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
  894: 
  895: #define GOLD 1.618034 
  896: #define GLIMIT 100.0 
  897: #define TINY 1.0e-20 
  898: 
  899: static double maxarg1,maxarg2;
  900: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
  901: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
  902:   
  903: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
  904: #define rint(a) floor(a+0.5)
  905: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
  906: #define mytinydouble 1.0e-16
  907: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
  908: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
  909: /* static double dsqrarg; */
  910: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
  911: static double sqrarg;
  912: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
  913: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
  914: int agegomp= AGEGOMP;
  915: 
  916: int imx; 
  917: int stepm=1;
  918: /* Stepm, step in month: minimum step interpolation*/
  919: 
  920: int estepm;
  921: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
  922: 
  923: int m,nb;
  924: long *num;
  925: int firstpass=0, lastpass=4,*cod, *cens;
  926: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
  927: 		   covariate for which somebody answered excluding 
  928: 		   undefined. Usually 2: 0 and 1. */
  929: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
  930: 			     covariate for which somebody answered including 
  931: 			     undefined. Usually 3: -1, 0 and 1. */
  932: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
  933: double **pmmij, ***probs;
  934: double *ageexmed,*agecens;
  935: double dateintmean=0;
  936: 
  937: double *weight;
  938: int **s; /* Status */
  939: double *agedc;
  940: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
  941: 		  * covar=matrix(0,NCOVMAX,1,n); 
  942: 		  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
  943: double  idx; 
  944: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
  945: int *Tage;
  946: int *Ndum; /** Freq of modality (tricode */
  947: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
  948: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
  949: double *lsurv, *lpop, *tpop;
  950: 
  951: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
  952: double ftolhess; /**< Tolerance for computing hessian */
  953: 
  954: /**************** split *************************/
  955: static	int split( char *path, char *dirc, char *name, char *ext, char *finame )
  956: {
  957:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
  958:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
  959:   */ 
  960:   char	*ss;				/* pointer */
  961:   int	l1=0, l2=0;				/* length counters */
  962: 
  963:   l1 = strlen(path );			/* length of path */
  964:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
  965:   ss= strrchr( path, DIRSEPARATOR );		/* find last / */
  966:   if ( ss == NULL ) {			/* no directory, so determine current directory */
  967:     strcpy( name, path );		/* we got the fullname name because no directory */
  968:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
  969:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
  970:     /* get current working directory */
  971:     /*    extern  char* getcwd ( char *buf , int len);*/
  972: #ifdef WIN32
  973:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
  974: #else
  975: 	if (getcwd(dirc, FILENAME_MAX) == NULL) {
  976: #endif
  977:       return( GLOCK_ERROR_GETCWD );
  978:     }
  979:     /* got dirc from getcwd*/
  980:     printf(" DIRC = %s \n",dirc);
  981:   } else {				/* strip directory from path */
  982:     ss++;				/* after this, the filename */
  983:     l2 = strlen( ss );			/* length of filename */
  984:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
  985:     strcpy( name, ss );		/* save file name */
  986:     strncpy( dirc, path, l1 - l2 );	/* now the directory */
  987:     dirc[l1-l2] = '\0';			/* add zero */
  988:     printf(" DIRC2 = %s \n",dirc);
  989:   }
  990:   /* We add a separator at the end of dirc if not exists */
  991:   l1 = strlen( dirc );			/* length of directory */
  992:   if( dirc[l1-1] != DIRSEPARATOR ){
  993:     dirc[l1] =  DIRSEPARATOR;
  994:     dirc[l1+1] = 0; 
  995:     printf(" DIRC3 = %s \n",dirc);
  996:   }
  997:   ss = strrchr( name, '.' );		/* find last / */
  998:   if (ss >0){
  999:     ss++;
 1000:     strcpy(ext,ss);			/* save extension */
 1001:     l1= strlen( name);
 1002:     l2= strlen(ss)+1;
 1003:     strncpy( finame, name, l1-l2);
 1004:     finame[l1-l2]= 0;
 1005:   }
 1006: 
 1007:   return( 0 );				/* we're done */
 1008: }
 1009: 
 1010: 
 1011: /******************************************/
 1012: 
 1013: void replace_back_to_slash(char *s, char*t)
 1014: {
 1015:   int i;
 1016:   int lg=0;
 1017:   i=0;
 1018:   lg=strlen(t);
 1019:   for(i=0; i<= lg; i++) {
 1020:     (s[i] = t[i]);
 1021:     if (t[i]== '\\') s[i]='/';
 1022:   }
 1023: }
 1024: 
 1025: char *trimbb(char *out, char *in)
 1026: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
 1027:   char *s;
 1028:   s=out;
 1029:   while (*in != '\0'){
 1030:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
 1031:       in++;
 1032:     }
 1033:     *out++ = *in++;
 1034:   }
 1035:   *out='\0';
 1036:   return s;
 1037: }
 1038: 
 1039: /* char *substrchaine(char *out, char *in, char *chain) */
 1040: /* { */
 1041: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
 1042: /*   char *s, *t; */
 1043: /*   t=in;s=out; */
 1044: /*   while ((*in != *chain) && (*in != '\0')){ */
 1045: /*     *out++ = *in++; */
 1046: /*   } */
 1047: 
 1048: /*   /\* *in matches *chain *\/ */
 1049: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
 1050: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1051: /*   } */
 1052: /*   in--; chain--; */
 1053: /*   while ( (*in != '\0')){ */
 1054: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1055: /*     *out++ = *in++; */
 1056: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1057: /*   } */
 1058: /*   *out='\0'; */
 1059: /*   out=s; */
 1060: /*   return out; */
 1061: /* } */
 1062: char *substrchaine(char *out, char *in, char *chain)
 1063: {
 1064:   /* Substract chain 'chain' from 'in', return and output 'out' */
 1065:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
 1066: 
 1067:   char *strloc;
 1068: 
 1069:   strcpy (out, in); 
 1070:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
 1071:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
 1072:   if(strloc != NULL){ 
 1073:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
 1074:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
 1075:     /* strcpy (strloc, strloc +strlen(chain));*/
 1076:   }
 1077:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
 1078:   return out;
 1079: }
 1080: 
 1081: 
 1082: char *cutl(char *blocc, char *alocc, char *in, char occ)
 1083: {
 1084:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
 1085:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
 1086:      gives blocc="abcdef" and alocc="ghi2j".
 1087:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
 1088:   */
 1089:   char *s, *t;
 1090:   t=in;s=in;
 1091:   while ((*in != occ) && (*in != '\0')){
 1092:     *alocc++ = *in++;
 1093:   }
 1094:   if( *in == occ){
 1095:     *(alocc)='\0';
 1096:     s=++in;
 1097:   }
 1098:  
 1099:   if (s == t) {/* occ not found */
 1100:     *(alocc-(in-s))='\0';
 1101:     in=s;
 1102:   }
 1103:   while ( *in != '\0'){
 1104:     *blocc++ = *in++;
 1105:   }
 1106: 
 1107:   *blocc='\0';
 1108:   return t;
 1109: }
 1110: char *cutv(char *blocc, char *alocc, char *in, char occ)
 1111: {
 1112:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
 1113:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
 1114:      gives blocc="abcdef2ghi" and alocc="j".
 1115:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
 1116:   */
 1117:   char *s, *t;
 1118:   t=in;s=in;
 1119:   while (*in != '\0'){
 1120:     while( *in == occ){
 1121:       *blocc++ = *in++;
 1122:       s=in;
 1123:     }
 1124:     *blocc++ = *in++;
 1125:   }
 1126:   if (s == t) /* occ not found */
 1127:     *(blocc-(in-s))='\0';
 1128:   else
 1129:     *(blocc-(in-s)-1)='\0';
 1130:   in=s;
 1131:   while ( *in != '\0'){
 1132:     *alocc++ = *in++;
 1133:   }
 1134: 
 1135:   *alocc='\0';
 1136:   return s;
 1137: }
 1138: 
 1139: int nbocc(char *s, char occ)
 1140: {
 1141:   int i,j=0;
 1142:   int lg=20;
 1143:   i=0;
 1144:   lg=strlen(s);
 1145:   for(i=0; i<= lg; i++) {
 1146:   if  (s[i] == occ ) j++;
 1147:   }
 1148:   return j;
 1149: }
 1150: 
 1151: /* void cutv(char *u,char *v, char*t, char occ) */
 1152: /* { */
 1153: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
 1154: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
 1155: /*      gives u="abcdef2ghi" and v="j" *\/ */
 1156: /*   int i,lg,j,p=0; */
 1157: /*   i=0; */
 1158: /*   lg=strlen(t); */
 1159: /*   for(j=0; j<=lg-1; j++) { */
 1160: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
 1161: /*   } */
 1162: 
 1163: /*   for(j=0; j<p; j++) { */
 1164: /*     (u[j] = t[j]); */
 1165: /*   } */
 1166: /*      u[p]='\0'; */
 1167: 
 1168: /*    for(j=0; j<= lg; j++) { */
 1169: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
 1170: /*   } */
 1171: /* } */
 1172: 
 1173: #ifdef _WIN32
 1174: char * strsep(char **pp, const char *delim)
 1175: {
 1176:   char *p, *q;
 1177:          
 1178:   if ((p = *pp) == NULL)
 1179:     return 0;
 1180:   if ((q = strpbrk (p, delim)) != NULL)
 1181:   {
 1182:     *pp = q + 1;
 1183:     *q = '\0';
 1184:   }
 1185:   else
 1186:     *pp = 0;
 1187:   return p;
 1188: }
 1189: #endif
 1190: 
 1191: /********************** nrerror ********************/
 1192: 
 1193: void nrerror(char error_text[])
 1194: {
 1195:   fprintf(stderr,"ERREUR ...\n");
 1196:   fprintf(stderr,"%s\n",error_text);
 1197:   exit(EXIT_FAILURE);
 1198: }
 1199: /*********************** vector *******************/
 1200: double *vector(int nl, int nh)
 1201: {
 1202:   double *v;
 1203:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
 1204:   if (!v) nrerror("allocation failure in vector");
 1205:   return v-nl+NR_END;
 1206: }
 1207: 
 1208: /************************ free vector ******************/
 1209: void free_vector(double*v, int nl, int nh)
 1210: {
 1211:   free((FREE_ARG)(v+nl-NR_END));
 1212: }
 1213: 
 1214: /************************ivector *******************************/
 1215: int *ivector(long nl,long nh)
 1216: {
 1217:   int *v;
 1218:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
 1219:   if (!v) nrerror("allocation failure in ivector");
 1220:   return v-nl+NR_END;
 1221: }
 1222: 
 1223: /******************free ivector **************************/
 1224: void free_ivector(int *v, long nl, long nh)
 1225: {
 1226:   free((FREE_ARG)(v+nl-NR_END));
 1227: }
 1228: 
 1229: /************************lvector *******************************/
 1230: long *lvector(long nl,long nh)
 1231: {
 1232:   long *v;
 1233:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
 1234:   if (!v) nrerror("allocation failure in ivector");
 1235:   return v-nl+NR_END;
 1236: }
 1237: 
 1238: /******************free lvector **************************/
 1239: void free_lvector(long *v, long nl, long nh)
 1240: {
 1241:   free((FREE_ARG)(v+nl-NR_END));
 1242: }
 1243: 
 1244: /******************* imatrix *******************************/
 1245: int **imatrix(long nrl, long nrh, long ncl, long nch) 
 1246:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
 1247: { 
 1248:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
 1249:   int **m; 
 1250:   
 1251:   /* allocate pointers to rows */ 
 1252:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
 1253:   if (!m) nrerror("allocation failure 1 in matrix()"); 
 1254:   m += NR_END; 
 1255:   m -= nrl; 
 1256:   
 1257:   
 1258:   /* allocate rows and set pointers to them */ 
 1259:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
 1260:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
 1261:   m[nrl] += NR_END; 
 1262:   m[nrl] -= ncl; 
 1263:   
 1264:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
 1265:   
 1266:   /* return pointer to array of pointers to rows */ 
 1267:   return m; 
 1268: } 
 1269: 
 1270: /****************** free_imatrix *************************/
 1271: void free_imatrix(m,nrl,nrh,ncl,nch)
 1272:       int **m;
 1273:       long nch,ncl,nrh,nrl; 
 1274:      /* free an int matrix allocated by imatrix() */ 
 1275: { 
 1276:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
 1277:   free((FREE_ARG) (m+nrl-NR_END)); 
 1278: } 
 1279: 
 1280: /******************* matrix *******************************/
 1281: double **matrix(long nrl, long nrh, long ncl, long nch)
 1282: {
 1283:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
 1284:   double **m;
 1285: 
 1286:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1287:   if (!m) nrerror("allocation failure 1 in matrix()");
 1288:   m += NR_END;
 1289:   m -= nrl;
 1290: 
 1291:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1292:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1293:   m[nrl] += NR_END;
 1294:   m[nrl] -= ncl;
 1295: 
 1296:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1297:   return m;
 1298:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
 1299: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
 1300: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
 1301:    */
 1302: }
 1303: 
 1304: /*************************free matrix ************************/
 1305: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
 1306: {
 1307:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1308:   free((FREE_ARG)(m+nrl-NR_END));
 1309: }
 1310: 
 1311: /******************* ma3x *******************************/
 1312: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
 1313: {
 1314:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
 1315:   double ***m;
 1316: 
 1317:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1318:   if (!m) nrerror("allocation failure 1 in matrix()");
 1319:   m += NR_END;
 1320:   m -= nrl;
 1321: 
 1322:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1323:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1324:   m[nrl] += NR_END;
 1325:   m[nrl] -= ncl;
 1326: 
 1327:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1328: 
 1329:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
 1330:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
 1331:   m[nrl][ncl] += NR_END;
 1332:   m[nrl][ncl] -= nll;
 1333:   for (j=ncl+1; j<=nch; j++) 
 1334:     m[nrl][j]=m[nrl][j-1]+nlay;
 1335:   
 1336:   for (i=nrl+1; i<=nrh; i++) {
 1337:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
 1338:     for (j=ncl+1; j<=nch; j++) 
 1339:       m[i][j]=m[i][j-1]+nlay;
 1340:   }
 1341:   return m; 
 1342:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
 1343:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
 1344:   */
 1345: }
 1346: 
 1347: /*************************free ma3x ************************/
 1348: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
 1349: {
 1350:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
 1351:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1352:   free((FREE_ARG)(m+nrl-NR_END));
 1353: }
 1354: 
 1355: /*************** function subdirf ***********/
 1356: char *subdirf(char fileres[])
 1357: {
 1358:   /* Caution optionfilefiname is hidden */
 1359:   strcpy(tmpout,optionfilefiname);
 1360:   strcat(tmpout,"/"); /* Add to the right */
 1361:   strcat(tmpout,fileres);
 1362:   return tmpout;
 1363: }
 1364: 
 1365: /*************** function subdirf2 ***********/
 1366: char *subdirf2(char fileres[], char *preop)
 1367: {
 1368:   
 1369:   /* Caution optionfilefiname is hidden */
 1370:   strcpy(tmpout,optionfilefiname);
 1371:   strcat(tmpout,"/");
 1372:   strcat(tmpout,preop);
 1373:   strcat(tmpout,fileres);
 1374:   return tmpout;
 1375: }
 1376: 
 1377: /*************** function subdirf3 ***********/
 1378: char *subdirf3(char fileres[], char *preop, char *preop2)
 1379: {
 1380:   
 1381:   /* Caution optionfilefiname is hidden */
 1382:   strcpy(tmpout,optionfilefiname);
 1383:   strcat(tmpout,"/");
 1384:   strcat(tmpout,preop);
 1385:   strcat(tmpout,preop2);
 1386:   strcat(tmpout,fileres);
 1387:   return tmpout;
 1388: }
 1389: 
 1390: char *asc_diff_time(long time_sec, char ascdiff[])
 1391: {
 1392:   long sec_left, days, hours, minutes;
 1393:   days = (time_sec) / (60*60*24);
 1394:   sec_left = (time_sec) % (60*60*24);
 1395:   hours = (sec_left) / (60*60) ;
 1396:   sec_left = (sec_left) %(60*60);
 1397:   minutes = (sec_left) /60;
 1398:   sec_left = (sec_left) % (60);
 1399:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
 1400:   return ascdiff;
 1401: }
 1402: 
 1403: /***************** f1dim *************************/
 1404: extern int ncom; 
 1405: extern double *pcom,*xicom;
 1406: extern double (*nrfunc)(double []); 
 1407:  
 1408: double f1dim(double x) 
 1409: { 
 1410:   int j; 
 1411:   double f;
 1412:   double *xt; 
 1413:  
 1414:   xt=vector(1,ncom); 
 1415:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
 1416:   f=(*nrfunc)(xt); 
 1417:   free_vector(xt,1,ncom); 
 1418:   return f; 
 1419: } 
 1420: 
 1421: /*****************brent *************************/
 1422: double brent(double ax, double bx, double cx, double (*f)(double), double tol, 	double *xmin) 
 1423: {
 1424:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
 1425:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
 1426:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
 1427:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
 1428:    * returned function value. 
 1429:   */
 1430:   int iter; 
 1431:   double a,b,d,etemp;
 1432:   double fu=0,fv,fw,fx;
 1433:   double ftemp=0.;
 1434:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
 1435:   double e=0.0; 
 1436:  
 1437:   a=(ax < cx ? ax : cx); 
 1438:   b=(ax > cx ? ax : cx); 
 1439:   x=w=v=bx; 
 1440:   fw=fv=fx=(*f)(x); 
 1441:   for (iter=1;iter<=ITMAX;iter++) { 
 1442:     xm=0.5*(a+b); 
 1443:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
 1444:     /*		if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
 1445:     printf(".");fflush(stdout);
 1446:     fprintf(ficlog,".");fflush(ficlog);
 1447: #ifdef DEBUGBRENT
 1448:     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);
 1449:     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);
 1450:     /*		if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
 1451: #endif
 1452:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
 1453:       *xmin=x; 
 1454:       return fx; 
 1455:     } 
 1456:     ftemp=fu;
 1457:     if (fabs(e) > tol1) { 
 1458:       r=(x-w)*(fx-fv); 
 1459:       q=(x-v)*(fx-fw); 
 1460:       p=(x-v)*q-(x-w)*r; 
 1461:       q=2.0*(q-r); 
 1462:       if (q > 0.0) p = -p; 
 1463:       q=fabs(q); 
 1464:       etemp=e; 
 1465:       e=d; 
 1466:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
 1467: 	d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1468:       else { 
 1469: 	d=p/q; 
 1470: 	u=x+d; 
 1471: 	if (u-a < tol2 || b-u < tol2) 
 1472: 	  d=SIGN(tol1,xm-x); 
 1473:       } 
 1474:     } else { 
 1475:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1476:     } 
 1477:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
 1478:     fu=(*f)(u); 
 1479:     if (fu <= fx) { 
 1480:       if (u >= x) a=x; else b=x; 
 1481:       SHFT(v,w,x,u) 
 1482:       SHFT(fv,fw,fx,fu) 
 1483:     } else { 
 1484:       if (u < x) a=u; else b=u; 
 1485:       if (fu <= fw || w == x) { 
 1486: 	v=w; 
 1487: 	w=u; 
 1488: 	fv=fw; 
 1489: 	fw=fu; 
 1490:       } else if (fu <= fv || v == x || v == w) { 
 1491: 	v=u; 
 1492: 	fv=fu; 
 1493:       } 
 1494:     } 
 1495:   } 
 1496:   nrerror("Too many iterations in brent"); 
 1497:   *xmin=x; 
 1498:   return fx; 
 1499: } 
 1500: 
 1501: /****************** mnbrak ***********************/
 1502: 
 1503: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
 1504: 	    double (*func)(double)) 
 1505: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
 1506: the downhill direction (defined by the function as evaluated at the initial points) and returns
 1507: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
 1508: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
 1509:    */
 1510:   double ulim,u,r,q, dum;
 1511:   double fu; 
 1512: 
 1513:   double scale=10.;
 1514:   int iterscale=0;
 1515: 
 1516:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
 1517:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
 1518: 
 1519: 
 1520:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
 1521:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
 1522:   /*   *bx = *ax - (*ax - *bx)/scale; */
 1523:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
 1524:   /* } */
 1525: 
 1526:   if (*fb > *fa) { 
 1527:     SHFT(dum,*ax,*bx,dum) 
 1528:     SHFT(dum,*fb,*fa,dum) 
 1529:   } 
 1530:   *cx=(*bx)+GOLD*(*bx-*ax); 
 1531:   *fc=(*func)(*cx); 
 1532: #ifdef DEBUG
 1533:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
 1534:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
 1535: #endif
 1536:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
 1537:     r=(*bx-*ax)*(*fb-*fc); 
 1538:     q=(*bx-*cx)*(*fb-*fa); 
 1539:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
 1540:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
 1541:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
 1542:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
 1543:       fu=(*func)(u); 
 1544: #ifdef DEBUG
 1545:       /* f(x)=A(x-u)**2+f(u) */
 1546:       double A, fparabu; 
 1547:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 1548:       fparabu= *fa - A*(*ax-u)*(*ax-u);
 1549:       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);
 1550:       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);
 1551:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
 1552:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
 1553:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
 1554:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
 1555: #endif 
 1556: #ifdef MNBRAKORIGINAL
 1557: #else
 1558: /*       if (fu > *fc) { */
 1559: /* #ifdef DEBUG */
 1560: /*       printf("mnbrak4  fu > fc \n"); */
 1561: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
 1562: /* #endif */
 1563: /* 	/\* 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 *\\/  *\/ */
 1564: /* 	/\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
 1565: /* 	dum=u; /\* Shifting c and u *\/ */
 1566: /* 	u = *cx; */
 1567: /* 	*cx = dum; */
 1568: /* 	dum = fu; */
 1569: /* 	fu = *fc; */
 1570: /* 	*fc =dum; */
 1571: /*       } else { /\* end *\/ */
 1572: /* #ifdef DEBUG */
 1573: /*       printf("mnbrak3  fu < fc \n"); */
 1574: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
 1575: /* #endif */
 1576: /* 	dum=u; /\* Shifting c and u *\/ */
 1577: /* 	u = *cx; */
 1578: /* 	*cx = dum; */
 1579: /* 	dum = fu; */
 1580: /* 	fu = *fc; */
 1581: /* 	*fc =dum; */
 1582: /*       } */
 1583: #ifdef DEBUG
 1584:       printf("mnbrak34  fu < or >= fc \n");
 1585:       fprintf(ficlog, "mnbrak34 fu < fc\n");
 1586: #endif
 1587:       dum=u; /* Shifting c and u */
 1588:       u = *cx;
 1589:       *cx = dum;
 1590:       dum = fu;
 1591:       fu = *fc;
 1592:       *fc =dum;
 1593: #endif
 1594:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
 1595: #ifdef DEBUG
 1596:       printf("mnbrak2  u after c but before ulim\n");
 1597:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
 1598: #endif
 1599:       fu=(*func)(u); 
 1600:       if (fu < *fc) { 
 1601: #ifdef DEBUG
 1602:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
 1603:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
 1604: #endif
 1605: 	SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
 1606: 	SHFT(*fb,*fc,fu,(*func)(u)) 
 1607:       } 
 1608:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
 1609: #ifdef DEBUG
 1610:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
 1611:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
 1612: #endif
 1613:       u=ulim; 
 1614:       fu=(*func)(u); 
 1615:     } else { /* u could be left to b (if r > q parabola has a maximum) */
 1616: #ifdef DEBUG
 1617:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
 1618:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
 1619: #endif
 1620:       u=(*cx)+GOLD*(*cx-*bx); 
 1621:       fu=(*func)(u); 
 1622:     } /* end tests */
 1623:     SHFT(*ax,*bx,*cx,u) 
 1624:     SHFT(*fa,*fb,*fc,fu) 
 1625: #ifdef DEBUG
 1626:       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);
 1627:       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);
 1628: #endif
 1629:   } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
 1630: } 
 1631: 
 1632: /*************** linmin ************************/
 1633: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
 1634: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
 1635: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
 1636: the value of func at the returned location p . This is actually all accomplished by calling the
 1637: routines mnbrak and brent .*/
 1638: int ncom; 
 1639: double *pcom,*xicom;
 1640: double (*nrfunc)(double []); 
 1641:  
 1642: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
 1643: { 
 1644:   double brent(double ax, double bx, double cx, 
 1645: 	       double (*f)(double), double tol, double *xmin); 
 1646:   double f1dim(double x); 
 1647:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
 1648: 	      double *fc, double (*func)(double)); 
 1649:   int j; 
 1650:   double xx,xmin,bx,ax; 
 1651:   double fx,fb,fa;
 1652: 
 1653: #ifdef LINMINORIGINAL
 1654: #else
 1655:   double scale=10., axs, xxs; /* Scale added for infinity */
 1656: #endif
 1657:   
 1658:   ncom=n; 
 1659:   pcom=vector(1,n); 
 1660:   xicom=vector(1,n); 
 1661:   nrfunc=func; 
 1662:   for (j=1;j<=n;j++) { 
 1663:     pcom[j]=p[j]; 
 1664:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
 1665:   } 
 1666: 
 1667: #ifdef LINMINORIGINAL
 1668:   xx=1.;
 1669: #else
 1670:   axs=0.0;
 1671:   xxs=1.;
 1672:   do{
 1673:     xx= xxs;
 1674: #endif
 1675:     ax=0.;
 1676:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
 1677:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
 1678:     /* 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))   */
 1679:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
 1680:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
 1681:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
 1682:     /* 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]]*/
 1683: #ifdef LINMINORIGINAL
 1684: #else
 1685:     if (fx != fx){
 1686:   	xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
 1687: 	printf("|");
 1688: 	fprintf(ficlog,"|");
 1689: #ifdef DEBUGLINMIN
 1690:   	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);
 1691: #endif
 1692:     }
 1693:   }while(fx != fx);
 1694: #endif
 1695:   
 1696: #ifdef DEBUGLINMIN
 1697:   printf("\nLinmin after mnbrak: ax=%12.7f xx=%12.7f bx=%12.7f fa=%12.2f fx=%12.2f fb=%12.2f\n",  ax,xx,bx,fa,fx,fb);
 1698:   fprintf(ficlog,"\nLinmin after mnbrak: ax=%12.7f xx=%12.7f bx=%12.7f fa=%12.2f fx=%12.2f fb=%12.2f\n",  ax,xx,bx,fa,fx,fb);
 1699: #endif
 1700:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
 1701:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
 1702:   /* fmin = f(p[j] + xmin * xi[j]) */
 1703:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
 1704:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
 1705: #ifdef DEBUG
 1706:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1707:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1708: #endif
 1709: #ifdef DEBUGLINMIN
 1710:   printf("linmin end ");
 1711:   fprintf(ficlog,"linmin end ");
 1712: #endif
 1713:   for (j=1;j<=n;j++) { 
 1714: #ifdef LINMINORIGINAL
 1715:     xi[j] *= xmin; 
 1716: #else
 1717: #ifdef DEBUGLINMIN
 1718:     if(xxs <1.0)
 1719:       printf(" before xi[%d]=%12.8f", j,xi[j]);
 1720: #endif
 1721:     xi[j] *= xmin*xxs; /* xi rescaled by xmin and number of loops: if xmin=-1.237 and xi=(1,0,...,0) xi=(-1.237,0,...,0) */
 1722: #ifdef DEBUGLINMIN
 1723:     if(xxs <1.0)
 1724:       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 );
 1725: #endif
 1726: #endif
 1727:     p[j] += xi[j]; /* Parameters values are updated accordingly */
 1728:   } 
 1729: #ifdef DEBUGLINMIN
 1730:   printf("\n");
 1731:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
 1732:   fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
 1733:   for (j=1;j<=n;j++) { 
 1734:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
 1735:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
 1736:     if(j % ncovmodel == 0){
 1737:       printf("\n");
 1738:       fprintf(ficlog,"\n");
 1739:     }
 1740:   }
 1741: #else
 1742: #endif
 1743:   free_vector(xicom,1,n); 
 1744:   free_vector(pcom,1,n); 
 1745: } 
 1746: 
 1747: 
 1748: /*************** powell ************************/
 1749: /*
 1750: Minimization of a function func of n variables. Input consists of an initial starting point
 1751: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
 1752: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
 1753: such that failure to decrease by more than this amount on one iteration signals doneness. On
 1754: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
 1755: function value at p , and iter is the number of iterations taken. The routine linmin is used.
 1756:  */
 1757: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
 1758: 	    double (*func)(double [])) 
 1759: { 
 1760:   void linmin(double p[], double xi[], int n, double *fret, 
 1761: 	      double (*func)(double [])); 
 1762:   int i,ibig,j; 
 1763:   double del,t,*pt,*ptt,*xit;
 1764:   double directest;
 1765:   double fp,fptt;
 1766:   double *xits;
 1767:   int niterf, itmp;
 1768: 
 1769:   pt=vector(1,n); 
 1770:   ptt=vector(1,n); 
 1771:   xit=vector(1,n); 
 1772:   xits=vector(1,n); 
 1773:   *fret=(*func)(p); 
 1774:   for (j=1;j<=n;j++) pt[j]=p[j]; 
 1775:   rcurr_time = time(NULL);  
 1776:   for (*iter=1;;++(*iter)) { 
 1777:     fp=(*fret); /* From former iteration or initial value */
 1778:     ibig=0; 
 1779:     del=0.0; 
 1780:     rlast_time=rcurr_time;
 1781:     /* (void) gettimeofday(&curr_time,&tzp); */
 1782:     rcurr_time = time(NULL);  
 1783:     curr_time = *localtime(&rcurr_time);
 1784:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
 1785:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
 1786: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
 1787:     for (i=1;i<=n;i++) {
 1788:       printf(" %d %.12f",i, p[i]);
 1789:       fprintf(ficlog," %d %.12lf",i, p[i]);
 1790:       fprintf(ficrespow," %.12lf", p[i]);
 1791:     }
 1792:     printf("\n");
 1793:     fprintf(ficlog,"\n");
 1794:     fprintf(ficrespow,"\n");fflush(ficrespow);
 1795:     if(*iter <=3){
 1796:       tml = *localtime(&rcurr_time);
 1797:       strcpy(strcurr,asctime(&tml));
 1798:       rforecast_time=rcurr_time; 
 1799:       itmp = strlen(strcurr);
 1800:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
 1801: 	strcurr[itmp-1]='\0';
 1802:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1803:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1804:       for(niterf=10;niterf<=30;niterf+=10){
 1805: 	rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
 1806: 	forecast_time = *localtime(&rforecast_time);
 1807: 	strcpy(strfor,asctime(&forecast_time));
 1808: 	itmp = strlen(strfor);
 1809: 	if(strfor[itmp-1]=='\n')
 1810: 	strfor[itmp-1]='\0';
 1811: 	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);
 1812: 	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);
 1813:       }
 1814:     }
 1815:     for (i=1;i<=n;i++) { /* For each direction i */
 1816:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
 1817:       fptt=(*fret); 
 1818: #ifdef DEBUG
 1819:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1820:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1821: #endif
 1822:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
 1823:       fprintf(ficlog,"%d",i);fflush(ficlog);
 1824:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
 1825: 				    /* Outputs are fret(new point p) p is updated and xit rescaled */
 1826:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
 1827: 	/* because that direction will be replaced unless the gain del is small */
 1828: 	/* in comparison with the 'probable' gain, mu^2, with the last average direction. */
 1829: 	/* Unless the n directions are conjugate some gain in the determinant may be obtained */
 1830: 	/* with the new direction. */
 1831: 	del=fabs(fptt-(*fret)); 
 1832: 	ibig=i; 
 1833:       } 
 1834: #ifdef DEBUG
 1835:       printf("%d %.12e",i,(*fret));
 1836:       fprintf(ficlog,"%d %.12e",i,(*fret));
 1837:       for (j=1;j<=n;j++) {
 1838: 	xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
 1839: 	printf(" x(%d)=%.12e",j,xit[j]);
 1840: 	fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
 1841:       }
 1842:       for(j=1;j<=n;j++) {
 1843: 	printf(" p(%d)=%.12e",j,p[j]);
 1844: 	fprintf(ficlog," p(%d)=%.12e",j,p[j]);
 1845:       }
 1846:       printf("\n");
 1847:       fprintf(ficlog,"\n");
 1848: #endif
 1849:     } /* end loop on each direction i */
 1850:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
 1851:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
 1852:     /* New value of last point Pn is not computed, P(n-1) */
 1853:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
 1854:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
 1855:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
 1856:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
 1857:       /* decreased of more than 3.84  */
 1858:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
 1859:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
 1860:       /* By adding 10 parameters more the gain should be 18.31 */
 1861: 
 1862:       /* Starting the program with initial values given by a former maximization will simply change */
 1863:       /* the scales of the directions and the directions, because the are reset to canonical directions */
 1864:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
 1865:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
 1866: #ifdef DEBUG
 1867:       int k[2],l;
 1868:       k[0]=1;
 1869:       k[1]=-1;
 1870:       printf("Max: %.12e",(*func)(p));
 1871:       fprintf(ficlog,"Max: %.12e",(*func)(p));
 1872:       for (j=1;j<=n;j++) {
 1873: 	printf(" %.12e",p[j]);
 1874: 	fprintf(ficlog," %.12e",p[j]);
 1875:       }
 1876:       printf("\n");
 1877:       fprintf(ficlog,"\n");
 1878:       for(l=0;l<=1;l++) {
 1879: 	for (j=1;j<=n;j++) {
 1880: 	  ptt[j]=p[j]+(p[j]-pt[j])*k[l];
 1881: 	  printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1882: 	  fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1883: 	}
 1884: 	printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1885: 	fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1886:       }
 1887: #endif
 1888: 
 1889: 
 1890:       free_vector(xit,1,n); 
 1891:       free_vector(xits,1,n); 
 1892:       free_vector(ptt,1,n); 
 1893:       free_vector(pt,1,n); 
 1894:       return; 
 1895:     } /* enough precision */ 
 1896:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
 1897:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
 1898:       ptt[j]=2.0*p[j]-pt[j]; 
 1899:       xit[j]=p[j]-pt[j]; 
 1900:       pt[j]=p[j]; 
 1901:     } 
 1902:     fptt=(*func)(ptt); /* f_3 */
 1903: #ifdef POWELLF1F3
 1904: #else
 1905:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
 1906: #endif
 1907:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
 1908:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
 1909:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
 1910:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
 1911:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
 1912:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
 1913:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
 1914: #ifdef NRCORIGINAL
 1915:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
 1916: #else
 1917:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
 1918:       t= t- del*SQR(fp-fptt);
 1919: #endif
 1920:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
 1921: #ifdef DEBUG
 1922:       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);
 1923:       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);
 1924:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 1925: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 1926:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 1927: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 1928:       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);
 1929:       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);
 1930: #endif
 1931: #ifdef POWELLORIGINAL
 1932:       if (t < 0.0) { /* Then we use it for new direction */
 1933: #else
 1934:       if (directest*t < 0.0) { /* Contradiction between both tests */
 1935: 	printf("directest= %.12lf (if <0 we include P0 Pn as new direction), t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
 1936:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 1937:         fprintf(ficlog,"directest= %.12lf (if <0 we include P0 Pn as new direction), t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
 1938:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 1939:       } 
 1940:       if (directest < 0.0) { /* Then we use it for new direction */
 1941: #endif
 1942: #ifdef DEBUGLINMIN
 1943: 	printf("Before linmin in direction P%d-P0\n",n);
 1944: 	for (j=1;j<=n;j++) { 
 1945: 	  printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 1946: 	  fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 1947: 	  if(j % ncovmodel == 0){
 1948: 	    printf("\n");
 1949: 	    fprintf(ficlog,"\n");
 1950: 	  }
 1951: 	}
 1952: #endif
 1953: 	linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
 1954: #ifdef DEBUGLINMIN
 1955: 	for (j=1;j<=n;j++) { 
 1956: 	  printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 1957: 	  fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 1958: 	  if(j % ncovmodel == 0){
 1959: 	    printf("\n");
 1960: 	    fprintf(ficlog,"\n");
 1961: 	  }
 1962: 	}
 1963: #endif
 1964: 	for (j=1;j<=n;j++) { 
 1965: 	  xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
 1966: 	  xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
 1967: 	}
 1968: 	printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 1969: 	fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 1970: 
 1971: #ifdef DEBUG
 1972: 	printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1973: 	fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1974: 	for(j=1;j<=n;j++){
 1975: 	  printf(" %.12e",xit[j]);
 1976: 	  fprintf(ficlog," %.12e",xit[j]);
 1977: 	}
 1978: 	printf("\n");
 1979: 	fprintf(ficlog,"\n");
 1980: #endif
 1981:       } /* end of t or directest negative */
 1982: #ifdef POWELLF1F3
 1983: #else
 1984:     } /* end if (fptt < fp)  */
 1985: #endif
 1986:   } /* loop iteration */ 
 1987: } 
 1988: 
 1989: /**** Prevalence limit (stable or period prevalence)  ****************/
 1990: 
 1991: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
 1992: {
 1993:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
 1994:      matrix by transitions matrix until convergence is reached with precision ftolpl */
 1995:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
 1996:   /* Wx is row vector: population in state 1, population in state 2, population dead */
 1997:   /* or prevalence in state 1, prevalence in state 2, 0 */
 1998:   /* newm is the matrix after multiplications, its rows are identical at a factor */
 1999:   /* Initial matrix pimij */
 2000:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
 2001:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
 2002:   /*  0,                   0                  , 1} */
 2003:   /*
 2004:    * and after some iteration: */
 2005:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
 2006:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
 2007:   /*  0,                   0                  , 1} */
 2008:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
 2009:   /* {0.51571254859325999, 0.4842874514067399, */
 2010:   /*  0.51326036147820708, 0.48673963852179264} */
 2011:   /* If we start from prlim again, prlim tends to a constant matrix */
 2012: 
 2013:   int i, ii,j,k;
 2014:   double *min, *max, *meandiff, maxmax,sumnew=0.;
 2015:   /* double **matprod2(); */ /* test */
 2016:   double **out, cov[NCOVMAX+1], **pmij();
 2017:   double **newm;
 2018:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
 2019:   int ncvloop=0;
 2020:   
 2021:   min=vector(1,nlstate);
 2022:   max=vector(1,nlstate);
 2023:   meandiff=vector(1,nlstate);
 2024: 
 2025:   for (ii=1;ii<=nlstate+ndeath;ii++)
 2026:     for (j=1;j<=nlstate+ndeath;j++){
 2027:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2028:     }
 2029:   
 2030:   cov[1]=1.;
 2031:   
 2032:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2033:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
 2034:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
 2035:     ncvloop++;
 2036:     newm=savm;
 2037:     /* Covariates have to be included here again */
 2038:     cov[2]=agefin;
 2039:     if(nagesqr==1)
 2040:       cov[3]= agefin*agefin;;
 2041:     for (k=1; k<=cptcovn;k++) {
 2042:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 2043:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 2044:       /* printf("prevalim ij=%d k=%d Tvar[%d]=%d nbcode=%d cov=%lf codtabm(%d,Tvar[%d])=%d \n",ij,k, k, Tvar[k],nbcode[Tvar[k]][codtabm(ij,Tvar[k])],cov[2+k], ij, k, codtabm(ij,Tvar[k])]); */
 2045:     }
 2046:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2047:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
 2048:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
 2049:     for (k=1; k<=cptcovprod;k++) /* Useless */
 2050:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 2051:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
 2052:     
 2053:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 2054:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 2055:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 2056:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2057:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 2058:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
 2059:     
 2060:     savm=oldm;
 2061:     oldm=newm;
 2062: 
 2063:     for(j=1; j<=nlstate; j++){
 2064:       max[j]=0.;
 2065:       min[j]=1.;
 2066:     }
 2067:     for(i=1;i<=nlstate;i++){
 2068:       sumnew=0;
 2069:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
 2070:       for(j=1; j<=nlstate; j++){ 
 2071: 	prlim[i][j]= newm[i][j]/(1-sumnew);
 2072: 	max[j]=FMAX(max[j],prlim[i][j]);
 2073: 	min[j]=FMIN(min[j],prlim[i][j]);
 2074:       }
 2075:     }
 2076: 
 2077:     maxmax=0.;
 2078:     for(j=1; j<=nlstate; j++){
 2079:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
 2080:       maxmax=FMAX(maxmax,meandiff[j]);
 2081:       /* printf(" age= %d meandiff[%d]=%f, agefin=%d max[%d]=%f min[%d]=%f maxmax=%f\n", (int)age, j, meandiff[j],(int)agefin, j, max[j], j, min[j],maxmax); */
 2082:     } /* j loop */
 2083:     *ncvyear= (int)age- (int)agefin;
 2084:     /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
 2085:     if(maxmax < ftolpl){
 2086:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
 2087:       free_vector(min,1,nlstate);
 2088:       free_vector(max,1,nlstate);
 2089:       free_vector(meandiff,1,nlstate);
 2090:       return prlim;
 2091:     }
 2092:   } /* age loop */
 2093:     /* After some age loop it doesn't converge */
 2094:   printf("Warning: the stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.0f years. Try to lower 'ftolpl'. \n\
 2095: Earliest age to start was %d-%d=%d, ncvloop=%d, ncvyear=%d\n", (int)age, maxmax, ftolpl, delaymax, (int)age, (int)delaymax, (int)agefin, ncvloop, *ncvyear);
 2096:   /* Try to lower 'ftol', for example from 1.e-8 to 6.e-9.\n", ftolpl, (int)age, (int)delaymax, (int)agefin, ncvloop, (int)age-(int)agefin); */
 2097:   free_vector(min,1,nlstate);
 2098:   free_vector(max,1,nlstate);
 2099:   free_vector(meandiff,1,nlstate);
 2100:   
 2101:   return prlim; /* should not reach here */
 2102: }
 2103: 
 2104: /*************** transition probabilities ***************/ 
 2105: 
 2106: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 2107: {
 2108:   /* According to parameters values stored in x and the covariate's values stored in cov,
 2109:      computes the probability to be observed in state j being in state i by appying the
 2110:      model to the ncovmodel covariates (including constant and age).
 2111:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 2112:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 2113:      ncth covariate in the global vector x is given by the formula:
 2114:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 2115:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 2116:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 2117:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 2118:      Outputs ps[i][j] the probability to be observed in j being in j according to
 2119:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 2120:   */
 2121:   double s1, lnpijopii;
 2122:   /*double t34;*/
 2123:   int i,j, nc, ii, jj;
 2124: 
 2125:     for(i=1; i<= nlstate; i++){
 2126:       for(j=1; j<i;j++){
 2127: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2128: 	  /*lnpijopii += param[i][j][nc]*cov[nc];*/
 2129: 	  lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 2130: /* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2131: 	}
 2132: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2133: /* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2134:       }
 2135:       for(j=i+1; j<=nlstate+ndeath;j++){
 2136: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2137: 	  /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 2138: 	  lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 2139: /* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 2140: 	}
 2141: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2142:       }
 2143:     }
 2144:     
 2145:     for(i=1; i<= nlstate; i++){
 2146:       s1=0;
 2147:       for(j=1; j<i; j++){
 2148: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2149: 	/*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2150:       }
 2151:       for(j=i+1; j<=nlstate+ndeath; j++){
 2152: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2153: 	/*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2154:       }
 2155:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 2156:       ps[i][i]=1./(s1+1.);
 2157:       /* Computing other pijs */
 2158:       for(j=1; j<i; j++)
 2159: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 2160:       for(j=i+1; j<=nlstate+ndeath; j++)
 2161: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 2162:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 2163:     } /* end i */
 2164:     
 2165:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 2166:       for(jj=1; jj<= nlstate+ndeath; jj++){
 2167: 	ps[ii][jj]=0;
 2168: 	ps[ii][ii]=1;
 2169:       }
 2170:     }
 2171:     
 2172:     
 2173:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 2174:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 2175:     /* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 2176:     /*   } */
 2177:     /*   printf("\n "); */
 2178:     /* } */
 2179:     /* printf("\n ");printf("%lf ",cov[2]);*/
 2180:     /*
 2181:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
 2182:       goto end;*/
 2183:     return ps;
 2184: }
 2185: 
 2186: /**************** Product of 2 matrices ******************/
 2187: 
 2188: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
 2189: {
 2190:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
 2191:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
 2192:   /* in, b, out are matrice of pointers which should have been initialized 
 2193:      before: only the contents of out is modified. The function returns
 2194:      a pointer to pointers identical to out */
 2195:   int i, j, k;
 2196:   for(i=nrl; i<= nrh; i++)
 2197:     for(k=ncolol; k<=ncoloh; k++){
 2198:       out[i][k]=0.;
 2199:       for(j=ncl; j<=nch; j++)
 2200:   	out[i][k] +=in[i][j]*b[j][k];
 2201:     }
 2202:   return out;
 2203: }
 2204: 
 2205: 
 2206: /************* Higher Matrix Product ***************/
 2207: 
 2208: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
 2209: {
 2210:   /* Computes the transition matrix starting at age 'age' over 
 2211:      'nhstepm*hstepm*stepm' months (i.e. until
 2212:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
 2213:      nhstepm*hstepm matrices. 
 2214:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
 2215:      (typically every 2 years instead of every month which is too big 
 2216:      for the memory).
 2217:      Model is determined by parameters x and covariates have to be 
 2218:      included manually here. 
 2219: 
 2220:      */
 2221: 
 2222:   int i, j, d, h, k;
 2223:   double **out, cov[NCOVMAX+1];
 2224:   double **newm;
 2225:   double agexact;
 2226: 
 2227:   /* Hstepm could be zero and should return the unit matrix */
 2228:   for (i=1;i<=nlstate+ndeath;i++)
 2229:     for (j=1;j<=nlstate+ndeath;j++){
 2230:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 2231:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 2232:     }
 2233:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2234:   for(h=1; h <=nhstepm; h++){
 2235:     for(d=1; d <=hstepm; d++){
 2236:       newm=savm;
 2237:       /* Covariates have to be included here again */
 2238:       cov[1]=1.;
 2239:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
 2240:       cov[2]=agexact;
 2241:       if(nagesqr==1)
 2242: 	cov[3]= agexact*agexact;
 2243:       for (k=1; k<=cptcovn;k++) 
 2244: 	cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 2245: 	/* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 2246:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
 2247: 	/* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2248: 	cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 2249: 	/* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
 2250:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
 2251: 	cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
 2252: 	/* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 2253: 
 2254: 
 2255:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 2256:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 2257:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
 2258: 		   pmij(pmmij,cov,ncovmodel,x,nlstate));
 2259:       savm=oldm;
 2260:       oldm=newm;
 2261:     }
 2262:     for(i=1; i<=nlstate+ndeath; i++)
 2263:       for(j=1;j<=nlstate+ndeath;j++) {
 2264: 	po[i][j][h]=newm[i][j];
 2265: 	/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 2266:       }
 2267:     /*printf("h=%d ",h);*/
 2268:   } /* end h */
 2269: /*     printf("\n H=%d \n",h); */
 2270:   return po;
 2271: }
 2272: 
 2273: #ifdef NLOPT
 2274:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
 2275:   double fret;
 2276:   double *xt;
 2277:   int j;
 2278:   myfunc_data *d2 = (myfunc_data *) pd;
 2279: /* xt = (p1-1); */
 2280:   xt=vector(1,n); 
 2281:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
 2282: 
 2283:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
 2284:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
 2285:   printf("Function = %.12lf ",fret);
 2286:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
 2287:   printf("\n");
 2288:  free_vector(xt,1,n);
 2289:   return fret;
 2290: }
 2291: #endif
 2292: 
 2293: /*************** log-likelihood *************/
 2294: double func( double *x)
 2295: {
 2296:   int i, ii, j, k, mi, d, kk;
 2297:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 2298:   double **out;
 2299:   double sw; /* Sum of weights */
 2300:   double lli; /* Individual log likelihood */
 2301:   int s1, s2;
 2302:   double bbh, survp;
 2303:   long ipmx;
 2304:   double agexact;
 2305:   /*extern weight */
 2306:   /* We are differentiating ll according to initial status */
 2307:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 2308:   /*for(i=1;i<imx;i++) 
 2309:     printf(" %d\n",s[4][i]);
 2310:   */
 2311: 
 2312:   ++countcallfunc;
 2313: 
 2314:   cov[1]=1.;
 2315: 
 2316:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 2317: 
 2318:   if(mle==1){
 2319:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2320:       /* Computes the values of the ncovmodel covariates of the model
 2321: 	 depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
 2322: 	 Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
 2323: 	 to be observed in j being in i according to the model.
 2324:        */
 2325:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
 2326: 	  cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2327:       }
 2328:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
 2329: 	 is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
 2330: 	 has been calculated etc */
 2331:       for(mi=1; mi<= wav[i]-1; mi++){
 2332: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2333: 	  for (j=1;j<=nlstate+ndeath;j++){
 2334: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2335: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2336: 	  }
 2337: 	for(d=0; d<dh[mi][i]; d++){
 2338: 	  newm=savm;
 2339: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2340: 	  cov[2]=agexact;
 2341: 	  if(nagesqr==1)
 2342: 	    cov[3]= agexact*agexact;
 2343: 	  for (kk=1; kk<=cptcovage;kk++) {
 2344: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
 2345: 	  }
 2346: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2347: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2348: 	  savm=oldm;
 2349: 	  oldm=newm;
 2350: 	} /* end mult */
 2351:       
 2352: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 2353: 	/* But now since version 0.9 we anticipate for bias at large stepm.
 2354: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 2355: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
 2356: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
 2357: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 2358: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
 2359: 	 * probability in order to take into account the bias as a fraction of the way
 2360: 	 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
 2361: 	 * -stepm/2 to stepm/2 .
 2362: 	 * For stepm=1 the results are the same as for previous versions of Imach.
 2363: 	 * For stepm > 1 the results are less biased than in previous versions. 
 2364: 	 */
 2365: 	s1=s[mw[mi][i]][i];
 2366: 	s2=s[mw[mi+1][i]][i];
 2367: 	bbh=(double)bh[mi][i]/(double)stepm; 
 2368: 	/* bias bh is positive if real duration
 2369: 	 * is higher than the multiple of stepm and negative otherwise.
 2370: 	 */
 2371: 	/* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
 2372: 	if( s2 > nlstate){ 
 2373: 	  /* i.e. if s2 is a death state and if the date of death is known 
 2374: 	     then the contribution to the likelihood is the probability to 
 2375: 	     die between last step unit time and current  step unit time, 
 2376: 	     which is also equal to probability to die before dh 
 2377: 	     minus probability to die before dh-stepm . 
 2378: 	     In version up to 0.92 likelihood was computed
 2379: 	as if date of death was unknown. Death was treated as any other
 2380: 	health state: the date of the interview describes the actual state
 2381: 	and not the date of a change in health state. The former idea was
 2382: 	to consider that at each interview the state was recorded
 2383: 	(healthy, disable or death) and IMaCh was corrected; but when we
 2384: 	introduced the exact date of death then we should have modified
 2385: 	the contribution of an exact death to the likelihood. This new
 2386: 	contribution is smaller and very dependent of the step unit
 2387: 	stepm. It is no more the probability to die between last interview
 2388: 	and month of death but the probability to survive from last
 2389: 	interview up to one month before death multiplied by the
 2390: 	probability to die within a month. Thanks to Chris
 2391: 	Jackson for correcting this bug.  Former versions increased
 2392: 	mortality artificially. The bad side is that we add another loop
 2393: 	which slows down the processing. The difference can be up to 10%
 2394: 	lower mortality.
 2395: 	  */
 2396: 	/* If, at the beginning of the maximization mostly, the
 2397: 	   cumulative probability or probability to be dead is
 2398: 	   constant (ie = 1) over time d, the difference is equal to
 2399: 	   0.  out[s1][3] = savm[s1][3]: probability, being at state
 2400: 	   s1 at precedent wave, to be dead a month before current
 2401: 	   wave is equal to probability, being at state s1 at
 2402: 	   precedent wave, to be dead at mont of the current
 2403: 	   wave. Then the observed probability (that this person died)
 2404: 	   is null according to current estimated parameter. In fact,
 2405: 	   it should be very low but not zero otherwise the log go to
 2406: 	   infinity.
 2407: 	*/
 2408: /* #ifdef INFINITYORIGINAL */
 2409: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 2410: /* #else */
 2411: /* 	  if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
 2412: /* 	    lli=log(mytinydouble); */
 2413: /* 	  else */
 2414: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 2415: /* #endif */
 2416: 	    lli=log(out[s1][s2] - savm[s1][s2]);
 2417: 
 2418: 	} else if  (s2==-2) {
 2419: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 2420: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2421: 	  /*survp += out[s1][j]; */
 2422: 	  lli= log(survp);
 2423: 	}
 2424: 	
 2425:  	else if  (s2==-4) { 
 2426: 	  for (j=3,survp=0. ; j<=nlstate; j++)  
 2427: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2428:  	  lli= log(survp); 
 2429:  	} 
 2430: 
 2431:  	else if  (s2==-5) { 
 2432:  	  for (j=1,survp=0. ; j<=2; j++)  
 2433: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2434:  	  lli= log(survp); 
 2435:  	} 
 2436: 	
 2437: 	else{
 2438: 	  lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2439: 	  /*  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 */
 2440: 	} 
 2441: 	/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 2442: 	/*if(lli ==000.0)*/
 2443: 	/*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); */
 2444:   	ipmx +=1;
 2445: 	sw += weight[i];
 2446: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2447: 	/* if (lli < log(mytinydouble)){ */
 2448: 	/*   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); */
 2449: 	/*   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]); */
 2450: 	/* } */
 2451:       } /* end of wave */
 2452:     } /* end of individual */
 2453:   }  else if(mle==2){
 2454:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2455:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2456:       for(mi=1; mi<= wav[i]-1; mi++){
 2457: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2458: 	  for (j=1;j<=nlstate+ndeath;j++){
 2459: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2460: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2461: 	  }
 2462: 	for(d=0; d<=dh[mi][i]; d++){
 2463: 	  newm=savm;
 2464: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2465: 	  cov[2]=agexact;
 2466: 	  if(nagesqr==1)
 2467: 	    cov[3]= agexact*agexact;
 2468: 	  for (kk=1; kk<=cptcovage;kk++) {
 2469: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2470: 	  }
 2471: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2472: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2473: 	  savm=oldm;
 2474: 	  oldm=newm;
 2475: 	} /* end mult */
 2476:       
 2477: 	s1=s[mw[mi][i]][i];
 2478: 	s2=s[mw[mi+1][i]][i];
 2479: 	bbh=(double)bh[mi][i]/(double)stepm; 
 2480: 	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 */
 2481: 	ipmx +=1;
 2482: 	sw += weight[i];
 2483: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2484:       } /* end of wave */
 2485:     } /* end of individual */
 2486:   }  else if(mle==3){  /* exponential inter-extrapolation */
 2487:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2488:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2489:       for(mi=1; mi<= wav[i]-1; mi++){
 2490: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2491: 	  for (j=1;j<=nlstate+ndeath;j++){
 2492: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2493: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2494: 	  }
 2495: 	for(d=0; d<dh[mi][i]; d++){
 2496: 	  newm=savm;
 2497: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2498: 	  cov[2]=agexact;
 2499: 	  if(nagesqr==1)
 2500: 	    cov[3]= agexact*agexact;
 2501: 	  for (kk=1; kk<=cptcovage;kk++) {
 2502: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2503: 	  }
 2504: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2505: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2506: 	  savm=oldm;
 2507: 	  oldm=newm;
 2508: 	} /* end mult */
 2509:       
 2510: 	s1=s[mw[mi][i]][i];
 2511: 	s2=s[mw[mi+1][i]][i];
 2512: 	bbh=(double)bh[mi][i]/(double)stepm; 
 2513: 	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 */
 2514: 	ipmx +=1;
 2515: 	sw += weight[i];
 2516: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2517:       } /* end of wave */
 2518:     } /* end of individual */
 2519:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
 2520:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2521:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2522:       for(mi=1; mi<= wav[i]-1; mi++){
 2523: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2524: 	  for (j=1;j<=nlstate+ndeath;j++){
 2525: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2526: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2527: 	  }
 2528: 	for(d=0; d<dh[mi][i]; d++){
 2529: 	  newm=savm;
 2530: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2531: 	  cov[2]=agexact;
 2532: 	  if(nagesqr==1)
 2533: 	    cov[3]= agexact*agexact;
 2534: 	  for (kk=1; kk<=cptcovage;kk++) {
 2535: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2536: 	  }
 2537: 	
 2538: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2539: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2540: 	  savm=oldm;
 2541: 	  oldm=newm;
 2542: 	} /* end mult */
 2543:       
 2544: 	s1=s[mw[mi][i]][i];
 2545: 	s2=s[mw[mi+1][i]][i];
 2546: 	if( s2 > nlstate){ 
 2547: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 2548: 	}else{
 2549: 	  lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 2550: 	}
 2551: 	ipmx +=1;
 2552: 	sw += weight[i];
 2553: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2554: /* 	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]); */
 2555:       } /* end of wave */
 2556:     } /* end of individual */
 2557:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
 2558:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2559:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2560:       for(mi=1; mi<= wav[i]-1; mi++){
 2561: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2562: 	  for (j=1;j<=nlstate+ndeath;j++){
 2563: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2564: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2565: 	  }
 2566: 	for(d=0; d<dh[mi][i]; d++){
 2567: 	  newm=savm;
 2568: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2569: 	  cov[2]=agexact;
 2570: 	  if(nagesqr==1)
 2571: 	    cov[3]= agexact*agexact;
 2572: 	  for (kk=1; kk<=cptcovage;kk++) {
 2573: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2574: 	  }
 2575: 	
 2576: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2577: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2578: 	  savm=oldm;
 2579: 	  oldm=newm;
 2580: 	} /* end mult */
 2581:       
 2582: 	s1=s[mw[mi][i]][i];
 2583: 	s2=s[mw[mi+1][i]][i];
 2584: 	lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 2585: 	ipmx +=1;
 2586: 	sw += weight[i];
 2587: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2588: 	/*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]);*/
 2589:       } /* end of wave */
 2590:     } /* end of individual */
 2591:   } /* End of if */
 2592:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 2593:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 2594:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 2595:   return -l;
 2596: }
 2597: 
 2598: /*************** log-likelihood *************/
 2599: double funcone( double *x)
 2600: {
 2601:   /* Same as likeli but slower because of a lot of printf and if */
 2602:   int i, ii, j, k, mi, d, kk;
 2603:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 2604:   double **out;
 2605:   double lli; /* Individual log likelihood */
 2606:   double llt;
 2607:   int s1, s2;
 2608:   double bbh, survp;
 2609:   double agexact;
 2610:   /*extern weight */
 2611:   /* We are differentiating ll according to initial status */
 2612:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 2613:   /*for(i=1;i<imx;i++) 
 2614:     printf(" %d\n",s[4][i]);
 2615:   */
 2616:   cov[1]=1.;
 2617: 
 2618:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 2619: 
 2620:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2621:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2622:     for(mi=1; mi<= wav[i]-1; mi++){
 2623:       for (ii=1;ii<=nlstate+ndeath;ii++)
 2624: 	for (j=1;j<=nlstate+ndeath;j++){
 2625: 	  oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2626: 	  savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2627: 	}
 2628:       for(d=0; d<dh[mi][i]; d++){
 2629: 	newm=savm;
 2630: 	agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2631: 	cov[2]=agexact;
 2632: 	if(nagesqr==1)
 2633: 	  cov[3]= agexact*agexact;
 2634: 	for (kk=1; kk<=cptcovage;kk++) {
 2635: 	  cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2636: 	}
 2637: 
 2638: 	/* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2639: 	out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2640: 		     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2641: 	/* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
 2642: 	/* 	     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
 2643: 	savm=oldm;
 2644: 	oldm=newm;
 2645:       } /* end mult */
 2646:       
 2647:       s1=s[mw[mi][i]][i];
 2648:       s2=s[mw[mi+1][i]][i];
 2649:       bbh=(double)bh[mi][i]/(double)stepm; 
 2650:       /* bias is positive if real duration
 2651:        * is higher than the multiple of stepm and negative otherwise.
 2652:        */
 2653:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
 2654: 	lli=log(out[s1][s2] - savm[s1][s2]);
 2655:       } else if  (s2==-2) {
 2656: 	for (j=1,survp=0. ; j<=nlstate; j++) 
 2657: 	  survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2658: 	lli= log(survp);
 2659:       }else if (mle==1){
 2660: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2661:       } else if(mle==2){
 2662: 	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 */
 2663:       } else if(mle==3){  /* exponential inter-extrapolation */
 2664: 	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 */
 2665:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
 2666: 	lli=log(out[s1][s2]); /* Original formula */
 2667:       } else{  /* mle=0 back to 1 */
 2668: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2669: 	/*lli=log(out[s1][s2]); */ /* Original formula */
 2670:       } /* End of if */
 2671:       ipmx +=1;
 2672:       sw += weight[i];
 2673:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2674:       /*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]); */
 2675:       if(globpr){
 2676: 	fprintf(ficresilk,"%9ld %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
 2677:  %11.6f %11.6f %11.6f ", \
 2678: 		num[i], agexact, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
 2679: 		2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
 2680: 	for(k=1,llt=0.,l=0.; k<=nlstate; k++){
 2681: 	  llt +=ll[k]*gipmx/gsw;
 2682: 	  fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
 2683: 	}
 2684: 	fprintf(ficresilk," %10.6f\n", -llt);
 2685:       }
 2686:     } /* end of wave */
 2687:   } /* end of individual */
 2688:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 2689:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 2690:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 2691:   if(globpr==0){ /* First time we count the contributions and weights */
 2692:     gipmx=ipmx;
 2693:     gsw=sw;
 2694:   }
 2695:   return -l;
 2696: }
 2697: 
 2698: 
 2699: /*************** function likelione ***********/
 2700: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
 2701: {
 2702:   /* This routine should help understanding what is done with 
 2703:      the selection of individuals/waves and
 2704:      to check the exact contribution to the likelihood.
 2705:      Plotting could be done.
 2706:    */
 2707:   int k;
 2708: 
 2709:   if(*globpri !=0){ /* Just counts and sums, no printings */
 2710:     strcpy(fileresilk,"ILK_"); 
 2711:     strcat(fileresilk,fileresu);
 2712:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
 2713:       printf("Problem with resultfile: %s\n", fileresilk);
 2714:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
 2715:     }
 2716:     fprintf(ficresilk, "#individual(line's_record) count age s1 s2 wave# effective_wave# number_of_matrices_product pij weight weight/gpw -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");
 2717:     fprintf(ficresilk, "#num_i age i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
 2718:     /* 	i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
 2719:     for(k=1; k<=nlstate; k++) 
 2720:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
 2721:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
 2722:   }
 2723: 
 2724:   *fretone=(*funcone)(p);
 2725:   if(*globpri !=0){
 2726:     fclose(ficresilk);
 2727:     if (mle ==0)
 2728:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
 2729:     else if(mle >=1)
 2730:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
 2731:     fprintf(fichtm," You should at least run with mle >= 1 to get starting values corresponding to the optimized parameters in order to visualize the real contribution of each individual/wave: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
 2732:     
 2733:       
 2734:     for (k=1; k<= nlstate ; k++) {
 2735:       fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j. Dot's sizes are related to corresponding weight: <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
 2736: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
 2737:     }
 2738:     fprintf(fichtm,"<br>- The function drawn is -2Log(L) in Log scale: by state of origin <a href=\"%s-ori.png\">%s-ori.png</a><br> \
 2739: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
 2740:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
 2741: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
 2742:     fflush(fichtm);
 2743:   }
 2744:   return;
 2745: }
 2746: 
 2747: 
 2748: /*********** Maximum Likelihood Estimation ***************/
 2749: 
 2750: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
 2751: {
 2752:   int i,j, iter=0;
 2753:   double **xi;
 2754:   double fret;
 2755:   double fretone; /* Only one call to likelihood */
 2756:   /*  char filerespow[FILENAMELENGTH];*/
 2757: 
 2758: #ifdef NLOPT
 2759:   int creturn;
 2760:   nlopt_opt opt;
 2761:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
 2762:   double *lb;
 2763:   double minf; /* the minimum objective value, upon return */
 2764:   double * p1; /* Shifted parameters from 0 instead of 1 */
 2765:   myfunc_data dinst, *d = &dinst;
 2766: #endif
 2767: 
 2768: 
 2769:   xi=matrix(1,npar,1,npar);
 2770:   for (i=1;i<=npar;i++)
 2771:     for (j=1;j<=npar;j++)
 2772:       xi[i][j]=(i==j ? 1.0 : 0.0);
 2773:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
 2774:   strcpy(filerespow,"POW_"); 
 2775:   strcat(filerespow,fileres);
 2776:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
 2777:     printf("Problem with resultfile: %s\n", filerespow);
 2778:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 2779:   }
 2780:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
 2781:   for (i=1;i<=nlstate;i++)
 2782:     for(j=1;j<=nlstate+ndeath;j++)
 2783:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 2784:   fprintf(ficrespow,"\n");
 2785: #ifdef POWELL
 2786:   powell(p,xi,npar,ftol,&iter,&fret,func);
 2787: #endif
 2788: 
 2789: #ifdef NLOPT
 2790: #ifdef NEWUOA
 2791:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
 2792: #else
 2793:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
 2794: #endif
 2795:   lb=vector(0,npar-1);
 2796:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
 2797:   nlopt_set_lower_bounds(opt, lb);
 2798:   nlopt_set_initial_step1(opt, 0.1);
 2799:   
 2800:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
 2801:   d->function = func;
 2802:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
 2803:   nlopt_set_min_objective(opt, myfunc, d);
 2804:   nlopt_set_xtol_rel(opt, ftol);
 2805:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
 2806:     printf("nlopt failed! %d\n",creturn); 
 2807:   }
 2808:   else {
 2809:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
 2810:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
 2811:     iter=1; /* not equal */
 2812:   }
 2813:   nlopt_destroy(opt);
 2814: #endif
 2815:   free_matrix(xi,1,npar,1,npar);
 2816:   fclose(ficrespow);
 2817:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2818:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2819:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2820: 
 2821: }
 2822: 
 2823: /**** Computes Hessian and covariance matrix ***/
 2824: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
 2825: {
 2826:   double  **a,**y,*x,pd;
 2827:   /* double **hess; */
 2828:   int i, j;
 2829:   int *indx;
 2830: 
 2831:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
 2832:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
 2833:   void lubksb(double **a, int npar, int *indx, double b[]) ;
 2834:   void ludcmp(double **a, int npar, int *indx, double *d) ;
 2835:   double gompertz(double p[]);
 2836:   /* hess=matrix(1,npar,1,npar); */
 2837: 
 2838:   printf("\nCalculation of the hessian matrix. Wait...\n");
 2839:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
 2840:   for (i=1;i<=npar;i++){
 2841:     printf("%d-",i);fflush(stdout);
 2842:     fprintf(ficlog,"%d-",i);fflush(ficlog);
 2843:    
 2844:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
 2845:     
 2846:     /*  printf(" %f ",p[i]);
 2847: 	printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
 2848:   }
 2849:   
 2850:   for (i=1;i<=npar;i++) {
 2851:     for (j=1;j<=npar;j++)  {
 2852:       if (j>i) { 
 2853: 	printf(".%d-%d",i,j);fflush(stdout);
 2854: 	fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
 2855: 	hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
 2856: 	
 2857: 	hess[j][i]=hess[i][j];    
 2858: 	/*printf(" %lf ",hess[i][j]);*/
 2859:       }
 2860:     }
 2861:   }
 2862:   printf("\n");
 2863:   fprintf(ficlog,"\n");
 2864: 
 2865:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
 2866:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
 2867:   
 2868:   a=matrix(1,npar,1,npar);
 2869:   y=matrix(1,npar,1,npar);
 2870:   x=vector(1,npar);
 2871:   indx=ivector(1,npar);
 2872:   for (i=1;i<=npar;i++)
 2873:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
 2874:   ludcmp(a,npar,indx,&pd);
 2875: 
 2876:   for (j=1;j<=npar;j++) {
 2877:     for (i=1;i<=npar;i++) x[i]=0;
 2878:     x[j]=1;
 2879:     lubksb(a,npar,indx,x);
 2880:     for (i=1;i<=npar;i++){ 
 2881:       matcov[i][j]=x[i];
 2882:     }
 2883:   }
 2884: 
 2885:   printf("\n#Hessian matrix#\n");
 2886:   fprintf(ficlog,"\n#Hessian matrix#\n");
 2887:   for (i=1;i<=npar;i++) { 
 2888:     for (j=1;j<=npar;j++) { 
 2889:       printf("%.6e ",hess[i][j]);
 2890:       fprintf(ficlog,"%.6e ",hess[i][j]);
 2891:     }
 2892:     printf("\n");
 2893:     fprintf(ficlog,"\n");
 2894:   }
 2895: 
 2896:   /* printf("\n#Covariance matrix#\n"); */
 2897:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
 2898:   /* for (i=1;i<=npar;i++) {  */
 2899:   /*   for (j=1;j<=npar;j++) {  */
 2900:   /*     printf("%.6e ",matcov[i][j]); */
 2901:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
 2902:   /*   } */
 2903:   /*   printf("\n"); */
 2904:   /*   fprintf(ficlog,"\n"); */
 2905:   /* } */
 2906: 
 2907:   /* Recompute Inverse */
 2908:   /* for (i=1;i<=npar;i++) */
 2909:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
 2910:   /* ludcmp(a,npar,indx,&pd); */
 2911: 
 2912:   /*  printf("\n#Hessian matrix recomputed#\n"); */
 2913: 
 2914:   /* for (j=1;j<=npar;j++) { */
 2915:   /*   for (i=1;i<=npar;i++) x[i]=0; */
 2916:   /*   x[j]=1; */
 2917:   /*   lubksb(a,npar,indx,x); */
 2918:   /*   for (i=1;i<=npar;i++){  */
 2919:   /*     y[i][j]=x[i]; */
 2920:   /*     printf("%.3e ",y[i][j]); */
 2921:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
 2922:   /*   } */
 2923:   /*   printf("\n"); */
 2924:   /*   fprintf(ficlog,"\n"); */
 2925:   /* } */
 2926: 
 2927:   /* Verifying the inverse matrix */
 2928: #ifdef DEBUGHESS
 2929:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
 2930: 
 2931:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
 2932:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
 2933: 
 2934:   for (j=1;j<=npar;j++) {
 2935:     for (i=1;i<=npar;i++){ 
 2936:       printf("%.2f ",y[i][j]);
 2937:       fprintf(ficlog,"%.2f ",y[i][j]);
 2938:     }
 2939:     printf("\n");
 2940:     fprintf(ficlog,"\n");
 2941:   }
 2942: #endif
 2943: 
 2944:   free_matrix(a,1,npar,1,npar);
 2945:   free_matrix(y,1,npar,1,npar);
 2946:   free_vector(x,1,npar);
 2947:   free_ivector(indx,1,npar);
 2948:   /* free_matrix(hess,1,npar,1,npar); */
 2949: 
 2950: 
 2951: }
 2952: 
 2953: /*************** hessian matrix ****************/
 2954: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
 2955: { /* Around values of x, computes the function func and returns the scales delti and hessian */
 2956:   int i;
 2957:   int l=1, lmax=20;
 2958:   double k1,k2, res, fx;
 2959:   double p2[MAXPARM+1]; /* identical to x */
 2960:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 2961:   int k=0,kmax=10;
 2962:   double l1;
 2963: 
 2964:   fx=func(x);
 2965:   for (i=1;i<=npar;i++) p2[i]=x[i];
 2966:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
 2967:     l1=pow(10,l);
 2968:     delts=delt;
 2969:     for(k=1 ; k <kmax; k=k+1){
 2970:       delt = delta*(l1*k);
 2971:       p2[theta]=x[theta] +delt;
 2972:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
 2973:       p2[theta]=x[theta]-delt;
 2974:       k2=func(p2)-fx;
 2975:       /*res= (k1-2.0*fx+k2)/delt/delt; */
 2976:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
 2977:       
 2978: #ifdef DEBUGHESSII
 2979:       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);
 2980:       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);
 2981: #endif
 2982:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
 2983:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 2984: 	k=kmax;
 2985:       }
 2986:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
 2987: 	k=kmax; l=lmax*10;
 2988:       }
 2989:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
 2990: 	delts=delt;
 2991:       }
 2992:     } /* End loop k */
 2993:   }
 2994:   delti[theta]=delts;
 2995:   return res; 
 2996:   
 2997: }
 2998: 
 2999: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
 3000: {
 3001:   int i;
 3002:   int l=1, lmax=20;
 3003:   double k1,k2,k3,k4,res,fx;
 3004:   double p2[MAXPARM+1];
 3005:   int k, kmax=1;
 3006:   double v1, v2, cv12, lc1, lc2;
 3007: 
 3008:   int firstime=0;
 3009:   
 3010:   fx=func(x);
 3011:   for (k=1; k<=kmax; k=k+10) {
 3012:     for (i=1;i<=npar;i++) p2[i]=x[i];
 3013:     p2[thetai]=x[thetai]+delti[thetai]*k;
 3014:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
 3015:     k1=func(p2)-fx;
 3016:   
 3017:     p2[thetai]=x[thetai]+delti[thetai]*k;
 3018:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
 3019:     k2=func(p2)-fx;
 3020:   
 3021:     p2[thetai]=x[thetai]-delti[thetai]*k;
 3022:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
 3023:     k3=func(p2)-fx;
 3024:   
 3025:     p2[thetai]=x[thetai]-delti[thetai]*k;
 3026:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
 3027:     k4=func(p2)-fx;
 3028:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
 3029:     if(k1*k2*k3*k4 <0.){
 3030:       firstime=1;
 3031:       kmax=kmax+10;
 3032:     }
 3033:     if(kmax >=10 || firstime ==1){
 3034:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
 3035:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
 3036:       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);
 3037:       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);
 3038:     }
 3039: #ifdef DEBUGHESSIJ
 3040:     v1=hess[thetai][thetai];
 3041:     v2=hess[thetaj][thetaj];
 3042:     cv12=res;
 3043:     /* Computing eigen value of Hessian matrix */
 3044:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3045:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3046:     if ((lc2 <0) || (lc1 <0) ){
 3047:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
 3048:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
 3049:       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);
 3050:       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);
 3051:     }
 3052: #endif
 3053:   }
 3054:   return res;
 3055: }
 3056: 
 3057:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
 3058: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
 3059: /* { */
 3060: /*   int i; */
 3061: /*   int l=1, lmax=20; */
 3062: /*   double k1,k2,k3,k4,res,fx; */
 3063: /*   double p2[MAXPARM+1]; */
 3064: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
 3065: /*   int k=0,kmax=10; */
 3066: /*   double l1; */
 3067:   
 3068: /*   fx=func(x); */
 3069: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
 3070: /*     l1=pow(10,l); */
 3071: /*     delts=delt; */
 3072: /*     for(k=1 ; k <kmax; k=k+1){ */
 3073: /*       delt = delti*(l1*k); */
 3074: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
 3075: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
 3076: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
 3077: /*       k1=func(p2)-fx; */
 3078:       
 3079: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
 3080: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
 3081: /*       k2=func(p2)-fx; */
 3082:       
 3083: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
 3084: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
 3085: /*       k3=func(p2)-fx; */
 3086:       
 3087: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
 3088: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
 3089: /*       k4=func(p2)-fx; */
 3090: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
 3091: /* #ifdef DEBUGHESSIJ */
 3092: /*       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); */
 3093: /*       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); */
 3094: /* #endif */
 3095: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
 3096: /* 	k=kmax; */
 3097: /*       } */
 3098: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
 3099: /* 	k=kmax; l=lmax*10; */
 3100: /*       } */
 3101: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
 3102: /* 	delts=delt; */
 3103: /*       } */
 3104: /*     } /\* End loop k *\/ */
 3105: /*   } */
 3106: /*   delti[theta]=delts; */
 3107: /*   return res;  */
 3108: /* } */
 3109: 
 3110: 
 3111: /************** Inverse of matrix **************/
 3112: void ludcmp(double **a, int n, int *indx, double *d) 
 3113: { 
 3114:   int i,imax,j,k; 
 3115:   double big,dum,sum,temp; 
 3116:   double *vv; 
 3117:  
 3118:   vv=vector(1,n); 
 3119:   *d=1.0; 
 3120:   for (i=1;i<=n;i++) { 
 3121:     big=0.0; 
 3122:     for (j=1;j<=n;j++) 
 3123:       if ((temp=fabs(a[i][j])) > big) big=temp; 
 3124:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
 3125:     vv[i]=1.0/big; 
 3126:   } 
 3127:   for (j=1;j<=n;j++) { 
 3128:     for (i=1;i<j;i++) { 
 3129:       sum=a[i][j]; 
 3130:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
 3131:       a[i][j]=sum; 
 3132:     } 
 3133:     big=0.0; 
 3134:     for (i=j;i<=n;i++) { 
 3135:       sum=a[i][j]; 
 3136:       for (k=1;k<j;k++) 
 3137: 	sum -= a[i][k]*a[k][j]; 
 3138:       a[i][j]=sum; 
 3139:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
 3140: 	big=dum; 
 3141: 	imax=i; 
 3142:       } 
 3143:     } 
 3144:     if (j != imax) { 
 3145:       for (k=1;k<=n;k++) { 
 3146: 	dum=a[imax][k]; 
 3147: 	a[imax][k]=a[j][k]; 
 3148: 	a[j][k]=dum; 
 3149:       } 
 3150:       *d = -(*d); 
 3151:       vv[imax]=vv[j]; 
 3152:     } 
 3153:     indx[j]=imax; 
 3154:     if (a[j][j] == 0.0) a[j][j]=TINY; 
 3155:     if (j != n) { 
 3156:       dum=1.0/(a[j][j]); 
 3157:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
 3158:     } 
 3159:   } 
 3160:   free_vector(vv,1,n);  /* Doesn't work */
 3161: ;
 3162: } 
 3163: 
 3164: void lubksb(double **a, int n, int *indx, double b[]) 
 3165: { 
 3166:   int i,ii=0,ip,j; 
 3167:   double sum; 
 3168:  
 3169:   for (i=1;i<=n;i++) { 
 3170:     ip=indx[i]; 
 3171:     sum=b[ip]; 
 3172:     b[ip]=b[i]; 
 3173:     if (ii) 
 3174:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
 3175:     else if (sum) ii=i; 
 3176:     b[i]=sum; 
 3177:   } 
 3178:   for (i=n;i>=1;i--) { 
 3179:     sum=b[i]; 
 3180:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
 3181:     b[i]=sum/a[i][i]; 
 3182:   } 
 3183: } 
 3184: 
 3185: void pstamp(FILE *fichier)
 3186: {
 3187:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
 3188: }
 3189: 
 3190: /************ Frequencies ********************/
 3191: 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[])
 3192: {  /* Some frequencies */
 3193:   
 3194:   int i, m, jk, j1, bool, z1,j;
 3195:   int first;
 3196:   double ***freq; /* Frequencies */
 3197:   double *pp, **prop;
 3198:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
 3199:   char fileresp[FILENAMELENGTH];
 3200:   
 3201:   pp=vector(1,nlstate);
 3202:   prop=matrix(1,nlstate,iagemin,iagemax+3);
 3203:   strcpy(fileresp,"P_");
 3204:   strcat(fileresp,fileresu);
 3205:   if((ficresp=fopen(fileresp,"w"))==NULL) {
 3206:     printf("Problem with prevalence resultfile: %s\n", fileresp);
 3207:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
 3208:     exit(0);
 3209:   }
 3210:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
 3211:   j1=0;
 3212:   
 3213:   j=cptcoveff;
 3214:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 3215: 
 3216:   first=1;
 3217: 
 3218:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
 3219:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
 3220:   /*    j1++; */
 3221:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
 3222:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
 3223: 	scanf("%d", i);*/
 3224:       for (i=-5; i<=nlstate+ndeath; i++)  
 3225: 	for (jk=-5; jk<=nlstate+ndeath; jk++)  
 3226: 	  for(m=iagemin; m <= iagemax+3; m++)
 3227: 	    freq[i][jk][m]=0;
 3228:       
 3229:       for (i=1; i<=nlstate; i++)  
 3230: 	for(m=iagemin; m <= iagemax+3; m++)
 3231: 	  prop[i][m]=0;
 3232:       
 3233:       dateintsum=0;
 3234:       k2cpt=0;
 3235:       for (i=1; i<=imx; i++) {
 3236: 	bool=1;
 3237: 	if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
 3238: 	  for (z1=1; z1<=cptcoveff; z1++)       
 3239:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
 3240:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
 3241:               bool=0;
 3242:               /* printf("bool=%d i=%d, z1=%d, Tvaraff[%d]=%d, covar[Tvarff][%d]=%2f, codtabm(%d,%d)=%d, nbcode[Tvaraff][codtabm(%d,%d)=%d, j1=%d\n", 
 3243:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
 3244:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
 3245:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
 3246:             } 
 3247: 	} /* cptcovn > 0 */
 3248:  
 3249: 	if (bool==1){
 3250: 	  for(m=firstpass; m<=lastpass; m++){
 3251: 	    k2=anint[m][i]+(mint[m][i]/12.);
 3252: 	    /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
 3253: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 3254: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 3255: 	      if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
 3256: 	      if (m<lastpass) {
 3257: 		freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
 3258: 		freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
 3259: 	      }
 3260: 	      
 3261: 	      if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3)) && (anint[m][i]!=9999) && (mint[m][i]!=99)) {
 3262: 		dateintsum=dateintsum+k2;
 3263: 		k2cpt++;
 3264: 		/* printf("i=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",i, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
 3265: 	      }
 3266: 	      /*}*/
 3267: 	  } /* end m */
 3268: 	} /* end bool */
 3269:       } /* end i = 1 to imx */
 3270:        
 3271:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 3272:       pstamp(ficresp);
 3273:       if  (cptcovn>0) {
 3274: 	fprintf(ficresp, "\n#********** Variable "); 
 3275: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 3276: 	fprintf(ficresp, "**********\n#");
 3277: 	fprintf(ficlog, "\n#********** Variable "); 
 3278: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 3279: 	fprintf(ficlog, "**********\n#");
 3280:       }
 3281:       for(i=1; i<=nlstate;i++) 
 3282: 	fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
 3283:       fprintf(ficresp, "\n");
 3284:       
 3285:       for(i=iagemin; i <= iagemax+3; i++){
 3286: 	if(i==iagemax+3){
 3287: 	  fprintf(ficlog,"Total");
 3288: 	}else{
 3289: 	  if(first==1){
 3290: 	    first=0;
 3291: 	    printf("See log file for details...\n");
 3292: 	  }
 3293: 	  fprintf(ficlog,"Age %d", i);
 3294: 	}
 3295: 	for(jk=1; jk <=nlstate ; jk++){
 3296: 	  for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
 3297: 	    pp[jk] += freq[jk][m][i]; 
 3298: 	}
 3299: 	for(jk=1; jk <=nlstate ; jk++){
 3300: 	  for(m=-1, pos=0; m <=0 ; m++)
 3301: 	    pos += freq[jk][m][i];
 3302: 	  if(pp[jk]>=1.e-10){
 3303: 	    if(first==1){
 3304: 	      printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 3305: 	    }
 3306: 	    fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 3307: 	  }else{
 3308: 	    if(first==1)
 3309: 	      printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 3310: 	    fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 3311: 	  }
 3312: 	}
 3313: 
 3314: 	for(jk=1; jk <=nlstate ; jk++){
 3315: 	  for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
 3316: 	    pp[jk] += freq[jk][m][i];
 3317: 	}	
 3318: 	for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
 3319: 	  pos += pp[jk];
 3320: 	  posprop += prop[jk][i];
 3321: 	}
 3322: 	for(jk=1; jk <=nlstate ; jk++){
 3323: 	  if(pos>=1.e-5){
 3324: 	    if(first==1)
 3325: 	      printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 3326: 	    fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 3327: 	  }else{
 3328: 	    if(first==1)
 3329: 	      printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 3330: 	    fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 3331: 	  }
 3332: 	  if( i <= iagemax){
 3333: 	    if(pos>=1.e-5){
 3334: 	      fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
 3335: 	      /*probs[i][jk][j1]= pp[jk]/pos;*/
 3336: 	      /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
 3337: 	    }
 3338: 	    else
 3339: 	      fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
 3340: 	  }
 3341: 	}
 3342: 	
 3343: 	for(jk=-1; jk <=nlstate+ndeath; jk++)
 3344: 	  for(m=-1; m <=nlstate+ndeath; m++)
 3345: 	    if(freq[jk][m][i] !=0 ) {
 3346: 	    if(first==1)
 3347: 	      printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
 3348: 	      fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
 3349: 	    }
 3350: 	if(i <= iagemax)
 3351: 	  fprintf(ficresp,"\n");
 3352: 	if(first==1)
 3353: 	  printf("Others in log...\n");
 3354: 	fprintf(ficlog,"\n");
 3355:       } /* end loop i */
 3356:       /*}*/
 3357:   } /* end j1 */
 3358:   dateintmean=dateintsum/k2cpt; 
 3359:  
 3360:   fclose(ficresp);
 3361:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
 3362:   free_vector(pp,1,nlstate);
 3363:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
 3364:   /* End of Freq */
 3365: }
 3366: 
 3367: /************ Prevalence ********************/
 3368: 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)
 3369: {  
 3370:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 3371:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 3372:      We still use firstpass and lastpass as another selection.
 3373:   */
 3374:  
 3375:   int i, m, jk, j1, bool, z1,j;
 3376: 
 3377:   double **prop;
 3378:   double posprop; 
 3379:   double  y2; /* in fractional years */
 3380:   int iagemin, iagemax;
 3381:   int first; /** to stop verbosity which is redirected to log file */
 3382: 
 3383:   iagemin= (int) agemin;
 3384:   iagemax= (int) agemax;
 3385:   /*pp=vector(1,nlstate);*/
 3386:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
 3387:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
 3388:   j1=0;
 3389:   
 3390:   /*j=cptcoveff;*/
 3391:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 3392:   
 3393:   first=1;
 3394:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
 3395:     /*for(i1=1; i1<=ncodemax[k1];i1++){
 3396:       j1++;*/
 3397:       
 3398:       for (i=1; i<=nlstate; i++)  
 3399: 	for(m=iagemin; m <= iagemax+3; m++)
 3400: 	  prop[i][m]=0.0;
 3401:      
 3402:       for (i=1; i<=imx; i++) { /* Each individual */
 3403: 	bool=1;
 3404: 	if  (cptcovn>0) {
 3405: 	  for (z1=1; z1<=cptcoveff; z1++) 
 3406: 	    if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
 3407: 	      bool=0;
 3408: 	} 
 3409: 	if (bool==1) { 
 3410: 	  for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
 3411: 	    y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
 3412: 	    if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
 3413: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 3414: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 3415: 	      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); 
 3416:  	      if (s[m][i]>0 && s[m][i]<=nlstate) { 
 3417: 		/*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]]);*/
 3418:  		prop[s[m][i]][(int)agev[m][i]] += weight[i];
 3419:  		prop[s[m][i]][iagemax+3] += weight[i]; 
 3420:  	      } 
 3421: 	    }
 3422: 	  } /* end selection of waves */
 3423: 	}
 3424:       }
 3425:       for(i=iagemin; i <= iagemax+3; i++){  
 3426:  	for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
 3427:  	  posprop += prop[jk][i]; 
 3428:  	} 
 3429: 	
 3430:  	for(jk=1; jk <=nlstate ; jk++){	    
 3431:  	  if( i <=  iagemax){ 
 3432:  	    if(posprop>=1.e-5){ 
 3433:  	      probs[i][jk][j1]= prop[jk][i]/posprop;
 3434:  	    } else{
 3435: 	      if(first==1){
 3436: 		first=0;
 3437: 		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]);
 3438: 	      }
 3439: 	    }
 3440:  	  } 
 3441:  	}/* end jk */ 
 3442:       }/* end i */ 
 3443:     /*} *//* end i1 */
 3444:   } /* end j1 */
 3445:   
 3446:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
 3447:   /*free_vector(pp,1,nlstate);*/
 3448:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
 3449: }  /* End of prevalence */
 3450: 
 3451: /************* Waves Concatenation ***************/
 3452: 
 3453: 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)
 3454: {
 3455:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 3456:      Death is a valid wave (if date is known).
 3457:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
 3458:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 3459:      and mw[mi+1][i]. dh depends on stepm.
 3460:      */
 3461: 
 3462:   int i, mi, m;
 3463:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
 3464:      double sum=0., jmean=0.;*/
 3465:   int first;
 3466:   int j, k=0,jk, ju, jl;
 3467:   double sum=0.;
 3468:   first=0;
 3469:   jmin=100000;
 3470:   jmax=-1;
 3471:   jmean=0.;
 3472:   for(i=1; i<=imx; i++){
 3473:     mi=0;
 3474:     m=firstpass;
 3475:     while(s[m][i] <= nlstate){
 3476:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
 3477: 	mw[++mi][i]=m;
 3478:       if(m >=lastpass)
 3479: 	break;
 3480:       else
 3481: 	m++;
 3482:     }/* end while */
 3483:     if (s[m][i] > nlstate){
 3484:       mi++;	/* Death is another wave */
 3485:       /* if(mi==0)  never been interviewed correctly before death */
 3486: 	 /* Only death is a correct wave */
 3487:       mw[mi][i]=m;
 3488:     }
 3489: 
 3490:     wav[i]=mi;
 3491:     if(mi==0){
 3492:       nbwarn++;
 3493:       if(first==0){
 3494: 	printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
 3495: 	first=1;
 3496:       }
 3497:       if(first==1){
 3498: 	fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
 3499:       }
 3500:     } /* end mi==0 */
 3501:   } /* End individuals */
 3502: 
 3503:   for(i=1; i<=imx; i++){
 3504:     for(mi=1; mi<wav[i];mi++){
 3505:       if (stepm <=0)
 3506: 	dh[mi][i]=1;
 3507:       else{
 3508: 	if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
 3509: 	  if (agedc[i] < 2*AGESUP) {
 3510: 	    j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
 3511: 	    if(j==0) j=1;  /* Survives at least one month after exam */
 3512: 	    else if(j<0){
 3513: 	      nberr++;
 3514: 	      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]);
 3515: 	      j=1; /* Temporary Dangerous patch */
 3516: 	      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);
 3517: 	      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]);
 3518: 	      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);
 3519: 	    }
 3520: 	    k=k+1;
 3521: 	    if (j >= jmax){
 3522: 	      jmax=j;
 3523: 	      ijmax=i;
 3524: 	    }
 3525: 	    if (j <= jmin){
 3526: 	      jmin=j;
 3527: 	      ijmin=i;
 3528: 	    }
 3529: 	    sum=sum+j;
 3530: 	    /*if (j<0) printf("j=%d num=%d \n",j,i);*/
 3531: 	    /*	  printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
 3532: 	  }
 3533: 	}
 3534: 	else{
 3535: 	  j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 3536: /* 	  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]); */
 3537: 
 3538: 	  k=k+1;
 3539: 	  if (j >= jmax) {
 3540: 	    jmax=j;
 3541: 	    ijmax=i;
 3542: 	  }
 3543: 	  else if (j <= jmin){
 3544: 	    jmin=j;
 3545: 	    ijmin=i;
 3546: 	  }
 3547: 	  /*	    if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
 3548: 	  /*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]);*/
 3549: 	  if(j<0){
 3550: 	    nberr++;
 3551: 	    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]);
 3552: 	    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]);
 3553: 	  }
 3554: 	  sum=sum+j;
 3555: 	}
 3556: 	jk= j/stepm;
 3557: 	jl= j -jk*stepm;
 3558: 	ju= j -(jk+1)*stepm;
 3559: 	if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
 3560: 	  if(jl==0){
 3561: 	    dh[mi][i]=jk;
 3562: 	    bh[mi][i]=0;
 3563: 	  }else{ /* We want a negative bias in order to only have interpolation ie
 3564: 		  * to avoid the price of an extra matrix product in likelihood */
 3565: 	    dh[mi][i]=jk+1;
 3566: 	    bh[mi][i]=ju;
 3567: 	  }
 3568: 	}else{
 3569: 	  if(jl <= -ju){
 3570: 	    dh[mi][i]=jk;
 3571: 	    bh[mi][i]=jl;	/* bias is positive if real duration
 3572: 				 * is higher than the multiple of stepm and negative otherwise.
 3573: 				 */
 3574: 	  }
 3575: 	  else{
 3576: 	    dh[mi][i]=jk+1;
 3577: 	    bh[mi][i]=ju;
 3578: 	  }
 3579: 	  if(dh[mi][i]==0){
 3580: 	    dh[mi][i]=1; /* At least one step */
 3581: 	    bh[mi][i]=ju; /* At least one step */
 3582: 	    /*  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);*/
 3583: 	  }
 3584: 	} /* end if mle */
 3585:       }
 3586:     } /* end wave */
 3587:   }
 3588:   jmean=sum/k;
 3589:   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);
 3590:   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);
 3591:  }
 3592: 
 3593: /*********** Tricode ****************************/
 3594: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
 3595: {
 3596:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
 3597:   /*	  Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
 3598:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
 3599:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
 3600:    * nbcode[Tvar[j]][1]= 
 3601:   */
 3602: 
 3603:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
 3604:   int modmaxcovj=0; /* Modality max of covariates j */
 3605:   int cptcode=0; /* Modality max of covariates j */
 3606:   int modmincovj=0; /* Modality min of covariates j */
 3607: 
 3608: 
 3609:   cptcoveff=0; 
 3610:  
 3611:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
 3612: 
 3613:   /* Loop on covariates without age and products */
 3614:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
 3615:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
 3616:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
 3617: 			       modality of this covariate Vj*/ 
 3618:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
 3619: 				    * If product of Vn*Vm, still boolean *:
 3620: 				    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
 3621: 				    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
 3622:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
 3623: 				      modality of the nth covariate of individual i. */
 3624:       if (ij > modmaxcovj)
 3625:         modmaxcovj=ij; 
 3626:       else if (ij < modmincovj) 
 3627: 	modmincovj=ij; 
 3628:       if ((ij < -1) && (ij > NCOVMAX)){
 3629: 	printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
 3630: 	exit(1);
 3631:       }else
 3632:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
 3633:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
 3634:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
 3635:       /* getting the maximum value of the modality of the covariate
 3636: 	 (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
 3637: 	 female is 1, then modmaxcovj=1.*/
 3638:     } /* end for loop on individuals i */
 3639:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
 3640:     fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
 3641:     cptcode=modmaxcovj;
 3642:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
 3643:    /*for (i=0; i<=cptcode; i++) {*/
 3644:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
 3645:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
 3646:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
 3647:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
 3648: 	if( k != -1){
 3649: 	  ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
 3650: 			     covariate for which somebody answered excluding 
 3651: 			     undefined. Usually 2: 0 and 1. */
 3652: 	}
 3653: 	ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
 3654: 			     covariate for which somebody answered including 
 3655: 			     undefined. Usually 3: -1, 0 and 1. */
 3656:       }
 3657:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
 3658: 	 historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
 3659:     } /* Ndum[-1] number of undefined modalities */
 3660: 
 3661:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
 3662:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
 3663:        If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
 3664:        modmincovj=3; modmaxcovj = 7;
 3665:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
 3666:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
 3667:        defining two dummy variables: variables V1_1 and V1_2.
 3668:        nbcode[Tvar[j]][ij]=k;
 3669:        nbcode[Tvar[j]][1]=0;
 3670:        nbcode[Tvar[j]][2]=1;
 3671:        nbcode[Tvar[j]][3]=2;
 3672:        To be continued (not working yet).
 3673:     */
 3674:     ij=0; /* ij is similar to i but can jump over null modalities */
 3675:     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 or from -1 or 0 to 1 currently*/
 3676:     	if (Ndum[i] == 0) { /* If nobody responded to this modality k */
 3677: 	  break;
 3678: 	}
 3679: 	ij++;
 3680: 	nbcode[Tvar[j]][ij]=i;  /* stores the original value of modality i in an array nbcode, ij modality from 1 to last non-nul modality.*/
 3681: 	cptcode = ij; /* New max modality for covar j */
 3682:     } /* end of loop on modality i=-1 to 1 or more */
 3683:       
 3684:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
 3685:     /* 	/\*recode from 0 *\/ */
 3686:     /* 				     k is a modality. If we have model=V1+V1*sex  */
 3687:     /* 				     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
 3688:     /* 				  But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
 3689:     /* 	} */
 3690:     /* 	/\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
 3691:     /* 	if (ij > ncodemax[j]) { */
 3692:     /* 	  printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
 3693:     /* 	  fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
 3694:     /* 	  break; */
 3695:     /* 	} */
 3696:     /*   }  /\* end of loop on modality k *\/ */
 3697:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
 3698:   
 3699:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
 3700:   
 3701:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
 3702:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
 3703:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
 3704:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
 3705:  } 
 3706: 
 3707:  ij=0;
 3708:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
 3709:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
 3710:    if((Ndum[i]!=0) && (i<=ncovcol)){
 3711:      ij++;
 3712:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
 3713:      Tvaraff[ij]=i; /*For printing (unclear) */
 3714:    }else{
 3715:        /* Tvaraff[ij]=0; */
 3716:    }
 3717:  }
 3718:  /* ij--; */
 3719:  cptcoveff=ij; /*Number of total covariates*/
 3720: 
 3721: }
 3722: 
 3723: 
 3724: /*********** Health Expectancies ****************/
 3725: 
 3726: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
 3727: 
 3728: {
 3729:   /* Health expectancies, no variances */
 3730:   int i, j, nhstepm, hstepm, h, nstepm;
 3731:   int nhstepma, nstepma; /* Decreasing with age */
 3732:   double age, agelim, hf;
 3733:   double ***p3mat;
 3734:   double eip;
 3735: 
 3736:   pstamp(ficreseij);
 3737:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
 3738:   fprintf(ficreseij,"# Age");
 3739:   for(i=1; i<=nlstate;i++){
 3740:     for(j=1; j<=nlstate;j++){
 3741:       fprintf(ficreseij," e%1d%1d ",i,j);
 3742:     }
 3743:     fprintf(ficreseij," e%1d. ",i);
 3744:   }
 3745:   fprintf(ficreseij,"\n");
 3746: 
 3747:   
 3748:   if(estepm < stepm){
 3749:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3750:   }
 3751:   else  hstepm=estepm;   
 3752:   /* We compute the life expectancy from trapezoids spaced every estepm months
 3753:    * This is mainly to measure the difference between two models: for example
 3754:    * if stepm=24 months pijx are given only every 2 years and by summing them
 3755:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 3756:    * progression in between and thus overestimating or underestimating according
 3757:    * to the curvature of the survival function. If, for the same date, we 
 3758:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 3759:    * to compare the new estimate of Life expectancy with the same linear 
 3760:    * hypothesis. A more precise result, taking into account a more precise
 3761:    * curvature will be obtained if estepm is as small as stepm. */
 3762: 
 3763:   /* For example we decided to compute the life expectancy with the smallest unit */
 3764:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3765:      nhstepm is the number of hstepm from age to agelim 
 3766:      nstepm is the number of stepm from age to agelin. 
 3767:      Look at hpijx to understand the reason of that which relies in memory size
 3768:      and note for a fixed period like estepm months */
 3769:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3770:      survival function given by stepm (the optimization length). Unfortunately it
 3771:      means that if the survival funtion is printed only each two years of age and if
 3772:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3773:      results. So we changed our mind and took the option of the best precision.
 3774:   */
 3775:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3776: 
 3777:   agelim=AGESUP;
 3778:   /* If stepm=6 months */
 3779:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
 3780:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 3781:     
 3782: /* nhstepm age range expressed in number of stepm */
 3783:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3784:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3785:   /* if (stepm >= YEARM) hstepm=1;*/
 3786:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3787:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3788: 
 3789:   for (age=bage; age<=fage; age ++){ 
 3790:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3791:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3792:     /* if (stepm >= YEARM) hstepm=1;*/
 3793:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 3794: 
 3795:     /* If stepm=6 months */
 3796:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 3797:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 3798:     
 3799:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 3800:     
 3801:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3802:     
 3803:     printf("%d|",(int)age);fflush(stdout);
 3804:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 3805:     
 3806:     /* Computing expectancies */
 3807:     for(i=1; i<=nlstate;i++)
 3808:       for(j=1; j<=nlstate;j++)
 3809: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 3810: 	  eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
 3811: 	  
 3812: 	  /* 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]);*/
 3813: 
 3814: 	}
 3815: 
 3816:     fprintf(ficreseij,"%3.0f",age );
 3817:     for(i=1; i<=nlstate;i++){
 3818:       eip=0;
 3819:       for(j=1; j<=nlstate;j++){
 3820: 	eip +=eij[i][j][(int)age];
 3821: 	fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
 3822:       }
 3823:       fprintf(ficreseij,"%9.4f", eip );
 3824:     }
 3825:     fprintf(ficreseij,"\n");
 3826:     
 3827:   }
 3828:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3829:   printf("\n");
 3830:   fprintf(ficlog,"\n");
 3831:   
 3832: }
 3833: 
 3834: 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[] )
 3835: 
 3836: {
 3837:   /* Covariances of health expectancies eij and of total life expectancies according
 3838:    to initial status i, ei. .
 3839:   */
 3840:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
 3841:   int nhstepma, nstepma; /* Decreasing with age */
 3842:   double age, agelim, hf;
 3843:   double ***p3matp, ***p3matm, ***varhe;
 3844:   double **dnewm,**doldm;
 3845:   double *xp, *xm;
 3846:   double **gp, **gm;
 3847:   double ***gradg, ***trgradg;
 3848:   int theta;
 3849: 
 3850:   double eip, vip;
 3851: 
 3852:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
 3853:   xp=vector(1,npar);
 3854:   xm=vector(1,npar);
 3855:   dnewm=matrix(1,nlstate*nlstate,1,npar);
 3856:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
 3857:   
 3858:   pstamp(ficresstdeij);
 3859:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
 3860:   fprintf(ficresstdeij,"# Age");
 3861:   for(i=1; i<=nlstate;i++){
 3862:     for(j=1; j<=nlstate;j++)
 3863:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
 3864:     fprintf(ficresstdeij," e%1d. ",i);
 3865:   }
 3866:   fprintf(ficresstdeij,"\n");
 3867: 
 3868:   pstamp(ficrescveij);
 3869:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
 3870:   fprintf(ficrescveij,"# Age");
 3871:   for(i=1; i<=nlstate;i++)
 3872:     for(j=1; j<=nlstate;j++){
 3873:       cptj= (j-1)*nlstate+i;
 3874:       for(i2=1; i2<=nlstate;i2++)
 3875: 	for(j2=1; j2<=nlstate;j2++){
 3876: 	  cptj2= (j2-1)*nlstate+i2;
 3877: 	  if(cptj2 <= cptj)
 3878: 	    fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
 3879: 	}
 3880:     }
 3881:   fprintf(ficrescveij,"\n");
 3882:   
 3883:   if(estepm < stepm){
 3884:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3885:   }
 3886:   else  hstepm=estepm;   
 3887:   /* We compute the life expectancy from trapezoids spaced every estepm months
 3888:    * This is mainly to measure the difference between two models: for example
 3889:    * if stepm=24 months pijx are given only every 2 years and by summing them
 3890:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 3891:    * progression in between and thus overestimating or underestimating according
 3892:    * to the curvature of the survival function. If, for the same date, we 
 3893:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 3894:    * to compare the new estimate of Life expectancy with the same linear 
 3895:    * hypothesis. A more precise result, taking into account a more precise
 3896:    * curvature will be obtained if estepm is as small as stepm. */
 3897: 
 3898:   /* For example we decided to compute the life expectancy with the smallest unit */
 3899:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3900:      nhstepm is the number of hstepm from age to agelim 
 3901:      nstepm is the number of stepm from age to agelin. 
 3902:      Look at hpijx to understand the reason of that which relies in memory size
 3903:      and note for a fixed period like estepm months */
 3904:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3905:      survival function given by stepm (the optimization length). Unfortunately it
 3906:      means that if the survival funtion is printed only each two years of age and if
 3907:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3908:      results. So we changed our mind and took the option of the best precision.
 3909:   */
 3910:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3911: 
 3912:   /* If stepm=6 months */
 3913:   /* nhstepm age range expressed in number of stepm */
 3914:   agelim=AGESUP;
 3915:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
 3916:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3917:   /* if (stepm >= YEARM) hstepm=1;*/
 3918:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3919:   
 3920:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3921:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3922:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
 3923:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
 3924:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
 3925:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
 3926: 
 3927:   for (age=bage; age<=fage; age ++){ 
 3928:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3929:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3930:     /* if (stepm >= YEARM) hstepm=1;*/
 3931:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 3932: 
 3933:     /* If stepm=6 months */
 3934:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 3935:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 3936:     
 3937:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3938: 
 3939:     /* Computing  Variances of health expectancies */
 3940:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
 3941:        decrease memory allocation */
 3942:     for(theta=1; theta <=npar; theta++){
 3943:       for(i=1; i<=npar; i++){ 
 3944: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3945: 	xm[i] = x[i] - (i==theta ?delti[theta]:0);
 3946:       }
 3947:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
 3948:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
 3949:   
 3950:       for(j=1; j<= nlstate; j++){
 3951: 	for(i=1; i<=nlstate; i++){
 3952: 	  for(h=0; h<=nhstepm-1; h++){
 3953: 	    gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
 3954: 	    gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
 3955: 	  }
 3956: 	}
 3957:       }
 3958:      
 3959:       for(ij=1; ij<= nlstate*nlstate; ij++)
 3960: 	for(h=0; h<=nhstepm-1; h++){
 3961: 	  gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
 3962: 	}
 3963:     }/* End theta */
 3964:     
 3965:     
 3966:     for(h=0; h<=nhstepm-1; h++)
 3967:       for(j=1; j<=nlstate*nlstate;j++)
 3968: 	for(theta=1; theta <=npar; theta++)
 3969: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 3970:     
 3971: 
 3972:      for(ij=1;ij<=nlstate*nlstate;ij++)
 3973:       for(ji=1;ji<=nlstate*nlstate;ji++)
 3974: 	varhe[ij][ji][(int)age] =0.;
 3975: 
 3976:      printf("%d|",(int)age);fflush(stdout);
 3977:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 3978:      for(h=0;h<=nhstepm-1;h++){
 3979:       for(k=0;k<=nhstepm-1;k++){
 3980: 	matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
 3981: 	matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
 3982: 	for(ij=1;ij<=nlstate*nlstate;ij++)
 3983: 	  for(ji=1;ji<=nlstate*nlstate;ji++)
 3984: 	    varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
 3985:       }
 3986:     }
 3987: 
 3988:     /* Computing expectancies */
 3989:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 3990:     for(i=1; i<=nlstate;i++)
 3991:       for(j=1; j<=nlstate;j++)
 3992: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 3993: 	  eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
 3994: 	  
 3995: 	  /* 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]);*/
 3996: 
 3997: 	}
 3998: 
 3999:     fprintf(ficresstdeij,"%3.0f",age );
 4000:     for(i=1; i<=nlstate;i++){
 4001:       eip=0.;
 4002:       vip=0.;
 4003:       for(j=1; j<=nlstate;j++){
 4004: 	eip += eij[i][j][(int)age];
 4005: 	for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
 4006: 	  vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
 4007: 	fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
 4008:       }
 4009:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
 4010:     }
 4011:     fprintf(ficresstdeij,"\n");
 4012: 
 4013:     fprintf(ficrescveij,"%3.0f",age );
 4014:     for(i=1; i<=nlstate;i++)
 4015:       for(j=1; j<=nlstate;j++){
 4016: 	cptj= (j-1)*nlstate+i;
 4017: 	for(i2=1; i2<=nlstate;i2++)
 4018: 	  for(j2=1; j2<=nlstate;j2++){
 4019: 	    cptj2= (j2-1)*nlstate+i2;
 4020: 	    if(cptj2 <= cptj)
 4021: 	      fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
 4022: 	  }
 4023:       }
 4024:     fprintf(ficrescveij,"\n");
 4025:    
 4026:   }
 4027:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
 4028:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
 4029:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
 4030:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
 4031:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4032:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4033:   printf("\n");
 4034:   fprintf(ficlog,"\n");
 4035: 
 4036:   free_vector(xm,1,npar);
 4037:   free_vector(xp,1,npar);
 4038:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
 4039:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
 4040:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
 4041: }
 4042: 
 4043: /************ Variance ******************/
 4044:  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 *ncvyearp, int ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[])
 4045: {
 4046:   /* Variance of health expectancies */
 4047:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
 4048:   /* double **newm;*/
 4049:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
 4050:   
 4051:   int movingaverage();
 4052:   double **dnewm,**doldm;
 4053:   double **dnewmp,**doldmp;
 4054:   int i, j, nhstepm, hstepm, h, nstepm ;
 4055:   int k;
 4056:   double *xp;
 4057:   double **gp, **gm;  /* for var eij */
 4058:   double ***gradg, ***trgradg; /*for var eij */
 4059:   double **gradgp, **trgradgp; /* for var p point j */
 4060:   double *gpp, *gmp; /* for var p point j */
 4061:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
 4062:   double ***p3mat;
 4063:   double age,agelim, hf;
 4064:   double ***mobaverage;
 4065:   int theta;
 4066:   char digit[4];
 4067:   char digitp[25];
 4068: 
 4069:   char fileresprobmorprev[FILENAMELENGTH];
 4070: 
 4071:   if(popbased==1){
 4072:     if(mobilav!=0)
 4073:       strcpy(digitp,"-POPULBASED-MOBILAV_");
 4074:     else strcpy(digitp,"-POPULBASED-NOMOBIL_");
 4075:   }
 4076:   else 
 4077:     strcpy(digitp,"-STABLBASED_");
 4078: 
 4079:   if (mobilav!=0) {
 4080:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4081:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 4082:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 4083:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 4084:     }
 4085:   }
 4086: 
 4087:   strcpy(fileresprobmorprev,"PRMORPREV-"); 
 4088:   sprintf(digit,"%-d",ij);
 4089:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
 4090:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
 4091:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
 4092:   strcat(fileresprobmorprev,fileresu);
 4093:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
 4094:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
 4095:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
 4096:   }
 4097:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 4098:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 4099:   pstamp(ficresprobmorprev);
 4100:   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);
 4101:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
 4102:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 4103:     fprintf(ficresprobmorprev," p.%-d SE",j);
 4104:     for(i=1; i<=nlstate;i++)
 4105:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 4106:   }  
 4107:   fprintf(ficresprobmorprev,"\n");
 4108:   
 4109:   fprintf(ficgp,"\n# Routine varevsij");
 4110:   fprintf(ficgp,"\nunset title \n");
 4111: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
 4112:   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");
 4113:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
 4114: /*   } */
 4115:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 4116:   pstamp(ficresvij);
 4117:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
 4118:   if(popbased==1)
 4119:     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);
 4120:   else
 4121:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
 4122:   fprintf(ficresvij,"# Age");
 4123:   for(i=1; i<=nlstate;i++)
 4124:     for(j=1; j<=nlstate;j++)
 4125:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
 4126:   fprintf(ficresvij,"\n");
 4127: 
 4128:   xp=vector(1,npar);
 4129:   dnewm=matrix(1,nlstate,1,npar);
 4130:   doldm=matrix(1,nlstate,1,nlstate);
 4131:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
 4132:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 4133: 
 4134:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
 4135:   gpp=vector(nlstate+1,nlstate+ndeath);
 4136:   gmp=vector(nlstate+1,nlstate+ndeath);
 4137:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 4138:   
 4139:   if(estepm < stepm){
 4140:     printf ("Problem %d lower than %d\n",estepm, stepm);
 4141:   }
 4142:   else  hstepm=estepm;   
 4143:   /* For example we decided to compute the life expectancy with the smallest unit */
 4144:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 4145:      nhstepm is the number of hstepm from age to agelim 
 4146:      nstepm is the number of stepm from age to agelim. 
 4147:      Look at function hpijx to understand why because of memory size limitations, 
 4148:      we decided (b) to get a life expectancy respecting the most precise curvature of the
 4149:      survival function given by stepm (the optimization length). Unfortunately it
 4150:      means that if the survival funtion is printed every two years of age and if
 4151:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 4152:      results. So we changed our mind and took the option of the best precision.
 4153:   */
 4154:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 4155:   agelim = AGESUP;
 4156:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 4157:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 4158:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 4159:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4160:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
 4161:     gp=matrix(0,nhstepm,1,nlstate);
 4162:     gm=matrix(0,nhstepm,1,nlstate);
 4163: 
 4164: 
 4165:     for(theta=1; theta <=npar; theta++){
 4166:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
 4167: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 4168:       }
 4169: 
 4170:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 4171: 
 4172:       if (popbased==1) {
 4173: 	if(mobilav ==0){
 4174: 	  for(i=1; i<=nlstate;i++)
 4175: 	    prlim[i][i]=probs[(int)age][i][ij];
 4176: 	}else{ /* mobilav */ 
 4177: 	  for(i=1; i<=nlstate;i++)
 4178: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 4179: 	}
 4180:       }
 4181:   
 4182:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
 4183:       for(j=1; j<= nlstate; j++){
 4184: 	for(h=0; h<=nhstepm; h++){
 4185: 	  for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 4186: 	    gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 4187: 	}
 4188:       }
 4189:       /* Next for computing probability of death (h=1 means
 4190:          computed over hstepm matrices product = hstepm*stepm months) 
 4191:          as a weighted average of prlim.
 4192:       */
 4193:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 4194: 	for(i=1,gpp[j]=0.; i<= nlstate; i++)
 4195: 	  gpp[j] += prlim[i][i]*p3mat[i][j][1];
 4196:       }    
 4197:       /* end probability of death */
 4198: 
 4199:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
 4200: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 4201: 
 4202:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
 4203:  
 4204:       if (popbased==1) {
 4205: 	if(mobilav ==0){
 4206: 	  for(i=1; i<=nlstate;i++)
 4207: 	    prlim[i][i]=probs[(int)age][i][ij];
 4208: 	}else{ /* mobilav */ 
 4209: 	  for(i=1; i<=nlstate;i++)
 4210: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 4211: 	}
 4212:       }
 4213: 
 4214:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 4215: 
 4216:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
 4217: 	for(h=0; h<=nhstepm; h++){
 4218: 	  for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 4219: 	    gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 4220: 	}
 4221:       }
 4222:       /* This for computing probability of death (h=1 means
 4223:          computed over hstepm matrices product = hstepm*stepm months) 
 4224:          as a weighted average of prlim.
 4225:       */
 4226:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 4227: 	for(i=1,gmp[j]=0.; i<= nlstate; i++)
 4228:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
 4229:       }    
 4230:       /* end probability of death */
 4231: 
 4232:       for(j=1; j<= nlstate; j++) /* vareij */
 4233: 	for(h=0; h<=nhstepm; h++){
 4234: 	  gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 4235: 	}
 4236: 
 4237:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
 4238: 	gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
 4239:       }
 4240: 
 4241:     } /* End theta */
 4242: 
 4243:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
 4244: 
 4245:     for(h=0; h<=nhstepm; h++) /* veij */
 4246:       for(j=1; j<=nlstate;j++)
 4247: 	for(theta=1; theta <=npar; theta++)
 4248: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 4249: 
 4250:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
 4251:       for(theta=1; theta <=npar; theta++)
 4252: 	trgradgp[j][theta]=gradgp[theta][j];
 4253:   
 4254: 
 4255:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 4256:     for(i=1;i<=nlstate;i++)
 4257:       for(j=1;j<=nlstate;j++)
 4258: 	vareij[i][j][(int)age] =0.;
 4259: 
 4260:     for(h=0;h<=nhstepm;h++){
 4261:       for(k=0;k<=nhstepm;k++){
 4262: 	matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 4263: 	matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
 4264: 	for(i=1;i<=nlstate;i++)
 4265: 	  for(j=1;j<=nlstate;j++)
 4266: 	    vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
 4267:       }
 4268:     }
 4269:   
 4270:     /* pptj */
 4271:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
 4272:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
 4273:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
 4274:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
 4275: 	varppt[j][i]=doldmp[j][i];
 4276:     /* end ppptj */
 4277:     /*  x centered again */
 4278: 
 4279:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
 4280:  
 4281:     if (popbased==1) {
 4282:       if(mobilav ==0){
 4283: 	for(i=1; i<=nlstate;i++)
 4284: 	  prlim[i][i]=probs[(int)age][i][ij];
 4285:       }else{ /* mobilav */ 
 4286: 	for(i=1; i<=nlstate;i++)
 4287: 	  prlim[i][i]=mobaverage[(int)age][i][ij];
 4288:       }
 4289:     }
 4290:              
 4291:     /* This for computing probability of death (h=1 means
 4292:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
 4293:        as a weighted average of prlim.
 4294:     */
 4295:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
 4296:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
 4297:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
 4298: 	gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
 4299:     }    
 4300:     /* end probability of death */
 4301: 
 4302:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
 4303:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 4304:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
 4305:       for(i=1; i<=nlstate;i++){
 4306: 	fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 4307:       }
 4308:     } 
 4309:     fprintf(ficresprobmorprev,"\n");
 4310: 
 4311:     fprintf(ficresvij,"%.0f ",age );
 4312:     for(i=1; i<=nlstate;i++)
 4313:       for(j=1; j<=nlstate;j++){
 4314: 	fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
 4315:       }
 4316:     fprintf(ficresvij,"\n");
 4317:     free_matrix(gp,0,nhstepm,1,nlstate);
 4318:     free_matrix(gm,0,nhstepm,1,nlstate);
 4319:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 4320:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 4321:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4322:   } /* End age */
 4323:   free_vector(gpp,nlstate+1,nlstate+ndeath);
 4324:   free_vector(gmp,nlstate+1,nlstate+ndeath);
 4325:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
 4326:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 4327:   /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
 4328:   fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
 4329:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
 4330:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
 4331:   fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
 4332: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
 4333: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
 4334: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
 4335:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
 4336:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
 4337:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
 4338:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
 4339:   fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"%s%s.svg\"> <br>\n", estepm,subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
 4340:   /*  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.svg\"> <br>\n", stepm,YEARM,digitp,digit);
 4341: */
 4342: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
 4343:   fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
 4344: 
 4345:   free_vector(xp,1,npar);
 4346:   free_matrix(doldm,1,nlstate,1,nlstate);
 4347:   free_matrix(dnewm,1,nlstate,1,npar);
 4348:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 4349:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
 4350:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 4351:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4352:   fclose(ficresprobmorprev);
 4353:   fflush(ficgp);
 4354:   fflush(fichtm); 
 4355: }  /* end varevsij */
 4356: 
 4357: /************ Variance of prevlim ******************/
 4358:  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 *ncvyearp, int ij, char strstart[])
 4359: {
 4360:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
 4361:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 4362: 
 4363:   double **dnewm,**doldm;
 4364:   int i, j, nhstepm, hstepm;
 4365:   double *xp;
 4366:   double *gp, *gm;
 4367:   double **gradg, **trgradg;
 4368:   double **mgm, **mgp;
 4369:   double age,agelim;
 4370:   int theta;
 4371:   
 4372:   pstamp(ficresvpl);
 4373:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
 4374:   fprintf(ficresvpl,"# Age");
 4375:   for(i=1; i<=nlstate;i++)
 4376:       fprintf(ficresvpl," %1d-%1d",i,i);
 4377:   fprintf(ficresvpl,"\n");
 4378: 
 4379:   xp=vector(1,npar);
 4380:   dnewm=matrix(1,nlstate,1,npar);
 4381:   doldm=matrix(1,nlstate,1,nlstate);
 4382:   
 4383:   hstepm=1*YEARM; /* Every year of age */
 4384:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 4385:   agelim = AGESUP;
 4386:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 4387:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 4388:     if (stepm >= YEARM) hstepm=1;
 4389:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 4390:     gradg=matrix(1,npar,1,nlstate);
 4391:     mgp=matrix(1,npar,1,nlstate);
 4392:     mgm=matrix(1,npar,1,nlstate);
 4393:     gp=vector(1,nlstate);
 4394:     gm=vector(1,nlstate);
 4395: 
 4396:     for(theta=1; theta <=npar; theta++){
 4397:       for(i=1; i<=npar; i++){ /* Computes gradient */
 4398: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 4399:       }
 4400:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
 4401: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 4402:       else
 4403: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 4404:       for(i=1;i<=nlstate;i++){
 4405: 	gp[i] = prlim[i][i];
 4406: 	mgp[theta][i] = prlim[i][i];
 4407:       }
 4408:       for(i=1; i<=npar; i++) /* Computes gradient */
 4409: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 4410:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
 4411: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 4412:       else
 4413: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 4414:       for(i=1;i<=nlstate;i++){
 4415: 	gm[i] = prlim[i][i];
 4416: 	mgm[theta][i] = prlim[i][i];
 4417:       }
 4418:       for(i=1;i<=nlstate;i++)
 4419: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 4420:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
 4421:     } /* End theta */
 4422: 
 4423:     trgradg =matrix(1,nlstate,1,npar);
 4424: 
 4425:     for(j=1; j<=nlstate;j++)
 4426:       for(theta=1; theta <=npar; theta++)
 4427: 	trgradg[j][theta]=gradg[theta][j];
 4428:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
 4429:     /*   printf("\nmgm mgp %d ",(int)age); */
 4430:     /*   for(j=1; j<=nlstate;j++){ */
 4431:     /* 	printf(" %d ",j); */
 4432:     /* 	for(theta=1; theta <=npar; theta++) */
 4433:     /* 	  printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
 4434:     /* 	printf("\n "); */
 4435:     /*   } */
 4436:     /* } */
 4437:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
 4438:     /*   printf("\n gradg %d ",(int)age); */
 4439:     /*   for(j=1; j<=nlstate;j++){ */
 4440:     /* 	printf("%d ",j); */
 4441:     /* 	for(theta=1; theta <=npar; theta++) */
 4442:     /* 	  printf("%d %lf ",theta,gradg[theta][j]); */
 4443:     /* 	printf("\n "); */
 4444:     /*   } */
 4445:     /* } */
 4446: 
 4447:     for(i=1;i<=nlstate;i++)
 4448:       varpl[i][(int)age] =0.;
 4449:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
 4450:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 4451:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 4452:     }else{
 4453:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 4454:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 4455:     }
 4456:     for(i=1;i<=nlstate;i++)
 4457:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 4458: 
 4459:     fprintf(ficresvpl,"%.0f ",age );
 4460:     for(i=1; i<=nlstate;i++)
 4461:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
 4462:     fprintf(ficresvpl,"\n");
 4463:     free_vector(gp,1,nlstate);
 4464:     free_vector(gm,1,nlstate);
 4465:     free_matrix(mgm,1,npar,1,nlstate);
 4466:     free_matrix(mgp,1,npar,1,nlstate);
 4467:     free_matrix(gradg,1,npar,1,nlstate);
 4468:     free_matrix(trgradg,1,nlstate,1,npar);
 4469:   } /* End age */
 4470: 
 4471:   free_vector(xp,1,npar);
 4472:   free_matrix(doldm,1,nlstate,1,npar);
 4473:   free_matrix(dnewm,1,nlstate,1,nlstate);
 4474: 
 4475: }
 4476: 
 4477: /************ Variance of one-step probabilities  ******************/
 4478: 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[])
 4479: {
 4480:   int i, j=0,  k1, l1, tj;
 4481:   int k2, l2, j1,  z1;
 4482:   int k=0, l;
 4483:   int first=1, first1, first2;
 4484:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
 4485:   double **dnewm,**doldm;
 4486:   double *xp;
 4487:   double *gp, *gm;
 4488:   double **gradg, **trgradg;
 4489:   double **mu;
 4490:   double age, cov[NCOVMAX+1];
 4491:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
 4492:   int theta;
 4493:   char fileresprob[FILENAMELENGTH];
 4494:   char fileresprobcov[FILENAMELENGTH];
 4495:   char fileresprobcor[FILENAMELENGTH];
 4496:   double ***varpij;
 4497: 
 4498:   strcpy(fileresprob,"PROB_"); 
 4499:   strcat(fileresprob,fileres);
 4500:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
 4501:     printf("Problem with resultfile: %s\n", fileresprob);
 4502:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
 4503:   }
 4504:   strcpy(fileresprobcov,"PROBCOV_"); 
 4505:   strcat(fileresprobcov,fileresu);
 4506:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
 4507:     printf("Problem with resultfile: %s\n", fileresprobcov);
 4508:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 4509:   }
 4510:   strcpy(fileresprobcor,"PROBCOR_"); 
 4511:   strcat(fileresprobcor,fileresu);
 4512:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 4513:     printf("Problem with resultfile: %s\n", fileresprobcor);
 4514:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 4515:   }
 4516:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 4517:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 4518:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 4519:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 4520:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 4521:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 4522:   pstamp(ficresprob);
 4523:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
 4524:   fprintf(ficresprob,"# Age");
 4525:   pstamp(ficresprobcov);
 4526:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
 4527:   fprintf(ficresprobcov,"# Age");
 4528:   pstamp(ficresprobcor);
 4529:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 4530:   fprintf(ficresprobcor,"# Age");
 4531: 
 4532: 
 4533:   for(i=1; i<=nlstate;i++)
 4534:     for(j=1; j<=(nlstate+ndeath);j++){
 4535:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
 4536:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
 4537:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
 4538:     }  
 4539:  /* fprintf(ficresprob,"\n");
 4540:   fprintf(ficresprobcov,"\n");
 4541:   fprintf(ficresprobcor,"\n");
 4542:  */
 4543:   xp=vector(1,npar);
 4544:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 4545:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 4546:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
 4547:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 4548:   first=1;
 4549:   fprintf(ficgp,"\n# Routine varprob");
 4550:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
 4551:   fprintf(fichtm,"\n");
 4552: 
 4553:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of one-step probabilities (drawings)</a></h4> this page is important in order to visualize confidence intervals and especially correlation between disability and recovery, or more generally, way in and way back.</li>\n",optionfilehtmcov);
 4554:   fprintf(fichtmcov,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n",optionfilehtmcov, optionfilehtmcov);
 4555:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
 4556: and drawn. It helps understanding how is the covariance between two incidences.\
 4557:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
 4558:   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. \
 4559: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
 4560: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
 4561: standard deviations wide on each axis. <br>\
 4562:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
 4563:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 4564: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
 4565: 
 4566:   cov[1]=1;
 4567:   /* tj=cptcoveff; */
 4568:   tj = (int) pow(2,cptcoveff);
 4569:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
 4570:   j1=0;
 4571:   for(j1=1; j1<=tj;j1++){
 4572:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
 4573:     /*j1++;*/
 4574:       if  (cptcovn>0) {
 4575: 	fprintf(ficresprob, "\n#********** Variable "); 
 4576: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 4577: 	fprintf(ficresprob, "**********\n#\n");
 4578: 	fprintf(ficresprobcov, "\n#********** Variable "); 
 4579: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 4580: 	fprintf(ficresprobcov, "**********\n#\n");
 4581: 	
 4582: 	fprintf(ficgp, "\n#********** Variable "); 
 4583: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 4584: 	fprintf(ficgp, "**********\n#\n");
 4585: 	
 4586: 	
 4587: 	fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
 4588: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 4589: 	fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
 4590: 	
 4591: 	fprintf(ficresprobcor, "\n#********** Variable ");    
 4592: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 4593: 	fprintf(ficresprobcor, "**********\n#");    
 4594:       }
 4595:       
 4596:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
 4597:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 4598:       gp=vector(1,(nlstate)*(nlstate+ndeath));
 4599:       gm=vector(1,(nlstate)*(nlstate+ndeath));
 4600:       for (age=bage; age<=fage; age ++){ 
 4601: 	cov[2]=age;
 4602: 	if(nagesqr==1)
 4603: 	  cov[3]= age*age;
 4604: 	for (k=1; k<=cptcovn;k++) {
 4605: 	  cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
 4606: 	  /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
 4607: 							 * 1  1 1 1 1
 4608: 							 * 2  2 1 1 1
 4609: 							 * 3  1 2 1 1
 4610: 							 */
 4611: 	  /* nbcode[1][1]=0 nbcode[1][2]=1;*/
 4612: 	}
 4613: 	/* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 4614: 	for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 4615: 	for (k=1; k<=cptcovprod;k++)
 4616: 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
 4617: 	
 4618:     
 4619: 	for(theta=1; theta <=npar; theta++){
 4620: 	  for(i=1; i<=npar; i++)
 4621: 	    xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
 4622: 	  
 4623: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 4624: 	  
 4625: 	  k=0;
 4626: 	  for(i=1; i<= (nlstate); i++){
 4627: 	    for(j=1; j<=(nlstate+ndeath);j++){
 4628: 	      k=k+1;
 4629: 	      gp[k]=pmmij[i][j];
 4630: 	    }
 4631: 	  }
 4632: 	  
 4633: 	  for(i=1; i<=npar; i++)
 4634: 	    xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
 4635:     
 4636: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 4637: 	  k=0;
 4638: 	  for(i=1; i<=(nlstate); i++){
 4639: 	    for(j=1; j<=(nlstate+ndeath);j++){
 4640: 	      k=k+1;
 4641: 	      gm[k]=pmmij[i][j];
 4642: 	    }
 4643: 	  }
 4644:      
 4645: 	  for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
 4646: 	    gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
 4647: 	}
 4648: 
 4649: 	for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
 4650: 	  for(theta=1; theta <=npar; theta++)
 4651: 	    trgradg[j][theta]=gradg[theta][j];
 4652: 	
 4653: 	matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
 4654: 	matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
 4655: 
 4656: 	pmij(pmmij,cov,ncovmodel,x,nlstate);
 4657: 	
 4658: 	k=0;
 4659: 	for(i=1; i<=(nlstate); i++){
 4660: 	  for(j=1; j<=(nlstate+ndeath);j++){
 4661: 	    k=k+1;
 4662: 	    mu[k][(int) age]=pmmij[i][j];
 4663: 	  }
 4664: 	}
 4665:      	for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 4666: 	  for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 4667: 	    varpij[i][j][(int)age] = doldm[i][j];
 4668: 
 4669: 	/*printf("\n%d ",(int)age);
 4670: 	  for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 4671: 	  printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 4672: 	  fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 4673: 	  }*/
 4674: 
 4675: 	fprintf(ficresprob,"\n%d ",(int)age);
 4676: 	fprintf(ficresprobcov,"\n%d ",(int)age);
 4677: 	fprintf(ficresprobcor,"\n%d ",(int)age);
 4678: 
 4679: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
 4680: 	  fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
 4681: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 4682: 	  fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
 4683: 	  fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
 4684: 	}
 4685: 	i=0;
 4686: 	for (k=1; k<=(nlstate);k++){
 4687:  	  for (l=1; l<=(nlstate+ndeath);l++){ 
 4688:  	    i++;
 4689: 	    fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 4690: 	    fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
 4691: 	    for (j=1; j<=i;j++){
 4692: 	      /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
 4693: 	      fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
 4694: 	      fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
 4695: 	    }
 4696: 	  }
 4697: 	}/* end of loop for state */
 4698:       } /* end of loop for age */
 4699:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
 4700:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 4701:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 4702:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 4703:       
 4704:       /* Confidence intervalle of pij  */
 4705:       /*
 4706: 	fprintf(ficgp,"\nunset parametric;unset label");
 4707: 	fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
 4708: 	fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 4709: 	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);
 4710: 	fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
 4711: 	fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
 4712: 	fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
 4713:       */
 4714: 
 4715:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
 4716:       first1=1;first2=2;
 4717:       for (k2=1; k2<=(nlstate);k2++){
 4718: 	for (l2=1; l2<=(nlstate+ndeath);l2++){ 
 4719: 	  if(l2==k2) continue;
 4720: 	  j=(k2-1)*(nlstate+ndeath)+l2;
 4721: 	  for (k1=1; k1<=(nlstate);k1++){
 4722: 	    for (l1=1; l1<=(nlstate+ndeath);l1++){ 
 4723: 	      if(l1==k1) continue;
 4724: 	      i=(k1-1)*(nlstate+ndeath)+l1;
 4725: 	      if(i<=j) continue;
 4726: 	      for (age=bage; age<=fage; age ++){ 
 4727: 		if ((int)age %5==0){
 4728: 		  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
 4729: 		  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
 4730: 		  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
 4731: 		  mu1=mu[i][(int) age]/stepm*YEARM ;
 4732: 		  mu2=mu[j][(int) age]/stepm*YEARM;
 4733: 		  c12=cv12/sqrt(v1*v2);
 4734: 		  /* Computing eigen value of matrix of covariance */
 4735: 		  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 4736: 		  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 4737: 		  if ((lc2 <0) || (lc1 <0) ){
 4738: 		    if(first2==1){
 4739: 		      first1=0;
 4740: 		    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);
 4741: 		    }
 4742: 		    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);
 4743: 		    /* lc1=fabs(lc1); */ /* If we want to have them positive */
 4744: 		    /* lc2=fabs(lc2); */
 4745: 		  }
 4746: 
 4747: 		  /* Eigen vectors */
 4748: 		  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
 4749: 		  /*v21=sqrt(1.-v11*v11); *//* error */
 4750: 		  v21=(lc1-v1)/cv12*v11;
 4751: 		  v12=-v21;
 4752: 		  v22=v11;
 4753: 		  tnalp=v21/v11;
 4754: 		  if(first1==1){
 4755: 		    first1=0;
 4756: 		    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);
 4757: 		  }
 4758: 		  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);
 4759: 		  /*printf(fignu*/
 4760: 		  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
 4761: 		  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
 4762: 		  if(first==1){
 4763: 		    first=0;
 4764:  		    fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
 4765:  		    fprintf(ficgp,"\nset parametric;unset label");
 4766: 		    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);
 4767: 		    fprintf(ficgp,"\nset ter svg size 640, 480");
 4768: 		    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
 4769:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
 4770: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
 4771: 			    subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
 4772: 			    subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 4773: 		    fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 4774: 		    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
 4775: 		    fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 4776: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 4777: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 4778: 		    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",\
 4779: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 4780: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 4781: 		  }else{
 4782: 		    first=0;
 4783: 		    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
 4784: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 4785: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 4786: 		    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",\
 4787: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 4788: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 4789: 		  }/* if first */
 4790: 		} /* age mod 5 */
 4791: 	      } /* end loop age */
 4792: 	      fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 4793: 	      first=1;
 4794: 	    } /*l12 */
 4795: 	  } /* k12 */
 4796: 	} /*l1 */
 4797:       }/* k1 */
 4798:       /* } */ /* loop covariates */
 4799:   }
 4800:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 4801:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
 4802:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 4803:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
 4804:   free_vector(xp,1,npar);
 4805:   fclose(ficresprob);
 4806:   fclose(ficresprobcov);
 4807:   fclose(ficresprobcor);
 4808:   fflush(ficgp);
 4809:   fflush(fichtmcov);
 4810: }
 4811: 
 4812: 
 4813: /******************* Printing html file ***********/
 4814: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
 4815: 		  int lastpass, int stepm, int weightopt, char model[],\
 4816: 		  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 4817: 		  int popforecast, int prevfcast, int estepm ,		\
 4818: 		  double jprev1, double mprev1,double anprev1, \
 4819: 		  double jprev2, double mprev2,double anprev2){
 4820:   int jj1, k1, i1, cpt;
 4821: 
 4822:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
 4823:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
 4824: </ul>");
 4825:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
 4826:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
 4827: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
 4828:    fprintf(fichtm,"\
 4829:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 4830: 	   stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
 4831:    fprintf(fichtm,"\
 4832:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 4833: 	   subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
 4834:    fprintf(fichtm,"\
 4835:  - (a) Life expectancies by health status at initial age, e<sub>i.</sub> (b) health expectancies by health status at initial age, e<sub>ij</sub> . 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): \
 4836:    <a href=\"%s\">%s</a> <br>\n",
 4837: 	   estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
 4838:    if(prevfcast==1){
 4839:      fprintf(fichtm,"\
 4840:  - Prevalence projections by age and states:				\
 4841:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
 4842:    }
 4843: 
 4844: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
 4845: 
 4846:  m=pow(2,cptcoveff);
 4847:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 4848: 
 4849:  jj1=0;
 4850:  for(k1=1; k1<=m;k1++){
 4851:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
 4852:      jj1++;
 4853:      if (cptcovn > 0) {
 4854:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 4855:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
 4856: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
 4857: 	 printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
 4858:        }
 4859:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 4860:      }
 4861:      /* aij, bij */
 4862:      fprintf(fichtm,"<br>- Logit model (yours is: 1+age+%s), for example: logit(pij)=log(pij/pii)= aij+ bij age + V1 age + etc. as a function of age: <a href=\"%s_%d-1.svg\">%s_%d-1.svg</a><br> \
 4863: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
 4864:      /* Pij */
 4865:      fprintf(fichtm,"<br>\n- P<sub>ij</sub> or conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s_%d-2.svg\">%s_%d-2.svg</a><br> \
 4866: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
 4867:      /* Quasi-incidences */
 4868:      fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
 4869:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
 4870:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
 4871: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
 4872: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
 4873:      /* Survival functions (period) in state j */
 4874:      for(cpt=1; cpt<=nlstate;cpt++){
 4875:        fprintf(fichtm,"<br>\n- Survival functions in state %d. Or probability to survive in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> \
 4876: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
 4877:      }
 4878:      /* State specific survival functions (period) */
 4879:      for(cpt=1; cpt<=nlstate;cpt++){
 4880:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
 4881:  Or probability to survive in various states (1 to %d) being in state %d at different ages.\
 4882:  <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> <img src=\"%s_%d-%d.svg\">", cpt, nlstate, cpt, subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1);
 4883:      }
 4884:      /* Period (stable) prevalence in each health state */
 4885:      for(cpt=1; cpt<=nlstate;cpt++){
 4886:        fprintf(fichtm,"<br>\n- 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.svg\">%s%d_%d.svg</a><br> \
 4887: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
 4888:      }
 4889:     if(prevfcast==1){
 4890:       /* Projection of prevalence up to period (stable) prevalence in each health state */
 4891:       for(cpt=1; cpt<=nlstate;cpt++){
 4892: 	fprintf(fichtm,"<br>\n- Projection of prevalece up 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.svg\">%s%d_%d.svg</a><br> \
 4893: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1);
 4894:       }
 4895:     }
 4896: 
 4897:      for(cpt=1; cpt<=nlstate;cpt++) {
 4898:        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) (or area under each survival functions): <a href=\"%s_%d%d.svg\">%s_%d%d.svg</a> <br> \
 4899: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
 4900:      }
 4901:    /* } /\* end i1 *\/ */
 4902:  }/* End k1 */
 4903:  fprintf(fichtm,"</ul>");
 4904: 
 4905:  fprintf(fichtm,"\
 4906: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
 4907:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
 4908:  - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
 4909: But because parameters are usually highly correlated (a higher incidence of disability \
 4910: and a higher incidence of recovery can give very close observed transition) it might \
 4911: be very useful to look not only at linear confidence intervals estimated from the \
 4912: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
 4913: (parameters) of the logistic regression, it might be more meaningful to visualize the \
 4914: covariance matrix of the one-step probabilities. \
 4915: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
 4916: 
 4917:  fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4918: 	 subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
 4919:  fprintf(fichtm,"\
 4920:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4921: 	 subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
 4922: 
 4923:  fprintf(fichtm,"\
 4924:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4925: 	 subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
 4926:  fprintf(fichtm,"\
 4927:  - 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): \
 4928:    <a href=\"%s\">%s</a> <br>\n</li>",
 4929: 	   estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
 4930:  fprintf(fichtm,"\
 4931:  - (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): \
 4932:    <a href=\"%s\">%s</a> <br>\n</li>",
 4933: 	   estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
 4934:  fprintf(fichtm,"\
 4935:  - 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",
 4936: 	 estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
 4937:  fprintf(fichtm,"\
 4938:  - 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",
 4939: 	 estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
 4940:  fprintf(fichtm,"\
 4941:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
 4942: 	 subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
 4943: 
 4944: /*  if(popforecast==1) fprintf(fichtm,"\n */
 4945: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
 4946: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
 4947: /* 	<br>",fileres,fileres,fileres,fileres); */
 4948: /*  else  */
 4949: /*    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); */
 4950:  fflush(fichtm);
 4951:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
 4952: 
 4953:  m=pow(2,cptcoveff);
 4954:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 4955: 
 4956:  jj1=0;
 4957:  for(k1=1; k1<=m;k1++){
 4958:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
 4959:      jj1++;
 4960:      if (cptcovn > 0) {
 4961:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 4962:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 4963: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
 4964:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 4965:      }
 4966:      for(cpt=1; cpt<=nlstate;cpt++) {
 4967:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
 4968: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d%d.svg\"> %s_%d-%d.svg <br>\
 4969: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);  
 4970:      }
 4971:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
 4972: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
 4973: true period expectancies (those weighted with period prevalences are also\
 4974:  drawn in addition to the population based expectancies computed using\
 4975:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg<br>\
 4976: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
 4977:    /* } /\* end i1 *\/ */
 4978:  }/* End k1 */
 4979:  fprintf(fichtm,"</ul>");
 4980:  fflush(fichtm);
 4981: }
 4982: 
 4983: /******************* Gnuplot file **************/
 4984:     void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, char pathc[], double p[]){
 4985: 
 4986:   char dirfileres[132],optfileres[132];
 4987:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
 4988:   int lv=0, vlv=0, kl=0;
 4989:   int ng=0;
 4990:   int vpopbased;
 4991: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
 4992: /*     printf("Problem with file %s",optionfilegnuplot); */
 4993: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
 4994: /*   } */
 4995: 
 4996:   /*#ifdef windows */
 4997:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 4998:     /*#endif */
 4999:   m=pow(2,cptcoveff);
 5000: 
 5001:   /* Contribution to likelihood */
 5002:   /* Plot the probability implied in the likelihood */
 5003:     fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
 5004:     fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
 5005:     /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
 5006:     fprintf(ficgp,"\nset ter pngcairo size 640, 480");
 5007: /* nice for mle=4 plot by number of matrix products.
 5008:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
 5009: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
 5010:     /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
 5011:     fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
 5012:     fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$12):5 t \"All sample, transitions colored by destination\" with dots lc variable; set out;\n",subdirf(fileresilk));
 5013:     fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
 5014:     fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$12):4 t \"All sample, transitions colored by origin\" with dots lc variable; set out;\n\n",subdirf(fileresilk));
 5015:     for (i=1; i<= nlstate ; i ++) {
 5016:       fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
 5017:       fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
 5018:       fprintf(ficgp,"  u  2:($4 == %d && $5==%d ? $9 : 1/0):($11/4.):5 t \"p%d%d\" with points pointtype 7 ps variable lc variable \\\n",i,1,i,1);
 5019:       for (j=2; j<= nlstate+ndeath ; j ++) {
 5020: 	fprintf(ficgp,",\\\n \"\" u  2:($4 == %d && $5==%d ? $9 : 1/0):($11/4.):5 t \"p%d%d\" with points pointtype 7 ps variable lc variable ",i,j,i,j);
 5021:       }
 5022:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
 5023:     }
 5024:     /* unset log; plot  "rrtest1_sorted_4/ILK_rrtest1_sorted_4.txt" u  2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with points lc variable */		 
 5025:     /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
 5026:     /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
 5027:     fprintf(ficgp,"\nset out;unset log\n");
 5028:     /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
 5029: 
 5030:   strcpy(dirfileres,optionfilefiname);
 5031:   strcpy(optfileres,"vpl");
 5032:  /* 1eme*/
 5033:   for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
 5034:     for (k1=1; k1<= m ; k1 ++) { /* For each combination of covariate */
 5035:       /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
 5036:       fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
 5037:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 5038: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 5039: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5040: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5041: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5042: 	vlv= nbcode[Tvaraff[lv]][lv];
 5043: 	fprintf(ficgp," V%d=%d ",k,vlv);
 5044:       }
 5045:       fprintf(ficgp,"\n#\n");
 5046: 
 5047:      fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
 5048:      fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
 5049:      fprintf(ficgp,"set xlabel \"Age\" \n\
 5050: set ylabel \"Probability\" \n\
 5051: set ter svg size 640, 480\n\
 5052: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
 5053: 
 5054:      for (i=1; i<= nlstate ; i ++) {
 5055:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 5056:        else        fprintf(ficgp," %%*lf (%%*lf)");
 5057:      }
 5058:      fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1);
 5059:      for (i=1; i<= nlstate ; i ++) {
 5060:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 5061:        else fprintf(ficgp," %%*lf (%%*lf)");
 5062:      } 
 5063:      fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1); 
 5064:      for (i=1; i<= nlstate ; i ++) {
 5065:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 5066:        else fprintf(ficgp," %%*lf (%%*lf)");
 5067:      }  
 5068:      fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence \" w l lt 2",subdirf2(fileresu,"P_"),k1-1,k1-1,2+4*(cpt-1));
 5069:      fprintf(ficgp,"\nset out \n");
 5070:     } /* k1 */
 5071:   } /* cpt */
 5072:   /*2 eme*/
 5073:   for (k1=1; k1<= m ; k1 ++) { 
 5074:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
 5075:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 5076: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 5077: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5078: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5079: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5080: 	vlv= nbcode[Tvaraff[lv]][lv];
 5081: 	fprintf(ficgp," V%d=%d ",k,vlv);
 5082:       }
 5083:       fprintf(ficgp,"\n#\n");
 5084: 
 5085:     fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
 5086:     for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 5087:       if(vpopbased==0)
 5088: 	fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
 5089:       else
 5090: 	fprintf(ficgp,"\nreplot ");
 5091:       for (i=1; i<= nlstate+1 ; i ++) {
 5092: 	k=2*i;
 5093: 	fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ?$4 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1, vpopbased);
 5094: 	for (j=1; j<= nlstate+1 ; j ++) {
 5095: 	  if (j==i) fprintf(ficgp," %%lf (%%lf)");
 5096: 	  else fprintf(ficgp," %%*lf (%%*lf)");
 5097: 	}   
 5098: 	if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
 5099: 	else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
 5100: 	fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ? $4-$5*2 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1,vpopbased);
 5101: 	for (j=1; j<= nlstate+1 ; j ++) {
 5102: 	  if (j==i) fprintf(ficgp," %%lf (%%lf)");
 5103: 	  else fprintf(ficgp," %%*lf (%%*lf)");
 5104: 	}   
 5105: 	fprintf(ficgp,"\" t\"\" w l lt 0,");
 5106: 	fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ? $4+$5*2 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1,vpopbased);
 5107: 	for (j=1; j<= nlstate+1 ; j ++) {
 5108: 	  if (j==i) fprintf(ficgp," %%lf (%%lf)");
 5109: 	  else fprintf(ficgp," %%*lf (%%*lf)");
 5110: 	}   
 5111: 	if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
 5112: 	else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
 5113:       } /* state */
 5114:     } /* vpopbased */
 5115:     fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
 5116:   } /* k1 */
 5117: 
 5118: 
 5119:   /*3eme*/
 5120:   for (k1=1; k1<= m ; k1 ++) { 
 5121:     for (cpt=1; cpt<= nlstate ; cpt ++) {
 5122:       fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  cov=%d state=%d",k1, cpt);
 5123:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 5124: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 5125: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5126: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5127: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5128: 	vlv= nbcode[Tvaraff[lv]][lv];
 5129: 	fprintf(ficgp," V%d=%d ",k,vlv);
 5130:       }
 5131:       fprintf(ficgp,"\n#\n");
 5132: 
 5133:       /*       k=2+nlstate*(2*cpt-2); */
 5134:       k=2+(nlstate+1)*(cpt-1);
 5135:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
 5136:       fprintf(ficgp,"set ter svg size 640, 480\n\
 5137: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileresu,"E_"),k1-1,k1-1,k,cpt);
 5138:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 5139: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 5140: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 5141: 	fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 5142: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 5143: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 5144: 	
 5145:       */
 5146:       for (i=1; i< nlstate ; i ++) {
 5147: 	fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+i,cpt,i+1);
 5148: 	/*	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);*/
 5149: 	
 5150:       } 
 5151:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
 5152:     }
 5153:   }
 5154:   
 5155:   /* Survival functions (period) from state i in state j by initial state i */
 5156:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
 5157:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 5158:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
 5159:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 5160: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 5161: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5162: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5163: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5164: 	vlv= nbcode[Tvaraff[lv]][lv];
 5165: 	fprintf(ficgp," V%d=%d ",k,vlv);
 5166:       }
 5167:       fprintf(ficgp,"\n#\n");
 5168: 
 5169:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
 5170:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
 5171: set ter svg size 640, 480\n\
 5172: unset log y\n\
 5173: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 5174:       k=3;
 5175:       for (i=1; i<= nlstate ; i ++){
 5176: 	if(i==1)
 5177: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 5178: 	else
 5179: 	  fprintf(ficgp,", '' ");
 5180: 	l=(nlstate+ndeath)*(i-1)+1;
 5181: 	fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 5182: 	for (j=2; j<= nlstate+ndeath ; j ++)
 5183: 	  fprintf(ficgp,"+$%d",k+l+j-1);
 5184: 	fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
 5185:       } /* nlstate */
 5186:       fprintf(ficgp,"\nset out\n");
 5187:     } /* end cpt state*/ 
 5188:   } /* end covariate */  
 5189: 
 5190:   /* Survival functions (period) from state i in state j by final state j */
 5191:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
 5192:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
 5193:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j and all livestates from state i by final state j: 'lij' files, cov=%d state=%d",k1, cpt);
 5194:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 5195: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 5196: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5197: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5198: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5199: 	vlv= nbcode[Tvaraff[lv]][lv];
 5200: 	fprintf(ficgp," V%d=%d ",k,vlv);
 5201:       }
 5202:       fprintf(ficgp,"\n#\n");
 5203: 
 5204:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
 5205:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
 5206: set ter svg size 640, 480\n\
 5207: unset log y\n\
 5208: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 5209:       k=3;
 5210:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
 5211: 	if(j==1)
 5212: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 5213: 	else
 5214: 	  fprintf(ficgp,", '' ");
 5215: 	l=(nlstate+ndeath)*(cpt-1) +j;
 5216: 	fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
 5217: 	/* for (i=2; i<= nlstate+ndeath ; i ++) */
 5218: 	/*   fprintf(ficgp,"+$%d",k+l+i-1); */
 5219: 	fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
 5220:       } /* nlstate */
 5221:       fprintf(ficgp,", '' ");
 5222:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
 5223:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
 5224: 	l=(nlstate+ndeath)*(cpt-1) +j;
 5225: 	if(j < nlstate)
 5226: 	  fprintf(ficgp,"$%d +",k+l);
 5227: 	else
 5228: 	  fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
 5229:       }
 5230:       fprintf(ficgp,"\nset out\n");
 5231:     } /* end cpt state*/ 
 5232:   } /* end covariate */  
 5233: 
 5234:   /* CV preval stable (period) for each covariate */
 5235:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
 5236:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 5237:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
 5238:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 5239: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 5240: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5241: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5242: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5243: 	vlv= nbcode[Tvaraff[lv]][lv];
 5244: 	fprintf(ficgp," V%d=%d ",k,vlv);
 5245:       }
 5246:       fprintf(ficgp,"\n#\n");
 5247: 
 5248:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
 5249:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 5250: set ter svg size 640, 480\n\
 5251: unset log y\n\
 5252: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 5253:       k=3; /* Offset */
 5254:       for (i=1; i<= nlstate ; i ++){
 5255: 	if(i==1)
 5256: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 5257: 	else
 5258: 	  fprintf(ficgp,", '' ");
 5259: 	l=(nlstate+ndeath)*(i-1)+1;
 5260: 	fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 5261: 	for (j=2; j<= nlstate ; j ++)
 5262: 	  fprintf(ficgp,"+$%d",k+l+j-1);
 5263: 	fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
 5264:       } /* nlstate */
 5265:       fprintf(ficgp,"\nset out\n");
 5266:     } /* end cpt state*/ 
 5267:   } /* end covariate */  
 5268: 
 5269:   if(prevfcast==1){
 5270:   /* Projection from cross-sectional to stable (period) for each covariate */
 5271: 
 5272:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
 5273:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 5274: 	fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
 5275: 	for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
 5276: 	  lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
 5277: 	  /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5278: 	  /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5279: 	  /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5280: 	  vlv= nbcode[Tvaraff[lv]][lv];
 5281: 	  fprintf(ficgp," V%d=%d ",k,vlv);
 5282: 	}
 5283: 	fprintf(ficgp,"\n#\n");
 5284: 	
 5285: 	fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
 5286: 	fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
 5287: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
 5288: set ter svg size 640, 480\n\
 5289: unset log y\n\
 5290: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 5291: 	for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
 5292: 	  /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 5293: 	  /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 5294: 	  /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 5295: 	  /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 5296: 	  if(i==1){
 5297: 	    fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
 5298: 	  }else{
 5299: 	    fprintf(ficgp,",\\\n '' ");
 5300: 	  }
 5301: 	  if(cptcoveff ==0){ /* No covariate */
 5302: 	    fprintf(ficgp," u 2:("); /* Age is in 2 */
 5303: 	    /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
 5304: 	    /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
 5305: 	    if(i==nlstate+1)
 5306: 	      fprintf(ficgp," $%d/(1.-$%d)) t 'p.%d' with line ", \
 5307: 			2+(cpt-1)*(nlstate+1)+1+(i-1),  2+1+(i-1)+(nlstate+1)*nlstate,cpt );
 5308: 	    else
 5309: 	      fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ", \
 5310: 		      2+(cpt-1)*(nlstate+1)+1+(i-1),  2+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
 5311: 	  }else{
 5312: 	    fprintf(ficgp,"u 6:(("); /* Age is in 6 */
 5313: 	    /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 5314: 	    /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 5315: 	    kl=0;
 5316: 	    for (k=1; k<=cptcoveff; k++){    /* For each covariate  */
 5317: 	      lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
 5318: 	      /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5319: 	      /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5320: 	      /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5321: 	      vlv= nbcode[Tvaraff[lv]][lv];
 5322: 	      kl++;
 5323: 	      /* kl=6+(cpt-1)*(nlstate+1)+1+(i-1); /\* 6+(1-1)*(2+1)+1+(1-1)=7, 6+(2-1)(2+1)+1+(1-1)=10 *\/ */
 5324: 	      /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
 5325: 	      /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
 5326: 	      /* ''  u 6:(($1==1 && $2==0 && $3==2 && $4==0)? $9/(1.-$15) : 1/0):($5==2000? 3:2) t 'p.1' with line lc variable*/
 5327: 	      if(k==cptcoveff)
 5328: 		if(i==nlstate+1)
 5329: 		  fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv], \
 5330: 			  6+(cpt-1)*(nlstate+1)+1+(i-1),  6+1+(i-1)+(nlstate+1)*nlstate,cpt );
 5331: 		else
 5332: 		  fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv], \
 5333: 			  6+(cpt-1)*(nlstate+1)+1+(i-1),  6+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
 5334: 	      else{
 5335: 		fprintf(ficgp,"$%d==%d && $%d==%d && ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv]);
 5336: 		kl++;
 5337: 	      }
 5338: 	    } /* end covariate */
 5339: 	  } /* end if covariate */
 5340: 	} /* nlstate */
 5341: 	fprintf(ficgp,"\nset out\n");
 5342:       } /* end cpt state*/
 5343:     } /* end covariate */
 5344:   } /* End if prevfcast */
 5345: 
 5346: 
 5347:   /* proba elementaires */
 5348:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
 5349:   for(i=1,jk=1; i <=nlstate; i++){
 5350:     fprintf(ficgp,"# initial state %d\n",i);
 5351:     for(k=1; k <=(nlstate+ndeath); k++){
 5352:       if (k != i) {
 5353: 	fprintf(ficgp,"#   current state %d\n",k);
 5354: 	for(j=1; j <=ncovmodel; j++){
 5355: 	  fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
 5356: 	  jk++; 
 5357: 	}
 5358: 	fprintf(ficgp,"\n");
 5359:       }
 5360:     }
 5361:    }
 5362:   fprintf(ficgp,"##############\n#\n");
 5363: 
 5364:   /*goto avoid;*/
 5365:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
 5366:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
 5367:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
 5368:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
 5369:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
 5370:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 5371:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 5372:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 5373:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 5374:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
 5375:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 5376:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
 5377:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
 5378:   fprintf(ficgp,"#\n");
 5379:    for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
 5380:      fprintf(ficgp,"# ng=%d\n",ng);
 5381:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
 5382:      for(jk=1; jk <=m; jk++) {
 5383:        fprintf(ficgp,"#    jk=%d\n",jk);
 5384:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
 5385:        fprintf(ficgp,"\nset ter svg size 640, 480 ");
 5386:        if (ng==1){
 5387: 	 fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
 5388: 	 fprintf(ficgp,"\nunset log y");
 5389:        }else if (ng==2){
 5390: 	 fprintf(ficgp,"\nset ylabel \"Probability\"\n");
 5391: 	 fprintf(ficgp,"\nset log y");
 5392:        }else if (ng==3){
 5393: 	 fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
 5394: 	 fprintf(ficgp,"\nset log y");
 5395:        }else
 5396: 	 fprintf(ficgp,"\nunset title ");
 5397:        fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
 5398:        i=1;
 5399:        for(k2=1; k2<=nlstate; k2++) {
 5400: 	 k3=i;
 5401: 	 for(k=1; k<=(nlstate+ndeath); k++) {
 5402: 	   if (k != k2){
 5403: 	     switch( ng) {
 5404: 	     case 1:
 5405: 	       if(nagesqr==0)
 5406: 		 fprintf(ficgp," p%d+p%d*x",i,i+1);
 5407: 	       else /* nagesqr =1 */
 5408: 		 fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
 5409: 	       break;
 5410: 	     case 2: /* ng=2 */
 5411: 	       if(nagesqr==0)
 5412: 		 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
 5413: 	       else /* nagesqr =1 */
 5414: 		   fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
 5415: 	       break;
 5416: 	     case 3:
 5417: 	       if(nagesqr==0)
 5418: 		 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
 5419: 	       else /* nagesqr =1 */
 5420: 		 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
 5421: 	       break;
 5422: 	     }
 5423: 	     ij=1;/* To be checked else nbcode[0][0] wrong */
 5424: 	     for(j=3; j <=ncovmodel-nagesqr; j++) {
 5425: 	       /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
 5426: 	       if(ij <=cptcovage) { /* Bug valgrind */
 5427: 		 if((j-2)==Tage[ij]) { /* Bug valgrind */
 5428: 		   fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
 5429: 		   /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
 5430: 		   ij++;
 5431: 		 }
 5432: 	       }
 5433: 	       else
 5434: 		 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
 5435: 	     }
 5436: 	     if(ng != 1){
 5437: 	       fprintf(ficgp,")/(1");
 5438: 	     
 5439: 	       for(k1=1; k1 <=nlstate; k1++){ 
 5440: 		 if(nagesqr==0)
 5441: 		   fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
 5442: 		 else /* nagesqr =1 */
 5443: 		   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);
 5444: 		 
 5445: 		 ij=1;
 5446: 		 for(j=3; j <=ncovmodel-nagesqr; j++){
 5447: 		   if(ij <=cptcovage) { /* Bug valgrind */
 5448: 		     if((j-2)==Tage[ij]) { /* Bug valgrind */
 5449: 		       fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
 5450: 		       /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
 5451: 		       ij++;
 5452: 		     }
 5453: 		   }
 5454: 		   else
 5455: 		     fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
 5456: 		 }
 5457: 		 fprintf(ficgp,")");
 5458: 	       }
 5459: 	       fprintf(ficgp,")");
 5460: 	       if(ng ==2)
 5461: 		 fprintf(ficgp," t \"p%d%d\" ", k2,k);
 5462: 	       else /* ng= 3 */
 5463: 		 fprintf(ficgp," t \"i%d%d\" ", k2,k);
 5464: 	     }else{ /* end ng <> 1 */
 5465: 	       fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
 5466: 	     }
 5467: 	     if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
 5468: 	     i=i+ncovmodel;
 5469: 	   }
 5470: 	 } /* end k */
 5471:        } /* end k2 */
 5472:        fprintf(ficgp,"\n set out\n");
 5473:      } /* end jk */
 5474:    } /* end ng */
 5475:  /* avoid: */
 5476:    fflush(ficgp); 
 5477: }  /* end gnuplot */
 5478: 
 5479: 
 5480: /*************** Moving average **************/
 5481: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
 5482: 
 5483:   int i, cpt, cptcod;
 5484:   int modcovmax =1;
 5485:   int mobilavrange, mob;
 5486:   double age;
 5487: 
 5488:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
 5489: 			   a covariate has 2 modalities */
 5490:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
 5491: 
 5492:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
 5493:     if(mobilav==1) mobilavrange=5; /* default */
 5494:     else mobilavrange=mobilav;
 5495:     for (age=bage; age<=fage; age++)
 5496:       for (i=1; i<=nlstate;i++)
 5497: 	for (cptcod=1;cptcod<=modcovmax;cptcod++)
 5498: 	  mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 5499:     /* We keep the original values on the extreme ages bage, fage and for 
 5500:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
 5501:        we use a 5 terms etc. until the borders are no more concerned. 
 5502:     */ 
 5503:     for (mob=3;mob <=mobilavrange;mob=mob+2){
 5504:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
 5505: 	for (i=1; i<=nlstate;i++){
 5506: 	  for (cptcod=1;cptcod<=modcovmax;cptcod++){
 5507: 	    mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
 5508: 	      for (cpt=1;cpt<=(mob-1)/2;cpt++){
 5509: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
 5510: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
 5511: 	      }
 5512: 	    mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
 5513: 	  }
 5514: 	}
 5515:       }/* end age */
 5516:     }/* end mob */
 5517:   }else return -1;
 5518:   return 0;
 5519: }/* End movingaverage */
 5520: 
 5521: 
 5522: /************** Forecasting ******************/
 5523: 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){
 5524:   /* proj1, year, month, day of starting projection 
 5525:      agemin, agemax range of age
 5526:      dateprev1 dateprev2 range of dates during which prevalence is computed
 5527:      anproj2 year of en of projection (same day and month as proj1).
 5528:   */
 5529:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
 5530:   double agec; /* generic age */
 5531:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
 5532:   double *popeffectif,*popcount;
 5533:   double ***p3mat;
 5534:   double ***mobaverage;
 5535:   char fileresf[FILENAMELENGTH];
 5536: 
 5537:   agelim=AGESUP;
 5538:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 5539:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 5540:      We still use firstpass and lastpass as another selection.
 5541:   */
 5542:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 5543:  
 5544:   strcpy(fileresf,"F_"); 
 5545:   strcat(fileresf,fileresu);
 5546:   if((ficresf=fopen(fileresf,"w"))==NULL) {
 5547:     printf("Problem with forecast resultfile: %s\n", fileresf);
 5548:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
 5549:   }
 5550:   printf("Computing forecasting: result on file '%s' \n", fileresf);
 5551:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
 5552: 
 5553:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 5554: 
 5555:   if (mobilav!=0) {
 5556:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 5557:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 5558:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 5559:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 5560:     }
 5561:   }
 5562: 
 5563:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 5564:   if (stepm<=12) stepsize=1;
 5565:   if(estepm < stepm){
 5566:     printf ("Problem %d lower than %d\n",estepm, stepm);
 5567:   }
 5568:   else  hstepm=estepm;   
 5569: 
 5570:   hstepm=hstepm/stepm; 
 5571:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
 5572:                                fractional in yp1 */
 5573:   anprojmean=yp;
 5574:   yp2=modf((yp1*12),&yp);
 5575:   mprojmean=yp;
 5576:   yp1=modf((yp2*30.5),&yp);
 5577:   jprojmean=yp;
 5578:   if(jprojmean==0) jprojmean=1;
 5579:   if(mprojmean==0) jprojmean=1;
 5580: 
 5581:   i1=cptcoveff;
 5582:   if (cptcovn < 1){i1=1;}
 5583:   
 5584:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
 5585:   
 5586:   fprintf(ficresf,"#****** Routine prevforecast **\n");
 5587: 
 5588: /* 	      if (h==(int)(YEARM*yearp)){ */
 5589:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
 5590:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 5591:       k=k+1;
 5592:       fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
 5593:       for(j=1;j<=cptcoveff;j++) {
 5594: 	fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 5595:       }
 5596:       fprintf(ficresf," yearproj age");
 5597:       for(j=1; j<=nlstate+ndeath;j++){ 
 5598: 	for(i=1; i<=nlstate;i++) 	      
 5599:           fprintf(ficresf," p%d%d",i,j);
 5600: 	fprintf(ficresf," p.%d",j);
 5601:       }
 5602:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
 5603: 	fprintf(ficresf,"\n");
 5604: 	fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
 5605: 
 5606:      	for (agec=fage; agec>=(ageminpar-1); agec--){ 
 5607: 	  nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
 5608: 	  nhstepm = nhstepm/hstepm; 
 5609: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5610: 	  oldm=oldms;savm=savms;
 5611: 	  hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
 5612: 	
 5613: 	  for (h=0; h<=nhstepm; h++){
 5614: 	    if (h*hstepm/YEARM*stepm ==yearp) {
 5615:               fprintf(ficresf,"\n");
 5616:               for(j=1;j<=cptcoveff;j++) 
 5617:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 5618: 	      fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
 5619: 	    } 
 5620: 	    for(j=1; j<=nlstate+ndeath;j++) {
 5621: 	      ppij=0.;
 5622: 	      for(i=1; i<=nlstate;i++) {
 5623: 		if (mobilav==1) 
 5624: 		  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
 5625: 		else {
 5626: 		  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
 5627: 		}
 5628: 		if (h*hstepm/YEARM*stepm== yearp) {
 5629: 		  fprintf(ficresf," %.3f", p3mat[i][j][h]);
 5630: 		}
 5631: 	      } /* end i */
 5632: 	      if (h*hstepm/YEARM*stepm==yearp) {
 5633: 		fprintf(ficresf," %.3f", ppij);
 5634: 	      }
 5635: 	    }/* end j */
 5636: 	  } /* end h */
 5637: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5638: 	} /* end agec */
 5639:       } /* end yearp */
 5640:     } /* end cptcod */
 5641:   } /* end  cptcov */
 5642:        
 5643:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 5644: 
 5645:   fclose(ficresf);
 5646: }
 5647: 
 5648: /************** Forecasting *****not tested NB*************/
 5649: 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){
 5650:   
 5651:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
 5652:   int *popage;
 5653:   double calagedatem, agelim, kk1, kk2;
 5654:   double *popeffectif,*popcount;
 5655:   double ***p3mat,***tabpop,***tabpopprev;
 5656:   double ***mobaverage;
 5657:   char filerespop[FILENAMELENGTH];
 5658: 
 5659:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 5660:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 5661:   agelim=AGESUP;
 5662:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
 5663:   
 5664:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 5665:   
 5666:   
 5667:   strcpy(filerespop,"POP_"); 
 5668:   strcat(filerespop,fileresu);
 5669:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
 5670:     printf("Problem with forecast resultfile: %s\n", filerespop);
 5671:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
 5672:   }
 5673:   printf("Computing forecasting: result on file '%s' \n", filerespop);
 5674:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
 5675: 
 5676:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 5677: 
 5678:   if (mobilav!=0) {
 5679:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 5680:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 5681:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 5682:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 5683:     }
 5684:   }
 5685: 
 5686:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 5687:   if (stepm<=12) stepsize=1;
 5688:   
 5689:   agelim=AGESUP;
 5690:   
 5691:   hstepm=1;
 5692:   hstepm=hstepm/stepm; 
 5693:   
 5694:   if (popforecast==1) {
 5695:     if((ficpop=fopen(popfile,"r"))==NULL) {
 5696:       printf("Problem with population file : %s\n",popfile);exit(0);
 5697:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
 5698:     } 
 5699:     popage=ivector(0,AGESUP);
 5700:     popeffectif=vector(0,AGESUP);
 5701:     popcount=vector(0,AGESUP);
 5702:     
 5703:     i=1;   
 5704:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
 5705:    
 5706:     imx=i;
 5707:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
 5708:   }
 5709: 
 5710:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
 5711:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 5712:       k=k+1;
 5713:       fprintf(ficrespop,"\n#******");
 5714:       for(j=1;j<=cptcoveff;j++) {
 5715: 	fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 5716:       }
 5717:       fprintf(ficrespop,"******\n");
 5718:       fprintf(ficrespop,"# Age");
 5719:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
 5720:       if (popforecast==1)  fprintf(ficrespop," [Population]");
 5721:       
 5722:       for (cpt=0; cpt<=0;cpt++) { 
 5723: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 5724: 	
 5725:      	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 5726: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 5727: 	  nhstepm = nhstepm/hstepm; 
 5728: 	  
 5729: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5730: 	  oldm=oldms;savm=savms;
 5731: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 5732: 	
 5733: 	  for (h=0; h<=nhstepm; h++){
 5734: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 5735: 	      fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 5736: 	    } 
 5737: 	    for(j=1; j<=nlstate+ndeath;j++) {
 5738: 	      kk1=0.;kk2=0;
 5739: 	      for(i=1; i<=nlstate;i++) {	      
 5740: 		if (mobilav==1) 
 5741: 		  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
 5742: 		else {
 5743: 		  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
 5744: 		}
 5745: 	      }
 5746: 	      if (h==(int)(calagedatem+12*cpt)){
 5747: 		tabpop[(int)(agedeb)][j][cptcod]=kk1;
 5748: 		  /*fprintf(ficrespop," %.3f", kk1);
 5749: 		    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
 5750: 	      }
 5751: 	    }
 5752: 	    for(i=1; i<=nlstate;i++){
 5753: 	      kk1=0.;
 5754: 		for(j=1; j<=nlstate;j++){
 5755: 		  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
 5756: 		}
 5757: 		  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
 5758: 	    }
 5759: 
 5760: 	    if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
 5761: 	      fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
 5762: 	  }
 5763: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5764: 	}
 5765:       }
 5766:  
 5767:   /******/
 5768: 
 5769:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
 5770: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 5771: 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 5772: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 5773: 	  nhstepm = nhstepm/hstepm; 
 5774: 	  
 5775: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5776: 	  oldm=oldms;savm=savms;
 5777: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 5778: 	  for (h=0; h<=nhstepm; h++){
 5779: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 5780: 	      fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 5781: 	    } 
 5782: 	    for(j=1; j<=nlstate+ndeath;j++) {
 5783: 	      kk1=0.;kk2=0;
 5784: 	      for(i=1; i<=nlstate;i++) {	      
 5785: 		kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];	
 5786: 	      }
 5787: 	      if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);	
 5788: 	    }
 5789: 	  }
 5790: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5791: 	}
 5792:       }
 5793:    } 
 5794:   }
 5795:  
 5796:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 5797: 
 5798:   if (popforecast==1) {
 5799:     free_ivector(popage,0,AGESUP);
 5800:     free_vector(popeffectif,0,AGESUP);
 5801:     free_vector(popcount,0,AGESUP);
 5802:   }
 5803:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 5804:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 5805:   fclose(ficrespop);
 5806: } /* End of popforecast */
 5807: 
 5808: int fileappend(FILE *fichier, char *optionfich)
 5809: {
 5810:   if((fichier=fopen(optionfich,"a"))==NULL) {
 5811:     printf("Problem with file: %s\n", optionfich);
 5812:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
 5813:     return (0);
 5814:   }
 5815:   fflush(fichier);
 5816:   return (1);
 5817: }
 5818: 
 5819: 
 5820: /**************** function prwizard **********************/
 5821: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
 5822: {
 5823: 
 5824:   /* Wizard to print covariance matrix template */
 5825: 
 5826:   char ca[32], cb[32];
 5827:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
 5828:   int numlinepar;
 5829: 
 5830:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 5831:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 5832:   for(i=1; i <=nlstate; i++){
 5833:     jj=0;
 5834:     for(j=1; j <=nlstate+ndeath; j++){
 5835:       if(j==i) continue;
 5836:       jj++;
 5837:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
 5838:       printf("%1d%1d",i,j);
 5839:       fprintf(ficparo,"%1d%1d",i,j);
 5840:       for(k=1; k<=ncovmodel;k++){
 5841: 	/* 	  printf(" %lf",param[i][j][k]); */
 5842: 	/* 	  fprintf(ficparo," %lf",param[i][j][k]); */
 5843: 	printf(" 0.");
 5844: 	fprintf(ficparo," 0.");
 5845:       }
 5846:       printf("\n");
 5847:       fprintf(ficparo,"\n");
 5848:     }
 5849:   }
 5850:   printf("# Scales (for hessian or gradient estimation)\n");
 5851:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
 5852:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
 5853:   for(i=1; i <=nlstate; i++){
 5854:     jj=0;
 5855:     for(j=1; j <=nlstate+ndeath; j++){
 5856:       if(j==i) continue;
 5857:       jj++;
 5858:       fprintf(ficparo,"%1d%1d",i,j);
 5859:       printf("%1d%1d",i,j);
 5860:       fflush(stdout);
 5861:       for(k=1; k<=ncovmodel;k++){
 5862: 	/* 	printf(" %le",delti3[i][j][k]); */
 5863: 	/* 	fprintf(ficparo," %le",delti3[i][j][k]); */
 5864: 	printf(" 0.");
 5865: 	fprintf(ficparo," 0.");
 5866:       }
 5867:       numlinepar++;
 5868:       printf("\n");
 5869:       fprintf(ficparo,"\n");
 5870:     }
 5871:   }
 5872:   printf("# Covariance matrix\n");
 5873: /* # 121 Var(a12)\n\ */
 5874: /* # 122 Cov(b12,a12) Var(b12)\n\ */
 5875: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 5876: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 5877: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 5878: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 5879: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 5880: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 5881:   fflush(stdout);
 5882:   fprintf(ficparo,"# Covariance matrix\n");
 5883:   /* # 121 Var(a12)\n\ */
 5884:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
 5885:   /* #   ...\n\ */
 5886:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
 5887:   
 5888:   for(itimes=1;itimes<=2;itimes++){
 5889:     jj=0;
 5890:     for(i=1; i <=nlstate; i++){
 5891:       for(j=1; j <=nlstate+ndeath; j++){
 5892: 	if(j==i) continue;
 5893: 	for(k=1; k<=ncovmodel;k++){
 5894: 	  jj++;
 5895: 	  ca[0]= k+'a'-1;ca[1]='\0';
 5896: 	  if(itimes==1){
 5897: 	    printf("#%1d%1d%d",i,j,k);
 5898: 	    fprintf(ficparo,"#%1d%1d%d",i,j,k);
 5899: 	  }else{
 5900: 	    printf("%1d%1d%d",i,j,k);
 5901: 	    fprintf(ficparo,"%1d%1d%d",i,j,k);
 5902: 	    /* 	printf(" %.5le",matcov[i][j]); */
 5903: 	  }
 5904: 	  ll=0;
 5905: 	  for(li=1;li <=nlstate; li++){
 5906: 	    for(lj=1;lj <=nlstate+ndeath; lj++){
 5907: 	      if(lj==li) continue;
 5908: 	      for(lk=1;lk<=ncovmodel;lk++){
 5909: 		ll++;
 5910: 		if(ll<=jj){
 5911: 		  cb[0]= lk +'a'-1;cb[1]='\0';
 5912: 		  if(ll<jj){
 5913: 		    if(itimes==1){
 5914: 		      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 5915: 		      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 5916: 		    }else{
 5917: 		      printf(" 0.");
 5918: 		      fprintf(ficparo," 0.");
 5919: 		    }
 5920: 		  }else{
 5921: 		    if(itimes==1){
 5922: 		      printf(" Var(%s%1d%1d)",ca,i,j);
 5923: 		      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
 5924: 		    }else{
 5925: 		      printf(" 0.");
 5926: 		      fprintf(ficparo," 0.");
 5927: 		    }
 5928: 		  }
 5929: 		}
 5930: 	      } /* end lk */
 5931: 	    } /* end lj */
 5932: 	  } /* end li */
 5933: 	  printf("\n");
 5934: 	  fprintf(ficparo,"\n");
 5935: 	  numlinepar++;
 5936: 	} /* end k*/
 5937:       } /*end j */
 5938:     } /* end i */
 5939:   } /* end itimes */
 5940: 
 5941: } /* end of prwizard */
 5942: /******************* Gompertz Likelihood ******************************/
 5943: double gompertz(double x[])
 5944: { 
 5945:   double A,B,L=0.0,sump=0.,num=0.;
 5946:   int i,n=0; /* n is the size of the sample */
 5947: 
 5948:   for (i=0;i<=imx-1 ; i++) {
 5949:     sump=sump+weight[i];
 5950:     /*    sump=sump+1;*/
 5951:     num=num+1;
 5952:   }
 5953:  
 5954:  
 5955:   /* for (i=0; i<=imx; i++) 
 5956:      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]);*/
 5957: 
 5958:   for (i=1;i<=imx ; i++)
 5959:     {
 5960:       if (cens[i] == 1 && wav[i]>1)
 5961: 	A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
 5962:       
 5963:       if (cens[i] == 0 && wav[i]>1)
 5964: 	A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
 5965: 	     +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
 5966:       
 5967:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 5968:       if (wav[i] > 1 ) { /* ??? */
 5969: 	L=L+A*weight[i];
 5970: 	/* 	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]);*/
 5971:       }
 5972:     }
 5973: 
 5974:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 5975:  
 5976:   return -2*L*num/sump;
 5977: }
 5978: 
 5979: #ifdef GSL
 5980: /******************* Gompertz_f Likelihood ******************************/
 5981: double gompertz_f(const gsl_vector *v, void *params)
 5982: { 
 5983:   double A,B,LL=0.0,sump=0.,num=0.;
 5984:   double *x= (double *) v->data;
 5985:   int i,n=0; /* n is the size of the sample */
 5986: 
 5987:   for (i=0;i<=imx-1 ; i++) {
 5988:     sump=sump+weight[i];
 5989:     /*    sump=sump+1;*/
 5990:     num=num+1;
 5991:   }
 5992:  
 5993:  
 5994:   /* for (i=0; i<=imx; i++) 
 5995:      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]);*/
 5996:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
 5997:   for (i=1;i<=imx ; i++)
 5998:     {
 5999:       if (cens[i] == 1 && wav[i]>1)
 6000: 	A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
 6001:       
 6002:       if (cens[i] == 0 && wav[i]>1)
 6003: 	A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
 6004: 	     +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
 6005:       
 6006:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 6007:       if (wav[i] > 1 ) { /* ??? */
 6008: 	LL=LL+A*weight[i];
 6009: 	/* 	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]);*/
 6010:       }
 6011:     }
 6012: 
 6013:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 6014:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
 6015:  
 6016:   return -2*LL*num/sump;
 6017: }
 6018: #endif
 6019: 
 6020: /******************* Printing html file ***********/
 6021: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
 6022: 		  int lastpass, int stepm, int weightopt, char model[],\
 6023: 		  int imx,  double p[],double **matcov,double agemortsup){
 6024:   int i,k;
 6025: 
 6026:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
 6027:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
 6028:   for (i=1;i<=2;i++) 
 6029:     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]));
 6030:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
 6031:   fprintf(fichtm,"</ul>");
 6032: 
 6033: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
 6034: 
 6035:  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>");
 6036: 
 6037:  for (k=agegomp;k<(agemortsup-2);k++) 
 6038:    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]);
 6039: 
 6040:  
 6041:   fflush(fichtm);
 6042: }
 6043: 
 6044: /******************* Gnuplot file **************/
 6045: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 6046: 
 6047:   char dirfileres[132],optfileres[132];
 6048: 
 6049:   int ng;
 6050: 
 6051: 
 6052:   /*#ifdef windows */
 6053:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 6054:     /*#endif */
 6055: 
 6056: 
 6057:   strcpy(dirfileres,optionfilefiname);
 6058:   strcpy(optfileres,"vpl");
 6059:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
 6060:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
 6061:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
 6062:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
 6063:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
 6064: 
 6065: } 
 6066: 
 6067: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
 6068: {
 6069: 
 6070:   /*-------- data file ----------*/
 6071:   FILE *fic;
 6072:   char dummy[]="                         ";
 6073:   int i=0, j=0, n=0;
 6074:   int linei, month, year,iout;
 6075:   char line[MAXLINE], linetmp[MAXLINE];
 6076:   char stra[MAXLINE], strb[MAXLINE];
 6077:   char *stratrunc;
 6078:   int lstra;
 6079: 
 6080: 
 6081:   if((fic=fopen(datafile,"r"))==NULL)    {
 6082:     printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
 6083:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
 6084:   }
 6085: 
 6086:   i=1;
 6087:   linei=0;
 6088:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
 6089:     linei=linei+1;
 6090:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
 6091:       if(line[j] == '\t')
 6092: 	line[j] = ' ';
 6093:     }
 6094:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
 6095:       ;
 6096:     };
 6097:     line[j+1]=0;  /* Trims blanks at end of line */
 6098:     if(line[0]=='#'){
 6099:       fprintf(ficlog,"Comment line\n%s\n",line);
 6100:       printf("Comment line\n%s\n",line);
 6101:       continue;
 6102:     }
 6103:     trimbb(linetmp,line); /* Trims multiple blanks in line */
 6104:     strcpy(line, linetmp);
 6105:   
 6106: 
 6107:     for (j=maxwav;j>=1;j--){
 6108:       cutv(stra, strb, line, ' '); 
 6109:       if(strb[0]=='.') { /* Missing status */
 6110: 	lval=-1;
 6111:       }else{
 6112: 	errno=0;
 6113: 	lval=strtol(strb,&endptr,10); 
 6114:       /*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
 6115: 	if( strb[0]=='\0' || (*endptr != '\0')){
 6116: 	  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);
 6117: 	  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);
 6118: 	  return 1;
 6119: 	}
 6120:       }
 6121:       s[j][i]=lval;
 6122:       
 6123:       strcpy(line,stra);
 6124:       cutv(stra, strb,line,' ');
 6125:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 6126:       }
 6127:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 6128: 	month=99;
 6129: 	year=9999;
 6130:       }else{
 6131: 	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);
 6132: 	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);
 6133: 	return 1;
 6134:       }
 6135:       anint[j][i]= (double) year; 
 6136:       mint[j][i]= (double)month; 
 6137:       strcpy(line,stra);
 6138:     } /* ENd Waves */
 6139:     
 6140:     cutv(stra, strb,line,' '); 
 6141:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 6142:     }
 6143:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 6144:       month=99;
 6145:       year=9999;
 6146:     }else{
 6147:       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);
 6148: 	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);
 6149: 	return 1;
 6150:     }
 6151:     andc[i]=(double) year; 
 6152:     moisdc[i]=(double) month; 
 6153:     strcpy(line,stra);
 6154:     
 6155:     cutv(stra, strb,line,' '); 
 6156:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 6157:     }
 6158:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
 6159:       month=99;
 6160:       year=9999;
 6161:     }else{
 6162:       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);
 6163:       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);
 6164: 	return 1;
 6165:     }
 6166:     if (year==9999) {
 6167:       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);
 6168:       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);
 6169: 	return 1;
 6170: 
 6171:     }
 6172:     annais[i]=(double)(year);
 6173:     moisnais[i]=(double)(month); 
 6174:     strcpy(line,stra);
 6175:     
 6176:     cutv(stra, strb,line,' '); 
 6177:     errno=0;
 6178:     dval=strtod(strb,&endptr); 
 6179:     if( strb[0]=='\0' || (*endptr != '\0')){
 6180:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
 6181:       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);
 6182:       fflush(ficlog);
 6183:       return 1;
 6184:     }
 6185:     weight[i]=dval; 
 6186:     strcpy(line,stra);
 6187:     
 6188:     for (j=ncovcol;j>=1;j--){
 6189:       cutv(stra, strb,line,' '); 
 6190:       if(strb[0]=='.') { /* Missing status */
 6191: 	lval=-1;
 6192:       }else{
 6193: 	errno=0;
 6194: 	lval=strtol(strb,&endptr,10); 
 6195: 	if( strb[0]=='\0' || (*endptr != '\0')){
 6196: 	  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);
 6197: 	  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);
 6198: 	  return 1;
 6199: 	}
 6200:       }
 6201:       if(lval <-1 || lval >1){
 6202: 	printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 6203:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 6204:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 6205:  For example, for multinomial values like 1, 2 and 3,\n \
 6206:  build V1=0 V2=0 for the reference value (1),\n \
 6207:         V1=1 V2=0 for (2) \n \
 6208:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 6209:  output of IMaCh is often meaningless.\n \
 6210:  Exiting.\n",lval,linei, i,line,j);
 6211: 	fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 6212:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 6213:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 6214:  For example, for multinomial values like 1, 2 and 3,\n \
 6215:  build V1=0 V2=0 for the reference value (1),\n \
 6216:         V1=1 V2=0 for (2) \n \
 6217:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 6218:  output of IMaCh is often meaningless.\n \
 6219:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
 6220: 	return 1;
 6221:       }
 6222:       covar[j][i]=(double)(lval);
 6223:       strcpy(line,stra);
 6224:     }  
 6225:     lstra=strlen(stra);
 6226:      
 6227:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
 6228:       stratrunc = &(stra[lstra-9]);
 6229:       num[i]=atol(stratrunc);
 6230:     }
 6231:     else
 6232:       num[i]=atol(stra);
 6233:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
 6234:       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;}*/
 6235:     
 6236:     i=i+1;
 6237:   } /* End loop reading  data */
 6238: 
 6239:   *imax=i-1; /* Number of individuals */
 6240:   fclose(fic);
 6241:  
 6242:   return (0);
 6243:   /* endread: */
 6244:     printf("Exiting readdata: ");
 6245:     fclose(fic);
 6246:     return (1);
 6247: 
 6248: 
 6249: 
 6250: }
 6251: void removespace(char *str) {
 6252:   char *p1 = str, *p2 = str;
 6253:   do
 6254:     while (*p2 == ' ')
 6255:       p2++;
 6256:   while (*p1++ == *p2++);
 6257: }
 6258: 
 6259: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
 6260:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
 6261:    * - nagesqr = 1 if age*age in the model, otherwise 0.
 6262:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
 6263:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
 6264:    * - cptcovage number of covariates with age*products =2
 6265:    * - cptcovs number of simple covariates
 6266:    * - 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
 6267:    *     which is a new column after the 9 (ncovcol) variables. 
 6268:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
 6269:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
 6270:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
 6271:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
 6272:  */
 6273: {
 6274:   int i, j, k, ks;
 6275:   int  j1, k1, k2;
 6276:   char modelsav[80];
 6277:   char stra[80], strb[80], strc[80], strd[80],stre[80];
 6278:   char *strpt;
 6279: 
 6280:   /*removespace(model);*/
 6281:   if (strlen(model) >1){ /* If there is at least 1 covariate */
 6282:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
 6283:     if (strstr(model,"AGE") !=0){
 6284:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
 6285:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
 6286:       return 1;
 6287:     }
 6288:     if (strstr(model,"v") !=0){
 6289:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
 6290:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
 6291:       return 1;
 6292:     }
 6293:     strcpy(modelsav,model); 
 6294:     if ((strpt=strstr(model,"age*age")) !=0){
 6295:       printf(" strpt=%s, model=%s\n",strpt, model);
 6296:       if(strpt != model){
 6297:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
 6298:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
 6299:  corresponding column of parameters.\n",model);
 6300:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
 6301:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
 6302:  corresponding column of parameters.\n",model); fflush(ficlog);
 6303:       return 1;
 6304:     }
 6305: 
 6306:       nagesqr=1;
 6307:       if (strstr(model,"+age*age") !=0)
 6308: 	substrchaine(modelsav, model, "+age*age");
 6309:       else if (strstr(model,"age*age+") !=0)
 6310: 	substrchaine(modelsav, model, "age*age+");
 6311:       else 
 6312: 	substrchaine(modelsav, model, "age*age");
 6313:     }else
 6314:       nagesqr=0;
 6315:     if (strlen(modelsav) >1){
 6316:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
 6317:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
 6318:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
 6319:       cptcovt= j+1; /* Number of total covariates in the model, not including
 6320: 		   * cst, age and age*age 
 6321: 		   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
 6322:                   /* including age products which are counted in cptcovage.
 6323: 		  * but the covariates which are products must be treated 
 6324: 		  * separately: ncovn=4- 2=2 (V1+V3). */
 6325:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
 6326:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
 6327: 
 6328:     
 6329:       /*   Design
 6330:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
 6331:        *  <          ncovcol=8                >
 6332:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
 6333:        *   k=  1    2      3       4     5       6      7        8
 6334:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
 6335:        *  covar[k,i], value of kth covariate if not including age for individual i:
 6336:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
 6337:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
 6338:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
 6339:        *  Tage[++cptcovage]=k
 6340:        *       if products, new covar are created after ncovcol with k1
 6341:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
 6342:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
 6343:        *  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
 6344:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
 6345:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
 6346:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
 6347:        *  <          ncovcol=8                >
 6348:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
 6349:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
 6350:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
 6351:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 6352:        * p Tprod[1]@2={                         6, 5}
 6353:        *p Tvard[1][1]@4= {7, 8, 5, 6}
 6354:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
 6355:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 6356:        *How to reorganize?
 6357:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
 6358:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 6359:        *       {2,   1,     4,      8,    5,      6,     3,       7}
 6360:        * Struct []
 6361:        */
 6362: 
 6363:       /* This loop fills the array Tvar from the string 'model'.*/
 6364:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
 6365:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
 6366:       /* 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
 6367:       /* 	k=3 V4 Tvar[k=3]= 4 (from V4) */
 6368:       /* 	k=2 V1 Tvar[k=2]= 1 (from V1) */
 6369:       /* 	k=1 Tvar[1]=2 (from V2) */
 6370:       /* 	k=5 Tvar[5] */
 6371:       /* for (k=1; k<=cptcovn;k++) { */
 6372:       /* 	cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 6373:       /* 	} */
 6374:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
 6375:       /*
 6376:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
 6377:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
 6378:         Tvar[k]=0;
 6379:       cptcovage=0;
 6380:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
 6381: 	cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
 6382: 					 modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
 6383: 	if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
 6384: 	/*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
 6385: 	/*scanf("%d",i);*/
 6386: 	if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
 6387: 	  cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
 6388: 	  if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
 6389: 	    /* covar is not filled and then is empty */
 6390: 	    cptcovprod--;
 6391: 	    cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
 6392: 	    Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
 6393: 	    cptcovage++; /* Sums the number of covariates which include age as a product */
 6394: 	    Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
 6395: 	    /*printf("stre=%s ", stre);*/
 6396: 	  } else if (strcmp(strd,"age")==0) { /* or age*Vn */
 6397: 	    cptcovprod--;
 6398: 	    cutl(stre,strb,strc,'V');
 6399: 	    Tvar[k]=atoi(stre);
 6400: 	    cptcovage++;
 6401: 	    Tage[cptcovage]=k;
 6402: 	  } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
 6403: 	    /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
 6404: 	    cptcovn++;
 6405: 	    cptcovprodnoage++;k1++;
 6406: 	    cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
 6407: 	    Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
 6408: 				   because this model-covariate is a construction we invent a new column
 6409: 				   ncovcol + k1
 6410: 				   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
 6411: 				   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
 6412: 	    cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
 6413: 	    Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
 6414: 	    Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
 6415: 	    Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
 6416: 	    k2=k2+2;
 6417: 	    Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
 6418: 	    Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
 6419: 	    for (i=1; i<=lastobs;i++){
 6420: 	      /* Computes the new covariate which is a product of
 6421: 		 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
 6422: 	      covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
 6423: 	    }
 6424: 	  } /* End age is not in the model */
 6425: 	} /* End if model includes a product */
 6426: 	else { /* no more sum */
 6427: 	  /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
 6428: 	  /*  scanf("%d",i);*/
 6429: 	  cutl(strd,strc,strb,'V');
 6430: 	  ks++; /**< Number of simple covariates */
 6431: 	  cptcovn++;
 6432: 	  Tvar[k]=atoi(strd);
 6433: 	}
 6434: 	strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
 6435: 	/*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
 6436: 	  scanf("%d",i);*/
 6437:       } /* end of loop + on total covariates */
 6438:     } /* end if strlen(modelsave == 0) age*age might exist */
 6439:   } /* end if strlen(model == 0) */
 6440:   
 6441:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
 6442:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
 6443: 
 6444:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
 6445:   printf("cptcovprod=%d ", cptcovprod);
 6446:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
 6447: 
 6448:   scanf("%d ",i);*/
 6449: 
 6450: 
 6451:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
 6452:   /*endread:*/
 6453:     printf("Exiting decodemodel: ");
 6454:     return (1);
 6455: }
 6456: 
 6457: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
 6458: {
 6459:   int i, m;
 6460: 
 6461:   for (i=1; i<=imx; i++) {
 6462:     for(m=2; (m<= maxwav); m++) {
 6463:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
 6464: 	anint[m][i]=9999;
 6465: 	s[m][i]=-1;
 6466:       }
 6467:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
 6468: 	*nberr = *nberr + 1;
 6469: 	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);
 6470: 	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);
 6471: 	s[m][i]=-1;
 6472:       }
 6473:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
 6474: 	(*nberr)++;
 6475: 	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]); 
 6476: 	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]); 
 6477: 	s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
 6478:       }
 6479:     }
 6480:   }
 6481: 
 6482:   for (i=1; i<=imx; i++)  {
 6483:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
 6484:     for(m=firstpass; (m<= lastpass); m++){
 6485:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
 6486: 	if (s[m][i] >= nlstate+1) {
 6487: 	  if(agedc[i]>0){
 6488: 	    if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
 6489: 	      agev[m][i]=agedc[i];
 6490: 	  /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
 6491: 	    }else {
 6492: 	      if ((int)andc[i]!=9999){
 6493: 		nbwarn++;
 6494: 		printf("Warning negative age at death: %ld line:%d\n",num[i],i);
 6495: 		fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
 6496: 		agev[m][i]=-1;
 6497: 	      }
 6498: 	    }
 6499: 	  } /* agedc > 0 */
 6500: 	}
 6501: 	else if(s[m][i] !=9){ /* Standard case, age in fractional
 6502: 				 years but with the precision of a month */
 6503: 	  agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
 6504: 	  if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
 6505: 	    agev[m][i]=1;
 6506: 	  else if(agev[m][i] < *agemin){ 
 6507: 	    *agemin=agev[m][i];
 6508: 	    printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
 6509: 	  }
 6510: 	  else if(agev[m][i] >*agemax){
 6511: 	    *agemax=agev[m][i];
 6512: 	    /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
 6513: 	  }
 6514: 	  /*agev[m][i]=anint[m][i]-annais[i];*/
 6515: 	  /*	 agev[m][i] = age[i]+2*m;*/
 6516: 	}
 6517: 	else { /* =9 */
 6518: 	  agev[m][i]=1;
 6519: 	  s[m][i]=-1;
 6520: 	}
 6521:       }
 6522:       else /*= 0 Unknown */
 6523: 	agev[m][i]=1;
 6524:     }
 6525:     
 6526:   }
 6527:   for (i=1; i<=imx; i++)  {
 6528:     for(m=firstpass; (m<=lastpass); m++){
 6529:       if (s[m][i] > (nlstate+ndeath)) {
 6530: 	(*nberr)++;
 6531: 	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);	
 6532: 	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);	
 6533: 	return 1;
 6534:       }
 6535:     }
 6536:   }
 6537: 
 6538:   /*for (i=1; i<=imx; i++){
 6539:   for (m=firstpass; (m<lastpass); m++){
 6540:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
 6541: }
 6542: 
 6543: }*/
 6544: 
 6545: 
 6546:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
 6547:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
 6548: 
 6549:   return (0);
 6550:  /* endread:*/
 6551:     printf("Exiting calandcheckages: ");
 6552:     return (1);
 6553: }
 6554: 
 6555: #if defined(_MSC_VER)
 6556: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 6557: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 6558: //#include "stdafx.h"
 6559: //#include <stdio.h>
 6560: //#include <tchar.h>
 6561: //#include <windows.h>
 6562: //#include <iostream>
 6563: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
 6564: 
 6565: LPFN_ISWOW64PROCESS fnIsWow64Process;
 6566: 
 6567: BOOL IsWow64()
 6568: {
 6569: 	BOOL bIsWow64 = FALSE;
 6570: 
 6571: 	//typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
 6572: 	//  (HANDLE, PBOOL);
 6573: 
 6574: 	//LPFN_ISWOW64PROCESS fnIsWow64Process;
 6575: 
 6576: 	HMODULE module = GetModuleHandle(_T("kernel32"));
 6577: 	const char funcName[] = "IsWow64Process";
 6578: 	fnIsWow64Process = (LPFN_ISWOW64PROCESS)
 6579: 		GetProcAddress(module, funcName);
 6580: 
 6581: 	if (NULL != fnIsWow64Process)
 6582: 	{
 6583: 		if (!fnIsWow64Process(GetCurrentProcess(),
 6584: 			&bIsWow64))
 6585: 			//throw std::exception("Unknown error");
 6586: 			printf("Unknown error\n");
 6587: 	}
 6588: 	return bIsWow64 != FALSE;
 6589: }
 6590: #endif
 6591: 
 6592: void syscompilerinfo(int logged)
 6593:  {
 6594:    /* #include "syscompilerinfo.h"*/
 6595:    /* command line Intel compiler 32bit windows, XP compatible:*/
 6596:    /* /GS /W3 /Gy
 6597:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
 6598:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
 6599:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
 6600:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
 6601:    */ 
 6602:    /* 64 bits */
 6603:    /*
 6604:      /GS /W3 /Gy
 6605:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
 6606:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
 6607:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
 6608:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
 6609:    /* Optimization are useless and O3 is slower than O2 */
 6610:    /*
 6611:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
 6612:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
 6613:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
 6614:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
 6615:    */
 6616:    /* Link is */ /* /OUT:"visual studio
 6617:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
 6618:       /PDB:"visual studio
 6619:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
 6620:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
 6621:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
 6622:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
 6623:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
 6624:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
 6625:       uiAccess='false'"
 6626:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
 6627:       /NOLOGO /TLBID:1
 6628:    */
 6629: #if defined __INTEL_COMPILER
 6630: #if defined(__GNUC__)
 6631: 	struct utsname sysInfo;  /* For Intel on Linux and OS/X */
 6632: #endif
 6633: #elif defined(__GNUC__) 
 6634: #ifndef  __APPLE__
 6635: #include <gnu/libc-version.h>  /* Only on gnu */
 6636: #endif
 6637:    struct utsname sysInfo;
 6638:    int cross = CROSS;
 6639:    if (cross){
 6640: 	   printf("Cross-");
 6641: 	   if(logged) fprintf(ficlog, "Cross-");
 6642:    }
 6643: #endif
 6644: 
 6645: #include <stdint.h>
 6646: 
 6647:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
 6648: #if defined(__clang__)
 6649:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");	/* Clang/LLVM. ---------------------------------------------- */
 6650: #endif
 6651: #if defined(__ICC) || defined(__INTEL_COMPILER)
 6652:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
 6653: #endif
 6654: #if defined(__GNUC__) || defined(__GNUG__)
 6655:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
 6656: #endif
 6657: #if defined(__HP_cc) || defined(__HP_aCC)
 6658:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
 6659: #endif
 6660: #if defined(__IBMC__) || defined(__IBMCPP__)
 6661:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
 6662: #endif
 6663: #if defined(_MSC_VER)
 6664:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
 6665: #endif
 6666: #if defined(__PGI)
 6667:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
 6668: #endif
 6669: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
 6670:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
 6671: #endif
 6672:    printf(" for "); if (logged) fprintf(ficlog, " for ");
 6673:    
 6674: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
 6675: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
 6676:     // Windows (x64 and x86)
 6677:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
 6678: #elif __unix__ // all unices, not all compilers
 6679:     // Unix
 6680:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
 6681: #elif __linux__
 6682:     // linux
 6683:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
 6684: #elif __APPLE__
 6685:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
 6686:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
 6687: #endif
 6688: 
 6689: /*  __MINGW32__	  */
 6690: /*  __CYGWIN__	 */
 6691: /* __MINGW64__  */
 6692: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
 6693: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
 6694: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
 6695: /* _WIN64  // Defined for applications for Win64. */
 6696: /* _M_X64 // Defined for compilations that target x64 processors. */
 6697: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
 6698: 
 6699: #if UINTPTR_MAX == 0xffffffff
 6700:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
 6701: #elif UINTPTR_MAX == 0xffffffffffffffff
 6702:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
 6703: #else
 6704:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
 6705: #endif
 6706: 
 6707: #if defined(__GNUC__)
 6708: # if defined(__GNUC_PATCHLEVEL__)
 6709: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 6710:                             + __GNUC_MINOR__ * 100 \
 6711:                             + __GNUC_PATCHLEVEL__)
 6712: # else
 6713: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 6714:                             + __GNUC_MINOR__ * 100)
 6715: # endif
 6716:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
 6717:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
 6718: 
 6719:    if (uname(&sysInfo) != -1) {
 6720:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 6721: 	 if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 6722:    }
 6723:    else
 6724:       perror("uname() error");
 6725:    //#ifndef __INTEL_COMPILER 
 6726: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
 6727:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
 6728:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
 6729: #endif
 6730: #endif
 6731: 
 6732:    //   void main()
 6733:    //   {
 6734: #if defined(_MSC_VER)
 6735:    if (IsWow64()){
 6736: 	   printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 6737: 	   if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 6738:    }
 6739:    else{
 6740: 	   printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 6741: 	   if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 6742:    }
 6743:    //	   printf("\nPress Enter to continue...");
 6744:    //	   getchar();
 6745:    //   }
 6746: 
 6747: #endif
 6748:    
 6749: 
 6750:  }
 6751: 
 6752:  int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
 6753:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 6754:   int i, j, k, i1 ;
 6755:   /* double ftolpl = 1.e-10; */
 6756:   double age, agebase, agelim;
 6757:   double tot;
 6758: 
 6759:   strcpy(filerespl,"PL_");
 6760:   strcat(filerespl,fileresu);
 6761:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
 6762:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
 6763:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
 6764:   }
 6765:   printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
 6766:   fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
 6767:   pstamp(ficrespl);
 6768:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
 6769:   fprintf(ficrespl,"#Age ");
 6770:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
 6771:   fprintf(ficrespl,"\n");
 6772:   
 6773:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
 6774: 
 6775:     agebase=ageminpar;
 6776:     agelim=agemaxpar;
 6777: 
 6778:     i1=pow(2,cptcoveff);
 6779:     if (cptcovn < 1){i1=1;}
 6780: 
 6781:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6782:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
 6783:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 6784: 	k=k+1;
 6785: 	/* to clean */
 6786: 	//printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
 6787: 	fprintf(ficrespl,"#******");
 6788: 	printf("#******");
 6789: 	fprintf(ficlog,"#******");
 6790: 	for(j=1;j<=cptcoveff;j++) {
 6791: 	  fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 6792: 	  printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 6793: 	  fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 6794: 	}
 6795: 	fprintf(ficrespl,"******\n");
 6796: 	printf("******\n");
 6797: 	fprintf(ficlog,"******\n");
 6798: 
 6799: 	fprintf(ficrespl,"#Age ");
 6800: 	for(j=1;j<=cptcoveff;j++) {
 6801: 	  fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 6802: 	}
 6803: 	for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
 6804: 	fprintf(ficrespl,"Total Years_to_converge\n");
 6805: 	
 6806: 	for (age=agebase; age<=agelim; age++){
 6807: 	/* for (age=agebase; age<=agebase; age++){ */
 6808: 	  prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
 6809: 	  fprintf(ficrespl,"%.0f ",age );
 6810: 	  for(j=1;j<=cptcoveff;j++)
 6811: 	    fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 6812: 	  tot=0.;
 6813: 	  for(i=1; i<=nlstate;i++){
 6814: 	    tot +=  prlim[i][i];
 6815: 	    fprintf(ficrespl," %.5f", prlim[i][i]);
 6816: 	  }
 6817: 	  fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
 6818: 	} /* Age */
 6819: 	/* was end of cptcod */
 6820:     } /* cptcov */
 6821: 	return 0;
 6822: }
 6823: 
 6824: int hPijx(double *p, int bage, int fage){
 6825:     /*------------- h Pij x at various ages ------------*/
 6826: 
 6827:   int stepsize;
 6828:   int agelim;
 6829:   int hstepm;
 6830:   int nhstepm;
 6831:   int h, i, i1, j, k;
 6832: 
 6833:   double agedeb;
 6834:   double ***p3mat;
 6835: 
 6836:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
 6837:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
 6838:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
 6839:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
 6840:     }
 6841:     printf("Computing pij: result on file '%s' \n", filerespij);
 6842:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
 6843:   
 6844:     stepsize=(int) (stepm+YEARM-1)/YEARM;
 6845:     /*if (stepm<=24) stepsize=2;*/
 6846: 
 6847:     agelim=AGESUP;
 6848:     hstepm=stepsize*YEARM; /* Every year of age */
 6849:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
 6850: 
 6851:     /* hstepm=1;   aff par mois*/
 6852:     pstamp(ficrespij);
 6853:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
 6854:     i1= pow(2,cptcoveff);
 6855:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 6856:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
 6857:    /*  	k=k+1;  */
 6858:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 6859:       fprintf(ficrespij,"\n#****** ");
 6860:       for(j=1;j<=cptcoveff;j++) 
 6861: 	fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 6862:       fprintf(ficrespij,"******\n");
 6863:       
 6864:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
 6865: 	nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 6866: 	nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 6867: 	
 6868: 	/*	  nhstepm=nhstepm*YEARM; aff par mois*/
 6869: 	
 6870: 	p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6871: 	oldm=oldms;savm=savms;
 6872: 	hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 6873: 	fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
 6874: 	for(i=1; i<=nlstate;i++)
 6875: 	  for(j=1; j<=nlstate+ndeath;j++)
 6876: 	    fprintf(ficrespij," %1d-%1d",i,j);
 6877: 	fprintf(ficrespij,"\n");
 6878: 	for (h=0; h<=nhstepm; h++){
 6879: 	  /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
 6880: 	  fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
 6881: 	  for(i=1; i<=nlstate;i++)
 6882: 	    for(j=1; j<=nlstate+ndeath;j++)
 6883: 	      fprintf(ficrespij," %.5f", p3mat[i][j][h]);
 6884: 	  fprintf(ficrespij,"\n");
 6885: 	}
 6886: 	free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6887: 	fprintf(ficrespij,"\n");
 6888:       }
 6889:       /*}*/
 6890:     }
 6891: 	return 0;
 6892: }
 6893: 
 6894: 
 6895: /***********************************************/
 6896: /**************** Main Program *****************/
 6897: /***********************************************/
 6898: 
 6899: int main(int argc, char *argv[])
 6900: {
 6901: #ifdef GSL
 6902:   const gsl_multimin_fminimizer_type *T;
 6903:   size_t iteri = 0, it;
 6904:   int rval = GSL_CONTINUE;
 6905:   int status = GSL_SUCCESS;
 6906:   double ssval;
 6907: #endif
 6908:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
 6909:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
 6910:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
 6911:   int jj, ll, li, lj, lk;
 6912:   int numlinepar=0; /* Current linenumber of parameter file */
 6913:   int num_filled;
 6914:   int itimes;
 6915:   int NDIM=2;
 6916:   int vpopbased=0;
 6917: 
 6918:   char ca[32], cb[32];
 6919:   /*  FILE *fichtm; *//* Html File */
 6920:   /* FILE *ficgp;*/ /*Gnuplot File */
 6921:   struct stat info;
 6922:   double agedeb=0.;
 6923: 
 6924:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
 6925: 
 6926:   double fret;
 6927:   double dum=0.; /* Dummy variable */
 6928:   double ***p3mat;
 6929:   double ***mobaverage;
 6930: 
 6931:   char line[MAXLINE];
 6932:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
 6933: 
 6934:   char model[MAXLINE], modeltemp[MAXLINE];
 6935:   char pathr[MAXLINE], pathimach[MAXLINE]; 
 6936:   char *tok, *val; /* pathtot */
 6937:   int firstobs=1, lastobs=10;
 6938:   int c,  h , cpt, c2;
 6939:   int jl=0;
 6940:   int i1, j1, jk, stepsize=0;
 6941:   int count=0;
 6942: 
 6943:   int *tab; 
 6944:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
 6945:   int mobilav=0,popforecast=0;
 6946:   int hstepm=0, nhstepm=0;
 6947:   int agemortsup;
 6948:   float  sumlpop=0.;
 6949:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
 6950:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
 6951: 
 6952:   double bage=0, fage=110., age, agelim=0., agebase=0.;
 6953:   double ftolpl=FTOL;
 6954:   double **prlim;
 6955:   double ***param; /* Matrix of parameters */
 6956:   double  *p;
 6957:   double **matcov; /* Matrix of covariance */
 6958:   double **hess; /* Hessian matrix */
 6959:   double ***delti3; /* Scale */
 6960:   double *delti; /* Scale */
 6961:   double ***eij, ***vareij;
 6962:   double **varpl; /* Variances of prevalence limits by age */
 6963:   double *epj, vepp;
 6964: 
 6965:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
 6966:   double **ximort;
 6967:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
 6968:   int *dcwave;
 6969: 
 6970:   char z[1]="c";
 6971: 
 6972:   /*char  *strt;*/
 6973:   char strtend[80];
 6974: 
 6975: 
 6976: /*   setlocale (LC_ALL, ""); */
 6977: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
 6978: /*   textdomain (PACKAGE); */
 6979: /*   setlocale (LC_CTYPE, ""); */
 6980: /*   setlocale (LC_MESSAGES, ""); */
 6981: 
 6982:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
 6983:   rstart_time = time(NULL);  
 6984:   /*  (void) gettimeofday(&start_time,&tzp);*/
 6985:   start_time = *localtime(&rstart_time);
 6986:   curr_time=start_time;
 6987:   /*tml = *localtime(&start_time.tm_sec);*/
 6988:   /* strcpy(strstart,asctime(&tml)); */
 6989:   strcpy(strstart,asctime(&start_time));
 6990: 
 6991: /*  printf("Localtime (at start)=%s",strstart); */
 6992: /*  tp.tm_sec = tp.tm_sec +86400; */
 6993: /*  tm = *localtime(&start_time.tm_sec); */
 6994: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
 6995: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
 6996: /*   tmg.tm_hour=tmg.tm_hour + 1; */
 6997: /*   tp.tm_sec = mktime(&tmg); */
 6998: /*   strt=asctime(&tmg); */
 6999: /*   printf("Time(after) =%s",strstart);  */
 7000: /*  (void) time (&time_value);
 7001: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
 7002: *  tm = *localtime(&time_value);
 7003: *  strstart=asctime(&tm);
 7004: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
 7005: */
 7006: 
 7007:   nberr=0; /* Number of errors and warnings */
 7008:   nbwarn=0;
 7009: #ifdef WIN32
 7010:   _getcwd(pathcd, size);
 7011: #else
 7012:   getcwd(pathcd, size);
 7013: #endif
 7014:   syscompilerinfo(0);
 7015:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
 7016:   if(argc <=1){
 7017:     printf("\nEnter the parameter file name: ");
 7018:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
 7019:       printf("ERROR Empty parameter file name\n");
 7020:       goto end;
 7021:     }
 7022:     i=strlen(pathr);
 7023:     if(pathr[i-1]=='\n')
 7024:       pathr[i-1]='\0';
 7025:     i=strlen(pathr);
 7026:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
 7027:       pathr[i-1]='\0';
 7028:     }
 7029:     i=strlen(pathr);
 7030:     if( i==0 ){
 7031:       printf("ERROR Empty parameter file name\n");
 7032:       goto end;
 7033:     }
 7034:     for (tok = pathr; tok != NULL; ){
 7035:       printf("Pathr |%s|\n",pathr);
 7036:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
 7037:       printf("val= |%s| pathr=%s\n",val,pathr);
 7038:       strcpy (pathtot, val);
 7039:       if(pathr[0] == '\0') break; /* Dirty */
 7040:     }
 7041:   }
 7042:   else{
 7043:     strcpy(pathtot,argv[1]);
 7044:   }
 7045:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
 7046:   /*cygwin_split_path(pathtot,path,optionfile);
 7047:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
 7048:   /* cutv(path,optionfile,pathtot,'\\');*/
 7049: 
 7050:   /* Split argv[0], imach program to get pathimach */
 7051:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
 7052:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 7053:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 7054:  /*   strcpy(pathimach,argv[0]); */
 7055:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
 7056:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
 7057:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
 7058: #ifdef WIN32
 7059:   _chdir(path); /* Can be a relative path */
 7060:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
 7061: #else
 7062:   chdir(path); /* Can be a relative path */
 7063:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
 7064: #endif
 7065:   printf("Current directory %s!\n",pathcd);
 7066:   strcpy(command,"mkdir ");
 7067:   strcat(command,optionfilefiname);
 7068:   if((outcmd=system(command)) != 0){
 7069:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
 7070:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
 7071:     /* fclose(ficlog); */
 7072: /*     exit(1); */
 7073:   }
 7074: /*   if((imk=mkdir(optionfilefiname))<0){ */
 7075: /*     perror("mkdir"); */
 7076: /*   } */
 7077: 
 7078:   /*-------- arguments in the command line --------*/
 7079: 
 7080:   /* Main Log file */
 7081:   strcat(filelog, optionfilefiname);
 7082:   strcat(filelog,".log");    /* */
 7083:   if((ficlog=fopen(filelog,"w"))==NULL)    {
 7084:     printf("Problem with logfile %s\n",filelog);
 7085:     goto end;
 7086:   }
 7087:   fprintf(ficlog,"Log filename:%s\n",filelog);
 7088:   fprintf(ficlog,"Version %s %s",version,fullversion);
 7089:   fprintf(ficlog,"\nEnter the parameter file name: \n");
 7090:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
 7091:  path=%s \n\
 7092:  optionfile=%s\n\
 7093:  optionfilext=%s\n\
 7094:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
 7095: 
 7096:   syscompilerinfo(1);
 7097: 
 7098:   printf("Local time (at start):%s",strstart);
 7099:   fprintf(ficlog,"Local time (at start): %s",strstart);
 7100:   fflush(ficlog);
 7101: /*   (void) gettimeofday(&curr_time,&tzp); */
 7102: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
 7103: 
 7104:   /* */
 7105:   strcpy(fileres,"r");
 7106:   strcat(fileres, optionfilefiname);
 7107:   strcat(fileresu, optionfilefiname); /* Without r in front */
 7108:   strcat(fileres,".txt");    /* Other files have txt extension */
 7109:   strcat(fileresu,".txt");    /* Other files have txt extension */
 7110: 
 7111:   /* Main ---------arguments file --------*/
 7112: 
 7113:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
 7114:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 7115:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 7116:     fflush(ficlog);
 7117:     /* goto end; */
 7118:     exit(70); 
 7119:   }
 7120: 
 7121: 
 7122: 
 7123:   strcpy(filereso,"o");
 7124:   strcat(filereso,fileresu);
 7125:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
 7126:     printf("Problem with Output resultfile: %s\n", filereso);
 7127:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
 7128:     fflush(ficlog);
 7129:     goto end;
 7130:   }
 7131: 
 7132:   /* Reads comments: lines beginning with '#' */
 7133:   numlinepar=0;
 7134: 
 7135:     /* First parameter line */
 7136:   while(fgets(line, MAXLINE, ficpar)) {
 7137:     /* If line starts with a # it is a comment */
 7138:     if (line[0] == '#') {
 7139:       numlinepar++;
 7140:       fputs(line,stdout);
 7141:       fputs(line,ficparo);
 7142:       fputs(line,ficlog);
 7143:       continue;
 7144:     }else
 7145:       break;
 7146:   }
 7147:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
 7148: 			title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
 7149:     if (num_filled != 5) {
 7150:       printf("Should be 5 parameters\n");
 7151:     }
 7152:     numlinepar++;
 7153:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
 7154:   }
 7155:   /* Second parameter line */
 7156:   while(fgets(line, MAXLINE, ficpar)) {
 7157:     /* If line starts with a # it is a comment */
 7158:     if (line[0] == '#') {
 7159:       numlinepar++;
 7160:       fputs(line,stdout);
 7161:       fputs(line,ficparo);
 7162:       fputs(line,ficlog);
 7163:       continue;
 7164:     }else
 7165:       break;
 7166:   }
 7167:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
 7168: 			&ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
 7169:     if (num_filled != 8) {
 7170:       printf("Not 8 parameters, for example:ftol=1.e-8 stepm=12 ncovcol=2 nlstate=2 ndeath=1 maxwav=3 mle=1 weight=1\n");
 7171:       printf("but line=%s\n",line);
 7172:     }
 7173:     printf("ftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n",ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt);
 7174:   }
 7175:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
 7176:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
 7177:   /* Third parameter line */
 7178:   while(fgets(line, MAXLINE, ficpar)) {
 7179:     /* If line starts with a # it is a comment */
 7180:     if (line[0] == '#') {
 7181:       numlinepar++;
 7182:       fputs(line,stdout);
 7183:       fputs(line,ficparo);
 7184:       fputs(line,ficlog);
 7185:       continue;
 7186:     }else
 7187:       break;
 7188:   }
 7189:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
 7190:     if (num_filled == 0)
 7191:             model[0]='\0';
 7192:     else if (num_filled != 1){
 7193:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
 7194:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
 7195:       model[0]='\0';
 7196:       goto end;
 7197:     }
 7198:     else{
 7199:       if (model[0]=='+'){
 7200: 	for(i=1; i<=strlen(model);i++)
 7201: 	  modeltemp[i-1]=model[i];
 7202: 	strcpy(model,modeltemp); 
 7203:       }
 7204:     }
 7205:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
 7206:     printf("model=1+age+%s\n",model);fflush(stdout);
 7207:   }
 7208:   /* 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); */
 7209:   /* numlinepar=numlinepar+3; /\* In general *\/ */
 7210:   /* 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); */
 7211:   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);
 7212:   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);
 7213:   fflush(ficlog);
 7214:   /* if(model[0]=='#'|| model[0]== '\0'){ */
 7215:   if(model[0]=='#'){
 7216:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
 7217:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
 7218:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");		\
 7219:     if(mle != -1){
 7220:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
 7221:       exit(1);
 7222:     }
 7223:   }
 7224:   while((c=getc(ficpar))=='#' && c!= EOF){
 7225:     ungetc(c,ficpar);
 7226:     fgets(line, MAXLINE, ficpar);
 7227:     numlinepar++;
 7228:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
 7229:       z[0]=line[1];
 7230:     }
 7231:     /* printf("****line [1] = %c \n",line[1]); */
 7232:     fputs(line, stdout);
 7233:     //puts(line);
 7234:     fputs(line,ficparo);
 7235:     fputs(line,ficlog);
 7236:   }
 7237:   ungetc(c,ficpar);
 7238: 
 7239:    
 7240:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
 7241:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
 7242:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
 7243:      v1+v2*age+v2*v3 makes cptcovn = 3
 7244:   */
 7245:   if (strlen(model)>1) 
 7246:     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*/
 7247:   else
 7248:     ncovmodel=2; /* Constant and age */
 7249:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
 7250:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
 7251:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
 7252:     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);
 7253:     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);
 7254:     fflush(stdout);
 7255:     fclose (ficlog);
 7256:     goto end;
 7257:   }
 7258:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 7259:   delti=delti3[1][1];
 7260:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
 7261:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
 7262:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 7263:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 7264:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 7265:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 7266:     fclose (ficparo);
 7267:     fclose (ficlog);
 7268:     goto end;
 7269:     exit(0);
 7270:   }
 7271:   else if(mle==-3) { /* Main Wizard */
 7272:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 7273:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 7274:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 7275:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 7276:     matcov=matrix(1,npar,1,npar);
 7277:     hess=matrix(1,npar,1,npar);
 7278:   }
 7279:   else{
 7280:     /* Read guessed parameters */
 7281:     /* Reads comments: lines beginning with '#' */
 7282:     while((c=getc(ficpar))=='#' && c!= EOF){
 7283:       ungetc(c,ficpar);
 7284:       fgets(line, MAXLINE, ficpar);
 7285:       numlinepar++;
 7286:       fputs(line,stdout);
 7287:       fputs(line,ficparo);
 7288:       fputs(line,ficlog);
 7289:     }
 7290:     ungetc(c,ficpar);
 7291:     
 7292:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 7293:     for(i=1; i <=nlstate; i++){
 7294:       j=0;
 7295:       for(jj=1; jj <=nlstate+ndeath; jj++){
 7296: 	if(jj==i) continue;
 7297: 	j++;
 7298: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 7299: 	if ((i1 != i) || (j1 != jj)){
 7300: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
 7301: It might be a problem of design; if ncovcol and the model are correct\n \
 7302: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
 7303: 	  exit(1);
 7304: 	}
 7305: 	fprintf(ficparo,"%1d%1d",i1,j1);
 7306: 	if(mle==1)
 7307: 	  printf("%1d%1d",i,jj);
 7308: 	fprintf(ficlog,"%1d%1d",i,jj);
 7309: 	for(k=1; k<=ncovmodel;k++){
 7310: 	  fscanf(ficpar," %lf",&param[i][j][k]);
 7311: 	  if(mle==1){
 7312: 	    printf(" %lf",param[i][j][k]);
 7313: 	    fprintf(ficlog," %lf",param[i][j][k]);
 7314: 	  }
 7315: 	  else
 7316: 	    fprintf(ficlog," %lf",param[i][j][k]);
 7317: 	  fprintf(ficparo," %lf",param[i][j][k]);
 7318: 	}
 7319: 	fscanf(ficpar,"\n");
 7320: 	numlinepar++;
 7321: 	if(mle==1)
 7322: 	  printf("\n");
 7323: 	fprintf(ficlog,"\n");
 7324: 	fprintf(ficparo,"\n");
 7325:       }
 7326:     }  
 7327:     fflush(ficlog);
 7328: 
 7329:     /* Reads scales values */
 7330:     p=param[1][1];
 7331:     
 7332:     /* Reads comments: lines beginning with '#' */
 7333:     while((c=getc(ficpar))=='#' && c!= EOF){
 7334:       ungetc(c,ficpar);
 7335:       fgets(line, MAXLINE, ficpar);
 7336:       numlinepar++;
 7337:       fputs(line,stdout);
 7338:       fputs(line,ficparo);
 7339:       fputs(line,ficlog);
 7340:     }
 7341:     ungetc(c,ficpar);
 7342: 
 7343:     for(i=1; i <=nlstate; i++){
 7344:       for(j=1; j <=nlstate+ndeath-1; j++){
 7345: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 7346: 	if ( (i1-i) * (j1-j) != 0){
 7347: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
 7348: 	  exit(1);
 7349: 	}
 7350: 	printf("%1d%1d",i,j);
 7351: 	fprintf(ficparo,"%1d%1d",i1,j1);
 7352: 	fprintf(ficlog,"%1d%1d",i1,j1);
 7353: 	for(k=1; k<=ncovmodel;k++){
 7354: 	  fscanf(ficpar,"%le",&delti3[i][j][k]);
 7355: 	  printf(" %le",delti3[i][j][k]);
 7356: 	  fprintf(ficparo," %le",delti3[i][j][k]);
 7357: 	  fprintf(ficlog," %le",delti3[i][j][k]);
 7358: 	}
 7359: 	fscanf(ficpar,"\n");
 7360: 	numlinepar++;
 7361: 	printf("\n");
 7362: 	fprintf(ficparo,"\n");
 7363: 	fprintf(ficlog,"\n");
 7364:       }
 7365:     }
 7366:     fflush(ficlog);
 7367: 
 7368:     /* Reads covariance matrix */
 7369:     delti=delti3[1][1];
 7370: 
 7371: 
 7372:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
 7373:   
 7374:     /* Reads comments: lines beginning with '#' */
 7375:     while((c=getc(ficpar))=='#' && c!= EOF){
 7376:       ungetc(c,ficpar);
 7377:       fgets(line, MAXLINE, ficpar);
 7378:       numlinepar++;
 7379:       fputs(line,stdout);
 7380:       fputs(line,ficparo);
 7381:       fputs(line,ficlog);
 7382:     }
 7383:     ungetc(c,ficpar);
 7384:   
 7385:     matcov=matrix(1,npar,1,npar);
 7386:     hess=matrix(1,npar,1,npar);
 7387:     for(i=1; i <=npar; i++)
 7388:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
 7389:       
 7390:     /* Scans npar lines */
 7391:     for(i=1; i <=npar; i++){
 7392:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
 7393:       if(count != 3){
 7394: 	printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
 7395: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
 7396: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
 7397: 	fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
 7398: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
 7399: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
 7400: 	exit(1);
 7401:       }else
 7402:       if(mle==1)
 7403: 	printf("%1d%1d%1d",i1,j1,jk);
 7404:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
 7405:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
 7406:       for(j=1; j <=i; j++){
 7407: 	fscanf(ficpar," %le",&matcov[i][j]);
 7408: 	if(mle==1){
 7409: 	  printf(" %.5le",matcov[i][j]);
 7410: 	}
 7411: 	fprintf(ficlog," %.5le",matcov[i][j]);
 7412: 	fprintf(ficparo," %.5le",matcov[i][j]);
 7413:       }
 7414:       fscanf(ficpar,"\n");
 7415:       numlinepar++;
 7416:       if(mle==1)
 7417: 	printf("\n");
 7418:       fprintf(ficlog,"\n");
 7419:       fprintf(ficparo,"\n");
 7420:     }
 7421:     /* End of read covariance matrix npar lines */
 7422:     for(i=1; i <=npar; i++)
 7423:       for(j=i+1;j<=npar;j++)
 7424: 	matcov[i][j]=matcov[j][i];
 7425:     
 7426:     if(mle==1)
 7427:       printf("\n");
 7428:     fprintf(ficlog,"\n");
 7429:     
 7430:     fflush(ficlog);
 7431:     
 7432:     /*-------- Rewriting parameter file ----------*/
 7433:     strcpy(rfileres,"r");    /* "Rparameterfile */
 7434:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
 7435:     strcat(rfileres,".");    /* */
 7436:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
 7437:     if((ficres =fopen(rfileres,"w"))==NULL) {
 7438:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
 7439:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
 7440:     }
 7441:     fprintf(ficres,"#%s\n",version);
 7442:   }    /* End of mle != -3 */
 7443: 
 7444:   /*  Main data
 7445:    */
 7446:   n= lastobs;
 7447:   num=lvector(1,n);
 7448:   moisnais=vector(1,n);
 7449:   annais=vector(1,n);
 7450:   moisdc=vector(1,n);
 7451:   andc=vector(1,n);
 7452:   agedc=vector(1,n);
 7453:   cod=ivector(1,n);
 7454:   weight=vector(1,n);
 7455:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
 7456:   mint=matrix(1,maxwav,1,n);
 7457:   anint=matrix(1,maxwav,1,n);
 7458:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
 7459:   tab=ivector(1,NCOVMAX);
 7460:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
 7461:   ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
 7462: 
 7463:   /* Reads data from file datafile */
 7464:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
 7465:     goto end;
 7466: 
 7467:   /* Calculation of the number of parameters from char model */
 7468:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
 7469: 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
 7470: 	k=3 V4 Tvar[k=3]= 4 (from V4)
 7471: 	k=2 V1 Tvar[k=2]= 1 (from V1)
 7472: 	k=1 Tvar[1]=2 (from V2)
 7473:     */
 7474:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
 7475:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
 7476:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
 7477:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
 7478:   */
 7479:   /* For model-covariate k tells which data-covariate to use but
 7480:     because this model-covariate is a construction we invent a new column
 7481:     ncovcol + k1
 7482:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
 7483:     Tvar[3=V1*V4]=4+1 etc */
 7484:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
 7485:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
 7486:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
 7487:   */
 7488:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
 7489:   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
 7490: 			    * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
 7491: 			    * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
 7492:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
 7493: 			 4 covariates (3 plus signs)
 7494: 			 Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
 7495: 		      */  
 7496: 
 7497: /* Main decodemodel */
 7498: 
 7499: 
 7500:   if(decodemodel(model, lastobs) == 1)
 7501:     goto end;
 7502: 
 7503:   if((double)(lastobs-imx)/(double)imx > 1.10){
 7504:     nbwarn++;
 7505:     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); 
 7506:     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); 
 7507:   }
 7508:     /*  if(mle==1){*/
 7509:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
 7510:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
 7511:   }
 7512: 
 7513:     /*-calculation of age at interview from date of interview and age at death -*/
 7514:   agev=matrix(1,maxwav,1,imx);
 7515: 
 7516:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
 7517:     goto end;
 7518: 
 7519: 
 7520:   agegomp=(int)agemin;
 7521:   free_vector(moisnais,1,n);
 7522:   free_vector(annais,1,n);
 7523:   /* free_matrix(mint,1,maxwav,1,n);
 7524:      free_matrix(anint,1,maxwav,1,n);*/
 7525:   free_vector(moisdc,1,n);
 7526:   free_vector(andc,1,n);
 7527:   /* */
 7528:   
 7529:   wav=ivector(1,imx);
 7530:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
 7531:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
 7532:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
 7533:    
 7534:   /* Concatenates waves */
 7535:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
 7536:   /* */
 7537:  
 7538:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
 7539: 
 7540:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
 7541:   ncodemax[1]=1;
 7542:   Ndum =ivector(-1,NCOVMAX);  
 7543:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
 7544:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
 7545:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
 7546:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
 7547:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
 7548: 
 7549:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
 7550:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
 7551:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
 7552:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
 7553:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
 7554:    * (currently 0 or 1) in the data.
 7555:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
 7556:    * corresponding modality (h,j).
 7557:    */
 7558: 
 7559:   h=0;
 7560: 
 7561: 
 7562:   /*if (cptcovn > 0) */
 7563:       
 7564:  
 7565:   m=pow(2,cptcoveff);
 7566:  
 7567: 	  /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
 7568: 	   * For k=4 covariates, h goes from 1 to m=2**k
 7569: 	   * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
 7570:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
 7571: 	   *     h\k   1     2     3     4
 7572: 	   *______________________________  
 7573: 	   *     1 i=1 1 i=1 1 i=1 1 i=1 1
 7574: 	   *     2     2     1     1     1
 7575: 	   *     3 i=2 1     2     1     1
 7576: 	   *     4     2     2     1     1
 7577: 	   *     5 i=3 1 i=2 1     2     1
 7578: 	   *     6     2     1     2     1
 7579: 	   *     7 i=4 1     2     2     1
 7580: 	   *     8     2     2     2     1
 7581: 	   *     9 i=5 1 i=3 1 i=2 1     2
 7582: 	   *    10     2     1     1     2
 7583: 	   *    11 i=6 1     2     1     2
 7584: 	   *    12     2     2     1     2
 7585: 	   *    13 i=7 1 i=4 1     2     2    
 7586: 	   *    14     2     1     2     2
 7587: 	   *    15 i=8 1     2     2     2
 7588: 	   *    16     2     2     2     2
 7589: 	   */
 7590:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
 7591:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
 7592:      * and the value of each covariate?
 7593:      * V1=1, V2=1, V3=2, V4=1 ?
 7594:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
 7595:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
 7596:      * In order to get the real value in the data, we use nbcode
 7597:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
 7598:      * We are keeping this crazy system in order to be able (in the future?) 
 7599:      * to have more than 2 values (0 or 1) for a covariate.
 7600:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
 7601:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
 7602:      *              bbbbbbbb
 7603:      *              76543210     
 7604:      *   h-1        00000101 (6-1=5)
 7605:      *(h-1)>>(k-1)= 00000001 >> (2-1) = 1 right shift
 7606:      *           &
 7607:      *     1        00000001 (1)
 7608:      *              00000001        = 1 & ((h-1) >> (k-1))
 7609:      *          +1= 00000010 =2 
 7610:      *
 7611:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
 7612:      *          h'      1101 =2^3+2^2+0x2^1+2^0
 7613:      *    >>k'            11
 7614:      *          &   00000001
 7615:      *            = 00000001
 7616:      *      +1    = 00000010=2    =  codtabm(14,3)   
 7617:      * Reverse h=6 and m=16?
 7618:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
 7619:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
 7620:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
 7621:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
 7622:      * V3=decodtabm(14,3,2**4)=2
 7623:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
 7624:      *(h-1) >> (j-1)    0011 =13 >> 2
 7625:      *          &1 000000001
 7626:      *           = 000000001
 7627:      *         +1= 000000010 =2
 7628:      *                  2211
 7629:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
 7630:      *                  V3=2
 7631:      */
 7632: 
 7633:   /* /\* for(h=1; h <=100 ;h++){  *\/ */
 7634:   /*   /\* printf("h=%2d ", h); *\/ */
 7635:   /*    /\* for(k=1; k <=10; k++){ *\/ */
 7636:   /*      /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
 7637:   /*    /\*   codtab[h][k]=codtabm(h,k); *\/ */
 7638:   /*    /\* } *\/ */
 7639:   /*    /\* printf("\n"); *\/ */
 7640:   /* } */
 7641:   /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
 7642:   /*   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 *\/  */
 7643:   /*     for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
 7644:   /* 	for(cpt=1; cpt <=pow(2,k-1); cpt++){  /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/  */
 7645:   /* 	  h++; */
 7646:   /* 	  if (h>m)  */
 7647:   /* 	    h=1; */
 7648:   /* 	  codtab[h][k]=j; */
 7649:   /* 	  /\* codtab[12][3]=1; *\/ */
 7650:   /* 	  /\*codtab[h][Tvar[k]]=j;*\/ */
 7651:   /* 	  /\* 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]]); *\/ */
 7652:   /* 	}  */
 7653:   /*     } */
 7654:   /*   } */
 7655:   /* }  */
 7656:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
 7657:      codtab[1][2]=1;codtab[2][2]=2; */
 7658:   /* for(i=1; i <=m ;i++){  */
 7659:   /*    for(k=1; k <=cptcovn; k++){ */
 7660:   /*      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
 7661:   /*    } */
 7662:   /*    printf("\n"); */
 7663:   /* } */
 7664:   /*   scanf("%d",i);*/
 7665: 
 7666:  free_ivector(Ndum,-1,NCOVMAX);
 7667: 
 7668: 
 7669:     
 7670:   /* Initialisation of ----------- gnuplot -------------*/
 7671:   strcpy(optionfilegnuplot,optionfilefiname);
 7672:   if(mle==-3)
 7673:     strcat(optionfilegnuplot,"-MORT_");
 7674:   strcat(optionfilegnuplot,".gp");
 7675: 
 7676:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
 7677:     printf("Problem with file %s",optionfilegnuplot);
 7678:   }
 7679:   else{
 7680:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
 7681:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
 7682:     //fprintf(ficgp,"set missing 'NaNq'\n");
 7683:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
 7684:   }
 7685:   /*  fclose(ficgp);*/
 7686: 
 7687: 
 7688:   /* Initialisation of --------- index.htm --------*/
 7689: 
 7690:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
 7691:   if(mle==-3)
 7692:     strcat(optionfilehtm,"-MORT_");
 7693:   strcat(optionfilehtm,".htm");
 7694:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
 7695:     printf("Problem with %s \n",optionfilehtm);
 7696:     exit(0);
 7697:   }
 7698: 
 7699:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
 7700:   strcat(optionfilehtmcov,"-cov.htm");
 7701:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
 7702:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
 7703:   }
 7704:   else{
 7705:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 7706: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 7707: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
 7708: 	  optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 7709:   }
 7710: 
 7711:   fprintf(fichtm,"<html><head>\n<head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n<title>IMaCh %s</title></head>\n <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n<font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>-EUROREVES-Institut de longévité-Japan Society for the Promotion of Sciences 日本学術振興会 (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - <a href=https://software.intel.com/en-us>Intel Software 2015</a></font><br>  \
 7712: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 7713: <font size=\"2\">IMaCh-%s <br> %s</font> \
 7714: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 7715: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
 7716: \n\
 7717: <hr  size=\"2\" color=\"#EC5E5E\">\
 7718:  <ul><li><h4>Parameter files</h4>\n\
 7719:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
 7720:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
 7721:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
 7722:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
 7723:  - Date and time at start: %s</ul>\n",\
 7724: 	  optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
 7725: 	  optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
 7726: 	  fileres,fileres,\
 7727: 	  filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
 7728:   fflush(fichtm);
 7729: 
 7730:   strcpy(pathr,path);
 7731:   strcat(pathr,optionfilefiname);
 7732: #ifdef WIN32
 7733:   _chdir(optionfilefiname); /* Move to directory named optionfile */
 7734: #else
 7735:   chdir(optionfilefiname); /* Move to directory named optionfile */
 7736: #endif
 7737: 	  
 7738:   
 7739:   /* Calculates basic frequencies. Computes observed prevalence at single age
 7740:      and prints on file fileres'p'. */
 7741:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
 7742: 
 7743:   fprintf(fichtm,"\n");
 7744:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
 7745: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
 7746: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
 7747: 	  imx,agemin,agemax,jmin,jmax,jmean);
 7748:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 7749:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 7750:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 7751:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 7752:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
 7753:     
 7754:    
 7755:   /* For Powell, parameters are in a vector p[] starting at p[1]
 7756:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
 7757:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
 7758: 
 7759:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
 7760:   /* For mortality only */
 7761:   if (mle==-3){
 7762:     ximort=matrix(1,NDIM,1,NDIM); 
 7763:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
 7764:     cens=ivector(1,n);
 7765:     ageexmed=vector(1,n);
 7766:     agecens=vector(1,n);
 7767:     dcwave=ivector(1,n);
 7768:  
 7769:     for (i=1; i<=imx; i++){
 7770:       dcwave[i]=-1;
 7771:       for (m=firstpass; m<=lastpass; m++)
 7772: 	if (s[m][i]>nlstate) {
 7773: 	  dcwave[i]=m;
 7774: 	  /*	printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
 7775: 	  break;
 7776: 	}
 7777:     }
 7778: 
 7779:     for (i=1; i<=imx; i++) {
 7780:       if (wav[i]>0){
 7781: 	ageexmed[i]=agev[mw[1][i]][i];
 7782: 	j=wav[i];
 7783: 	agecens[i]=1.; 
 7784: 
 7785: 	if (ageexmed[i]> 1 && wav[i] > 0){
 7786: 	  agecens[i]=agev[mw[j][i]][i];
 7787: 	  cens[i]= 1;
 7788: 	}else if (ageexmed[i]< 1) 
 7789: 	  cens[i]= -1;
 7790: 	if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
 7791: 	  cens[i]=0 ;
 7792:       }
 7793:       else cens[i]=-1;
 7794:     }
 7795:     
 7796:     for (i=1;i<=NDIM;i++) {
 7797:       for (j=1;j<=NDIM;j++)
 7798: 	ximort[i][j]=(i == j ? 1.0 : 0.0);
 7799:     }
 7800:     
 7801:     /*p[1]=0.0268; p[NDIM]=0.083;*/
 7802:     /*printf("%lf %lf", p[1], p[2]);*/
 7803:     
 7804:     
 7805: #ifdef GSL
 7806:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
 7807: #else
 7808:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
 7809: #endif
 7810:     strcpy(filerespow,"POW-MORT_"); 
 7811:     strcat(filerespow,fileresu);
 7812:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
 7813:       printf("Problem with resultfile: %s\n", filerespow);
 7814:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 7815:     }
 7816: #ifdef GSL
 7817:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
 7818: #else
 7819:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
 7820: #endif
 7821:     /*  for (i=1;i<=nlstate;i++)
 7822: 	for(j=1;j<=nlstate+ndeath;j++)
 7823: 	if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 7824:     */
 7825:     fprintf(ficrespow,"\n");
 7826: #ifdef GSL
 7827:     /* gsl starts here */ 
 7828:     T = gsl_multimin_fminimizer_nmsimplex;
 7829:     gsl_multimin_fminimizer *sfm = NULL;
 7830:     gsl_vector *ss, *x;
 7831:     gsl_multimin_function minex_func;
 7832: 
 7833:     /* Initial vertex size vector */
 7834:     ss = gsl_vector_alloc (NDIM);
 7835:     
 7836:     if (ss == NULL){
 7837:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
 7838:     }
 7839:     /* Set all step sizes to 1 */
 7840:     gsl_vector_set_all (ss, 0.001);
 7841: 
 7842:     /* Starting point */
 7843:     
 7844:     x = gsl_vector_alloc (NDIM);
 7845:     
 7846:     if (x == NULL){
 7847:       gsl_vector_free(ss);
 7848:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
 7849:     }
 7850:   
 7851:     /* Initialize method and iterate */
 7852:     /*     p[1]=0.0268; p[NDIM]=0.083; */
 7853:     /*     gsl_vector_set(x, 0, 0.0268); */
 7854:     /*     gsl_vector_set(x, 1, 0.083); */
 7855:     gsl_vector_set(x, 0, p[1]);
 7856:     gsl_vector_set(x, 1, p[2]);
 7857: 
 7858:     minex_func.f = &gompertz_f;
 7859:     minex_func.n = NDIM;
 7860:     minex_func.params = (void *)&p; /* ??? */
 7861:     
 7862:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
 7863:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
 7864:     
 7865:     printf("Iterations beginning .....\n\n");
 7866:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
 7867: 
 7868:     iteri=0;
 7869:     while (rval == GSL_CONTINUE){
 7870:       iteri++;
 7871:       status = gsl_multimin_fminimizer_iterate(sfm);
 7872:       
 7873:       if (status) printf("error: %s\n", gsl_strerror (status));
 7874:       fflush(0);
 7875:       
 7876:       if (status) 
 7877:         break;
 7878:       
 7879:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
 7880:       ssval = gsl_multimin_fminimizer_size (sfm);
 7881:       
 7882:       if (rval == GSL_SUCCESS)
 7883:         printf ("converged to a local maximum at\n");
 7884:       
 7885:       printf("%5d ", iteri);
 7886:       for (it = 0; it < NDIM; it++){
 7887: 	printf ("%10.5f ", gsl_vector_get (sfm->x, it));
 7888:       }
 7889:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
 7890:     }
 7891:     
 7892:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
 7893:     
 7894:     gsl_vector_free(x); /* initial values */
 7895:     gsl_vector_free(ss); /* inital step size */
 7896:     for (it=0; it<NDIM; it++){
 7897:       p[it+1]=gsl_vector_get(sfm->x,it);
 7898:       fprintf(ficrespow," %.12lf", p[it]);
 7899:     }
 7900:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
 7901: #endif
 7902: #ifdef POWELL
 7903:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
 7904: #endif  
 7905:     fclose(ficrespow);
 7906:     
 7907:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
 7908: 
 7909:     for(i=1; i <=NDIM; i++)
 7910:       for(j=i+1;j<=NDIM;j++)
 7911: 	matcov[i][j]=matcov[j][i];
 7912:     
 7913:     printf("\nCovariance matrix\n ");
 7914:     fprintf(ficlog,"\nCovariance matrix\n ");
 7915:     for(i=1; i <=NDIM; i++) {
 7916:       for(j=1;j<=NDIM;j++){ 
 7917: 	printf("%f ",matcov[i][j]);
 7918: 	fprintf(ficlog,"%f ",matcov[i][j]);
 7919:       }
 7920:       printf("\n ");  fprintf(ficlog,"\n ");
 7921:     }
 7922:     
 7923:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
 7924:     for (i=1;i<=NDIM;i++) {
 7925:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
 7926:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
 7927:     }
 7928:     lsurv=vector(1,AGESUP);
 7929:     lpop=vector(1,AGESUP);
 7930:     tpop=vector(1,AGESUP);
 7931:     lsurv[agegomp]=100000;
 7932:     
 7933:     for (k=agegomp;k<=AGESUP;k++) {
 7934:       agemortsup=k;
 7935:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
 7936:     }
 7937:     
 7938:     for (k=agegomp;k<agemortsup;k++)
 7939:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
 7940:     
 7941:     for (k=agegomp;k<agemortsup;k++){
 7942:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
 7943:       sumlpop=sumlpop+lpop[k];
 7944:     }
 7945:     
 7946:     tpop[agegomp]=sumlpop;
 7947:     for (k=agegomp;k<(agemortsup-3);k++){
 7948:       /*  tpop[k+1]=2;*/
 7949:       tpop[k+1]=tpop[k]-lpop[k];
 7950:     }
 7951:     
 7952:     
 7953:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
 7954:     for (k=agegomp;k<(agemortsup-2);k++) 
 7955:       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]);
 7956:     
 7957:     
 7958:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 7959:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
 7960:       	printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
 7961: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
 7962: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
 7963:       	fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
 7964: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
 7965: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
 7966:     }else
 7967:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 7968:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
 7969: 		     stepm, weightopt,\
 7970: 		     model,imx,p,matcov,agemortsup);
 7971:     
 7972:     free_vector(lsurv,1,AGESUP);
 7973:     free_vector(lpop,1,AGESUP);
 7974:     free_vector(tpop,1,AGESUP);
 7975: #ifdef GSL
 7976:     free_ivector(cens,1,n);
 7977:     free_vector(agecens,1,n);
 7978:     free_ivector(dcwave,1,n);
 7979:     free_matrix(ximort,1,NDIM,1,NDIM);
 7980: #endif
 7981:   } /* Endof if mle==-3 mortality only */
 7982:   /* Standard  */
 7983:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
 7984:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
 7985:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
 7986:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 7987:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 7988:     for (k=1; k<=npar;k++)
 7989:       printf(" %d %8.5f",k,p[k]);
 7990:     printf("\n");
 7991:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
 7992:       /* mlikeli uses func not funcone */
 7993:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
 7994:     }
 7995:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
 7996:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
 7997:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
 7998:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 7999:     }
 8000:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
 8001:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 8002:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 8003:     for (k=1; k<=npar;k++)
 8004:       printf(" %d %8.5f",k,p[k]);
 8005:     printf("\n");
 8006:     
 8007:     /*--------- results files --------------*/
 8008:     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);
 8009:     
 8010:     
 8011:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 8012:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 8013:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 8014:     for(i=1,jk=1; i <=nlstate; i++){
 8015:       for(k=1; k <=(nlstate+ndeath); k++){
 8016: 	if (k != i) {
 8017: 	  printf("%d%d ",i,k);
 8018: 	  fprintf(ficlog,"%d%d ",i,k);
 8019: 	  fprintf(ficres,"%1d%1d ",i,k);
 8020: 	  for(j=1; j <=ncovmodel; j++){
 8021: 	    printf("%12.7f ",p[jk]);
 8022: 	    fprintf(ficlog,"%12.7f ",p[jk]);
 8023: 	    fprintf(ficres,"%12.7f ",p[jk]);
 8024: 	    jk++; 
 8025: 	  }
 8026: 	  printf("\n");
 8027: 	  fprintf(ficlog,"\n");
 8028: 	  fprintf(ficres,"\n");
 8029: 	}
 8030:       }
 8031:     }
 8032:     if(mle != 0){
 8033:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
 8034:       ftolhess=ftol; /* Usually correct */
 8035:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
 8036:       printf("Parameters and 95%% confidence intervals\n W is simply the result of the division of the parameter by the square root of covariance of the parameter.\n And Wald-based confidence intervals plus and minus 1.96 * W .\n But be careful that parameters are highly correlated because incidence of disability is highly correlated to incidence of recovery.\n It might be better to visualize the covariance matrix. See the page 'Matrix of variance-covariance of one-step probabilities' and its graphs.\n");
 8037:       fprintf(ficlog, "Parameters, Wald tests and Wald-based confidence intervals\n W is simply the result of the division of the parameter by the square root of covariance of the parameter.\n And Wald-based confidence intervals plus and minus 1.96 * W \n  It might be better to visualize the covariance matrix. See the page 'Matrix of variance-covariance of one-step probabilities' and its graphs.\n");
 8038:       for(i=1,jk=1; i <=nlstate; i++){
 8039: 	for(k=1; k <=(nlstate+ndeath); k++){
 8040: 	  if (k != i) {
 8041: 	    printf("%d%d ",i,k);
 8042: 	    fprintf(ficlog,"%d%d ",i,k);
 8043: 	    for(j=1; j <=ncovmodel; j++){
 8044: 	      printf("%12.7f W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
 8045: 	      fprintf(ficlog,"%12.7f W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
 8046: 	      jk++; 
 8047: 	    }
 8048: 	    printf("\n");
 8049: 	    fprintf(ficlog,"\n");
 8050: 	  }
 8051: 	}
 8052:       }
 8053:     } /* end of hesscov and Wald tests */
 8054: 
 8055:     /*  */
 8056:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
 8057:     printf("# Scales (for hessian or gradient estimation)\n");
 8058:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
 8059:     for(i=1,jk=1; i <=nlstate; i++){
 8060:       for(j=1; j <=nlstate+ndeath; j++){
 8061: 	if (j!=i) {
 8062: 	  fprintf(ficres,"%1d%1d",i,j);
 8063: 	  printf("%1d%1d",i,j);
 8064: 	  fprintf(ficlog,"%1d%1d",i,j);
 8065: 	  for(k=1; k<=ncovmodel;k++){
 8066: 	    printf(" %.5e",delti[jk]);
 8067: 	    fprintf(ficlog," %.5e",delti[jk]);
 8068: 	    fprintf(ficres," %.5e",delti[jk]);
 8069: 	    jk++;
 8070: 	  }
 8071: 	  printf("\n");
 8072: 	  fprintf(ficlog,"\n");
 8073: 	  fprintf(ficres,"\n");
 8074: 	}
 8075:       }
 8076:     }
 8077:     
 8078:     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");
 8079:     if(mle >= 1) /* To big for the screen */
 8080:       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");
 8081:     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");
 8082:     /* # 121 Var(a12)\n\ */
 8083:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
 8084:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 8085:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 8086:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 8087:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 8088:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 8089:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 8090:     
 8091:     
 8092:     /* Just to have a covariance matrix which will be more understandable
 8093:        even is we still don't want to manage dictionary of variables
 8094:     */
 8095:     for(itimes=1;itimes<=2;itimes++){
 8096:       jj=0;
 8097:       for(i=1; i <=nlstate; i++){
 8098: 	for(j=1; j <=nlstate+ndeath; j++){
 8099: 	  if(j==i) continue;
 8100: 	  for(k=1; k<=ncovmodel;k++){
 8101: 	    jj++;
 8102: 	    ca[0]= k+'a'-1;ca[1]='\0';
 8103: 	    if(itimes==1){
 8104: 	      if(mle>=1)
 8105: 		printf("#%1d%1d%d",i,j,k);
 8106: 	      fprintf(ficlog,"#%1d%1d%d",i,j,k);
 8107: 	      fprintf(ficres,"#%1d%1d%d",i,j,k);
 8108: 	    }else{
 8109: 	      if(mle>=1)
 8110: 		printf("%1d%1d%d",i,j,k);
 8111: 	      fprintf(ficlog,"%1d%1d%d",i,j,k);
 8112: 	      fprintf(ficres,"%1d%1d%d",i,j,k);
 8113: 	    }
 8114: 	    ll=0;
 8115: 	    for(li=1;li <=nlstate; li++){
 8116: 	      for(lj=1;lj <=nlstate+ndeath; lj++){
 8117: 		if(lj==li) continue;
 8118: 		for(lk=1;lk<=ncovmodel;lk++){
 8119: 		  ll++;
 8120: 		  if(ll<=jj){
 8121: 		    cb[0]= lk +'a'-1;cb[1]='\0';
 8122: 		    if(ll<jj){
 8123: 		      if(itimes==1){
 8124: 			if(mle>=1)
 8125: 			  printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 8126: 			fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 8127: 			fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 8128: 		      }else{
 8129: 			if(mle>=1)
 8130: 			  printf(" %.5e",matcov[jj][ll]); 
 8131: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 8132: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 8133: 		      }
 8134: 		    }else{
 8135: 		      if(itimes==1){
 8136: 			if(mle>=1)
 8137: 			  printf(" Var(%s%1d%1d)",ca,i,j);
 8138: 			fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
 8139: 			fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
 8140: 		      }else{
 8141: 			if(mle>=1)
 8142: 			  printf(" %.7e",matcov[jj][ll]); 
 8143: 			fprintf(ficlog," %.7e",matcov[jj][ll]); 
 8144: 			fprintf(ficres," %.7e",matcov[jj][ll]); 
 8145: 		      }
 8146: 		    }
 8147: 		  }
 8148: 		} /* end lk */
 8149: 	      } /* end lj */
 8150: 	    } /* end li */
 8151: 	    if(mle>=1)
 8152: 	      printf("\n");
 8153: 	    fprintf(ficlog,"\n");
 8154: 	    fprintf(ficres,"\n");
 8155: 	    numlinepar++;
 8156: 	  } /* end k*/
 8157: 	} /*end j */
 8158:       } /* end i */
 8159:     } /* end itimes */
 8160:     
 8161:     fflush(ficlog);
 8162:     fflush(ficres);
 8163:       while(fgets(line, MAXLINE, ficpar)) {
 8164:     /* If line starts with a # it is a comment */
 8165:     if (line[0] == '#') {
 8166:       numlinepar++;
 8167:       fputs(line,stdout);
 8168:       fputs(line,ficparo);
 8169:       fputs(line,ficlog);
 8170:       continue;
 8171:     }else
 8172:       break;
 8173:   }
 8174: 
 8175:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
 8176:     /*   ungetc(c,ficpar); */
 8177:     /*   fgets(line, MAXLINE, ficpar); */
 8178:     /*   fputs(line,stdout); */
 8179:     /*   fputs(line,ficparo); */
 8180:     /* } */
 8181:     /* ungetc(c,ficpar); */
 8182:     
 8183:     estepm=0;
 8184:     if((num_filled=sscanf(line,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm, &ftolpl)) !=EOF){
 8185: 
 8186:     if (num_filled != 6) {
 8187:       printf("Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n");
 8188:       printf("but line=%s\n",line);
 8189:       goto end;
 8190:     }
 8191:     printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
 8192:   }
 8193:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
 8194:   /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
 8195: 
 8196:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
 8197:     if (estepm==0 || estepm < stepm) estepm=stepm;
 8198:     if (fage <= 2) {
 8199:       bage = ageminpar;
 8200:       fage = agemaxpar;
 8201:     }
 8202:     
 8203:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
 8204:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
 8205:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
 8206: 
 8207:     /* Other stuffs, more or less useful */    
 8208:     while((c=getc(ficpar))=='#' && c!= EOF){
 8209:       ungetc(c,ficpar);
 8210:       fgets(line, MAXLINE, ficpar);
 8211:       fputs(line,stdout);
 8212:       fputs(line,ficparo);
 8213:     }
 8214:     ungetc(c,ficpar);
 8215:     
 8216:     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);
 8217:     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);
 8218:     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);
 8219:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
 8220:     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);
 8221:     
 8222:     while((c=getc(ficpar))=='#' && c!= EOF){
 8223:       ungetc(c,ficpar);
 8224:       fgets(line, MAXLINE, ficpar);
 8225:       fputs(line,stdout);
 8226:       fputs(line,ficparo);
 8227:     }
 8228:     ungetc(c,ficpar);
 8229:     
 8230:     
 8231:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
 8232:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
 8233:     
 8234:     fscanf(ficpar,"pop_based=%d\n",&popbased);
 8235:     fprintf(ficlog,"pop_based=%d\n",popbased);
 8236:     fprintf(ficparo,"pop_based=%d\n",popbased);   
 8237:     fprintf(ficres,"pop_based=%d\n",popbased);   
 8238:     
 8239:     while((c=getc(ficpar))=='#' && c!= EOF){
 8240:       ungetc(c,ficpar);
 8241:       fgets(line, MAXLINE, ficpar);
 8242:       fputs(line,stdout);
 8243:       fputs(line,ficparo);
 8244:     }
 8245:     ungetc(c,ficpar);
 8246:     
 8247:     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);
 8248:     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);
 8249:     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);
 8250:     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);
 8251:     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);
 8252:     /* day and month of proj2 are not used but only year anproj2.*/
 8253:     
 8254:     
 8255:     
 8256:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
 8257:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
 8258:     
 8259:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 8260:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
 8261:       	printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
 8262: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
 8263: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
 8264:       	fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
 8265: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
 8266: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
 8267:     }else
 8268:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, pathc,p);
 8269:     
 8270:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
 8271: 		 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,estepm, \
 8272: 		 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
 8273:       
 8274:    /*------------ free_vector  -------------*/
 8275:    /*  chdir(path); */
 8276:  
 8277:     free_ivector(wav,1,imx);
 8278:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
 8279:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
 8280:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
 8281:     free_lvector(num,1,n);
 8282:     free_vector(agedc,1,n);
 8283:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
 8284:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
 8285:     fclose(ficparo);
 8286:     fclose(ficres);
 8287: 
 8288: 
 8289:     /* Other results (useful)*/
 8290: 
 8291: 
 8292:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 8293:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
 8294:     prlim=matrix(1,nlstate,1,nlstate);
 8295:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
 8296:     fclose(ficrespl);
 8297: 
 8298: #ifdef FREEEXIT2
 8299: #include "freeexit2.h"
 8300: #endif
 8301: 
 8302:     /*------------- h Pij x at various ages ------------*/
 8303:     /*#include "hpijx.h"*/
 8304:     hPijx(p, bage, fage);
 8305:     fclose(ficrespij);
 8306: 
 8307:   /*-------------- Variance of one-step probabilities---*/
 8308:     k=1;
 8309:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
 8310: 
 8311: 
 8312:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 8313:     for(i=1;i<=AGESUP;i++)
 8314:       for(j=1;j<=NCOVMAX;j++)
 8315: 	for(k=1;k<=NCOVMAX;k++)
 8316: 	  probs[i][j][k]=0.;
 8317: 
 8318:     /*---------- Forecasting ------------------*/
 8319:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
 8320:     if(prevfcast==1){
 8321:       /*    if(stepm ==1){*/
 8322:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
 8323:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
 8324:       /*      }  */
 8325:       /*      else{ */
 8326:       /*        erreur=108; */
 8327:       /*        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); */
 8328:       /*        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); */
 8329:       /*      } */
 8330:     }
 8331:  
 8332:     /* ------ Other prevalence ratios------------ */
 8333: 
 8334:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
 8335: 
 8336:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 8337:     /*  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",\
 8338: 	ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
 8339:     */
 8340: 
 8341:     if (mobilav!=0) {
 8342:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 8343:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 8344: 	fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 8345: 	printf(" Error in movingaverage mobilav=%d\n",mobilav);
 8346:       }
 8347:     }
 8348: 
 8349: 
 8350:     /*---------- Health expectancies, no variances ------------*/
 8351: 
 8352:     strcpy(filerese,"E_");
 8353:     strcat(filerese,fileresu);
 8354:     if((ficreseij=fopen(filerese,"w"))==NULL) {
 8355:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 8356:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 8357:     }
 8358:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
 8359:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
 8360:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 8361:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 8362:           
 8363:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 8364: 	fprintf(ficreseij,"\n#****** ");
 8365: 	for(j=1;j<=cptcoveff;j++) {
 8366: 	  fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8367: 	}
 8368: 	fprintf(ficreseij,"******\n");
 8369: 
 8370: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 8371: 	oldm=oldms;savm=savms;
 8372: 	evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
 8373:       
 8374: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 8375:       /*}*/
 8376:     }
 8377:     fclose(ficreseij);
 8378:     printf("done evsij\n");fflush(stdout);
 8379:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
 8380: 
 8381:     /*---------- Health expectancies and variances ------------*/
 8382: 
 8383: 
 8384:     strcpy(filerest,"T_");
 8385:     strcat(filerest,fileresu);
 8386:     if((ficrest=fopen(filerest,"w"))==NULL) {
 8387:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
 8388:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
 8389:     }
 8390:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
 8391:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
 8392: 
 8393: 
 8394:     strcpy(fileresstde,"STDE_");
 8395:     strcat(fileresstde,fileresu);
 8396:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
 8397:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 8398:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 8399:     }
 8400:     printf("  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 8401:     fprintf(ficlog,"  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 8402: 
 8403:     strcpy(filerescve,"CVE_");
 8404:     strcat(filerescve,fileresu);
 8405:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
 8406:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 8407:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 8408:     }
 8409:     printf("    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 8410:     fprintf(ficlog,"    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 8411: 
 8412:     strcpy(fileresv,"V_");
 8413:     strcat(fileresv,fileresu);
 8414:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
 8415:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
 8416:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
 8417:     }
 8418:     printf("      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
 8419:     fprintf(ficlog,"      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
 8420: 
 8421:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 8422:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 8423:           
 8424:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 8425:       fprintf(ficrest,"\n#****** ");
 8426:       for(j=1;j<=cptcoveff;j++) 
 8427: 	fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8428:       fprintf(ficrest,"******\n");
 8429:       
 8430:       fprintf(ficresstdeij,"\n#****** ");
 8431:       fprintf(ficrescveij,"\n#****** ");
 8432:       for(j=1;j<=cptcoveff;j++) {
 8433: 	fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8434: 	fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8435:       }
 8436:       fprintf(ficresstdeij,"******\n");
 8437:       fprintf(ficrescveij,"******\n");
 8438:       
 8439:       fprintf(ficresvij,"\n#****** ");
 8440:       for(j=1;j<=cptcoveff;j++) 
 8441: 	fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8442:       fprintf(ficresvij,"******\n");
 8443:       
 8444:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 8445:       oldm=oldms;savm=savms;
 8446:       printf(" cvevsij %d, ",k);
 8447:       fprintf(ficlog, " cvevsij %d, ",k);
 8448:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
 8449:       printf(" end cvevsij \n ");
 8450:       fprintf(ficlog, " end cvevsij \n ");
 8451:       
 8452:       /*
 8453:        */
 8454:       /* goto endfree; */
 8455:       
 8456:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 8457:       pstamp(ficrest);
 8458:       
 8459:       
 8460:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 8461: 	oldm=oldms;savm=savms; /* ZZ Segmentation fault */
 8462: 	cptcod= 0; /* To be deleted */
 8463: 	printf("varevsij %d \n",vpopbased);
 8464: 	fprintf(ficlog, "varevsij %d \n",vpopbased);
 8465: 	varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); /* cptcod not initialized Intel */
 8466: 	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 ");
 8467: 	if(vpopbased==1)
 8468: 	  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);
 8469: 	else
 8470: 	  fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
 8471: 	fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
 8472: 	for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
 8473: 	fprintf(ficrest,"\n");
 8474: 	/* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
 8475: 	epj=vector(1,nlstate+1);
 8476: 	printf("Computing age specific period (stable) prevalences in each health state \n");
 8477: 	fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
 8478: 	for(age=bage; age <=fage ;age++){
 8479: 	  prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
 8480: 	  if (vpopbased==1) {
 8481: 	    if(mobilav ==0){
 8482: 	      for(i=1; i<=nlstate;i++)
 8483: 		prlim[i][i]=probs[(int)age][i][k];
 8484: 	    }else{ /* mobilav */ 
 8485: 	      for(i=1; i<=nlstate;i++)
 8486: 		prlim[i][i]=mobaverage[(int)age][i][k];
 8487: 	    }
 8488: 	  }
 8489: 	  
 8490: 	  fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
 8491: 	  /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
 8492: 	  /* printf(" age %4.0f ",age); */
 8493: 	  for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
 8494: 	    for(i=1, epj[j]=0.;i <=nlstate;i++) {
 8495: 	      epj[j] += prlim[i][i]*eij[i][j][(int)age];
 8496: 	      /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
 8497: 	      /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
 8498: 	    }
 8499: 	    epj[nlstate+1] +=epj[j];
 8500: 	  }
 8501: 	  /* printf(" age %4.0f \n",age); */
 8502: 	  
 8503: 	  for(i=1, vepp=0.;i <=nlstate;i++)
 8504: 	    for(j=1;j <=nlstate;j++)
 8505: 	      vepp += vareij[i][j][(int)age];
 8506: 	  fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
 8507: 	  for(j=1;j <=nlstate;j++){
 8508: 	    fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
 8509: 	  }
 8510: 	  fprintf(ficrest,"\n");
 8511: 	}
 8512:       } /* End vpopbased */
 8513:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 8514:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 8515:       free_vector(epj,1,nlstate+1);
 8516:       printf("done \n");fflush(stdout);
 8517:       fprintf(ficlog,"done\n");fflush(ficlog);
 8518:       
 8519:       /*}*/
 8520:     } /* End k */
 8521:     free_vector(weight,1,n);
 8522:     free_imatrix(Tvard,1,NCOVMAX,1,2);
 8523:     free_imatrix(s,1,maxwav+1,1,n);
 8524:     free_matrix(anint,1,maxwav,1,n); 
 8525:     free_matrix(mint,1,maxwav,1,n);
 8526:     free_ivector(cod,1,n);
 8527:     free_ivector(tab,1,NCOVMAX);
 8528:     fclose(ficresstdeij);
 8529:     fclose(ficrescveij);
 8530:     fclose(ficresvij);
 8531:     fclose(ficrest);
 8532:     printf("done Health expectancies\n");fflush(stdout);
 8533:     fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
 8534:     fclose(ficpar);
 8535:   
 8536:     /*------- Variance of period (stable) prevalence------*/   
 8537: 
 8538:     strcpy(fileresvpl,"VPL_");
 8539:     strcat(fileresvpl,fileresu);
 8540:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
 8541:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
 8542:       exit(0);
 8543:     }
 8544:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
 8545:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
 8546: 
 8547:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 8548:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 8549:           
 8550:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 8551:     	fprintf(ficresvpl,"\n#****** ");
 8552: 	for(j=1;j<=cptcoveff;j++) 
 8553: 	  fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8554: 	fprintf(ficresvpl,"******\n");
 8555:       
 8556: 	varpl=matrix(1,nlstate,(int) bage, (int) fage);
 8557: 	oldm=oldms;savm=savms;
 8558: 	varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
 8559: 	free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
 8560:       /*}*/
 8561:     }
 8562: 
 8563:     fclose(ficresvpl);
 8564:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
 8565:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
 8566: 
 8567:     /*---------- End : free ----------------*/
 8568:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 8569:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 8570:   }  /* mle==-3 arrives here for freeing */
 8571:  /* endfree:*/
 8572:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
 8573:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
 8574:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
 8575:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
 8576:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
 8577:     free_matrix(covar,0,NCOVMAX,1,n);
 8578:     free_matrix(matcov,1,npar,1,npar);
 8579:     free_matrix(hess,1,npar,1,npar);
 8580:     /*free_vector(delti,1,npar);*/
 8581:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 8582:     free_matrix(agev,1,maxwav,1,imx);
 8583:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
 8584: 
 8585:     free_ivector(ncodemax,1,NCOVMAX);
 8586:     free_ivector(ncodemaxwundef,1,NCOVMAX);
 8587:     free_ivector(Tvar,1,NCOVMAX);
 8588:     free_ivector(Tprod,1,NCOVMAX);
 8589:     free_ivector(Tvaraff,1,NCOVMAX);
 8590:     free_ivector(Tage,1,NCOVMAX);
 8591: 
 8592:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
 8593:     /* free_imatrix(codtab,1,100,1,10); */
 8594:   fflush(fichtm);
 8595:   fflush(ficgp);
 8596:   
 8597: 
 8598:   if((nberr >0) || (nbwarn>0)){
 8599:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
 8600:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
 8601:   }else{
 8602:     printf("End of Imach\n");
 8603:     fprintf(ficlog,"End of Imach\n");
 8604:   }
 8605:   printf("See log file on %s\n",filelog);
 8606:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
 8607:   /*(void) gettimeofday(&end_time,&tzp);*/
 8608:   rend_time = time(NULL);  
 8609:   end_time = *localtime(&rend_time);
 8610:   /* tml = *localtime(&end_time.tm_sec); */
 8611:   strcpy(strtend,asctime(&end_time));
 8612:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
 8613:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
 8614:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 8615: 
 8616:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 8617:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 8618:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 8619:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
 8620: /*   if(fileappend(fichtm,optionfilehtm)){ */
 8621:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 8622:   fclose(fichtm);
 8623:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 8624:   fclose(fichtmcov);
 8625:   fclose(ficgp);
 8626:   fclose(ficlog);
 8627:   /*------ End -----------*/
 8628: 
 8629: 
 8630:    printf("Before Current directory %s!\n",pathcd);
 8631: #ifdef WIN32
 8632:    if (_chdir(pathcd) != 0)
 8633: 	   printf("Can't move to directory %s!\n",path);
 8634:    if(_getcwd(pathcd,MAXLINE) > 0)
 8635: #else
 8636:    if(chdir(pathcd) != 0)
 8637: 	   printf("Can't move to directory %s!\n", path);
 8638:    if (getcwd(pathcd, MAXLINE) > 0)
 8639: #endif 
 8640:     printf("Current directory %s!\n",pathcd);
 8641:   /*strcat(plotcmd,CHARSEPARATOR);*/
 8642:   sprintf(plotcmd,"gnuplot");
 8643: #ifdef _WIN32
 8644:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
 8645: #endif
 8646:   if(!stat(plotcmd,&info)){
 8647:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 8648:     if(!stat(getenv("GNUPLOTBIN"),&info)){
 8649:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
 8650:     }else
 8651:       strcpy(pplotcmd,plotcmd);
 8652: #ifdef __unix
 8653:     strcpy(plotcmd,GNUPLOTPROGRAM);
 8654:     if(!stat(plotcmd,&info)){
 8655:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 8656:     }else
 8657:       strcpy(pplotcmd,plotcmd);
 8658: #endif
 8659:   }else
 8660:     strcpy(pplotcmd,plotcmd);
 8661:   
 8662:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
 8663:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
 8664: 
 8665:   if((outcmd=system(plotcmd)) != 0){
 8666:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
 8667:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
 8668:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
 8669:     if((outcmd=system(plotcmd)) != 0)
 8670:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
 8671:   }
 8672:   printf(" Successful, please wait...");
 8673:   while (z[0] != 'q') {
 8674:     /* chdir(path); */
 8675:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
 8676:     scanf("%s",z);
 8677: /*     if (z[0] == 'c') system("./imach"); */
 8678:     if (z[0] == 'e') {
 8679: #ifdef __APPLE__
 8680:       sprintf(pplotcmd, "open %s", optionfilehtm);
 8681: #elif __linux
 8682:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
 8683: #else
 8684:       sprintf(pplotcmd, "%s", optionfilehtm);
 8685: #endif
 8686:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
 8687:       system(pplotcmd);
 8688:     }
 8689:     else if (z[0] == 'g') system(plotcmd);
 8690:     else if (z[0] == 'q') exit(0);
 8691:   }
 8692:   end:
 8693:   while (z[0] != 'q') {
 8694:     printf("\nType  q for exiting: "); fflush(stdout);
 8695:     scanf("%s",z);
 8696:   }
 8697: }

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