File:  [Local Repository] / imach / src / imach.c
Revision 1.222: download - view: text, annotated - select for diffs
Wed Feb 17 08:14:50 2016 UTC (8 years, 3 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
Summary: Probably last 0.98 stable version 0.98r6

    1: /* $Id: imach.c,v 1.222 2016/02/17 08:14:50 brouard Exp $
    2:   $State: Exp $
    3:   $Log: imach.c,v $
    4:   Revision 1.222  2016/02/17 08:14:50  brouard
    5:   Summary: Probably last 0.98 stable version 0.98r6
    6: 
    7:   Revision 1.221  2016/02/15 23:35:36  brouard
    8:   Summary: minor bug
    9: 
   10:   Revision 1.219  2016/02/15 00:48:12  brouard
   11:   *** empty log message ***
   12: 
   13:   Revision 1.218  2016/02/12 11:29:23  brouard
   14:   Summary: 0.99 Back projections
   15: 
   16:   Revision 1.217  2015/12/23 17:18:31  brouard
   17:   Summary: Experimental backcast
   18: 
   19:   Revision 1.216  2015/12/18 17:32:11  brouard
   20:   Summary: 0.98r4 Warning and status=-2
   21: 
   22:   Version 0.98r4 is now:
   23:    - displaying an error when status is -1, date of interview unknown and date of death known;
   24:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
   25:   Older changes concerning s=-2, dating from 2005 have been supersed.
   26: 
   27:   Revision 1.215  2015/12/16 08:52:24  brouard
   28:   Summary: 0.98r4 working
   29: 
   30:   Revision 1.214  2015/12/16 06:57:54  brouard
   31:   Summary: temporary not working
   32: 
   33:   Revision 1.213  2015/12/11 18:22:17  brouard
   34:   Summary: 0.98r4
   35: 
   36:   Revision 1.212  2015/11/21 12:47:24  brouard
   37:   Summary: minor typo
   38: 
   39:   Revision 1.211  2015/11/21 12:41:11  brouard
   40:   Summary: 0.98r3 with some graph of projected cross-sectional
   41: 
   42:   Author: Nicolas Brouard
   43: 
   44:   Revision 1.210  2015/11/18 17:41:20  brouard
   45:   Summary: Start working on projected prevalences
   46: 
   47:   Revision 1.209  2015/11/17 22:12:03  brouard
   48:   Summary: Adding ftolpl parameter
   49:   Author: N Brouard
   50: 
   51:   We had difficulties to get smoothed confidence intervals. It was due
   52:   to the period prevalence which wasn't computed accurately. The inner
   53:   parameter ftolpl is now an outer parameter of the .imach parameter
   54:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
   55:   computation are long.
   56: 
   57:   Revision 1.208  2015/11/17 14:31:57  brouard
   58:   Summary: temporary
   59: 
   60:   Revision 1.207  2015/10/27 17:36:57  brouard
   61:   *** empty log message ***
   62: 
   63:   Revision 1.206  2015/10/24 07:14:11  brouard
   64:   *** empty log message ***
   65: 
   66:   Revision 1.205  2015/10/23 15:50:53  brouard
   67:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
   68: 
   69:   Revision 1.204  2015/10/01 16:20:26  brouard
   70:   Summary: Some new graphs of contribution to likelihood
   71: 
   72:   Revision 1.203  2015/09/30 17:45:14  brouard
   73:   Summary: looking at better estimation of the hessian
   74: 
   75:   Also a better criteria for convergence to the period prevalence And
   76:   therefore adding the number of years needed to converge. (The
   77:   prevalence in any alive state shold sum to one
   78: 
   79:   Revision 1.202  2015/09/22 19:45:16  brouard
   80:   Summary: Adding some overall graph on contribution to likelihood. Might change
   81: 
   82:   Revision 1.201  2015/09/15 17:34:58  brouard
   83:   Summary: 0.98r0
   84: 
   85:   - Some new graphs like suvival functions
   86:   - Some bugs fixed like model=1+age+V2.
   87: 
   88:   Revision 1.200  2015/09/09 16:53:55  brouard
   89:   Summary: Big bug thanks to Flavia
   90: 
   91:   Even model=1+age+V2. did not work anymore
   92: 
   93:   Revision 1.199  2015/09/07 14:09:23  brouard
   94:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
   95: 
   96:   Revision 1.198  2015/09/03 07:14:39  brouard
   97:   Summary: 0.98q5 Flavia
   98: 
   99:   Revision 1.197  2015/09/01 18:24:39  brouard
  100:   *** empty log message ***
  101: 
  102:   Revision 1.196  2015/08/18 23:17:52  brouard
  103:   Summary: 0.98q5
  104: 
  105:   Revision 1.195  2015/08/18 16:28:39  brouard
  106:   Summary: Adding a hack for testing purpose
  107: 
  108:   After reading the title, ftol and model lines, if the comment line has
  109:   a q, starting with #q, the answer at the end of the run is quit. It
  110:   permits to run test files in batch with ctest. The former workaround was
  111:   $ echo q | imach foo.imach
  112: 
  113:   Revision 1.194  2015/08/18 13:32:00  brouard
  114:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
  115: 
  116:   Revision 1.193  2015/08/04 07:17:42  brouard
  117:   Summary: 0.98q4
  118: 
  119:   Revision 1.192  2015/07/16 16:49:02  brouard
  120:   Summary: Fixing some outputs
  121: 
  122:   Revision 1.191  2015/07/14 10:00:33  brouard
  123:   Summary: Some fixes
  124: 
  125:   Revision 1.190  2015/05/05 08:51:13  brouard
  126:   Summary: Adding digits in output parameters (7 digits instead of 6)
  127: 
  128:   Fix 1+age+.
  129: 
  130:   Revision 1.189  2015/04/30 14:45:16  brouard
  131:   Summary: 0.98q2
  132: 
  133:   Revision 1.188  2015/04/30 08:27:53  brouard
  134:   *** empty log message ***
  135: 
  136:   Revision 1.187  2015/04/29 09:11:15  brouard
  137:   *** empty log message ***
  138: 
  139:   Revision 1.186  2015/04/23 12:01:52  brouard
  140:   Summary: V1*age is working now, version 0.98q1
  141: 
  142:   Some codes had been disabled in order to simplify and Vn*age was
  143:   working in the optimization phase, ie, giving correct MLE parameters,
  144:   but, as usual, outputs were not correct and program core dumped.
  145: 
  146:   Revision 1.185  2015/03/11 13:26:42  brouard
  147:   Summary: Inclusion of compile and links command line for Intel Compiler
  148: 
  149:   Revision 1.184  2015/03/11 11:52:39  brouard
  150:   Summary: Back from Windows 8. Intel Compiler
  151: 
  152:   Revision 1.183  2015/03/10 20:34:32  brouard
  153:   Summary: 0.98q0, trying with directest, mnbrak fixed
  154: 
  155:   We use directest instead of original Powell test; probably no
  156:   incidence on the results, but better justifications;
  157:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
  158:   wrong results.
  159: 
  160:   Revision 1.182  2015/02/12 08:19:57  brouard
  161:   Summary: Trying to keep directest which seems simpler and more general
  162:   Author: Nicolas Brouard
  163: 
  164:   Revision 1.181  2015/02/11 23:22:24  brouard
  165:   Summary: Comments on Powell added
  166: 
  167:   Author:
  168: 
  169:   Revision 1.180  2015/02/11 17:33:45  brouard
  170:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
  171: 
  172:   Revision 1.179  2015/01/04 09:57:06  brouard
  173:   Summary: back to OS/X
  174: 
  175:   Revision 1.178  2015/01/04 09:35:48  brouard
  176:   *** empty log message ***
  177: 
  178:   Revision 1.177  2015/01/03 18:40:56  brouard
  179:   Summary: Still testing ilc32 on OSX
  180: 
  181:   Revision 1.176  2015/01/03 16:45:04  brouard
  182:   *** empty log message ***
  183: 
  184:   Revision 1.175  2015/01/03 16:33:42  brouard
  185:   *** empty log message ***
  186: 
  187:   Revision 1.174  2015/01/03 16:15:49  brouard
  188:   Summary: Still in cross-compilation
  189: 
  190:   Revision 1.173  2015/01/03 12:06:26  brouard
  191:   Summary: trying to detect cross-compilation
  192: 
  193:   Revision 1.172  2014/12/27 12:07:47  brouard
  194:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
  195: 
  196:   Revision 1.171  2014/12/23 13:26:59  brouard
  197:   Summary: Back from Visual C
  198: 
  199:   Still problem with utsname.h on Windows
  200: 
  201:   Revision 1.170  2014/12/23 11:17:12  brouard
  202:   Summary: Cleaning some \%% back to %%
  203: 
  204:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
  205: 
  206:   Revision 1.169  2014/12/22 23:08:31  brouard
  207:   Summary: 0.98p
  208: 
  209:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
  210: 
  211:   Revision 1.168  2014/12/22 15:17:42  brouard
  212:   Summary: update
  213: 
  214:   Revision 1.167  2014/12/22 13:50:56  brouard
  215:   Summary: Testing uname and compiler version and if compiled 32 or 64
  216: 
  217:   Testing on Linux 64
  218: 
  219:   Revision 1.166  2014/12/22 11:40:47  brouard
  220:   *** empty log message ***
  221: 
  222:   Revision 1.165  2014/12/16 11:20:36  brouard
  223:   Summary: After compiling on Visual C
  224: 
  225:   * imach.c (Module): Merging 1.61 to 1.162
  226: 
  227:   Revision 1.164  2014/12/16 10:52:11  brouard
  228:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
  229: 
  230:   * imach.c (Module): Merging 1.61 to 1.162
  231: 
  232:   Revision 1.163  2014/12/16 10:30:11  brouard
  233:   * imach.c (Module): Merging 1.61 to 1.162
  234: 
  235:   Revision 1.162  2014/09/25 11:43:39  brouard
  236:   Summary: temporary backup 0.99!
  237: 
  238:   Revision 1.1  2014/09/16 11:06:58  brouard
  239:   Summary: With some code (wrong) for nlopt
  240: 
  241:   Author:
  242: 
  243:   Revision 1.161  2014/09/15 20:41:41  brouard
  244:   Summary: Problem with macro SQR on Intel compiler
  245: 
  246:   Revision 1.160  2014/09/02 09:24:05  brouard
  247:   *** empty log message ***
  248: 
  249:   Revision 1.159  2014/09/01 10:34:10  brouard
  250:   Summary: WIN32
  251:   Author: Brouard
  252: 
  253:   Revision 1.158  2014/08/27 17:11:51  brouard
  254:   *** empty log message ***
  255: 
  256:   Revision 1.157  2014/08/27 16:26:55  brouard
  257:   Summary: Preparing windows Visual studio version
  258:   Author: Brouard
  259: 
  260:   In order to compile on Visual studio, time.h is now correct and time_t
  261:   and tm struct should be used. difftime should be used but sometimes I
  262:   just make the differences in raw time format (time(&now).
  263:   Trying to suppress #ifdef LINUX
  264:   Add xdg-open for __linux in order to open default browser.
  265: 
  266:   Revision 1.156  2014/08/25 20:10:10  brouard
  267:   *** empty log message ***
  268: 
  269:   Revision 1.155  2014/08/25 18:32:34  brouard
  270:   Summary: New compile, minor changes
  271:   Author: Brouard
  272: 
  273:   Revision 1.154  2014/06/20 17:32:08  brouard
  274:   Summary: Outputs now all graphs of convergence to period prevalence
  275: 
  276:   Revision 1.153  2014/06/20 16:45:46  brouard
  277:   Summary: If 3 live state, convergence to period prevalence on same graph
  278:   Author: Brouard
  279: 
  280:   Revision 1.152  2014/06/18 17:54:09  brouard
  281:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
  282: 
  283:   Revision 1.151  2014/06/18 16:43:30  brouard
  284:   *** empty log message ***
  285: 
  286:   Revision 1.150  2014/06/18 16:42:35  brouard
  287:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
  288:   Author: brouard
  289: 
  290:   Revision 1.149  2014/06/18 15:51:14  brouard
  291:   Summary: Some fixes in parameter files errors
  292:   Author: Nicolas Brouard
  293: 
  294:   Revision 1.148  2014/06/17 17:38:48  brouard
  295:   Summary: Nothing new
  296:   Author: Brouard
  297: 
  298:   Just a new packaging for OS/X version 0.98nS
  299: 
  300:   Revision 1.147  2014/06/16 10:33:11  brouard
  301:   *** empty log message ***
  302: 
  303:   Revision 1.146  2014/06/16 10:20:28  brouard
  304:   Summary: Merge
  305:   Author: Brouard
  306: 
  307:   Merge, before building revised version.
  308: 
  309:   Revision 1.145  2014/06/10 21:23:15  brouard
  310:   Summary: Debugging with valgrind
  311:   Author: Nicolas Brouard
  312: 
  313:   Lot of changes in order to output the results with some covariates
  314:   After the Edimburgh REVES conference 2014, it seems mandatory to
  315:   improve the code.
  316:   No more memory valgrind error but a lot has to be done in order to
  317:   continue the work of splitting the code into subroutines.
  318:   Also, decodemodel has been improved. Tricode is still not
  319:   optimal. nbcode should be improved. Documentation has been added in
  320:   the source code.
  321: 
  322:   Revision 1.143  2014/01/26 09:45:38  brouard
  323:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
  324: 
  325:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  326:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
  327: 
  328:   Revision 1.142  2014/01/26 03:57:36  brouard
  329:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
  330: 
  331:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  332: 
  333:   Revision 1.141  2014/01/26 02:42:01  brouard
  334:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  335: 
  336:   Revision 1.140  2011/09/02 10:37:54  brouard
  337:   Summary: times.h is ok with mingw32 now.
  338: 
  339:   Revision 1.139  2010/06/14 07:50:17  brouard
  340:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
  341:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
  342: 
  343:   Revision 1.138  2010/04/30 18:19:40  brouard
  344:   *** empty log message ***
  345: 
  346:   Revision 1.137  2010/04/29 18:11:38  brouard
  347:   (Module): Checking covariates for more complex models
  348:   than V1+V2. A lot of change to be done. Unstable.
  349: 
  350:   Revision 1.136  2010/04/26 20:30:53  brouard
  351:   (Module): merging some libgsl code. Fixing computation
  352:   of likelione (using inter/intrapolation if mle = 0) in order to
  353:   get same likelihood as if mle=1.
  354:   Some cleaning of code and comments added.
  355: 
  356:   Revision 1.135  2009/10/29 15:33:14  brouard
  357:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  358: 
  359:   Revision 1.134  2009/10/29 13:18:53  brouard
  360:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  361: 
  362:   Revision 1.133  2009/07/06 10:21:25  brouard
  363:   just nforces
  364: 
  365:   Revision 1.132  2009/07/06 08:22:05  brouard
  366:   Many tings
  367: 
  368:   Revision 1.131  2009/06/20 16:22:47  brouard
  369:   Some dimensions resccaled
  370: 
  371:   Revision 1.130  2009/05/26 06:44:34  brouard
  372:   (Module): Max Covariate is now set to 20 instead of 8. A
  373:   lot of cleaning with variables initialized to 0. Trying to make
  374:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
  375: 
  376:   Revision 1.129  2007/08/31 13:49:27  lievre
  377:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
  378: 
  379:   Revision 1.128  2006/06/30 13:02:05  brouard
  380:   (Module): Clarifications on computing e.j
  381: 
  382:   Revision 1.127  2006/04/28 18:11:50  brouard
  383:   (Module): Yes the sum of survivors was wrong since
  384:   imach-114 because nhstepm was no more computed in the age
  385:   loop. Now we define nhstepma in the age loop.
  386:   (Module): In order to speed up (in case of numerous covariates) we
  387:   compute health expectancies (without variances) in a first step
  388:   and then all the health expectancies with variances or standard
  389:   deviation (needs data from the Hessian matrices) which slows the
  390:   computation.
  391:   In the future we should be able to stop the program is only health
  392:   expectancies and graph are needed without standard deviations.
  393: 
  394:   Revision 1.126  2006/04/28 17:23:28  brouard
  395:   (Module): Yes the sum of survivors was wrong since
  396:   imach-114 because nhstepm was no more computed in the age
  397:   loop. Now we define nhstepma in the age loop.
  398:   Version 0.98h
  399: 
  400:   Revision 1.125  2006/04/04 15:20:31  lievre
  401:   Errors in calculation of health expectancies. Age was not initialized.
  402:   Forecasting file added.
  403: 
  404:   Revision 1.124  2006/03/22 17:13:53  lievre
  405:   Parameters are printed with %lf instead of %f (more numbers after the comma).
  406:   The log-likelihood is printed in the log file
  407: 
  408:   Revision 1.123  2006/03/20 10:52:43  brouard
  409:   * imach.c (Module): <title> changed, corresponds to .htm file
  410:   name. <head> headers where missing.
  411: 
  412:   * imach.c (Module): Weights can have a decimal point as for
  413:   English (a comma might work with a correct LC_NUMERIC environment,
  414:   otherwise the weight is truncated).
  415:   Modification of warning when the covariates values are not 0 or
  416:   1.
  417:   Version 0.98g
  418: 
  419:   Revision 1.122  2006/03/20 09:45:41  brouard
  420:   (Module): Weights can have a decimal point as for
  421:   English (a comma might work with a correct LC_NUMERIC environment,
  422:   otherwise the weight is truncated).
  423:   Modification of warning when the covariates values are not 0 or
  424:   1.
  425:   Version 0.98g
  426: 
  427:   Revision 1.121  2006/03/16 17:45:01  lievre
  428:   * imach.c (Module): Comments concerning covariates added
  429: 
  430:   * imach.c (Module): refinements in the computation of lli if
  431:   status=-2 in order to have more reliable computation if stepm is
  432:   not 1 month. Version 0.98f
  433: 
  434:   Revision 1.120  2006/03/16 15:10:38  lievre
  435:   (Module): refinements in the computation of lli if
  436:   status=-2 in order to have more reliable computation if stepm is
  437:   not 1 month. Version 0.98f
  438: 
  439:   Revision 1.119  2006/03/15 17:42:26  brouard
  440:   (Module): Bug if status = -2, the loglikelihood was
  441:   computed as likelihood omitting the logarithm. Version O.98e
  442: 
  443:   Revision 1.118  2006/03/14 18:20:07  brouard
  444:   (Module): varevsij Comments added explaining the second
  445:   table of variances if popbased=1 .
  446:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  447:   (Module): Function pstamp added
  448:   (Module): Version 0.98d
  449: 
  450:   Revision 1.117  2006/03/14 17:16:22  brouard
  451:   (Module): varevsij Comments added explaining the second
  452:   table of variances if popbased=1 .
  453:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  454:   (Module): Function pstamp added
  455:   (Module): Version 0.98d
  456: 
  457:   Revision 1.116  2006/03/06 10:29:27  brouard
  458:   (Module): Variance-covariance wrong links and
  459:   varian-covariance of ej. is needed (Saito).
  460: 
  461:   Revision 1.115  2006/02/27 12:17:45  brouard
  462:   (Module): One freematrix added in mlikeli! 0.98c
  463: 
  464:   Revision 1.114  2006/02/26 12:57:58  brouard
  465:   (Module): Some improvements in processing parameter
  466:   filename with strsep.
  467: 
  468:   Revision 1.113  2006/02/24 14:20:24  brouard
  469:   (Module): Memory leaks checks with valgrind and:
  470:   datafile was not closed, some imatrix were not freed and on matrix
  471:   allocation too.
  472: 
  473:   Revision 1.112  2006/01/30 09:55:26  brouard
  474:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
  475: 
  476:   Revision 1.111  2006/01/25 20:38:18  brouard
  477:   (Module): Lots of cleaning and bugs added (Gompertz)
  478:   (Module): Comments can be added in data file. Missing date values
  479:   can be a simple dot '.'.
  480: 
  481:   Revision 1.110  2006/01/25 00:51:50  brouard
  482:   (Module): Lots of cleaning and bugs added (Gompertz)
  483: 
  484:   Revision 1.109  2006/01/24 19:37:15  brouard
  485:   (Module): Comments (lines starting with a #) are allowed in data.
  486: 
  487:   Revision 1.108  2006/01/19 18:05:42  lievre
  488:   Gnuplot problem appeared...
  489:   To be fixed
  490: 
  491:   Revision 1.107  2006/01/19 16:20:37  brouard
  492:   Test existence of gnuplot in imach path
  493: 
  494:   Revision 1.106  2006/01/19 13:24:36  brouard
  495:   Some cleaning and links added in html output
  496: 
  497:   Revision 1.105  2006/01/05 20:23:19  lievre
  498:   *** empty log message ***
  499: 
  500:   Revision 1.104  2005/09/30 16:11:43  lievre
  501:   (Module): sump fixed, loop imx fixed, and simplifications.
  502:   (Module): If the status is missing at the last wave but we know
  503:   that the person is alive, then we can code his/her status as -2
  504:   (instead of missing=-1 in earlier versions) and his/her
  505:   contributions to the likelihood is 1 - Prob of dying from last
  506:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
  507:   the healthy state at last known wave). Version is 0.98
  508: 
  509:   Revision 1.103  2005/09/30 15:54:49  lievre
  510:   (Module): sump fixed, loop imx fixed, and simplifications.
  511: 
  512:   Revision 1.102  2004/09/15 17:31:30  brouard
  513:   Add the possibility to read data file including tab characters.
  514: 
  515:   Revision 1.101  2004/09/15 10:38:38  brouard
  516:   Fix on curr_time
  517: 
  518:   Revision 1.100  2004/07/12 18:29:06  brouard
  519:   Add version for Mac OS X. Just define UNIX in Makefile
  520: 
  521:   Revision 1.99  2004/06/05 08:57:40  brouard
  522:   *** empty log message ***
  523: 
  524:   Revision 1.98  2004/05/16 15:05:56  brouard
  525:   New version 0.97 . First attempt to estimate force of mortality
  526:   directly from the data i.e. without the need of knowing the health
  527:   state at each age, but using a Gompertz model: log u =a + b*age .
  528:   This is the basic analysis of mortality and should be done before any
  529:   other analysis, in order to test if the mortality estimated from the
  530:   cross-longitudinal survey is different from the mortality estimated
  531:   from other sources like vital statistic data.
  532: 
  533:   The same imach parameter file can be used but the option for mle should be -3.
  534: 
  535:   Agnès, who wrote this part of the code, tried to keep most of the
  536:   former routines in order to include the new code within the former code.
  537: 
  538:   The output is very simple: only an estimate of the intercept and of
  539:   the slope with 95% confident intervals.
  540: 
  541:   Current limitations:
  542:   A) Even if you enter covariates, i.e. with the
  543:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
  544:   B) There is no computation of Life Expectancy nor Life Table.
  545: 
  546:   Revision 1.97  2004/02/20 13:25:42  lievre
  547:   Version 0.96d. Population forecasting command line is (temporarily)
  548:   suppressed.
  549: 
  550:   Revision 1.96  2003/07/15 15:38:55  brouard
  551:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
  552:   rewritten within the same printf. Workaround: many printfs.
  553: 
  554:   Revision 1.95  2003/07/08 07:54:34  brouard
  555:   * imach.c (Repository):
  556:   (Repository): Using imachwizard code to output a more meaningful covariance
  557:   matrix (cov(a12,c31) instead of numbers.
  558: 
  559:   Revision 1.94  2003/06/27 13:00:02  brouard
  560:   Just cleaning
  561: 
  562:   Revision 1.93  2003/06/25 16:33:55  brouard
  563:   (Module): On windows (cygwin) function asctime_r doesn't
  564:   exist so I changed back to asctime which exists.
  565:   (Module): Version 0.96b
  566: 
  567:   Revision 1.92  2003/06/25 16:30:45  brouard
  568:   (Module): On windows (cygwin) function asctime_r doesn't
  569:   exist so I changed back to asctime which exists.
  570: 
  571:   Revision 1.91  2003/06/25 15:30:29  brouard
  572:   * imach.c (Repository): Duplicated warning errors corrected.
  573:   (Repository): Elapsed time after each iteration is now output. It
  574:   helps to forecast when convergence will be reached. Elapsed time
  575:   is stamped in powell.  We created a new html file for the graphs
  576:   concerning matrix of covariance. It has extension -cov.htm.
  577: 
  578:   Revision 1.90  2003/06/24 12:34:15  brouard
  579:   (Module): Some bugs corrected for windows. Also, when
  580:   mle=-1 a template is output in file "or"mypar.txt with the design
  581:   of the covariance matrix to be input.
  582: 
  583:   Revision 1.89  2003/06/24 12:30:52  brouard
  584:   (Module): Some bugs corrected for windows. Also, when
  585:   mle=-1 a template is output in file "or"mypar.txt with the design
  586:   of the covariance matrix to be input.
  587: 
  588:   Revision 1.88  2003/06/23 17:54:56  brouard
  589:   * 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.
  590: 
  591:   Revision 1.87  2003/06/18 12:26:01  brouard
  592:   Version 0.96
  593: 
  594:   Revision 1.86  2003/06/17 20:04:08  brouard
  595:   (Module): Change position of html and gnuplot routines and added
  596:   routine fileappend.
  597: 
  598:   Revision 1.85  2003/06/17 13:12:43  brouard
  599:   * imach.c (Repository): Check when date of death was earlier that
  600:   current date of interview. It may happen when the death was just
  601:   prior to the death. In this case, dh was negative and likelihood
  602:   was wrong (infinity). We still send an "Error" but patch by
  603:   assuming that the date of death was just one stepm after the
  604:   interview.
  605:   (Repository): Because some people have very long ID (first column)
  606:   we changed int to long in num[] and we added a new lvector for
  607:   memory allocation. But we also truncated to 8 characters (left
  608:   truncation)
  609:   (Repository): No more line truncation errors.
  610: 
  611:   Revision 1.84  2003/06/13 21:44:43  brouard
  612:   * imach.c (Repository): Replace "freqsummary" at a correct
  613:   place. It differs from routine "prevalence" which may be called
  614:   many times. Probs is memory consuming and must be used with
  615:   parcimony.
  616:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
  617: 
  618:   Revision 1.83  2003/06/10 13:39:11  lievre
  619:   *** empty log message ***
  620: 
  621:   Revision 1.82  2003/06/05 15:57:20  brouard
  622:   Add log in  imach.c and  fullversion number is now printed.
  623: 
  624: */
  625: /*
  626:    Interpolated Markov Chain
  627: 
  628:   Short summary of the programme:
  629:   
  630:   This program computes Healthy Life Expectancies from
  631:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
  632:   first survey ("cross") where individuals from different ages are
  633:   interviewed on their health status or degree of disability (in the
  634:   case of a health survey which is our main interest) -2- at least a
  635:   second wave of interviews ("longitudinal") which measure each change
  636:   (if any) in individual health status.  Health expectancies are
  637:   computed from the time spent in each health state according to a
  638:   model. More health states you consider, more time is necessary to reach the
  639:   Maximum Likelihood of the parameters involved in the model.  The
  640:   simplest model is the multinomial logistic model where pij is the
  641:   probability to be observed in state j at the second wave
  642:   conditional to be observed in state i at the first wave. Therefore
  643:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
  644:   'age' is age and 'sex' is a covariate. If you want to have a more
  645:   complex model than "constant and age", you should modify the program
  646:   where the markup *Covariates have to be included here again* invites
  647:   you to do it.  More covariates you add, slower the
  648:   convergence.
  649: 
  650:   The advantage of this computer programme, compared to a simple
  651:   multinomial logistic model, is clear when the delay between waves is not
  652:   identical for each individual. Also, if a individual missed an
  653:   intermediate interview, the information is lost, but taken into
  654:   account using an interpolation or extrapolation.  
  655: 
  656:   hPijx is the probability to be observed in state i at age x+h
  657:   conditional to the observed state i at age x. The delay 'h' can be
  658:   split into an exact number (nh*stepm) of unobserved intermediate
  659:   states. This elementary transition (by month, quarter,
  660:   semester or year) is modelled as a multinomial logistic.  The hPx
  661:   matrix is simply the matrix product of nh*stepm elementary matrices
  662:   and the contribution of each individual to the likelihood is simply
  663:   hPijx.
  664: 
  665:   Also this programme outputs the covariance matrix of the parameters but also
  666:   of the life expectancies. It also computes the period (stable) prevalence.
  667: 
  668: Back prevalence and projections:
  669:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp, double dateprev1,double dateprev2, int firstpass, int lastpass, int mobilavproj)
  670:     Computes the back prevalence limit  for any combination	of covariate values k
  671:     at any age between ageminpar and agemaxpar and returns it in **bprlim. In the loops,
  672:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm, **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
  673:  - hBijx Back Probability to be in state i at age x-h being in j at x
  674:    Computes for any combination of covariates k and any age between bage and fage 
  675:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
  676:  			oldm=oldms;savm=savms;
  677: 	 - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
  678:      Computes the transition matrix starting at age 'age' over
  679:      'nhstepm*hstepm*stepm' months (i.e. until
  680:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
  681:      nhstepm*hstepm matrices. Returns p3mat[i][j][h] after calling 
  682:      p3mat[i][j][h]=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\
  683: 									 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
  684: 
  685:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
  686:            Institut national d'études démographiques, Paris.
  687:   This software have been partly granted by Euro-REVES, a concerted action
  688:   from the European Union.
  689:   It is copyrighted identically to a GNU software product, ie programme and
  690:   software can be distributed freely for non commercial use. Latest version
  691:   can be accessed at http://euroreves.ined.fr/imach .
  692: 
  693:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
  694:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
  695:   
  696:   **********************************************************************/
  697: /*
  698:   main
  699:   read parameterfile
  700:   read datafile
  701:   concatwav
  702:   freqsummary
  703:   if (mle >= 1)
  704:     mlikeli
  705:   print results files
  706:   if mle==1 
  707:      computes hessian
  708:   read end of parameter file: agemin, agemax, bage, fage, estepm
  709:       begin-prev-date,...
  710:   open gnuplot file
  711:   open html file
  712:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
  713:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
  714:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
  715:     freexexit2 possible for memory heap.
  716: 
  717:   h Pij x                         | pij_nom  ficrestpij
  718:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
  719:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
  720:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
  721: 
  722:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
  723:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
  724:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
  725:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
  726:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
  727: 
  728:   forecasting if prevfcast==1 prevforecast call prevalence()
  729:   health expectancies
  730:   Variance-covariance of DFLE
  731:   prevalence()
  732:    movingaverage()
  733:   varevsij() 
  734:   if popbased==1 varevsij(,popbased)
  735:   total life expectancies
  736:   Variance of period (stable) prevalence
  737:  end
  738: */
  739: 
  740: /* #define DEBUG */
  741: /* #define DEBUGBRENT */
  742: /* #define DEBUGLINMIN */
  743: /* #define DEBUGHESS */
  744: #define DEBUGHESSIJ
  745: #define LINMINORIGINAL  /* Don't use loop on scale in linmin (accepting nan)*/
  746: #define POWELL /* Instead of NLOPT */
  747: #define POWELLF1F3 /* Skip test */
  748: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
  749: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
  750: 
  751: #include <math.h>
  752: #include <stdio.h>
  753: #include <stdlib.h>
  754: #include <string.h>
  755: 
  756: #ifdef _WIN32
  757: #include <io.h>
  758: #include <windows.h>
  759: #include <tchar.h>
  760: #else
  761: #include <unistd.h>
  762: #endif
  763: 
  764: #include <limits.h>
  765: #include <sys/types.h>
  766: 
  767: #if defined(__GNUC__)
  768: #include <sys/utsname.h> /* Doesn't work on Windows */
  769: #endif
  770: 
  771: #include <sys/stat.h>
  772: #include <errno.h>
  773: /* extern int errno; */
  774: 
  775: /* #ifdef LINUX */
  776: /* #include <time.h> */
  777: /* #include "timeval.h" */
  778: /* #else */
  779: /* #include <sys/time.h> */
  780: /* #endif */
  781: 
  782: #include <time.h>
  783: 
  784: #ifdef GSL
  785: #include <gsl/gsl_errno.h>
  786: #include <gsl/gsl_multimin.h>
  787: #endif
  788: 
  789: 
  790: #ifdef NLOPT
  791: #include <nlopt.h>
  792: typedef struct {
  793:   double (* function)(double [] );
  794: } myfunc_data ;
  795: #endif
  796: 
  797: /* #include <libintl.h> */
  798: /* #define _(String) gettext (String) */
  799: 
  800: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
  801: 
  802: #define GNUPLOTPROGRAM "gnuplot"
  803: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
  804: #define FILENAMELENGTH 132
  805: 
  806: #define	GLOCK_ERROR_NOPATH		-1	/* empty path */
  807: #define	GLOCK_ERROR_GETCWD		-2	/* cannot get cwd */
  808: 
  809: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
  810: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
  811: 
  812: #define NINTERVMAX 8
  813: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
  814: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
  815: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
  816: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
  817: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
  818: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
  819: #define MAXN 20000
  820: #define YEARM 12. /**< Number of months per year */
  821: /* #define AGESUP 130 */
  822: #define AGESUP 150
  823: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
  824: #define AGEBASE 40
  825: #define AGEOVERFLOW 1.e20
  826: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
  827: #ifdef _WIN32
  828: #define DIRSEPARATOR '\\'
  829: #define CHARSEPARATOR "\\"
  830: #define ODIRSEPARATOR '/'
  831: #else
  832: #define DIRSEPARATOR '/'
  833: #define CHARSEPARATOR "/"
  834: #define ODIRSEPARATOR '\\'
  835: #endif
  836: 
  837: /* $Id: imach.c,v 1.222 2016/02/17 08:14:50 brouard Exp $ */
  838: /* $State: Exp $ */
  839: #include "version.h"
  840: char version[]=__IMACH_VERSION__;
  841: 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";
  842: char fullversion[]="$Revision: 1.222 $ $Date: 2016/02/17 08:14:50 $"; 
  843: char strstart[80];
  844: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
  845: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
  846: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
  847: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
  848: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
  849: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
  850: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
  851: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
  852: int cptcovprodnoage=0; /**< Number of covariate products without age */   
  853: int cptcoveff=0; /* Total number of covariates to vary for printing results */
  854: int cptcov=0; /* Working variable */
  855: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
  856: int npar=NPARMAX;
  857: int nlstate=2; /* Number of live states */
  858: int ndeath=1; /* Number of dead states */
  859: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
  860: int popbased=0;
  861: 
  862: int *wav; /* Number of waves for this individuual 0 is possible */
  863: int maxwav=0; /* Maxim number of waves */
  864: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
  865: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
  866: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
  867: 		   to the likelihood and the sum of weights (done by funcone)*/
  868: int mle=1, weightopt=0;
  869: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
  870: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
  871: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
  872: 	   * wave mi and wave mi+1 is not an exact multiple of stepm. */
  873: int countcallfunc=0;  /* Count the number of calls to func */
  874: double jmean=1; /* Mean space between 2 waves */
  875: double **matprod2(); /* test */
  876: double **oldm, **newm, **savm; /* Working pointers to matrices */
  877: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
  878: double	 **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
  879: 
  880: /*FILE *fic ; */ /* Used in readdata only */
  881: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
  882: FILE *ficlog, *ficrespow;
  883: int globpr=0; /* Global variable for printing or not */
  884: double fretone; /* Only one call to likelihood */
  885: long ipmx=0; /* Number of contributions */
  886: double sw; /* Sum of weights */
  887: char filerespow[FILENAMELENGTH];
  888: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
  889: FILE *ficresilk;
  890: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
  891: FILE *ficresprobmorprev;
  892: FILE *fichtm, *fichtmcov; /* Html File */
  893: FILE *ficreseij;
  894: char filerese[FILENAMELENGTH];
  895: FILE *ficresstdeij;
  896: char fileresstde[FILENAMELENGTH];
  897: FILE *ficrescveij;
  898: char filerescve[FILENAMELENGTH];
  899: FILE  *ficresvij;
  900: char fileresv[FILENAMELENGTH];
  901: FILE  *ficresvpl;
  902: char fileresvpl[FILENAMELENGTH];
  903: char title[MAXLINE];
  904: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
  905: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
  906: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
  907: char command[FILENAMELENGTH];
  908: int  outcmd=0;
  909: 
  910: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
  911: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
  912: char filelog[FILENAMELENGTH]; /* Log file */
  913: char filerest[FILENAMELENGTH];
  914: char fileregp[FILENAMELENGTH];
  915: char popfile[FILENAMELENGTH];
  916: 
  917: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
  918: 
  919: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
  920: /* struct timezone tzp; */
  921: /* extern int gettimeofday(); */
  922: struct tm tml, *gmtime(), *localtime();
  923: 
  924: extern time_t time();
  925: 
  926: struct tm start_time, end_time, curr_time, last_time, forecast_time;
  927: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
  928: struct tm tm;
  929: 
  930: char strcurr[80], strfor[80];
  931: 
  932: char *endptr;
  933: long lval;
  934: double dval;
  935: 
  936: #define NR_END 1
  937: #define FREE_ARG char*
  938: #define FTOL 1.0e-10
  939: 
  940: #define NRANSI 
  941: #define ITMAX 200 
  942: 
  943: #define TOL 2.0e-4 
  944: 
  945: #define CGOLD 0.3819660 
  946: #define ZEPS 1.0e-10 
  947: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
  948: 
  949: #define GOLD 1.618034 
  950: #define GLIMIT 100.0 
  951: #define TINY 1.0e-20 
  952: 
  953: static double maxarg1,maxarg2;
  954: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
  955: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
  956:   
  957: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
  958: #define rint(a) floor(a+0.5)
  959: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
  960: #define mytinydouble 1.0e-16
  961: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
  962: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
  963: /* static double dsqrarg; */
  964: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
  965: static double sqrarg;
  966: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
  967: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
  968: int agegomp= AGEGOMP;
  969: 
  970: int imx; 
  971: int stepm=1;
  972: /* Stepm, step in month: minimum step interpolation*/
  973: 
  974: int estepm;
  975: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
  976: 
  977: int m,nb;
  978: long *num;
  979: int firstpass=0, lastpass=4,*cod, *cens;
  980: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
  981: 		   covariate for which somebody answered excluding 
  982: 		   undefined. Usually 2: 0 and 1. */
  983: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
  984: 			     covariate for which somebody answered including 
  985: 			     undefined. Usually 3: -1, 0 and 1. */
  986: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
  987: double **pmmij, ***probs; /* Global pointer */
  988: double ***mobaverage, ***mobaverages; /* New global variable */
  989: double *ageexmed,*agecens;
  990: double dateintmean=0;
  991: 
  992: double *weight;
  993: int **s; /* Status */
  994: double *agedc;
  995: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
  996: 		  * covar=matrix(0,NCOVMAX,1,n); 
  997: 		  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
  998: double  idx; 
  999: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
 1000: int *Tage;
 1001: int *Ndum; /** Freq of modality (tricode */
 1002: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
 1003: int **Tvard, *Tprod, cptcovprod, *Tvaraff, *invalidvarcomb;
 1004: double *lsurv, *lpop, *tpop;
 1005: 
 1006: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
 1007: double ftolhess; /**< Tolerance for computing hessian */
 1008: 
 1009: /**************** split *************************/
 1010: static	int split( char *path, char *dirc, char *name, char *ext, char *finame )
 1011: {
 1012:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
 1013:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
 1014:   */ 
 1015:   char	*ss;				/* pointer */
 1016:   int	l1=0, l2=0;				/* length counters */
 1017: 
 1018:   l1 = strlen(path );			/* length of path */
 1019:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
 1020:   ss= strrchr( path, DIRSEPARATOR );		/* find last / */
 1021:   if ( ss == NULL ) {			/* no directory, so determine current directory */
 1022:     strcpy( name, path );		/* we got the fullname name because no directory */
 1023:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
 1024:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
 1025:     /* get current working directory */
 1026:     /*    extern  char* getcwd ( char *buf , int len);*/
 1027: #ifdef WIN32
 1028:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
 1029: #else
 1030: 	if (getcwd(dirc, FILENAME_MAX) == NULL) {
 1031: #endif
 1032:       return( GLOCK_ERROR_GETCWD );
 1033:     }
 1034:     /* got dirc from getcwd*/
 1035:     printf(" DIRC = %s \n",dirc);
 1036:   } else {				/* strip directory from path */
 1037:     ss++;				/* after this, the filename */
 1038:     l2 = strlen( ss );			/* length of filename */
 1039:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
 1040:     strcpy( name, ss );		/* save file name */
 1041:     strncpy( dirc, path, l1 - l2 );	/* now the directory */
 1042:     dirc[l1-l2] = '\0';			/* add zero */
 1043:     printf(" DIRC2 = %s \n",dirc);
 1044:   }
 1045:   /* We add a separator at the end of dirc if not exists */
 1046:   l1 = strlen( dirc );			/* length of directory */
 1047:   if( dirc[l1-1] != DIRSEPARATOR ){
 1048:     dirc[l1] =  DIRSEPARATOR;
 1049:     dirc[l1+1] = 0; 
 1050:     printf(" DIRC3 = %s \n",dirc);
 1051:   }
 1052:   ss = strrchr( name, '.' );		/* find last / */
 1053:   if (ss >0){
 1054:     ss++;
 1055:     strcpy(ext,ss);			/* save extension */
 1056:     l1= strlen( name);
 1057:     l2= strlen(ss)+1;
 1058:     strncpy( finame, name, l1-l2);
 1059:     finame[l1-l2]= 0;
 1060:   }
 1061: 
 1062:   return( 0 );				/* we're done */
 1063: }
 1064: 
 1065: 
 1066: /******************************************/
 1067: 
 1068: void replace_back_to_slash(char *s, char*t)
 1069: {
 1070:   int i;
 1071:   int lg=0;
 1072:   i=0;
 1073:   lg=strlen(t);
 1074:   for(i=0; i<= lg; i++) {
 1075:     (s[i] = t[i]);
 1076:     if (t[i]== '\\') s[i]='/';
 1077:   }
 1078: }
 1079: 
 1080: char *trimbb(char *out, char *in)
 1081: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
 1082:   char *s;
 1083:   s=out;
 1084:   while (*in != '\0'){
 1085:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
 1086:       in++;
 1087:     }
 1088:     *out++ = *in++;
 1089:   }
 1090:   *out='\0';
 1091:   return s;
 1092: }
 1093: 
 1094: /* char *substrchaine(char *out, char *in, char *chain) */
 1095: /* { */
 1096: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
 1097: /*   char *s, *t; */
 1098: /*   t=in;s=out; */
 1099: /*   while ((*in != *chain) && (*in != '\0')){ */
 1100: /*     *out++ = *in++; */
 1101: /*   } */
 1102: 
 1103: /*   /\* *in matches *chain *\/ */
 1104: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
 1105: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1106: /*   } */
 1107: /*   in--; chain--; */
 1108: /*   while ( (*in != '\0')){ */
 1109: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1110: /*     *out++ = *in++; */
 1111: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1112: /*   } */
 1113: /*   *out='\0'; */
 1114: /*   out=s; */
 1115: /*   return out; */
 1116: /* } */
 1117: char *substrchaine(char *out, char *in, char *chain)
 1118: {
 1119:   /* Substract chain 'chain' from 'in', return and output 'out' */
 1120:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
 1121: 
 1122:   char *strloc;
 1123: 
 1124:   strcpy (out, in); 
 1125:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
 1126:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
 1127:   if(strloc != NULL){ 
 1128:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
 1129:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
 1130:     /* strcpy (strloc, strloc +strlen(chain));*/
 1131:   }
 1132:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
 1133:   return out;
 1134: }
 1135: 
 1136: 
 1137: char *cutl(char *blocc, char *alocc, char *in, char occ)
 1138: {
 1139:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
 1140:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
 1141:      gives blocc="abcdef" and alocc="ghi2j".
 1142:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
 1143:   */
 1144:   char *s, *t;
 1145:   t=in;s=in;
 1146:   while ((*in != occ) && (*in != '\0')){
 1147:     *alocc++ = *in++;
 1148:   }
 1149:   if( *in == occ){
 1150:     *(alocc)='\0';
 1151:     s=++in;
 1152:   }
 1153:  
 1154:   if (s == t) {/* occ not found */
 1155:     *(alocc-(in-s))='\0';
 1156:     in=s;
 1157:   }
 1158:   while ( *in != '\0'){
 1159:     *blocc++ = *in++;
 1160:   }
 1161: 
 1162:   *blocc='\0';
 1163:   return t;
 1164: }
 1165: char *cutv(char *blocc, char *alocc, char *in, char occ)
 1166: {
 1167:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
 1168:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
 1169:      gives blocc="abcdef2ghi" and alocc="j".
 1170:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
 1171:   */
 1172:   char *s, *t;
 1173:   t=in;s=in;
 1174:   while (*in != '\0'){
 1175:     while( *in == occ){
 1176:       *blocc++ = *in++;
 1177:       s=in;
 1178:     }
 1179:     *blocc++ = *in++;
 1180:   }
 1181:   if (s == t) /* occ not found */
 1182:     *(blocc-(in-s))='\0';
 1183:   else
 1184:     *(blocc-(in-s)-1)='\0';
 1185:   in=s;
 1186:   while ( *in != '\0'){
 1187:     *alocc++ = *in++;
 1188:   }
 1189: 
 1190:   *alocc='\0';
 1191:   return s;
 1192: }
 1193: 
 1194: int nbocc(char *s, char occ)
 1195: {
 1196:   int i,j=0;
 1197:   int lg=20;
 1198:   i=0;
 1199:   lg=strlen(s);
 1200:   for(i=0; i<= lg; i++) {
 1201:   if  (s[i] == occ ) j++;
 1202:   }
 1203:   return j;
 1204: }
 1205: 
 1206: /* void cutv(char *u,char *v, char*t, char occ) */
 1207: /* { */
 1208: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
 1209: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
 1210: /*      gives u="abcdef2ghi" and v="j" *\/ */
 1211: /*   int i,lg,j,p=0; */
 1212: /*   i=0; */
 1213: /*   lg=strlen(t); */
 1214: /*   for(j=0; j<=lg-1; j++) { */
 1215: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
 1216: /*   } */
 1217: 
 1218: /*   for(j=0; j<p; j++) { */
 1219: /*     (u[j] = t[j]); */
 1220: /*   } */
 1221: /*      u[p]='\0'; */
 1222: 
 1223: /*    for(j=0; j<= lg; j++) { */
 1224: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
 1225: /*   } */
 1226: /* } */
 1227: 
 1228: #ifdef _WIN32
 1229: char * strsep(char **pp, const char *delim)
 1230: {
 1231:   char *p, *q;
 1232:          
 1233:   if ((p = *pp) == NULL)
 1234:     return 0;
 1235:   if ((q = strpbrk (p, delim)) != NULL)
 1236:   {
 1237:     *pp = q + 1;
 1238:     *q = '\0';
 1239:   }
 1240:   else
 1241:     *pp = 0;
 1242:   return p;
 1243: }
 1244: #endif
 1245: 
 1246: /********************** nrerror ********************/
 1247: 
 1248: void nrerror(char error_text[])
 1249: {
 1250:   fprintf(stderr,"ERREUR ...\n");
 1251:   fprintf(stderr,"%s\n",error_text);
 1252:   exit(EXIT_FAILURE);
 1253: }
 1254: /*********************** vector *******************/
 1255: double *vector(int nl, int nh)
 1256: {
 1257:   double *v;
 1258:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
 1259:   if (!v) nrerror("allocation failure in vector");
 1260:   return v-nl+NR_END;
 1261: }
 1262: 
 1263: /************************ free vector ******************/
 1264: void free_vector(double*v, int nl, int nh)
 1265: {
 1266:   free((FREE_ARG)(v+nl-NR_END));
 1267: }
 1268: 
 1269: /************************ivector *******************************/
 1270: int *ivector(long nl,long nh)
 1271: {
 1272:   int *v;
 1273:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
 1274:   if (!v) nrerror("allocation failure in ivector");
 1275:   return v-nl+NR_END;
 1276: }
 1277: 
 1278: /******************free ivector **************************/
 1279: void free_ivector(int *v, long nl, long nh)
 1280: {
 1281:   free((FREE_ARG)(v+nl-NR_END));
 1282: }
 1283: 
 1284: /************************lvector *******************************/
 1285: long *lvector(long nl,long nh)
 1286: {
 1287:   long *v;
 1288:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
 1289:   if (!v) nrerror("allocation failure in ivector");
 1290:   return v-nl+NR_END;
 1291: }
 1292: 
 1293: /******************free lvector **************************/
 1294: void free_lvector(long *v, long nl, long nh)
 1295: {
 1296:   free((FREE_ARG)(v+nl-NR_END));
 1297: }
 1298: 
 1299: /******************* imatrix *******************************/
 1300: int **imatrix(long nrl, long nrh, long ncl, long nch) 
 1301:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
 1302: { 
 1303:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
 1304:   int **m; 
 1305:   
 1306:   /* allocate pointers to rows */ 
 1307:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
 1308:   if (!m) nrerror("allocation failure 1 in matrix()"); 
 1309:   m += NR_END; 
 1310:   m -= nrl; 
 1311:   
 1312:   
 1313:   /* allocate rows and set pointers to them */ 
 1314:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
 1315:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
 1316:   m[nrl] += NR_END; 
 1317:   m[nrl] -= ncl; 
 1318:   
 1319:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
 1320:   
 1321:   /* return pointer to array of pointers to rows */ 
 1322:   return m; 
 1323: } 
 1324: 
 1325: /****************** free_imatrix *************************/
 1326: void free_imatrix(m,nrl,nrh,ncl,nch)
 1327:       int **m;
 1328:       long nch,ncl,nrh,nrl; 
 1329:      /* free an int matrix allocated by imatrix() */ 
 1330: { 
 1331:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
 1332:   free((FREE_ARG) (m+nrl-NR_END)); 
 1333: } 
 1334: 
 1335: /******************* matrix *******************************/
 1336: double **matrix(long nrl, long nrh, long ncl, long nch)
 1337: {
 1338:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
 1339:   double **m;
 1340: 
 1341:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1342:   if (!m) nrerror("allocation failure 1 in matrix()");
 1343:   m += NR_END;
 1344:   m -= nrl;
 1345: 
 1346:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1347:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1348:   m[nrl] += NR_END;
 1349:   m[nrl] -= ncl;
 1350: 
 1351:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1352:   return m;
 1353:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
 1354: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
 1355: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
 1356:    */
 1357: }
 1358: 
 1359: /*************************free matrix ************************/
 1360: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
 1361: {
 1362:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1363:   free((FREE_ARG)(m+nrl-NR_END));
 1364: }
 1365: 
 1366: /******************* ma3x *******************************/
 1367: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
 1368: {
 1369:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
 1370:   double ***m;
 1371: 
 1372:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1373:   if (!m) nrerror("allocation failure 1 in matrix()");
 1374:   m += NR_END;
 1375:   m -= nrl;
 1376: 
 1377:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1378:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1379:   m[nrl] += NR_END;
 1380:   m[nrl] -= ncl;
 1381: 
 1382:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1383: 
 1384:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
 1385:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
 1386:   m[nrl][ncl] += NR_END;
 1387:   m[nrl][ncl] -= nll;
 1388:   for (j=ncl+1; j<=nch; j++) 
 1389:     m[nrl][j]=m[nrl][j-1]+nlay;
 1390:   
 1391:   for (i=nrl+1; i<=nrh; i++) {
 1392:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
 1393:     for (j=ncl+1; j<=nch; j++) 
 1394:       m[i][j]=m[i][j-1]+nlay;
 1395:   }
 1396:   return m; 
 1397:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
 1398:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
 1399:   */
 1400: }
 1401: 
 1402: /*************************free ma3x ************************/
 1403: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
 1404: {
 1405:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
 1406:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1407:   free((FREE_ARG)(m+nrl-NR_END));
 1408: }
 1409: 
 1410: /*************** function subdirf ***********/
 1411: char *subdirf(char fileres[])
 1412: {
 1413:   /* Caution optionfilefiname is hidden */
 1414:   strcpy(tmpout,optionfilefiname);
 1415:   strcat(tmpout,"/"); /* Add to the right */
 1416:   strcat(tmpout,fileres);
 1417:   return tmpout;
 1418: }
 1419: 
 1420: /*************** function subdirf2 ***********/
 1421: char *subdirf2(char fileres[], char *preop)
 1422: {
 1423:   
 1424:   /* Caution optionfilefiname is hidden */
 1425:   strcpy(tmpout,optionfilefiname);
 1426:   strcat(tmpout,"/");
 1427:   strcat(tmpout,preop);
 1428:   strcat(tmpout,fileres);
 1429:   return tmpout;
 1430: }
 1431: 
 1432: /*************** function subdirf3 ***********/
 1433: char *subdirf3(char fileres[], char *preop, char *preop2)
 1434: {
 1435:   
 1436:   /* Caution optionfilefiname is hidden */
 1437:   strcpy(tmpout,optionfilefiname);
 1438:   strcat(tmpout,"/");
 1439:   strcat(tmpout,preop);
 1440:   strcat(tmpout,preop2);
 1441:   strcat(tmpout,fileres);
 1442:   return tmpout;
 1443: }
 1444:  
 1445: /*************** function subdirfext ***********/
 1446: char *subdirfext(char fileres[], char *preop, char *postop)
 1447: {
 1448:   
 1449:   strcpy(tmpout,preop);
 1450:   strcat(tmpout,fileres);
 1451:   strcat(tmpout,postop);
 1452:   return tmpout;
 1453: }
 1454: 
 1455: /*************** function subdirfext3 ***********/
 1456: char *subdirfext3(char fileres[], char *preop, char *postop)
 1457: {
 1458:   
 1459:   /* Caution optionfilefiname is hidden */
 1460:   strcpy(tmpout,optionfilefiname);
 1461:   strcat(tmpout,"/");
 1462:   strcat(tmpout,preop);
 1463:   strcat(tmpout,fileres);
 1464:   strcat(tmpout,postop);
 1465:   return tmpout;
 1466: }
 1467:  
 1468: char *asc_diff_time(long time_sec, char ascdiff[])
 1469: {
 1470:   long sec_left, days, hours, minutes;
 1471:   days = (time_sec) / (60*60*24);
 1472:   sec_left = (time_sec) % (60*60*24);
 1473:   hours = (sec_left) / (60*60) ;
 1474:   sec_left = (sec_left) %(60*60);
 1475:   minutes = (sec_left) /60;
 1476:   sec_left = (sec_left) % (60);
 1477:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
 1478:   return ascdiff;
 1479: }
 1480: 
 1481: /***************** f1dim *************************/
 1482: extern int ncom; 
 1483: extern double *pcom,*xicom;
 1484: extern double (*nrfunc)(double []); 
 1485:  
 1486: double f1dim(double x) 
 1487: { 
 1488:   int j; 
 1489:   double f;
 1490:   double *xt; 
 1491:  
 1492:   xt=vector(1,ncom); 
 1493:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
 1494:   f=(*nrfunc)(xt); 
 1495:   free_vector(xt,1,ncom); 
 1496:   return f; 
 1497: } 
 1498: 
 1499: /*****************brent *************************/
 1500: double brent(double ax, double bx, double cx, double (*f)(double), double tol, 	double *xmin) 
 1501: {
 1502:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
 1503:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
 1504:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
 1505:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
 1506:    * returned function value. 
 1507:   */
 1508:   int iter; 
 1509:   double a,b,d,etemp;
 1510:   double fu=0,fv,fw,fx;
 1511:   double ftemp=0.;
 1512:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
 1513:   double e=0.0; 
 1514:  
 1515:   a=(ax < cx ? ax : cx); 
 1516:   b=(ax > cx ? ax : cx); 
 1517:   x=w=v=bx; 
 1518:   fw=fv=fx=(*f)(x); 
 1519:   for (iter=1;iter<=ITMAX;iter++) { 
 1520:     xm=0.5*(a+b); 
 1521:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
 1522:     /*		if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
 1523:     printf(".");fflush(stdout);
 1524:     fprintf(ficlog,".");fflush(ficlog);
 1525: #ifdef DEBUGBRENT
 1526:     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);
 1527:     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);
 1528:     /*		if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
 1529: #endif
 1530:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
 1531:       *xmin=x; 
 1532:       return fx; 
 1533:     } 
 1534:     ftemp=fu;
 1535:     if (fabs(e) > tol1) { 
 1536:       r=(x-w)*(fx-fv); 
 1537:       q=(x-v)*(fx-fw); 
 1538:       p=(x-v)*q-(x-w)*r; 
 1539:       q=2.0*(q-r); 
 1540:       if (q > 0.0) p = -p; 
 1541:       q=fabs(q); 
 1542:       etemp=e; 
 1543:       e=d; 
 1544:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
 1545: 	d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1546:       else { 
 1547: 	d=p/q; 
 1548: 	u=x+d; 
 1549: 	if (u-a < tol2 || b-u < tol2) 
 1550: 	  d=SIGN(tol1,xm-x); 
 1551:       } 
 1552:     } else { 
 1553:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1554:     } 
 1555:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
 1556:     fu=(*f)(u); 
 1557:     if (fu <= fx) { 
 1558:       if (u >= x) a=x; else b=x; 
 1559:       SHFT(v,w,x,u) 
 1560:       SHFT(fv,fw,fx,fu) 
 1561:     } else { 
 1562:       if (u < x) a=u; else b=u; 
 1563:       if (fu <= fw || w == x) { 
 1564: 	v=w; 
 1565: 	w=u; 
 1566: 	fv=fw; 
 1567: 	fw=fu; 
 1568:       } else if (fu <= fv || v == x || v == w) { 
 1569: 	v=u; 
 1570: 	fv=fu; 
 1571:       } 
 1572:     } 
 1573:   } 
 1574:   nrerror("Too many iterations in brent"); 
 1575:   *xmin=x; 
 1576:   return fx; 
 1577: } 
 1578: 
 1579: /****************** mnbrak ***********************/
 1580: 
 1581: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
 1582: 	    double (*func)(double)) 
 1583: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
 1584: the downhill direction (defined by the function as evaluated at the initial points) and returns
 1585: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
 1586: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
 1587:    */
 1588:   double ulim,u,r,q, dum;
 1589:   double fu; 
 1590: 
 1591:   double scale=10.;
 1592:   int iterscale=0;
 1593: 
 1594:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
 1595:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
 1596: 
 1597: 
 1598:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
 1599:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
 1600:   /*   *bx = *ax - (*ax - *bx)/scale; */
 1601:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
 1602:   /* } */
 1603: 
 1604:   if (*fb > *fa) { 
 1605:     SHFT(dum,*ax,*bx,dum) 
 1606:     SHFT(dum,*fb,*fa,dum) 
 1607:   } 
 1608:   *cx=(*bx)+GOLD*(*bx-*ax); 
 1609:   *fc=(*func)(*cx); 
 1610: #ifdef DEBUG
 1611:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
 1612:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
 1613: #endif
 1614:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
 1615:     r=(*bx-*ax)*(*fb-*fc); 
 1616:     q=(*bx-*cx)*(*fb-*fa); 
 1617:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
 1618:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
 1619:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
 1620:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
 1621:       fu=(*func)(u); 
 1622: #ifdef DEBUG
 1623:       /* f(x)=A(x-u)**2+f(u) */
 1624:       double A, fparabu; 
 1625:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 1626:       fparabu= *fa - A*(*ax-u)*(*ax-u);
 1627:       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);
 1628:       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);
 1629:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
 1630:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
 1631:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
 1632:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
 1633: #endif 
 1634: #ifdef MNBRAKORIGINAL
 1635: #else
 1636: /*       if (fu > *fc) { */
 1637: /* #ifdef DEBUG */
 1638: /*       printf("mnbrak4  fu > fc \n"); */
 1639: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
 1640: /* #endif */
 1641: /* 	/\* 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 *\\/  *\/ */
 1642: /* 	/\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
 1643: /* 	dum=u; /\* Shifting c and u *\/ */
 1644: /* 	u = *cx; */
 1645: /* 	*cx = dum; */
 1646: /* 	dum = fu; */
 1647: /* 	fu = *fc; */
 1648: /* 	*fc =dum; */
 1649: /*       } else { /\* end *\/ */
 1650: /* #ifdef DEBUG */
 1651: /*       printf("mnbrak3  fu < fc \n"); */
 1652: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
 1653: /* #endif */
 1654: /* 	dum=u; /\* Shifting c and u *\/ */
 1655: /* 	u = *cx; */
 1656: /* 	*cx = dum; */
 1657: /* 	dum = fu; */
 1658: /* 	fu = *fc; */
 1659: /* 	*fc =dum; */
 1660: /*       } */
 1661: #ifdef DEBUG
 1662:       printf("mnbrak34  fu < or >= fc \n");
 1663:       fprintf(ficlog, "mnbrak34 fu < fc\n");
 1664: #endif
 1665:       dum=u; /* Shifting c and u */
 1666:       u = *cx;
 1667:       *cx = dum;
 1668:       dum = fu;
 1669:       fu = *fc;
 1670:       *fc =dum;
 1671: #endif
 1672:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
 1673: #ifdef DEBUG
 1674:       printf("mnbrak2  u after c but before ulim\n");
 1675:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
 1676: #endif
 1677:       fu=(*func)(u); 
 1678:       if (fu < *fc) { 
 1679: #ifdef DEBUG
 1680:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
 1681:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
 1682: #endif
 1683: 	SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
 1684: 	SHFT(*fb,*fc,fu,(*func)(u)) 
 1685:       } 
 1686:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
 1687: #ifdef DEBUG
 1688:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
 1689:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
 1690: #endif
 1691:       u=ulim; 
 1692:       fu=(*func)(u); 
 1693:     } else { /* u could be left to b (if r > q parabola has a maximum) */
 1694: #ifdef DEBUG
 1695:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
 1696:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
 1697: #endif
 1698:       u=(*cx)+GOLD*(*cx-*bx); 
 1699:       fu=(*func)(u); 
 1700:     } /* end tests */
 1701:     SHFT(*ax,*bx,*cx,u) 
 1702:     SHFT(*fa,*fb,*fc,fu) 
 1703: #ifdef DEBUG
 1704:       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);
 1705:       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);
 1706: #endif
 1707:   } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
 1708: } 
 1709: 
 1710: /*************** linmin ************************/
 1711: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
 1712: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
 1713: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
 1714: the value of func at the returned location p . This is actually all accomplished by calling the
 1715: routines mnbrak and brent .*/
 1716: int ncom; 
 1717: double *pcom,*xicom;
 1718: double (*nrfunc)(double []); 
 1719:  
 1720: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
 1721: { 
 1722:   double brent(double ax, double bx, double cx, 
 1723: 	       double (*f)(double), double tol, double *xmin); 
 1724:   double f1dim(double x); 
 1725:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
 1726: 	      double *fc, double (*func)(double)); 
 1727:   int j; 
 1728:   double xx,xmin,bx,ax; 
 1729:   double fx,fb,fa;
 1730: 
 1731: #ifdef LINMINORIGINAL
 1732: #else
 1733:   double scale=10., axs, xxs; /* Scale added for infinity */
 1734: #endif
 1735:   
 1736:   ncom=n; 
 1737:   pcom=vector(1,n); 
 1738:   xicom=vector(1,n); 
 1739:   nrfunc=func; 
 1740:   for (j=1;j<=n;j++) { 
 1741:     pcom[j]=p[j]; 
 1742:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
 1743:   } 
 1744: 
 1745: #ifdef LINMINORIGINAL
 1746:   xx=1.;
 1747: #else
 1748:   axs=0.0;
 1749:   xxs=1.;
 1750:   do{
 1751:     xx= xxs;
 1752: #endif
 1753:     ax=0.;
 1754:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
 1755:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
 1756:     /* 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))   */
 1757:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
 1758:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
 1759:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
 1760:     /* 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]]*/
 1761: #ifdef LINMINORIGINAL
 1762: #else
 1763:     if (fx != fx){
 1764:   	xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
 1765: 	printf("|");
 1766: 	fprintf(ficlog,"|");
 1767: #ifdef DEBUGLINMIN
 1768:   	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);
 1769: #endif
 1770:     }
 1771:   }while(fx != fx);
 1772: #endif
 1773:   
 1774: #ifdef DEBUGLINMIN
 1775:   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);
 1776:   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);
 1777: #endif
 1778:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
 1779:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
 1780:   /* fmin = f(p[j] + xmin * xi[j]) */
 1781:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
 1782:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
 1783: #ifdef DEBUG
 1784:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1785:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1786: #endif
 1787: #ifdef DEBUGLINMIN
 1788:   printf("linmin end ");
 1789:   fprintf(ficlog,"linmin end ");
 1790: #endif
 1791:   for (j=1;j<=n;j++) { 
 1792: #ifdef LINMINORIGINAL
 1793:     xi[j] *= xmin; 
 1794: #else
 1795: #ifdef DEBUGLINMIN
 1796:     if(xxs <1.0)
 1797:       printf(" before xi[%d]=%12.8f", j,xi[j]);
 1798: #endif
 1799:     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) */
 1800: #ifdef DEBUGLINMIN
 1801:     if(xxs <1.0)
 1802:       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 );
 1803: #endif
 1804: #endif
 1805:     p[j] += xi[j]; /* Parameters values are updated accordingly */
 1806:   } 
 1807: #ifdef DEBUGLINMIN
 1808:   printf("\n");
 1809:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
 1810:   fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
 1811:   for (j=1;j<=n;j++) { 
 1812:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
 1813:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
 1814:     if(j % ncovmodel == 0){
 1815:       printf("\n");
 1816:       fprintf(ficlog,"\n");
 1817:     }
 1818:   }
 1819: #else
 1820: #endif
 1821:   free_vector(xicom,1,n); 
 1822:   free_vector(pcom,1,n); 
 1823: } 
 1824: 
 1825: 
 1826: /*************** powell ************************/
 1827: /*
 1828: Minimization of a function func of n variables. Input consists of an initial starting point
 1829: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
 1830: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
 1831: such that failure to decrease by more than this amount on one iteration signals doneness. On
 1832: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
 1833: function value at p , and iter is the number of iterations taken. The routine linmin is used.
 1834:  */
 1835: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
 1836: 	    double (*func)(double [])) 
 1837: { 
 1838:   void linmin(double p[], double xi[], int n, double *fret, 
 1839: 	      double (*func)(double [])); 
 1840:   int i,ibig,j; 
 1841:   double del,t,*pt,*ptt,*xit;
 1842:   double directest;
 1843:   double fp,fptt;
 1844:   double *xits;
 1845:   int niterf, itmp;
 1846: 
 1847:   pt=vector(1,n); 
 1848:   ptt=vector(1,n); 
 1849:   xit=vector(1,n); 
 1850:   xits=vector(1,n); 
 1851:   *fret=(*func)(p); 
 1852:   for (j=1;j<=n;j++) pt[j]=p[j]; 
 1853:   rcurr_time = time(NULL);  
 1854:   for (*iter=1;;++(*iter)) { 
 1855:     fp=(*fret); /* From former iteration or initial value */
 1856:     ibig=0; 
 1857:     del=0.0; 
 1858:     rlast_time=rcurr_time;
 1859:     /* (void) gettimeofday(&curr_time,&tzp); */
 1860:     rcurr_time = time(NULL);  
 1861:     curr_time = *localtime(&rcurr_time);
 1862:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
 1863:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
 1864: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
 1865:     for (i=1;i<=n;i++) {
 1866:       printf(" %d %.12f",i, p[i]);
 1867:       fprintf(ficlog," %d %.12lf",i, p[i]);
 1868:       fprintf(ficrespow," %.12lf", p[i]);
 1869:     }
 1870:     printf("\n");
 1871:     fprintf(ficlog,"\n");
 1872:     fprintf(ficrespow,"\n");fflush(ficrespow);
 1873:     if(*iter <=3){
 1874:       tml = *localtime(&rcurr_time);
 1875:       strcpy(strcurr,asctime(&tml));
 1876:       rforecast_time=rcurr_time; 
 1877:       itmp = strlen(strcurr);
 1878:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
 1879: 	strcurr[itmp-1]='\0';
 1880:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1881:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1882:       for(niterf=10;niterf<=30;niterf+=10){
 1883: 	rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
 1884: 	forecast_time = *localtime(&rforecast_time);
 1885: 	strcpy(strfor,asctime(&forecast_time));
 1886: 	itmp = strlen(strfor);
 1887: 	if(strfor[itmp-1]=='\n')
 1888: 	strfor[itmp-1]='\0';
 1889: 	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);
 1890: 	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);
 1891:       }
 1892:     }
 1893:     for (i=1;i<=n;i++) { /* For each direction i */
 1894:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
 1895:       fptt=(*fret); 
 1896: #ifdef DEBUG
 1897:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1898:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1899: #endif
 1900:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
 1901:       fprintf(ficlog,"%d",i);fflush(ficlog);
 1902:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
 1903: 				    /* Outputs are fret(new point p) p is updated and xit rescaled */
 1904:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
 1905: 	/* because that direction will be replaced unless the gain del is small */
 1906: 	/* in comparison with the 'probable' gain, mu^2, with the last average direction. */
 1907: 	/* Unless the n directions are conjugate some gain in the determinant may be obtained */
 1908: 	/* with the new direction. */
 1909: 	del=fabs(fptt-(*fret)); 
 1910: 	ibig=i; 
 1911:       } 
 1912: #ifdef DEBUG
 1913:       printf("%d %.12e",i,(*fret));
 1914:       fprintf(ficlog,"%d %.12e",i,(*fret));
 1915:       for (j=1;j<=n;j++) {
 1916: 	xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
 1917: 	printf(" x(%d)=%.12e",j,xit[j]);
 1918: 	fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
 1919:       }
 1920:       for(j=1;j<=n;j++) {
 1921: 	printf(" p(%d)=%.12e",j,p[j]);
 1922: 	fprintf(ficlog," p(%d)=%.12e",j,p[j]);
 1923:       }
 1924:       printf("\n");
 1925:       fprintf(ficlog,"\n");
 1926: #endif
 1927:     } /* end loop on each direction i */
 1928:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
 1929:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
 1930:     /* New value of last point Pn is not computed, P(n-1) */
 1931:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
 1932:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
 1933:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
 1934:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
 1935:       /* decreased of more than 3.84  */
 1936:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
 1937:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
 1938:       /* By adding 10 parameters more the gain should be 18.31 */
 1939: 
 1940:       /* Starting the program with initial values given by a former maximization will simply change */
 1941:       /* the scales of the directions and the directions, because the are reset to canonical directions */
 1942:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
 1943:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
 1944: #ifdef DEBUG
 1945:       int k[2],l;
 1946:       k[0]=1;
 1947:       k[1]=-1;
 1948:       printf("Max: %.12e",(*func)(p));
 1949:       fprintf(ficlog,"Max: %.12e",(*func)(p));
 1950:       for (j=1;j<=n;j++) {
 1951: 	printf(" %.12e",p[j]);
 1952: 	fprintf(ficlog," %.12e",p[j]);
 1953:       }
 1954:       printf("\n");
 1955:       fprintf(ficlog,"\n");
 1956:       for(l=0;l<=1;l++) {
 1957: 	for (j=1;j<=n;j++) {
 1958: 	  ptt[j]=p[j]+(p[j]-pt[j])*k[l];
 1959: 	  printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1960: 	  fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1961: 	}
 1962: 	printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1963: 	fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1964:       }
 1965: #endif
 1966: 
 1967: 
 1968:       free_vector(xit,1,n); 
 1969:       free_vector(xits,1,n); 
 1970:       free_vector(ptt,1,n); 
 1971:       free_vector(pt,1,n); 
 1972:       return; 
 1973:     } /* enough precision */ 
 1974:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
 1975:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
 1976:       ptt[j]=2.0*p[j]-pt[j]; 
 1977:       xit[j]=p[j]-pt[j]; 
 1978:       pt[j]=p[j]; 
 1979:     } 
 1980:     fptt=(*func)(ptt); /* f_3 */
 1981: #ifdef POWELLF1F3
 1982: #else
 1983:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
 1984: #endif
 1985:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
 1986:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
 1987:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
 1988:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
 1989:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
 1990:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
 1991:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
 1992: #ifdef NRCORIGINAL
 1993:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
 1994: #else
 1995:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
 1996:       t= t- del*SQR(fp-fptt);
 1997: #endif
 1998:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
 1999: #ifdef DEBUG
 2000:       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);
 2001:       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);
 2002:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 2003: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 2004:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 2005: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 2006:       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);
 2007:       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);
 2008: #endif
 2009: #ifdef POWELLORIGINAL
 2010:       if (t < 0.0) { /* Then we use it for new direction */
 2011: #else
 2012:       if (directest*t < 0.0) { /* Contradiction between both tests */
 2013: 	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);
 2014:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 2015:         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);
 2016:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 2017:       } 
 2018:       if (directest < 0.0) { /* Then we use it for new direction */
 2019: #endif
 2020: #ifdef DEBUGLINMIN
 2021: 	printf("Before linmin in direction P%d-P0\n",n);
 2022: 	for (j=1;j<=n;j++) { 
 2023: 	  printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2024: 	  fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2025: 	  if(j % ncovmodel == 0){
 2026: 	    printf("\n");
 2027: 	    fprintf(ficlog,"\n");
 2028: 	  }
 2029: 	}
 2030: #endif
 2031: 	linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
 2032: #ifdef DEBUGLINMIN
 2033: 	for (j=1;j<=n;j++) { 
 2034: 	  printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2035: 	  fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2036: 	  if(j % ncovmodel == 0){
 2037: 	    printf("\n");
 2038: 	    fprintf(ficlog,"\n");
 2039: 	  }
 2040: 	}
 2041: #endif
 2042: 	for (j=1;j<=n;j++) { 
 2043: 	  xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
 2044: 	  xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
 2045: 	}
 2046: 	printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 2047: 	fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 2048: 
 2049: #ifdef DEBUG
 2050: 	printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 2051: 	fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 2052: 	for(j=1;j<=n;j++){
 2053: 	  printf(" %.12e",xit[j]);
 2054: 	  fprintf(ficlog," %.12e",xit[j]);
 2055: 	}
 2056: 	printf("\n");
 2057: 	fprintf(ficlog,"\n");
 2058: #endif
 2059:       } /* end of t or directest negative */
 2060: #ifdef POWELLF1F3
 2061: #else
 2062:     } /* end if (fptt < fp)  */
 2063: #endif
 2064:   } /* loop iteration */ 
 2065: } 
 2066: 
 2067: /**** Prevalence limit (stable or period prevalence)  ****************/
 2068: 
 2069: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
 2070: {
 2071:   /* Computes the prevalence limit in each live state at age x and for covariate ij by left multiplying the unit
 2072:      matrix by transitions matrix until convergence is reached with precision ftolpl */
 2073:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
 2074:   /* Wx is row vector: population in state 1, population in state 2, population dead */
 2075:   /* or prevalence in state 1, prevalence in state 2, 0 */
 2076:   /* newm is the matrix after multiplications, its rows are identical at a factor */
 2077:   /* Initial matrix pimij */
 2078:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
 2079:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
 2080:   /*  0,                   0                  , 1} */
 2081:   /*
 2082:    * and after some iteration: */
 2083:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
 2084:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
 2085:   /*  0,                   0                  , 1} */
 2086:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
 2087:   /* {0.51571254859325999, 0.4842874514067399, */
 2088:   /*  0.51326036147820708, 0.48673963852179264} */
 2089:   /* If we start from prlim again, prlim tends to a constant matrix */
 2090: 
 2091:   int i, ii,j,k;
 2092:   double *min, *max, *meandiff, maxmax,sumnew=0.;
 2093:   /* double **matprod2(); */ /* test */
 2094:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
 2095:   double **newm;
 2096:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
 2097:   int ncvloop=0;
 2098:   
 2099:   min=vector(1,nlstate);
 2100:   max=vector(1,nlstate);
 2101:   meandiff=vector(1,nlstate);
 2102: 
 2103: 	/* Starting with matrix unity */
 2104:   for (ii=1;ii<=nlstate+ndeath;ii++)
 2105:     for (j=1;j<=nlstate+ndeath;j++){
 2106:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2107:     }
 2108:   
 2109:   cov[1]=1.;
 2110:   
 2111:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2112:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
 2113:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
 2114:     ncvloop++;
 2115:     newm=savm;
 2116:     /* Covariates have to be included here again */
 2117:     cov[2]=agefin;
 2118:     if(nagesqr==1)
 2119:       cov[3]= agefin*agefin;;
 2120:     for (k=1; k<=cptcovn;k++) {
 2121:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 2122: 			/* Here comes the value of the covariate 'ij' */
 2123:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 2124:       /* 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])]); */
 2125:     }
 2126:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2127:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
 2128:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
 2129:     for (k=1; k<=cptcovprod;k++) /* Useless */
 2130:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 2131:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
 2132:     
 2133:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 2134:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 2135:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 2136:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2137:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 2138: 		/* age and covariate values of ij are in 'cov' */
 2139:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
 2140:     
 2141:     savm=oldm;
 2142:     oldm=newm;
 2143: 
 2144:     for(j=1; j<=nlstate; j++){
 2145:       max[j]=0.;
 2146:       min[j]=1.;
 2147:     }
 2148:     for(i=1;i<=nlstate;i++){
 2149:       sumnew=0;
 2150:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
 2151:       for(j=1; j<=nlstate; j++){ 
 2152: 	prlim[i][j]= newm[i][j]/(1-sumnew);
 2153: 	max[j]=FMAX(max[j],prlim[i][j]);
 2154: 	min[j]=FMIN(min[j],prlim[i][j]);
 2155:       }
 2156:     }
 2157: 
 2158:     maxmax=0.;
 2159:     for(j=1; j<=nlstate; j++){
 2160:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
 2161:       maxmax=FMAX(maxmax,meandiff[j]);
 2162:       /* 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); */
 2163:     } /* j loop */
 2164:     *ncvyear= (int)age- (int)agefin;
 2165:     /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
 2166:     if(maxmax < ftolpl){
 2167:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
 2168:       free_vector(min,1,nlstate);
 2169:       free_vector(max,1,nlstate);
 2170:       free_vector(meandiff,1,nlstate);
 2171:       return prlim;
 2172:     }
 2173:   } /* age loop */
 2174:     /* After some age loop it doesn't converge */
 2175:   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\
 2176: 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);
 2177:   /* 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); */
 2178:   free_vector(min,1,nlstate);
 2179:   free_vector(max,1,nlstate);
 2180:   free_vector(meandiff,1,nlstate);
 2181:   
 2182:   return prlim; /* should not reach here */
 2183: }
 2184: 
 2185: 
 2186:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
 2187: 
 2188:  /* double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ageminpar, double agemaxpar, double **oldm, double **savm, double **dnewm, double **doldm, double **dsavm, double ftolpl, int *ncvyear, int ij) */
 2189:  /* double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double **oldm, double **savm, double **dnewm, double **doldm, double **dsavm, double ftolpl, int *ncvyear, int ij) */
 2190:  double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij)
 2191: {
 2192:   /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
 2193:      matrix by transitions matrix until convergence is reached with precision ftolpl */
 2194:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
 2195:   /* Wx is row vector: population in state 1, population in state 2, population dead */
 2196:   /* or prevalence in state 1, prevalence in state 2, 0 */
 2197:   /* newm is the matrix after multiplications, its rows are identical at a factor */
 2198:   /* Initial matrix pimij */
 2199:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
 2200:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
 2201:   /*  0,                   0                  , 1} */
 2202:   /*
 2203:    * and after some iteration: */
 2204:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
 2205:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
 2206:   /*  0,                   0                  , 1} */
 2207:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
 2208:   /* {0.51571254859325999, 0.4842874514067399, */
 2209:   /*  0.51326036147820708, 0.48673963852179264} */
 2210:   /* If we start from prlim again, prlim tends to a constant matrix */
 2211: 
 2212:   int i, ii,j,k;
 2213:   double *min, *max, *meandiff, maxmax,sumnew=0.;
 2214:   /* double **matprod2(); */ /* test */
 2215:   double **out, cov[NCOVMAX+1], **bmij();
 2216:   double **newm;
 2217:   double	 **dnewm, **doldm, **dsavm;  /* for use */
 2218:   double	 **oldm, **savm;  /* for use */
 2219: 
 2220:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
 2221:   int ncvloop=0;
 2222:   
 2223:   min=vector(1,nlstate);
 2224:   max=vector(1,nlstate);
 2225:   meandiff=vector(1,nlstate);
 2226: 
 2227: 	dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
 2228: 	oldm=oldms; savm=savms;
 2229: 
 2230: 	/* Starting with matrix unity */
 2231: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2232: 		for (j=1;j<=nlstate+ndeath;j++){
 2233:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2234:     }
 2235:   
 2236:   cov[1]=1.;
 2237:   
 2238:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2239:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
 2240:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
 2241:   for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
 2242:     ncvloop++;
 2243:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
 2244: 		/* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
 2245:     /* Covariates have to be included here again */
 2246:     cov[2]=agefin;
 2247:     if(nagesqr==1)
 2248:       cov[3]= agefin*agefin;;
 2249:     for (k=1; k<=cptcovn;k++) {
 2250:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 2251:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 2252:       /* 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])]); */
 2253:     }
 2254:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2255:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
 2256:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
 2257:     for (k=1; k<=cptcovprod;k++) /* Useless */
 2258:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 2259:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
 2260:     
 2261:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 2262:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 2263:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 2264:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2265:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 2266: 		/* ij should be linked to the correct index of cov */
 2267: 		/* age and covariate values ij are in 'cov', but we need to pass
 2268: 		 * ij for the observed prevalence at age and status and covariate
 2269: 		 * number:  prevacurrent[(int)agefin][ii][ij]
 2270: 		 */
 2271:     /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, ageminpar, agemaxpar, dnewm, doldm, dsavm,ij)); /\* Bug Valgrind *\/ */
 2272:     /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij)); /\* Bug Valgrind *\/ */
 2273:     out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij)); /* Bug Valgrind */
 2274:     savm=oldm;
 2275:     oldm=newm;
 2276:     for(j=1; j<=nlstate; j++){
 2277:       max[j]=0.;
 2278:       min[j]=1.;
 2279:     }
 2280:     for(j=1; j<=nlstate; j++){ 
 2281:       for(i=1;i<=nlstate;i++){
 2282: 				/* bprlim[i][j]= newm[i][j]/(1-sumnew); */
 2283: 				bprlim[i][j]= newm[i][j];
 2284: 				max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
 2285: 				min[i]=FMIN(min[i],bprlim[i][j]);
 2286:       }
 2287:     }
 2288: 		
 2289:     maxmax=0.;
 2290:     for(i=1; i<=nlstate; i++){
 2291:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
 2292:       maxmax=FMAX(maxmax,meandiff[i]);
 2293:       /* printf("Back age= %d meandiff[%d]=%f, agefin=%d max[%d]=%f min[%d]=%f maxmax=%f\n", (int)age, i, meandiff[i],(int)agefin, i, max[i], i, min[i],maxmax); */
 2294:     } /* j loop */
 2295:     *ncvyear= -( (int)age- (int)agefin);
 2296:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
 2297:     if(maxmax < ftolpl){
 2298:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
 2299:       free_vector(min,1,nlstate);
 2300:       free_vector(max,1,nlstate);
 2301:       free_vector(meandiff,1,nlstate);
 2302:       return bprlim;
 2303:     }
 2304:   } /* age loop */
 2305:     /* After some age loop it doesn't converge */
 2306:   printf("Warning: the back stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.0f years. Try to lower 'ftolpl'. \n\
 2307: Oldest 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);
 2308:   /* 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); */
 2309:   free_vector(min,1,nlstate);
 2310:   free_vector(max,1,nlstate);
 2311:   free_vector(meandiff,1,nlstate);
 2312:   
 2313:   return bprlim; /* should not reach here */
 2314: }
 2315: 
 2316: /*************** transition probabilities ***************/ 
 2317: 
 2318: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 2319: {
 2320:   /* According to parameters values stored in x and the covariate's values stored in cov,
 2321:      computes the probability to be observed in state j being in state i by appying the
 2322:      model to the ncovmodel covariates (including constant and age).
 2323:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 2324:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 2325:      ncth covariate in the global vector x is given by the formula:
 2326:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 2327:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 2328:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 2329:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 2330:      Outputs ps[i][j] the probability to be observed in j being in j according to
 2331:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 2332:   */
 2333:   double s1, lnpijopii;
 2334:   /*double t34;*/
 2335:   int i,j, nc, ii, jj;
 2336: 
 2337: 	for(i=1; i<= nlstate; i++){
 2338: 		for(j=1; j<i;j++){
 2339: 			for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2340: 				/*lnpijopii += param[i][j][nc]*cov[nc];*/
 2341: 				lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 2342: 				/* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2343: 			}
 2344: 			ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2345: 			/* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2346: 		}
 2347: 		for(j=i+1; j<=nlstate+ndeath;j++){
 2348: 			for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2349: 				/*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 2350: 				lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 2351: 				/* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 2352: 			}
 2353: 			ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2354: 		}
 2355: 	}
 2356:   
 2357: 	for(i=1; i<= nlstate; i++){
 2358: 		s1=0;
 2359: 		for(j=1; j<i; j++){
 2360: 			s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2361: 			/*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2362: 		}
 2363: 		for(j=i+1; j<=nlstate+ndeath; j++){
 2364: 			s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2365: 			/*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2366: 		}
 2367: 		/* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 2368: 		ps[i][i]=1./(s1+1.);
 2369: 		/* Computing other pijs */
 2370: 		for(j=1; j<i; j++)
 2371: 			ps[i][j]= exp(ps[i][j])*ps[i][i];
 2372: 		for(j=i+1; j<=nlstate+ndeath; j++)
 2373: 			ps[i][j]= exp(ps[i][j])*ps[i][i];
 2374: 		/* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 2375: 	} /* end i */
 2376:   
 2377: 	for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 2378: 		for(jj=1; jj<= nlstate+ndeath; jj++){
 2379: 			ps[ii][jj]=0;
 2380: 			ps[ii][ii]=1;
 2381: 		}
 2382: 	}
 2383:   
 2384:   
 2385: 	/* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 2386: 	/*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 2387: 	/* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 2388: 	/*   } */
 2389: 	/*   printf("\n "); */
 2390: 	/* } */
 2391: 	/* printf("\n ");printf("%lf ",cov[2]);*/
 2392: 	/*
 2393: 		for(i=1; i<= npar; i++) printf("%f ",x[i]);
 2394: 		goto end;*/
 2395: 	return ps;
 2396: }
 2397: 
 2398: /*************** backward transition probabilities ***************/ 
 2399: 
 2400:  /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ageminpar, double agemaxpar, double ***dnewm, double **doldm, double **dsavm, int ij ) */
 2401: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
 2402:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
 2403: {
 2404:   /* Computes the backward probability at age agefin and covariate ij
 2405:    * and returns in **ps as well as **bmij.
 2406:    */
 2407:   int i, ii, j,k;
 2408:   
 2409:   double **out, **pmij();
 2410:   double sumnew=0.;
 2411:   double agefin;
 2412:   
 2413:   double **dnewm, **dsavm, **doldm;
 2414:   double **bbmij;
 2415:   
 2416:   doldm=ddoldms; /* global pointers */
 2417:   dnewm=ddnewms;
 2418:   dsavm=ddsavms;
 2419:   
 2420:   agefin=cov[2];
 2421:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
 2422:      the observed prevalence (with this covariate ij) */
 2423:   dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
 2424:   /* We do have the matrix Px in savm  and we need pij */
 2425:   for (j=1;j<=nlstate+ndeath;j++){
 2426:     sumnew=0.; /* w1 p11 + w2 p21 only on live states */
 2427:     for (ii=1;ii<=nlstate;ii++){
 2428:       sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
 2429:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
 2430:     for (ii=1;ii<=nlstate+ndeath;ii++){
 2431:       if(sumnew >= 1.e-10){
 2432: 	/* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
 2433: 	/* 	doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
 2434: 	/* }else if(agefin >= agemaxpar+stepm/YEARM){ */
 2435: 	/* 	doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
 2436: 	/* }else */
 2437: 	doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
 2438:       }else{
 2439: 	printf("ii=%d, i=%d, doldm=%lf dsavm=%lf, probs=%lf, sumnew=%lf,agefin=%d\n",ii,j,doldm[ii][j],dsavm[ii][j],prevacurrent[(int)agefin][ii][ij],sumnew, (int)agefin);
 2440:       }
 2441:     } /*End ii */
 2442:   } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
 2443:   /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
 2444:   bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
 2445:   /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
 2446:   /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
 2447:   /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
 2448:   /* left Product of this matrix by diag matrix of prevalences (savm) */
 2449:   for (j=1;j<=nlstate+ndeath;j++){
 2450:     for (ii=1;ii<=nlstate+ndeath;ii++){
 2451:       dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
 2452:     }
 2453:   } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
 2454:   ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
 2455:   /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
 2456:   /* end bmij */
 2457:   return ps; 
 2458: }
 2459: /*************** transition probabilities ***************/ 
 2460: 
 2461: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 2462: {
 2463:   /* According to parameters values stored in x and the covariate's values stored in cov,
 2464:      computes the probability to be observed in state j being in state i by appying the
 2465:      model to the ncovmodel covariates (including constant and age).
 2466:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 2467:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 2468:      ncth covariate in the global vector x is given by the formula:
 2469:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 2470:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 2471:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 2472:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 2473:      Outputs ps[i][j] the probability to be observed in j being in j according to
 2474:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 2475:   */
 2476:   double s1, lnpijopii;
 2477:   /*double t34;*/
 2478:   int i,j, nc, ii, jj;
 2479: 
 2480: 	for(i=1; i<= nlstate; i++){
 2481: 		for(j=1; j<i;j++){
 2482: 			for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2483: 				/*lnpijopii += param[i][j][nc]*cov[nc];*/
 2484: 				lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 2485: 				/* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2486: 			}
 2487: 			ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2488: 			/* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2489: 		}
 2490: 		for(j=i+1; j<=nlstate+ndeath;j++){
 2491: 			for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2492: 				/*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 2493: 				lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 2494: 				/* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 2495: 			}
 2496: 			ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2497: 		}
 2498: 	}
 2499: 	
 2500: 	for(i=1; i<= nlstate; i++){
 2501: 		s1=0;
 2502: 		for(j=1; j<i; j++){
 2503: 			s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2504: 			/*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2505: 		}
 2506: 		for(j=i+1; j<=nlstate+ndeath; j++){
 2507: 			s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2508: 			/*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2509: 		}
 2510: 		/* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 2511: 		ps[i][i]=1./(s1+1.);
 2512: 		/* Computing other pijs */
 2513: 		for(j=1; j<i; j++)
 2514: 			ps[i][j]= exp(ps[i][j])*ps[i][i];
 2515: 		for(j=i+1; j<=nlstate+ndeath; j++)
 2516: 			ps[i][j]= exp(ps[i][j])*ps[i][i];
 2517: 		/* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 2518: 	} /* end i */
 2519: 	
 2520: 	for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 2521: 		for(jj=1; jj<= nlstate+ndeath; jj++){
 2522: 			ps[ii][jj]=0;
 2523: 			ps[ii][ii]=1;
 2524: 		}
 2525: 	}
 2526: 	/* Added for backcast */ /* Transposed matrix too */
 2527: 	for(jj=1; jj<= nlstate+ndeath; jj++){
 2528: 		s1=0.;
 2529: 		for(ii=1; ii<= nlstate+ndeath; ii++){
 2530: 			s1+=ps[ii][jj];
 2531: 		}
 2532: 		for(ii=1; ii<= nlstate; ii++){
 2533: 			ps[ii][jj]=ps[ii][jj]/s1;
 2534: 		}
 2535: 	}
 2536: 	/* Transposition */
 2537: 	for(jj=1; jj<= nlstate+ndeath; jj++){
 2538: 		for(ii=jj; ii<= nlstate+ndeath; ii++){
 2539: 			s1=ps[ii][jj];
 2540: 			ps[ii][jj]=ps[jj][ii];
 2541: 			ps[jj][ii]=s1;
 2542: 		}
 2543: 	}
 2544: 	/* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 2545: 	/*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 2546: 	/* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 2547: 	/*   } */
 2548: 	/*   printf("\n "); */
 2549: 	/* } */
 2550: 	/* printf("\n ");printf("%lf ",cov[2]);*/
 2551: 	/*
 2552: 		for(i=1; i<= npar; i++) printf("%f ",x[i]);
 2553: 		goto end;*/
 2554: 	return ps;
 2555: }
 2556: 
 2557: 
 2558: /**************** Product of 2 matrices ******************/
 2559: 
 2560: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
 2561: {
 2562:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
 2563:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
 2564:   /* in, b, out are matrice of pointers which should have been initialized 
 2565:      before: only the contents of out is modified. The function returns
 2566:      a pointer to pointers identical to out */
 2567:   int i, j, k;
 2568:   for(i=nrl; i<= nrh; i++)
 2569:     for(k=ncolol; k<=ncoloh; k++){
 2570:       out[i][k]=0.;
 2571:       for(j=ncl; j<=nch; j++)
 2572:   	out[i][k] +=in[i][j]*b[j][k];
 2573:     }
 2574:   return out;
 2575: }
 2576: 
 2577: 
 2578: /************* Higher Matrix Product ***************/
 2579: 
 2580: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
 2581: {
 2582:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
 2583:      'nhstepm*hstepm*stepm' months (i.e. until
 2584:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
 2585:      nhstepm*hstepm matrices. 
 2586:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
 2587:      (typically every 2 years instead of every month which is too big 
 2588:      for the memory).
 2589:      Model is determined by parameters x and covariates have to be 
 2590:      included manually here. 
 2591: 
 2592:      */
 2593: 
 2594:   int i, j, d, h, k;
 2595:   double **out, cov[NCOVMAX+1];
 2596:   double **newm;
 2597:   double agexact;
 2598:   double agebegin, ageend;
 2599: 
 2600:   /* Hstepm could be zero and should return the unit matrix */
 2601:   for (i=1;i<=nlstate+ndeath;i++)
 2602:     for (j=1;j<=nlstate+ndeath;j++){
 2603:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 2604:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 2605:     }
 2606:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2607:   for(h=1; h <=nhstepm; h++){
 2608:     for(d=1; d <=hstepm; d++){
 2609:       newm=savm;
 2610:       /* Covariates have to be included here again */
 2611:       cov[1]=1.;
 2612:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
 2613:       cov[2]=agexact;
 2614:       if(nagesqr==1)
 2615: 				cov[3]= agexact*agexact;
 2616:       for (k=1; k<=cptcovn;k++) 
 2617: 				cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 2618: 			/* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 2619:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
 2620: 				/* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2621: 				cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 2622: 			/* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
 2623:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
 2624: 				cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
 2625: 			/* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 2626: 
 2627: 
 2628:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 2629:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 2630: 			/* right multiplication of oldm by the current matrix */
 2631:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
 2632: 		   pmij(pmmij,cov,ncovmodel,x,nlstate));
 2633:       /* if((int)age == 70){ */
 2634:       /* 	printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
 2635:       /* 	for(i=1; i<=nlstate+ndeath; i++) { */
 2636:       /* 	  printf("%d pmmij ",i); */
 2637:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 2638:       /* 	    printf("%f ",pmmij[i][j]); */
 2639:       /* 	  } */
 2640:       /* 	  printf(" oldm "); */
 2641:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 2642:       /* 	    printf("%f ",oldm[i][j]); */
 2643:       /* 	  } */
 2644:       /* 	  printf("\n"); */
 2645:       /* 	} */
 2646:       /* } */
 2647:       savm=oldm;
 2648:       oldm=newm;
 2649:     }
 2650:     for(i=1; i<=nlstate+ndeath; i++)
 2651:       for(j=1;j<=nlstate+ndeath;j++) {
 2652: 				po[i][j][h]=newm[i][j];
 2653: 				/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 2654:       }
 2655:     /*printf("h=%d ",h);*/
 2656:   } /* end h */
 2657: 	/*     printf("\n H=%d \n",h); */
 2658:   return po;
 2659: }
 2660: 
 2661: /************* Higher Back Matrix Product ***************/
 2662: /* double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, double **oldm, double **savm, double **dnewm, double **doldm, double **dsavm, int ij ) */
 2663: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
 2664: {
 2665:   /* Computes the transition matrix starting at age 'age' over
 2666:      'nhstepm*hstepm*stepm' months (i.e. until
 2667:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
 2668:      nhstepm*hstepm matrices.
 2669:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
 2670:      (typically every 2 years instead of every month which is too big
 2671:      for the memory).
 2672:      Model is determined by parameters x and covariates have to be
 2673:      included manually here.
 2674: 
 2675:   */
 2676: 
 2677:   int i, j, d, h, k;
 2678:   double **out, cov[NCOVMAX+1];
 2679:   double **newm;
 2680:   double agexact;
 2681:   double agebegin, ageend;
 2682:   double **oldm, **savm;
 2683: 
 2684:   oldm=oldms;savm=savms;
 2685:   /* Hstepm could be zero and should return the unit matrix */
 2686:   for (i=1;i<=nlstate+ndeath;i++)
 2687:     for (j=1;j<=nlstate+ndeath;j++){
 2688:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 2689:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 2690:     }
 2691:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2692:   for(h=1; h <=nhstepm; h++){
 2693:     for(d=1; d <=hstepm; d++){
 2694:       newm=savm;
 2695:       /* Covariates have to be included here again */
 2696:       cov[1]=1.;
 2697:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
 2698:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
 2699:       cov[2]=agexact;
 2700:       if(nagesqr==1)
 2701: 	cov[3]= agexact*agexact;
 2702:       for (k=1; k<=cptcovn;k++)
 2703: 	cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 2704:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 2705:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
 2706: 	/* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2707: 	cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 2708:       /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
 2709:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
 2710: 	cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
 2711:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 2712: 			
 2713: 			
 2714:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 2715:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 2716:       /* Careful transposed matrix */
 2717:       /* age is in cov[2] */
 2718:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
 2719:       /* 						 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
 2720:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
 2721: 		   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
 2722:       /* if((int)age == 70){ */
 2723:       /* 	printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
 2724:       /* 	for(i=1; i<=nlstate+ndeath; i++) { */
 2725:       /* 	  printf("%d pmmij ",i); */
 2726:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 2727:       /* 	    printf("%f ",pmmij[i][j]); */
 2728:       /* 	  } */
 2729:       /* 	  printf(" oldm "); */
 2730:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 2731:       /* 	    printf("%f ",oldm[i][j]); */
 2732:       /* 	  } */
 2733:       /* 	  printf("\n"); */
 2734:       /* 	} */
 2735:       /* } */
 2736:       savm=oldm;
 2737:       oldm=newm;
 2738:     }
 2739:     for(i=1; i<=nlstate+ndeath; i++)
 2740:       for(j=1;j<=nlstate+ndeath;j++) {
 2741: 	po[i][j][h]=newm[i][j];
 2742: 	/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 2743:       }
 2744:     /*printf("h=%d ",h);*/
 2745:   } /* end h */
 2746:   /*     printf("\n H=%d \n",h); */
 2747:   return po;
 2748: }
 2749: 
 2750: 
 2751: #ifdef NLOPT
 2752:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
 2753:   double fret;
 2754:   double *xt;
 2755:   int j;
 2756:   myfunc_data *d2 = (myfunc_data *) pd;
 2757: /* xt = (p1-1); */
 2758:   xt=vector(1,n); 
 2759:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
 2760: 
 2761:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
 2762:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
 2763:   printf("Function = %.12lf ",fret);
 2764:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
 2765:   printf("\n");
 2766:  free_vector(xt,1,n);
 2767:   return fret;
 2768: }
 2769: #endif
 2770: 
 2771: /*************** log-likelihood *************/
 2772: double func( double *x)
 2773: {
 2774:   int i, ii, j, k, mi, d, kk;
 2775:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 2776:   double **out;
 2777:   double sw; /* Sum of weights */
 2778:   double lli; /* Individual log likelihood */
 2779:   int s1, s2;
 2780:   double bbh, survp;
 2781:   long ipmx;
 2782:   double agexact;
 2783:   /*extern weight */
 2784:   /* We are differentiating ll according to initial status */
 2785:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 2786:   /*for(i=1;i<imx;i++) 
 2787:     printf(" %d\n",s[4][i]);
 2788:   */
 2789: 
 2790:   ++countcallfunc;
 2791: 
 2792:   cov[1]=1.;
 2793: 
 2794:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 2795: 
 2796:   if(mle==1){
 2797:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2798:       /* Computes the values of the ncovmodel covariates of the model
 2799: 	 depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
 2800: 	 Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
 2801: 	 to be observed in j being in i according to the model.
 2802:        */
 2803:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
 2804: 	  cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2805:       }
 2806:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
 2807: 	 is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
 2808: 	 has been calculated etc */
 2809:       for(mi=1; mi<= wav[i]-1; mi++){
 2810: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2811: 	  for (j=1;j<=nlstate+ndeath;j++){
 2812: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2813: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2814: 	  }
 2815: 	for(d=0; d<dh[mi][i]; d++){
 2816: 	  newm=savm;
 2817: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2818: 	  cov[2]=agexact;
 2819: 	  if(nagesqr==1)
 2820: 	    cov[3]= agexact*agexact;
 2821: 	  for (kk=1; kk<=cptcovage;kk++) {
 2822: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
 2823: 	  }
 2824: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2825: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2826: 	  savm=oldm;
 2827: 	  oldm=newm;
 2828: 	} /* end mult */
 2829:       
 2830: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 2831: 	/* But now since version 0.9 we anticipate for bias at large stepm.
 2832: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 2833: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
 2834: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
 2835: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 2836: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
 2837: 	 * probability in order to take into account the bias as a fraction of the way
 2838: 	 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
 2839: 	 * -stepm/2 to stepm/2 .
 2840: 	 * For stepm=1 the results are the same as for previous versions of Imach.
 2841: 	 * For stepm > 1 the results are less biased than in previous versions. 
 2842: 	 */
 2843: 	s1=s[mw[mi][i]][i];
 2844: 	s2=s[mw[mi+1][i]][i];
 2845: 	bbh=(double)bh[mi][i]/(double)stepm; 
 2846: 	/* bias bh is positive if real duration
 2847: 	 * is higher than the multiple of stepm and negative otherwise.
 2848: 	 */
 2849: 	/* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
 2850: 	if( s2 > nlstate){ 
 2851: 	  /* i.e. if s2 is a death state and if the date of death is known 
 2852: 	     then the contribution to the likelihood is the probability to 
 2853: 	     die between last step unit time and current  step unit time, 
 2854: 	     which is also equal to probability to die before dh 
 2855: 	     minus probability to die before dh-stepm . 
 2856: 	     In version up to 0.92 likelihood was computed
 2857: 	as if date of death was unknown. Death was treated as any other
 2858: 	health state: the date of the interview describes the actual state
 2859: 	and not the date of a change in health state. The former idea was
 2860: 	to consider that at each interview the state was recorded
 2861: 	(healthy, disable or death) and IMaCh was corrected; but when we
 2862: 	introduced the exact date of death then we should have modified
 2863: 	the contribution of an exact death to the likelihood. This new
 2864: 	contribution is smaller and very dependent of the step unit
 2865: 	stepm. It is no more the probability to die between last interview
 2866: 	and month of death but the probability to survive from last
 2867: 	interview up to one month before death multiplied by the
 2868: 	probability to die within a month. Thanks to Chris
 2869: 	Jackson for correcting this bug.  Former versions increased
 2870: 	mortality artificially. The bad side is that we add another loop
 2871: 	which slows down the processing. The difference can be up to 10%
 2872: 	lower mortality.
 2873: 	  */
 2874: 	/* If, at the beginning of the maximization mostly, the
 2875: 	   cumulative probability or probability to be dead is
 2876: 	   constant (ie = 1) over time d, the difference is equal to
 2877: 	   0.  out[s1][3] = savm[s1][3]: probability, being at state
 2878: 	   s1 at precedent wave, to be dead a month before current
 2879: 	   wave is equal to probability, being at state s1 at
 2880: 	   precedent wave, to be dead at mont of the current
 2881: 	   wave. Then the observed probability (that this person died)
 2882: 	   is null according to current estimated parameter. In fact,
 2883: 	   it should be very low but not zero otherwise the log go to
 2884: 	   infinity.
 2885: 	*/
 2886: /* #ifdef INFINITYORIGINAL */
 2887: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 2888: /* #else */
 2889: /* 	  if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
 2890: /* 	    lli=log(mytinydouble); */
 2891: /* 	  else */
 2892: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 2893: /* #endif */
 2894: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 2895: 	  
 2896: 	} else if  ( s2==-1 ) { /* alive */
 2897: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 2898: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2899: 	  /*survp += out[s1][j]; */
 2900: 	  lli= log(survp);
 2901: 	}
 2902:  	else if  (s2==-4) { 
 2903: 	  for (j=3,survp=0. ; j<=nlstate; j++)  
 2904: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2905:  	  lli= log(survp); 
 2906:  	} 
 2907:  	else if  (s2==-5) { 
 2908:  	  for (j=1,survp=0. ; j<=2; j++)  
 2909: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2910:  	  lli= log(survp); 
 2911:  	} 
 2912: 	else{
 2913: 	  lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2914: 	  /*  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 */
 2915: 	} 
 2916: 	/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 2917: 	/*if(lli ==000.0)*/
 2918: 	/*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); */
 2919:   	ipmx +=1;
 2920: 	sw += weight[i];
 2921: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2922: 	/* if (lli < log(mytinydouble)){ */
 2923: 	/*   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); */
 2924: 	/*   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]); */
 2925: 	/* } */
 2926:       } /* end of wave */
 2927:     } /* end of individual */
 2928:   }  else if(mle==2){
 2929:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2930:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2931:       for(mi=1; mi<= wav[i]-1; mi++){
 2932: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2933: 	  for (j=1;j<=nlstate+ndeath;j++){
 2934: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2935: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2936: 	  }
 2937: 	for(d=0; d<=dh[mi][i]; d++){
 2938: 	  newm=savm;
 2939: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2940: 	  cov[2]=agexact;
 2941: 	  if(nagesqr==1)
 2942: 	    cov[3]= agexact*agexact;
 2943: 	  for (kk=1; kk<=cptcovage;kk++) {
 2944: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2945: 	  }
 2946: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2947: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2948: 	  savm=oldm;
 2949: 	  oldm=newm;
 2950: 	} /* end mult */
 2951:       
 2952: 	s1=s[mw[mi][i]][i];
 2953: 	s2=s[mw[mi+1][i]][i];
 2954: 	bbh=(double)bh[mi][i]/(double)stepm; 
 2955: 	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 */
 2956: 	ipmx +=1;
 2957: 	sw += weight[i];
 2958: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2959:       } /* end of wave */
 2960:     } /* end of individual */
 2961:   }  else if(mle==3){  /* exponential inter-extrapolation */
 2962:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2963:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2964:       for(mi=1; mi<= wav[i]-1; mi++){
 2965: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2966: 	  for (j=1;j<=nlstate+ndeath;j++){
 2967: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2968: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2969: 	  }
 2970: 	for(d=0; d<dh[mi][i]; d++){
 2971: 	  newm=savm;
 2972: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2973: 	  cov[2]=agexact;
 2974: 	  if(nagesqr==1)
 2975: 	    cov[3]= agexact*agexact;
 2976: 	  for (kk=1; kk<=cptcovage;kk++) {
 2977: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2978: 	  }
 2979: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2980: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2981: 	  savm=oldm;
 2982: 	  oldm=newm;
 2983: 	} /* end mult */
 2984:       
 2985: 	s1=s[mw[mi][i]][i];
 2986: 	s2=s[mw[mi+1][i]][i];
 2987: 	bbh=(double)bh[mi][i]/(double)stepm; 
 2988: 	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 */
 2989: 	ipmx +=1;
 2990: 	sw += weight[i];
 2991: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2992:       } /* end of wave */
 2993:     } /* end of individual */
 2994:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
 2995:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2996:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2997:       for(mi=1; mi<= wav[i]-1; mi++){
 2998: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2999: 	  for (j=1;j<=nlstate+ndeath;j++){
 3000: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3001: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3002: 	  }
 3003: 	for(d=0; d<dh[mi][i]; d++){
 3004: 	  newm=savm;
 3005: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3006: 	  cov[2]=agexact;
 3007: 	  if(nagesqr==1)
 3008: 	    cov[3]= agexact*agexact;
 3009: 	  for (kk=1; kk<=cptcovage;kk++) {
 3010: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3011: 	  }
 3012: 	
 3013: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3014: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3015: 	  savm=oldm;
 3016: 	  oldm=newm;
 3017: 	} /* end mult */
 3018:       
 3019: 	s1=s[mw[mi][i]][i];
 3020: 	s2=s[mw[mi+1][i]][i];
 3021: 	if( s2 > nlstate){ 
 3022: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 3023: 	} else if  ( s2==-1 ) { /* alive */
 3024: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 3025: 	    survp += out[s1][j];
 3026: 	  lli= log(survp);
 3027: 	}else{
 3028: 	  lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 3029: 	}
 3030: 	ipmx +=1;
 3031: 	sw += weight[i];
 3032: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3033: /* 	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]); */
 3034:       } /* end of wave */
 3035:     } /* end of individual */
 3036:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
 3037:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3038:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 3039:       for(mi=1; mi<= wav[i]-1; mi++){
 3040: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 3041: 	  for (j=1;j<=nlstate+ndeath;j++){
 3042: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3043: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3044: 	  }
 3045: 	for(d=0; d<dh[mi][i]; d++){
 3046: 	  newm=savm;
 3047: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3048: 	  cov[2]=agexact;
 3049: 	  if(nagesqr==1)
 3050: 	    cov[3]= agexact*agexact;
 3051: 	  for (kk=1; kk<=cptcovage;kk++) {
 3052: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3053: 	  }
 3054: 	
 3055: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3056: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3057: 	  savm=oldm;
 3058: 	  oldm=newm;
 3059: 	} /* end mult */
 3060:       
 3061: 	s1=s[mw[mi][i]][i];
 3062: 	s2=s[mw[mi+1][i]][i];
 3063: 	lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 3064: 	ipmx +=1;
 3065: 	sw += weight[i];
 3066: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3067: 	/*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]);*/
 3068:       } /* end of wave */
 3069:     } /* end of individual */
 3070:   } /* End of if */
 3071:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 3072:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 3073:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 3074:   return -l;
 3075: }
 3076: 
 3077: /*************** log-likelihood *************/
 3078: double funcone( double *x)
 3079: {
 3080:   /* Same as likeli but slower because of a lot of printf and if */
 3081:   int i, ii, j, k, mi, d, kk;
 3082:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 3083:   double **out;
 3084:   double lli; /* Individual log likelihood */
 3085:   double llt;
 3086:   int s1, s2;
 3087:   double bbh, survp;
 3088:   double agexact;
 3089:   double agebegin, ageend;
 3090:   /*extern weight */
 3091:   /* We are differentiating ll according to initial status */
 3092:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 3093:   /*for(i=1;i<imx;i++) 
 3094:     printf(" %d\n",s[4][i]);
 3095:   */
 3096:   cov[1]=1.;
 3097: 
 3098:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 3099: 
 3100:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3101:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 3102:     for(mi=1; mi<= wav[i]-1; mi++){
 3103:       for (ii=1;ii<=nlstate+ndeath;ii++)
 3104: 	for (j=1;j<=nlstate+ndeath;j++){
 3105: 	  oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3106: 	  savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3107: 	}
 3108:       
 3109:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
 3110:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
 3111:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
 3112: 	/*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 3113: 	  and mw[mi+1][i]. dh depends on stepm.*/
 3114: 	newm=savm;
 3115: 	agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3116: 	cov[2]=agexact;
 3117: 	if(nagesqr==1)
 3118: 	  cov[3]= agexact*agexact;
 3119: 	for (kk=1; kk<=cptcovage;kk++) {
 3120: 	  cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3121: 	}
 3122: 
 3123: 	/* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 3124: 	out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3125: 		     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3126: 	/* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
 3127: 	/* 	     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
 3128: 	savm=oldm;
 3129: 	oldm=newm;
 3130:       } /* end mult */
 3131:       
 3132:       s1=s[mw[mi][i]][i];
 3133:       s2=s[mw[mi+1][i]][i];
 3134:       /* if(s2==-1){ */
 3135:       /* 	printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
 3136:       /* 	/\* exit(1); *\/ */
 3137:       /* } */
 3138:       bbh=(double)bh[mi][i]/(double)stepm; 
 3139:       /* bias is positive if real duration
 3140:        * is higher than the multiple of stepm and negative otherwise.
 3141:        */
 3142:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
 3143: 	lli=log(out[s1][s2] - savm[s1][s2]);
 3144:       } else if  ( s2==-1 ) { /* alive */
 3145: 	for (j=1,survp=0. ; j<=nlstate; j++) 
 3146: 	  survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 3147: 	lli= log(survp);
 3148:       }else if (mle==1){
 3149: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 3150:       } else if(mle==2){
 3151: 	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 */
 3152:       } else if(mle==3){  /* exponential inter-extrapolation */
 3153: 	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 */
 3154:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
 3155: 	lli=log(out[s1][s2]); /* Original formula */
 3156:       } else{  /* mle=0 back to 1 */
 3157: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 3158: 	/*lli=log(out[s1][s2]); */ /* Original formula */
 3159:       } /* End of if */
 3160:       ipmx +=1;
 3161:       sw += weight[i];
 3162:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3163:       /*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]); */
 3164:       if(globpr){
 3165: 	fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
 3166:  %11.6f %11.6f %11.6f ", \
 3167: 		num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
 3168: 		2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
 3169: 	for(k=1,llt=0.,l=0.; k<=nlstate; k++){
 3170: 	  llt +=ll[k]*gipmx/gsw;
 3171: 	  fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
 3172: 	}
 3173: 	fprintf(ficresilk," %10.6f\n", -llt);
 3174:       }
 3175:     } /* end of wave */
 3176:   } /* end of individual */
 3177:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 3178:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 3179:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 3180:   if(globpr==0){ /* First time we count the contributions and weights */
 3181:     gipmx=ipmx;
 3182:     gsw=sw;
 3183:   }
 3184:   return -l;
 3185: }
 3186: 
 3187: 
 3188: /*************** function likelione ***********/
 3189: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
 3190: {
 3191:   /* This routine should help understanding what is done with 
 3192:      the selection of individuals/waves and
 3193:      to check the exact contribution to the likelihood.
 3194:      Plotting could be done.
 3195:    */
 3196:   int k;
 3197: 
 3198:   if(*globpri !=0){ /* Just counts and sums, no printings */
 3199:     strcpy(fileresilk,"ILK_"); 
 3200:     strcat(fileresilk,fileresu);
 3201:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
 3202:       printf("Problem with resultfile: %s\n", fileresilk);
 3203:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
 3204:     }
 3205:     fprintf(ficresilk, "#individual(line's_record) count ageb ageend 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");
 3206:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
 3207:     /* 	i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
 3208:     for(k=1; k<=nlstate; k++) 
 3209:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
 3210:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
 3211:   }
 3212: 
 3213:   *fretone=(*funcone)(p);
 3214:   if(*globpri !=0){
 3215:     fclose(ficresilk);
 3216:     if (mle ==0)
 3217:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
 3218:     else if(mle >=1)
 3219:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
 3220:     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));
 3221:     
 3222:       
 3223:     for (k=1; k<= nlstate ; k++) {
 3224:       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> \
 3225: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
 3226:     }
 3227:     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> \
 3228: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
 3229:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
 3230: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
 3231:     fflush(fichtm);
 3232:   }
 3233:   return;
 3234: }
 3235: 
 3236: 
 3237: /*********** Maximum Likelihood Estimation ***************/
 3238: 
 3239: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
 3240: {
 3241:   int i,j, iter=0;
 3242:   double **xi;
 3243:   double fret;
 3244:   double fretone; /* Only one call to likelihood */
 3245:   /*  char filerespow[FILENAMELENGTH];*/
 3246: 
 3247: #ifdef NLOPT
 3248:   int creturn;
 3249:   nlopt_opt opt;
 3250:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
 3251:   double *lb;
 3252:   double minf; /* the minimum objective value, upon return */
 3253:   double * p1; /* Shifted parameters from 0 instead of 1 */
 3254:   myfunc_data dinst, *d = &dinst;
 3255: #endif
 3256: 
 3257: 
 3258:   xi=matrix(1,npar,1,npar);
 3259:   for (i=1;i<=npar;i++)
 3260:     for (j=1;j<=npar;j++)
 3261:       xi[i][j]=(i==j ? 1.0 : 0.0);
 3262:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
 3263:   strcpy(filerespow,"POW_"); 
 3264:   strcat(filerespow,fileres);
 3265:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
 3266:     printf("Problem with resultfile: %s\n", filerespow);
 3267:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 3268:   }
 3269:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
 3270:   for (i=1;i<=nlstate;i++)
 3271:     for(j=1;j<=nlstate+ndeath;j++)
 3272:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 3273:   fprintf(ficrespow,"\n");
 3274: #ifdef POWELL
 3275:   powell(p,xi,npar,ftol,&iter,&fret,func);
 3276: #endif
 3277: 
 3278: #ifdef NLOPT
 3279: #ifdef NEWUOA
 3280:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
 3281: #else
 3282:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
 3283: #endif
 3284:   lb=vector(0,npar-1);
 3285:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
 3286:   nlopt_set_lower_bounds(opt, lb);
 3287:   nlopt_set_initial_step1(opt, 0.1);
 3288:   
 3289:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
 3290:   d->function = func;
 3291:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
 3292:   nlopt_set_min_objective(opt, myfunc, d);
 3293:   nlopt_set_xtol_rel(opt, ftol);
 3294:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
 3295:     printf("nlopt failed! %d\n",creturn); 
 3296:   }
 3297:   else {
 3298:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
 3299:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
 3300:     iter=1; /* not equal */
 3301:   }
 3302:   nlopt_destroy(opt);
 3303: #endif
 3304:   free_matrix(xi,1,npar,1,npar);
 3305:   fclose(ficrespow);
 3306:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 3307:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 3308:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 3309: 
 3310: }
 3311: 
 3312: /**** Computes Hessian and covariance matrix ***/
 3313: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
 3314: {
 3315:   double  **a,**y,*x,pd;
 3316:   /* double **hess; */
 3317:   int i, j;
 3318:   int *indx;
 3319: 
 3320:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
 3321:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
 3322:   void lubksb(double **a, int npar, int *indx, double b[]) ;
 3323:   void ludcmp(double **a, int npar, int *indx, double *d) ;
 3324:   double gompertz(double p[]);
 3325:   /* hess=matrix(1,npar,1,npar); */
 3326: 
 3327:   printf("\nCalculation of the hessian matrix. Wait...\n");
 3328:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
 3329:   for (i=1;i<=npar;i++){
 3330:     printf("%d-",i);fflush(stdout);
 3331:     fprintf(ficlog,"%d-",i);fflush(ficlog);
 3332:    
 3333:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
 3334:     
 3335:     /*  printf(" %f ",p[i]);
 3336: 	printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
 3337:   }
 3338:   
 3339:   for (i=1;i<=npar;i++) {
 3340:     for (j=1;j<=npar;j++)  {
 3341:       if (j>i) { 
 3342: 	printf(".%d-%d",i,j);fflush(stdout);
 3343: 	fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
 3344: 	hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
 3345: 	
 3346: 	hess[j][i]=hess[i][j];    
 3347: 	/*printf(" %lf ",hess[i][j]);*/
 3348:       }
 3349:     }
 3350:   }
 3351:   printf("\n");
 3352:   fprintf(ficlog,"\n");
 3353: 
 3354:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
 3355:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
 3356:   
 3357:   a=matrix(1,npar,1,npar);
 3358:   y=matrix(1,npar,1,npar);
 3359:   x=vector(1,npar);
 3360:   indx=ivector(1,npar);
 3361:   for (i=1;i<=npar;i++)
 3362:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
 3363:   ludcmp(a,npar,indx,&pd);
 3364: 
 3365:   for (j=1;j<=npar;j++) {
 3366:     for (i=1;i<=npar;i++) x[i]=0;
 3367:     x[j]=1;
 3368:     lubksb(a,npar,indx,x);
 3369:     for (i=1;i<=npar;i++){ 
 3370:       matcov[i][j]=x[i];
 3371:     }
 3372:   }
 3373: 
 3374:   printf("\n#Hessian matrix#\n");
 3375:   fprintf(ficlog,"\n#Hessian matrix#\n");
 3376:   for (i=1;i<=npar;i++) { 
 3377:     for (j=1;j<=npar;j++) { 
 3378:       printf("%.6e ",hess[i][j]);
 3379:       fprintf(ficlog,"%.6e ",hess[i][j]);
 3380:     }
 3381:     printf("\n");
 3382:     fprintf(ficlog,"\n");
 3383:   }
 3384: 
 3385:   /* printf("\n#Covariance matrix#\n"); */
 3386:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
 3387:   /* for (i=1;i<=npar;i++) {  */
 3388:   /*   for (j=1;j<=npar;j++) {  */
 3389:   /*     printf("%.6e ",matcov[i][j]); */
 3390:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
 3391:   /*   } */
 3392:   /*   printf("\n"); */
 3393:   /*   fprintf(ficlog,"\n"); */
 3394:   /* } */
 3395: 
 3396:   /* Recompute Inverse */
 3397:   /* for (i=1;i<=npar;i++) */
 3398:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
 3399:   /* ludcmp(a,npar,indx,&pd); */
 3400: 
 3401:   /*  printf("\n#Hessian matrix recomputed#\n"); */
 3402: 
 3403:   /* for (j=1;j<=npar;j++) { */
 3404:   /*   for (i=1;i<=npar;i++) x[i]=0; */
 3405:   /*   x[j]=1; */
 3406:   /*   lubksb(a,npar,indx,x); */
 3407:   /*   for (i=1;i<=npar;i++){  */
 3408:   /*     y[i][j]=x[i]; */
 3409:   /*     printf("%.3e ",y[i][j]); */
 3410:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
 3411:   /*   } */
 3412:   /*   printf("\n"); */
 3413:   /*   fprintf(ficlog,"\n"); */
 3414:   /* } */
 3415: 
 3416:   /* Verifying the inverse matrix */
 3417: #ifdef DEBUGHESS
 3418:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
 3419: 
 3420:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
 3421:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
 3422: 
 3423:   for (j=1;j<=npar;j++) {
 3424:     for (i=1;i<=npar;i++){ 
 3425:       printf("%.2f ",y[i][j]);
 3426:       fprintf(ficlog,"%.2f ",y[i][j]);
 3427:     }
 3428:     printf("\n");
 3429:     fprintf(ficlog,"\n");
 3430:   }
 3431: #endif
 3432: 
 3433:   free_matrix(a,1,npar,1,npar);
 3434:   free_matrix(y,1,npar,1,npar);
 3435:   free_vector(x,1,npar);
 3436:   free_ivector(indx,1,npar);
 3437:   /* free_matrix(hess,1,npar,1,npar); */
 3438: 
 3439: 
 3440: }
 3441: 
 3442: /*************** hessian matrix ****************/
 3443: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
 3444: { /* Around values of x, computes the function func and returns the scales delti and hessian */
 3445:   int i;
 3446:   int l=1, lmax=20;
 3447:   double k1,k2, res, fx;
 3448:   double p2[MAXPARM+1]; /* identical to x */
 3449:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 3450:   int k=0,kmax=10;
 3451:   double l1;
 3452: 
 3453:   fx=func(x);
 3454:   for (i=1;i<=npar;i++) p2[i]=x[i];
 3455:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
 3456:     l1=pow(10,l);
 3457:     delts=delt;
 3458:     for(k=1 ; k <kmax; k=k+1){
 3459:       delt = delta*(l1*k);
 3460:       p2[theta]=x[theta] +delt;
 3461:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
 3462:       p2[theta]=x[theta]-delt;
 3463:       k2=func(p2)-fx;
 3464:       /*res= (k1-2.0*fx+k2)/delt/delt; */
 3465:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
 3466:       
 3467: #ifdef DEBUGHESSII
 3468:       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);
 3469:       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);
 3470: #endif
 3471:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
 3472:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 3473: 	k=kmax;
 3474:       }
 3475:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
 3476: 	k=kmax; l=lmax*10;
 3477:       }
 3478:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
 3479: 	delts=delt;
 3480:       }
 3481:     } /* End loop k */
 3482:   }
 3483:   delti[theta]=delts;
 3484:   return res; 
 3485:   
 3486: }
 3487: 
 3488: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
 3489: {
 3490:   int i;
 3491:   int l=1, lmax=20;
 3492:   double k1,k2,k3,k4,res,fx;
 3493:   double p2[MAXPARM+1];
 3494:   int k, kmax=1;
 3495:   double v1, v2, cv12, lc1, lc2;
 3496: 
 3497:   int firstime=0;
 3498:   
 3499:   fx=func(x);
 3500:   for (k=1; k<=kmax; k=k+10) {
 3501:     for (i=1;i<=npar;i++) p2[i]=x[i];
 3502:     p2[thetai]=x[thetai]+delti[thetai]*k;
 3503:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
 3504:     k1=func(p2)-fx;
 3505:   
 3506:     p2[thetai]=x[thetai]+delti[thetai]*k;
 3507:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
 3508:     k2=func(p2)-fx;
 3509:   
 3510:     p2[thetai]=x[thetai]-delti[thetai]*k;
 3511:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
 3512:     k3=func(p2)-fx;
 3513:   
 3514:     p2[thetai]=x[thetai]-delti[thetai]*k;
 3515:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
 3516:     k4=func(p2)-fx;
 3517:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
 3518:     if(k1*k2*k3*k4 <0.){
 3519:       firstime=1;
 3520:       kmax=kmax+10;
 3521:     }
 3522:     if(kmax >=10 || firstime ==1){
 3523:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you may increase ftol=%.2e\n",thetai,thetaj, ftol);
 3524:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you may increase ftol=%.2e\n",thetai,thetaj, ftol);
 3525:       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);
 3526:       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);
 3527:     }
 3528: #ifdef DEBUGHESSIJ
 3529:     v1=hess[thetai][thetai];
 3530:     v2=hess[thetaj][thetaj];
 3531:     cv12=res;
 3532:     /* Computing eigen value of Hessian matrix */
 3533:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3534:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3535:     if ((lc2 <0) || (lc1 <0) ){
 3536:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
 3537:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
 3538:       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);
 3539:       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);
 3540:     }
 3541: #endif
 3542:   }
 3543:   return res;
 3544: }
 3545: 
 3546:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
 3547: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
 3548: /* { */
 3549: /*   int i; */
 3550: /*   int l=1, lmax=20; */
 3551: /*   double k1,k2,k3,k4,res,fx; */
 3552: /*   double p2[MAXPARM+1]; */
 3553: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
 3554: /*   int k=0,kmax=10; */
 3555: /*   double l1; */
 3556:   
 3557: /*   fx=func(x); */
 3558: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
 3559: /*     l1=pow(10,l); */
 3560: /*     delts=delt; */
 3561: /*     for(k=1 ; k <kmax; k=k+1){ */
 3562: /*       delt = delti*(l1*k); */
 3563: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
 3564: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
 3565: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
 3566: /*       k1=func(p2)-fx; */
 3567:       
 3568: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
 3569: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
 3570: /*       k2=func(p2)-fx; */
 3571:       
 3572: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
 3573: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
 3574: /*       k3=func(p2)-fx; */
 3575:       
 3576: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
 3577: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
 3578: /*       k4=func(p2)-fx; */
 3579: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
 3580: /* #ifdef DEBUGHESSIJ */
 3581: /*       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); */
 3582: /*       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); */
 3583: /* #endif */
 3584: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
 3585: /* 	k=kmax; */
 3586: /*       } */
 3587: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
 3588: /* 	k=kmax; l=lmax*10; */
 3589: /*       } */
 3590: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
 3591: /* 	delts=delt; */
 3592: /*       } */
 3593: /*     } /\* End loop k *\/ */
 3594: /*   } */
 3595: /*   delti[theta]=delts; */
 3596: /*   return res;  */
 3597: /* } */
 3598: 
 3599: 
 3600: /************** Inverse of matrix **************/
 3601: void ludcmp(double **a, int n, int *indx, double *d) 
 3602: { 
 3603:   int i,imax,j,k; 
 3604:   double big,dum,sum,temp; 
 3605:   double *vv; 
 3606:  
 3607:   vv=vector(1,n); 
 3608:   *d=1.0; 
 3609:   for (i=1;i<=n;i++) { 
 3610:     big=0.0; 
 3611:     for (j=1;j<=n;j++) 
 3612:       if ((temp=fabs(a[i][j])) > big) big=temp; 
 3613:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
 3614:     vv[i]=1.0/big; 
 3615:   } 
 3616:   for (j=1;j<=n;j++) { 
 3617:     for (i=1;i<j;i++) { 
 3618:       sum=a[i][j]; 
 3619:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
 3620:       a[i][j]=sum; 
 3621:     } 
 3622:     big=0.0; 
 3623:     for (i=j;i<=n;i++) { 
 3624:       sum=a[i][j]; 
 3625:       for (k=1;k<j;k++) 
 3626: 	sum -= a[i][k]*a[k][j]; 
 3627:       a[i][j]=sum; 
 3628:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
 3629: 	big=dum; 
 3630: 	imax=i; 
 3631:       } 
 3632:     } 
 3633:     if (j != imax) { 
 3634:       for (k=1;k<=n;k++) { 
 3635: 	dum=a[imax][k]; 
 3636: 	a[imax][k]=a[j][k]; 
 3637: 	a[j][k]=dum; 
 3638:       } 
 3639:       *d = -(*d); 
 3640:       vv[imax]=vv[j]; 
 3641:     } 
 3642:     indx[j]=imax; 
 3643:     if (a[j][j] == 0.0) a[j][j]=TINY; 
 3644:     if (j != n) { 
 3645:       dum=1.0/(a[j][j]); 
 3646:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
 3647:     } 
 3648:   } 
 3649:   free_vector(vv,1,n);  /* Doesn't work */
 3650: ;
 3651: } 
 3652: 
 3653: void lubksb(double **a, int n, int *indx, double b[]) 
 3654: { 
 3655:   int i,ii=0,ip,j; 
 3656:   double sum; 
 3657:  
 3658:   for (i=1;i<=n;i++) { 
 3659:     ip=indx[i]; 
 3660:     sum=b[ip]; 
 3661:     b[ip]=b[i]; 
 3662:     if (ii) 
 3663:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
 3664:     else if (sum) ii=i; 
 3665:     b[i]=sum; 
 3666:   } 
 3667:   for (i=n;i>=1;i--) { 
 3668:     sum=b[i]; 
 3669:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
 3670:     b[i]=sum/a[i][i]; 
 3671:   } 
 3672: } 
 3673: 
 3674: void pstamp(FILE *fichier)
 3675: {
 3676:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
 3677: }
 3678: 
 3679: /************ Frequencies ********************/
 3680:  void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
 3681: 									 int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[],	\
 3682: 									 int firstpass,  int lastpass, int stepm, int weightopt, char model[])
 3683:  {  /* Some frequencies */
 3684:   
 3685: 	 int i, m, jk, j1, bool, z1,j;
 3686: 	 int iind=0, iage=0;
 3687: 	 int mi; /* Effective wave */
 3688: 	 int first;
 3689: 	 double ***freq; /* Frequencies */
 3690: 	 double *pp, **prop, *posprop, *pospropt;
 3691: 	 double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
 3692: 	 char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
 3693: 	 double agebegin, ageend;
 3694:     
 3695: 	 pp=vector(1,nlstate);
 3696: 	 prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
 3697: 	 posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
 3698: 	 pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
 3699: 	 /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
 3700: 	 strcpy(fileresp,"P_");
 3701: 	 strcat(fileresp,fileresu);
 3702: 	 /*strcat(fileresphtm,fileresu);*/
 3703: 	 if((ficresp=fopen(fileresp,"w"))==NULL) {
 3704: 		 printf("Problem with prevalence resultfile: %s\n", fileresp);
 3705: 		 fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
 3706: 		 exit(0);
 3707: 	 }
 3708: 
 3709: 	 strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
 3710: 	 if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
 3711: 		 printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
 3712: 		 fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
 3713: 		 fflush(ficlog);
 3714: 		 exit(70); 
 3715: 	 }
 3716: 	 else{
 3717: 		 fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 3718: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 3719: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
 3720: 						 fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 3721: 	 }
 3722: 	 fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies and prevalence by age at begin of transition</h4>\n",fileresphtm, fileresphtm);
 3723:     
 3724: 	 strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
 3725: 	 if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
 3726: 		 printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
 3727: 		 fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
 3728: 		 fflush(ficlog);
 3729: 		 exit(70); 
 3730: 	 }
 3731: 	 else{
 3732: 		 fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 3733: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 3734: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
 3735: 						 fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 3736: 	 }
 3737: 	 fprintf(ficresphtmfr,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies of all effective transitions by age at begin of transition </h4>Unknown status is -1<br/>\n",fileresphtmfr, fileresphtmfr);
 3738: 
 3739: 	 freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
 3740: 	 j1=0;
 3741:   
 3742: 	 j=cptcoveff;
 3743: 	 if (cptcovn<1) {j=1;ncodemax[1]=1;}
 3744: 
 3745: 	 first=1;
 3746: 
 3747: 	 /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
 3748: 			reference=low_education V1=0,V2=0
 3749: 			med_educ                V1=1 V2=0, 
 3750: 			high_educ               V1=0 V2=1
 3751: 			Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
 3752: 	 */
 3753: 
 3754: 	 for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){ /* Loop on covariates combination */
 3755: 		 posproptt=0.;
 3756: 		 /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
 3757: 			 scanf("%d", i);*/
 3758: 		 for (i=-5; i<=nlstate+ndeath; i++)  
 3759: 			 for (jk=-5; jk<=nlstate+ndeath; jk++)  
 3760: 				 for(m=iagemin; m <= iagemax+3; m++)
 3761: 					 freq[i][jk][m]=0;
 3762:       
 3763: 		 for (i=1; i<=nlstate; i++)  {
 3764: 			 for(m=iagemin; m <= iagemax+3; m++)
 3765: 				 prop[i][m]=0;
 3766: 			 posprop[i]=0;
 3767: 			 pospropt[i]=0;
 3768: 		 }
 3769:       
 3770: 		 dateintsum=0;
 3771: 		 k2cpt=0;
 3772: 
 3773: 		 for (iind=1; iind<=imx; iind++) { /* For each individual iind */
 3774: 			 bool=1;
 3775: 			 if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
 3776: 				 for (z1=1; z1<=cptcoveff; z1++) {      
 3777: 					 if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
 3778: 						 /* Tests if the value of each of the covariates of i is equal to filter j1 */
 3779: 						 bool=0;
 3780: 						 /* 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", 
 3781:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
 3782:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
 3783: 						 /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
 3784: 					 } 
 3785: 				 } /* end z1 */
 3786: 			 } /* cptcovn > 0 */
 3787: 
 3788: 			 if (bool==1){
 3789: 				 /* for(m=firstpass; m<=lastpass; m++){ */
 3790: 				 for(mi=1; mi<wav[iind];mi++){
 3791: 					 m=mw[mi][iind];
 3792: 					 /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
 3793: 							and mw[mi+1][iind]. dh depends on stepm. */
 3794: 					 agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
 3795: 					 ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
 3796: 					 if(m >=firstpass && m <=lastpass){
 3797: 						 k2=anint[m][iind]+(mint[m][iind]/12.);
 3798: 						 /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
 3799: 						 if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
 3800: 						 if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
 3801: 						 if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
 3802: 							 prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
 3803: 						 if (m<lastpass) {
 3804: 							 /* if(s[m][iind]==4 && s[m+1][iind]==4) */
 3805: 							 /*   printf(" num=%ld m=%d, iind=%d s1=%d s2=%d agev at m=%d\n", num[iind], m, iind,s[m][iind],s[m+1][iind], (int)agev[m][iind]); */
 3806: 							 if(s[m][iind]==-1)
 3807: 								 printf(" num=%ld m=%d, iind=%d s1=%d s2=%d agev at m=%d agebegin=%.2f ageend=%.2f, agemed=%d\n", num[iind], m, iind,s[m][iind],s[m+1][iind], (int)agev[m][iind],agebegin, ageend, (int)((agebegin+ageend)/2.));
 3808: 							 freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
 3809: 							 /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
 3810: 							 freq[s[m][iind]][s[m+1][iind]][iagemax+3] += weight[iind]; /* Total is in iagemax+3 *//* At age of beginning of transition, where status is known */
 3811: 						 }
 3812: 					 }  
 3813: 					 if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99)) {
 3814: 						 dateintsum=dateintsum+k2;
 3815: 						 k2cpt++;
 3816: 						 /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
 3817: 					 }
 3818: 					 /*}*/
 3819: 				 } /* end m */
 3820: 			 } /* end bool */
 3821: 		 } /* end iind = 1 to imx */
 3822:        /* prop[s][age] is feeded for any initial and valid live state as well as
 3823: 					freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
 3824: 
 3825: 
 3826: 		 /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 3827: 		 pstamp(ficresp);
 3828: 		 if  (cptcovn>0) {
 3829: 			 fprintf(ficresp, "\n#********** Variable "); 
 3830: 			 fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
 3831: 			 fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
 3832: 			 for (z1=1; z1<=cptcoveff; z1++){
 3833: 				 fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 3834: 				 fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 3835: 				 fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 3836: 			 }
 3837: 			 fprintf(ficresp, "**********\n#");
 3838: 			 fprintf(ficresphtm, "**********</h3>\n");
 3839: 			 fprintf(ficresphtmfr, "**********</h3>\n");
 3840: 			 fprintf(ficlog, "\n#********** Variable "); 
 3841: 			 for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 3842: 			 fprintf(ficlog, "**********\n");
 3843: 		 }
 3844: 		 fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
 3845: 		 for(i=1; i<=nlstate;i++) {
 3846: 			 fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
 3847: 			 fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
 3848: 		 }
 3849: 		 fprintf(ficresp, "\n");
 3850: 		 fprintf(ficresphtm, "\n");
 3851:       
 3852: 		 /* Header of frequency table by age */
 3853: 		 fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
 3854: 		 fprintf(ficresphtmfr,"<th>Age</th> ");
 3855: 		 for(jk=-1; jk <=nlstate+ndeath; jk++){
 3856: 			 for(m=-1; m <=nlstate+ndeath; m++){
 3857: 				 if(jk!=0 && m!=0)
 3858: 					 fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
 3859: 			 }
 3860: 		 }
 3861: 		 fprintf(ficresphtmfr, "\n");
 3862:       
 3863: 		 /* For each age */
 3864: 		 for(iage=iagemin; iage <= iagemax+3; iage++){
 3865: 			 fprintf(ficresphtm,"<tr>");
 3866: 			 if(iage==iagemax+1){
 3867: 				 fprintf(ficlog,"1");
 3868: 				 fprintf(ficresphtmfr,"<tr><th>0</th> ");
 3869: 			 }else if(iage==iagemax+2){
 3870: 				 fprintf(ficlog,"0");
 3871: 				 fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
 3872: 			 }else if(iage==iagemax+3){
 3873: 				 fprintf(ficlog,"Total");
 3874: 				 fprintf(ficresphtmfr,"<tr><th>Total</th> ");
 3875: 			 }else{
 3876: 				 if(first==1){
 3877: 					 first=0;
 3878: 					 printf("See log file for details...\n");
 3879: 				 }
 3880: 				 fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
 3881: 				 fprintf(ficlog,"Age %d", iage);
 3882: 			 }
 3883: 			 for(jk=1; jk <=nlstate ; jk++){
 3884: 				 for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
 3885: 					 pp[jk] += freq[jk][m][iage]; 
 3886: 			 }
 3887: 			 for(jk=1; jk <=nlstate ; jk++){
 3888: 				 for(m=-1, pos=0; m <=0 ; m++)
 3889: 					 pos += freq[jk][m][iage];
 3890: 				 if(pp[jk]>=1.e-10){
 3891: 					 if(first==1){
 3892: 						 printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 3893: 					 }
 3894: 					 fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 3895: 				 }else{
 3896: 					 if(first==1)
 3897: 						 printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 3898: 					 fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 3899: 				 }
 3900: 			 }
 3901: 
 3902: 			 for(jk=1; jk <=nlstate ; jk++){ 
 3903: 				 /* posprop[jk]=0; */
 3904: 				 for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
 3905: 					 pp[jk] += freq[jk][m][iage];
 3906: 			 }	/* pp[jk] is the total number of transitions starting from state jk and any ending status until this age */
 3907: 
 3908: 			 for(jk=1,pos=0, pospropta=0.; jk <=nlstate ; jk++){
 3909: 				 pos += pp[jk]; /* pos is the total number of transitions until this age */
 3910: 				 posprop[jk] += prop[jk][iage]; /* prop is the number of transitions from a live state
 3911: 																					 from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
 3912: 				 pospropta += prop[jk][iage]; /* prop is the number of transitions from a live state
 3913: 																					 from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
 3914: 			 }
 3915: 			 for(jk=1; jk <=nlstate ; jk++){
 3916: 				 if(pos>=1.e-5){
 3917: 					 if(first==1)
 3918: 						 printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 3919: 					 fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 3920: 				 }else{
 3921: 					 if(first==1)
 3922: 						 printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 3923: 					 fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 3924: 				 }
 3925: 				 if( iage <= iagemax){
 3926: 					 if(pos>=1.e-5){
 3927: 						 fprintf(ficresp," %d %.5f %.0f %.0f",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
 3928: 						 fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
 3929: 						 /*probs[iage][jk][j1]= pp[jk]/pos;*/
 3930: 						 /*printf("\niage=%d jk=%d j1=%d %.5f %.0f %.0f %f",iage,jk,j1,pp[jk]/pos, pp[jk],pos,probs[iage][jk][j1]);*/
 3931: 					 }
 3932: 					 else{
 3933: 						 fprintf(ficresp," %d NaNq %.0f %.0f",iage,prop[jk][iage],pospropta);
 3934: 						 fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[jk][iage],pospropta);
 3935: 					 }
 3936: 				 }
 3937: 				 pospropt[jk] +=posprop[jk];
 3938: 			 } /* end loop jk */
 3939: 			 /* pospropt=0.; */
 3940: 			 for(jk=-1; jk <=nlstate+ndeath; jk++){
 3941: 				 for(m=-1; m <=nlstate+ndeath; m++){
 3942: 					 if(freq[jk][m][iage] !=0 ) { /* minimizing output */
 3943: 						 if(first==1){
 3944: 							 printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]);
 3945: 						 }
 3946: 						 fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iage]);
 3947: 					 }
 3948: 					 if(jk!=0 && m!=0)
 3949: 						 fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][iage]);
 3950: 				 }
 3951: 			 } /* end loop jk */
 3952: 			 posproptt=0.; 
 3953: 			 for(jk=1; jk <=nlstate; jk++){
 3954: 				 posproptt += pospropt[jk];
 3955: 			 }
 3956: 			 fprintf(ficresphtmfr,"</tr>\n ");
 3957: 			 if(iage <= iagemax){
 3958: 				 fprintf(ficresp,"\n");
 3959: 				 fprintf(ficresphtm,"</tr>\n");
 3960: 			 }
 3961: 			 if(first==1)
 3962: 				 printf("Others in log...\n");
 3963: 			 fprintf(ficlog,"\n");
 3964: 		 } /* end loop age iage */
 3965: 		 fprintf(ficresphtm,"<tr><th>Tot</th>");
 3966: 		 for(jk=1; jk <=nlstate ; jk++){
 3967: 			 if(posproptt < 1.e-5){
 3968: 				 fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[jk],posproptt);	
 3969: 			 }else{
 3970: 				 fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[jk]/posproptt,pospropt[jk],posproptt);	
 3971: 			 }
 3972: 		 }
 3973: 		 fprintf(ficresphtm,"</tr>\n");
 3974: 		 fprintf(ficresphtm,"</table>\n");
 3975: 		 fprintf(ficresphtmfr,"</table>\n");
 3976: 		 if(posproptt < 1.e-5){
 3977: 			 fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
 3978: 			 fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
 3979: 			 fprintf(ficres,"\n  This combination (%d) is not valid and no result will be produced\n\n",j1);
 3980: 			 invalidvarcomb[j1]=1;
 3981: 		 }else{
 3982: 			 fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
 3983: 			 invalidvarcomb[j1]=0;
 3984: 		 }
 3985: 		 fprintf(ficresphtmfr,"</table>\n");
 3986: 	 } /* end selected combination of covariate j1 */
 3987: 	 dateintmean=dateintsum/k2cpt; 
 3988: 		 
 3989: 	 fclose(ficresp);
 3990: 	 fclose(ficresphtm);
 3991: 	 fclose(ficresphtmfr);
 3992: 	 free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);
 3993: 	 free_vector(pospropt,1,nlstate);
 3994: 	 free_vector(posprop,1,nlstate);
 3995: 	 free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);
 3996: 	 free_vector(pp,1,nlstate);
 3997: 	 /* End of Freq */
 3998:  }
 3999: 
 4000: /************ Prevalence ********************/
 4001:  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)
 4002:  {  
 4003:    /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 4004:       in each health status at the date of interview (if between dateprev1 and dateprev2).
 4005:       We still use firstpass and lastpass as another selection.
 4006:    */
 4007:  
 4008:    int i, m, jk, j1, bool, z1,j;
 4009:    int mi; /* Effective wave */
 4010:    int iage;
 4011:    double agebegin, ageend;
 4012: 
 4013:    double **prop;
 4014:    double posprop; 
 4015:    double  y2; /* in fractional years */
 4016:    int iagemin, iagemax;
 4017:    int first; /** to stop verbosity which is redirected to log file */
 4018: 
 4019:    iagemin= (int) agemin;
 4020:    iagemax= (int) agemax;
 4021:    /*pp=vector(1,nlstate);*/
 4022:    prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
 4023:    /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
 4024:    j1=0;
 4025:   
 4026:    /*j=cptcoveff;*/
 4027:    if (cptcovn<1) {j=1;ncodemax[1]=1;}
 4028:   
 4029:    first=1;
 4030:    for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
 4031:      for (i=1; i<=nlstate; i++)  
 4032:        for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)
 4033: 	 prop[i][iage]=0.0;
 4034:     
 4035:      for (i=1; i<=imx; i++) { /* Each individual */
 4036:        bool=1;
 4037:        if  (cptcovn>0) {  /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
 4038: 	 for (z1=1; z1<=cptcoveff; z1++) /* For each covariate, look at the value for individual i and checks if it is equal to the corresponding value of this covariate according to current combination j1*/
 4039: 	   if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
 4040: 	     bool=0;
 4041:        } 
 4042:        if (bool==1) { /* For this combination of covariates values, this individual fits */
 4043: 	 /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
 4044: 	 for(mi=1; mi<wav[i];mi++){
 4045: 	   m=mw[mi][i];
 4046: 	   agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
 4047: 	   /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
 4048: 	   if(m >=firstpass && m <=lastpass){
 4049: 	     y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
 4050: 	     if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
 4051: 	       if(agev[m][i]==0) agev[m][i]=iagemax+1;
 4052: 	       if(agev[m][i]==1) agev[m][i]=iagemax+2;
 4053: 	       if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){
 4054: 		 printf("Error on individual # %d agev[m][i]=%f <%d-%d or > %d+3+%d  m=%d; either change agemin or agemax or fix data\n",i, agev[m][i],iagemin,AGEMARGE, iagemax,AGEMARGE,m); 
 4055: 		 exit(1);
 4056: 	       }
 4057: 	       if (s[m][i]>0 && s[m][i]<=nlstate) { 
 4058: 		 /*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]]);*/
 4059: 		 prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
 4060: 		 prop[s[m][i]][iagemax+3] += weight[i]; 
 4061: 	       } /* end valid statuses */ 
 4062: 	     } /* end selection of dates */
 4063: 	   } /* end selection of waves */
 4064: 	 } /* end effective waves */
 4065:        } /* end bool */
 4066:      }
 4067:      for(i=iagemin; i <= iagemax+3; i++){  
 4068:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
 4069: 	 posprop += prop[jk][i]; 
 4070:        } 
 4071:       
 4072:        for(jk=1; jk <=nlstate ; jk++){	    
 4073: 	 if( i <=  iagemax){ 
 4074: 	   if(posprop>=1.e-5){ 
 4075: 	     probs[i][jk][j1]= prop[jk][i]/posprop;
 4076: 	   } else{
 4077: 	     if(first==1){
 4078: 	       first=0;
 4079: 	       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]);
 4080: 	     }
 4081: 	   }
 4082: 	 } 
 4083:        }/* end jk */ 
 4084:      }/* end i */ 
 4085:      /*} *//* end i1 */
 4086:    } /* end j1 */
 4087:   
 4088:    /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
 4089:    /*free_vector(pp,1,nlstate);*/
 4090:    free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);
 4091:  }  /* End of prevalence */
 4092: 
 4093: /************* Waves Concatenation ***************/
 4094: 
 4095: 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)
 4096: {
 4097:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 4098:      Death is a valid wave (if date is known).
 4099:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
 4100:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 4101:      and mw[mi+1][i]. dh depends on stepm.
 4102:      */
 4103: 
 4104:   int i, mi, m;
 4105:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
 4106:      double sum=0., jmean=0.;*/
 4107:   int first, firstwo, firsthree, firstfour;
 4108:   int j, k=0,jk, ju, jl;
 4109:   double sum=0.;
 4110:   first=0;
 4111:   firstwo=0;
 4112:   firsthree=0;
 4113:   firstfour=0;
 4114:   jmin=100000;
 4115:   jmax=-1;
 4116:   jmean=0.;
 4117:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
 4118:     mi=0;
 4119:     m=firstpass;
 4120:     while(s[m][i] <= nlstate){  /* a live state */
 4121:       if(s[m][i]>=1 || s[m][i]==-4 || s[m][i]==-5){ /* Since 0.98r4 if status=-2 vital status is really unknown, wave should be skipped */
 4122: 	mw[++mi][i]=m;
 4123:       }
 4124:       if(m >=lastpass){
 4125: 	if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
 4126: 	  if(firsthree == 0){
 4127: 	    printf("Information! Unknown health status for individual %ld line=%d occurred at last wave %d at known date %d/%d. Please, check if your unknown date of death %d/%d means a live state %d at wave %d. This case(%d)/wave(%d) contributes to the likelihood.\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], (int) moisdc[i], (int) andc[i], s[m][i], m, i, m);
 4128: 	    firsthree=1;
 4129: 	  }
 4130: 	  fprintf(ficlog,"Information! Unknown status for individual %ld line=%d occurred at last wave %d at known date %d/%d. Please, check if your unknown date of death %d/%d means a live state %d at wave %d. This case(%d)/wave(%d) contributes to the likelihood.\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], (int) moisdc[i], (int) andc[i], s[m][i], m, i, m);
 4131: 	  mw[++mi][i]=m;
 4132: 	}
 4133: 	if(s[m][i]==-2){ /* Vital status is really unknown */
 4134: 	  nbwarn++;
 4135: 	  if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
 4136: 	    printf("Warning! Vital status for individual %ld (line=%d) at last wave %d interviewed at date %d/%d is unknown %d. Please, check if the vital status and the date of death %d/%d are really unknown. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], (int) moisdc[i], (int) andc[i], i, m);
 4137: 	    fprintf(ficlog,"Warning! Vital status for individual %ld (line=%d) at last wave %d interviewed at date %d/%d is unknown %d. Please, check if the vital status and the date of death %d/%d are really unknown. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], (int) moisdc[i], (int) andc[i], i, m);
 4138: 	  }
 4139: 	  break;
 4140: 	}
 4141: 	break;
 4142:       }
 4143:       else
 4144: 	m++;
 4145:     }/* end while */
 4146:     
 4147:     /* After last pass */
 4148:     if (s[m][i] > nlstate){  /* In a death state */
 4149:       mi++;	/* Death is another wave */
 4150:       /* if(mi==0)  never been interviewed correctly before death */
 4151: 	 /* Only death is a correct wave */
 4152:       mw[mi][i]=m;
 4153:     }else if ((int) andc[i] != 9999) { /* Status is either death or negative. A death occured after lastpass, we can't take it into account because of potential bias */
 4154:       /* m++; */
 4155:       /* mi++; */
 4156:       /* s[m][i]=nlstate+1;  /\* We are setting the status to the last of non live state *\/ */
 4157:       /* mw[mi][i]=m; */
 4158:       nberr++;
 4159:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
 4160: 	if(firstwo==0){
 4161: 	  printf("Error! Death for individual %ld line=%d  occurred %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
 4162: 	  firstwo=1;
 4163: 	}
 4164: 	fprintf(ficlog,"Error! Death for individual %ld line=%d  occurred %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
 4165:       }else{ /* end date of interview is known */
 4166: 	/* death is known but not confirmed by death status at any wave */
 4167: 	if(firstfour==0){
 4168: 	  printf("Error! Death for individual %ld line=%d  occurred %d/%d but not confirmed by any death status for any wave, including last wave %d at unknown date %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
 4169: 	  firstfour=1;
 4170: 	}
 4171: 	fprintf(ficlog,"Error! Death for individual %ld line=%d  occurred %d/%d but not confirmed by any death status for any wave, including last wave %d at unknown date %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
 4172:       }
 4173:     }
 4174:     wav[i]=mi;
 4175:     if(mi==0){
 4176:       nbwarn++;
 4177:       if(first==0){
 4178: 	printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
 4179: 	first=1;
 4180:       }
 4181:       if(first==1){
 4182: 	fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
 4183:       }
 4184:     } /* end mi==0 */
 4185:   } /* End individuals */
 4186:   /* wav and mw are no more changed */
 4187: 
 4188:   
 4189:   for(i=1; i<=imx; i++){
 4190:     for(mi=1; mi<wav[i];mi++){
 4191:       if (stepm <=0)
 4192: 	dh[mi][i]=1;
 4193:       else{
 4194: 	if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
 4195: 	  if (agedc[i] < 2*AGESUP) {
 4196: 	    j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
 4197: 	    if(j==0) j=1;  /* Survives at least one month after exam */
 4198: 	    else if(j<0){
 4199: 	      nberr++;
 4200: 	      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]);
 4201: 	      j=1; /* Temporary Dangerous patch */
 4202: 	      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);
 4203: 	      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]);
 4204: 	      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);
 4205: 	    }
 4206: 	    k=k+1;
 4207: 	    if (j >= jmax){
 4208: 	      jmax=j;
 4209: 	      ijmax=i;
 4210: 	    }
 4211: 	    if (j <= jmin){
 4212: 	      jmin=j;
 4213: 	      ijmin=i;
 4214: 	    }
 4215: 	    sum=sum+j;
 4216: 	    /*if (j<0) printf("j=%d num=%d \n",j,i);*/
 4217: 	    /*	  printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
 4218: 	  }
 4219: 	}
 4220: 	else{
 4221: 	  j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 4222: /* 	  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]); */
 4223: 
 4224: 	  k=k+1;
 4225: 	  if (j >= jmax) {
 4226: 	    jmax=j;
 4227: 	    ijmax=i;
 4228: 	  }
 4229: 	  else if (j <= jmin){
 4230: 	    jmin=j;
 4231: 	    ijmin=i;
 4232: 	  }
 4233: 	  /*	    if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
 4234: 	  /*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]);*/
 4235: 	  if(j<0){
 4236: 	    nberr++;
 4237: 	    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]);
 4238: 	    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]);
 4239: 	  }
 4240: 	  sum=sum+j;
 4241: 	}
 4242: 	jk= j/stepm;
 4243: 	jl= j -jk*stepm;
 4244: 	ju= j -(jk+1)*stepm;
 4245: 	if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
 4246: 	  if(jl==0){
 4247: 	    dh[mi][i]=jk;
 4248: 	    bh[mi][i]=0;
 4249: 	  }else{ /* We want a negative bias in order to only have interpolation ie
 4250: 		  * to avoid the price of an extra matrix product in likelihood */
 4251: 	    dh[mi][i]=jk+1;
 4252: 	    bh[mi][i]=ju;
 4253: 	  }
 4254: 	}else{
 4255: 	  if(jl <= -ju){
 4256: 	    dh[mi][i]=jk;
 4257: 	    bh[mi][i]=jl;	/* bias is positive if real duration
 4258: 				 * is higher than the multiple of stepm and negative otherwise.
 4259: 				 */
 4260: 	  }
 4261: 	  else{
 4262: 	    dh[mi][i]=jk+1;
 4263: 	    bh[mi][i]=ju;
 4264: 	  }
 4265: 	  if(dh[mi][i]==0){
 4266: 	    dh[mi][i]=1; /* At least one step */
 4267: 	    bh[mi][i]=ju; /* At least one step */
 4268: 	    /*  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);*/
 4269: 	  }
 4270: 	} /* end if mle */
 4271:       }
 4272:     } /* end wave */
 4273:   }
 4274:   jmean=sum/k;
 4275:   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);
 4276:   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);
 4277:  }
 4278: 
 4279: /*********** Tricode ****************************/
 4280:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
 4281: {
 4282:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
 4283:   /*	  Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
 4284:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
 4285:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
 4286:    * nbcode[Tvar[5]][1]= nbcode[2][1]=0, nbcode[2][2]=1 (usually);
 4287:   */
 4288: 
 4289:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
 4290:   int modmaxcovj=0; /* Modality max of covariates j */
 4291:   int cptcode=0; /* Modality max of covariates j */
 4292:   int modmincovj=0; /* Modality min of covariates j */
 4293: 
 4294: 
 4295:   /* cptcoveff=0;  */
 4296: 	*cptcov=0;
 4297:  
 4298:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
 4299: 
 4300:   /* Loop on covariates without age and products */
 4301:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
 4302:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
 4303:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
 4304: 																modality of this covariate Vj*/ 
 4305:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
 4306: 																		* If product of Vn*Vm, still boolean *:
 4307: 																		* If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
 4308: 																		* 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
 4309:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
 4310: 				      modality of the nth covariate of individual i. */
 4311:       if (ij > modmaxcovj)
 4312:         modmaxcovj=ij; 
 4313:       else if (ij < modmincovj) 
 4314: 				modmincovj=ij; 
 4315:       if ((ij < -1) && (ij > NCOVMAX)){
 4316: 				printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
 4317: 				exit(1);
 4318:       }else
 4319:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
 4320:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
 4321:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
 4322:       /* getting the maximum value of the modality of the covariate
 4323: 	 (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
 4324: 	 female is 1, then modmaxcovj=1.*/
 4325:     } /* end for loop on individuals i */
 4326:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
 4327:     fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
 4328:     cptcode=modmaxcovj;
 4329:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
 4330:    /*for (i=0; i<=cptcode; i++) {*/
 4331:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
 4332:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
 4333:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
 4334:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
 4335: 				if( k != -1){
 4336: 					ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
 4337: 														 covariate for which somebody answered excluding 
 4338: 														 undefined. Usually 2: 0 and 1. */
 4339: 				}
 4340: 				ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
 4341: 																covariate for which somebody answered including 
 4342: 																undefined. Usually 3: -1, 0 and 1. */
 4343:       }
 4344:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
 4345: 				 historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
 4346:     } /* Ndum[-1] number of undefined modalities */
 4347: 		
 4348:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
 4349:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
 4350:        If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
 4351:        modmincovj=3; modmaxcovj = 7;
 4352:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
 4353:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
 4354:        defining two dummy variables: variables V1_1 and V1_2.
 4355:        nbcode[Tvar[j]][ij]=k;
 4356:        nbcode[Tvar[j]][1]=0;
 4357:        nbcode[Tvar[j]][2]=1;
 4358:        nbcode[Tvar[j]][3]=2;
 4359:        To be continued (not working yet).
 4360:     */
 4361:     ij=0; /* ij is similar to i but can jump over null modalities */
 4362:     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*/
 4363:     	if (Ndum[i] == 0) { /* If nobody responded to this modality k */
 4364: 				break;
 4365: 			}
 4366: 	ij++;
 4367: 	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.*/
 4368: 	cptcode = ij; /* New max modality for covar j */
 4369:     } /* end of loop on modality i=-1 to 1 or more */
 4370:       
 4371:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
 4372:     /* 	/\*recode from 0 *\/ */
 4373:     /* 				     k is a modality. If we have model=V1+V1*sex  */
 4374:     /* 				     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
 4375:     /* 				  But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
 4376:     /* 	} */
 4377:     /* 	/\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
 4378:     /* 	if (ij > ncodemax[j]) { */
 4379:     /* 	  printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
 4380:     /* 	  fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
 4381:     /* 	  break; */
 4382:     /* 	} */
 4383:     /*   }  /\* end of loop on modality k *\/ */
 4384:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
 4385:   
 4386: 	for (k=-1; k< maxncov; k++) Ndum[k]=0; 
 4387:   
 4388:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
 4389: 		/* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
 4390: 		ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
 4391: 		Ndum[ij]++; /* Might be supersed V1 + V1*age */
 4392: 	} 
 4393: 	
 4394: 	ij=0;
 4395: 	for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
 4396: 		/*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
 4397: 		if((Ndum[i]!=0) && (i<=ncovcol)){
 4398: 			ij++;
 4399: 			/*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
 4400: 			Tvaraff[ij]=i; /*For printing (unclear) */
 4401: 		}else{
 4402: 			/* Tvaraff[ij]=0; */
 4403: 		}
 4404: 	}
 4405: 	/* ij--; */
 4406: 	/* cptcoveff=ij; /\*Number of total covariates*\/ */
 4407: 	*cptcov=ij; /*Number of total covariates*/
 4408: 	
 4409: }
 4410: 
 4411: 
 4412: /*********** Health Expectancies ****************/
 4413: 
 4414: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
 4415: 
 4416: {
 4417:   /* Health expectancies, no variances */
 4418:   int i, j, nhstepm, hstepm, h, nstepm;
 4419:   int nhstepma, nstepma; /* Decreasing with age */
 4420:   double age, agelim, hf;
 4421:   double ***p3mat;
 4422:   double eip;
 4423: 
 4424:   pstamp(ficreseij);
 4425:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
 4426:   fprintf(ficreseij,"# Age");
 4427:   for(i=1; i<=nlstate;i++){
 4428:     for(j=1; j<=nlstate;j++){
 4429:       fprintf(ficreseij," e%1d%1d ",i,j);
 4430:     }
 4431:     fprintf(ficreseij," e%1d. ",i);
 4432:   }
 4433:   fprintf(ficreseij,"\n");
 4434: 
 4435:   
 4436:   if(estepm < stepm){
 4437:     printf ("Problem %d lower than %d\n",estepm, stepm);
 4438:   }
 4439:   else  hstepm=estepm;   
 4440:   /* We compute the life expectancy from trapezoids spaced every estepm months
 4441:    * This is mainly to measure the difference between two models: for example
 4442:    * if stepm=24 months pijx are given only every 2 years and by summing them
 4443:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 4444:    * progression in between and thus overestimating or underestimating according
 4445:    * to the curvature of the survival function. If, for the same date, we 
 4446:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 4447:    * to compare the new estimate of Life expectancy with the same linear 
 4448:    * hypothesis. A more precise result, taking into account a more precise
 4449:    * curvature will be obtained if estepm is as small as stepm. */
 4450: 
 4451:   /* For example we decided to compute the life expectancy with the smallest unit */
 4452:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 4453:      nhstepm is the number of hstepm from age to agelim 
 4454:      nstepm is the number of stepm from age to agelin. 
 4455:      Look at hpijx to understand the reason of that which relies in memory size
 4456:      and note for a fixed period like estepm months */
 4457:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 4458:      survival function given by stepm (the optimization length). Unfortunately it
 4459:      means that if the survival funtion is printed only each two years of age and if
 4460:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 4461:      results. So we changed our mind and took the option of the best precision.
 4462:   */
 4463:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 4464: 
 4465:   agelim=AGESUP;
 4466:   /* If stepm=6 months */
 4467:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
 4468:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 4469:     
 4470: /* nhstepm age range expressed in number of stepm */
 4471:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 4472:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 4473:   /* if (stepm >= YEARM) hstepm=1;*/
 4474:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 4475:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4476: 
 4477:   for (age=bage; age<=fage; age ++){ 
 4478:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 4479:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 4480:     /* if (stepm >= YEARM) hstepm=1;*/
 4481:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 4482: 
 4483:     /* If stepm=6 months */
 4484:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 4485:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 4486:     
 4487:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 4488:     
 4489:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 4490:     
 4491:     printf("%d|",(int)age);fflush(stdout);
 4492:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 4493:     
 4494:     /* Computing expectancies */
 4495:     for(i=1; i<=nlstate;i++)
 4496:       for(j=1; j<=nlstate;j++)
 4497: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 4498: 	  eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
 4499: 	  
 4500: 	  /* 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]);*/
 4501: 
 4502: 	}
 4503: 
 4504:     fprintf(ficreseij,"%3.0f",age );
 4505:     for(i=1; i<=nlstate;i++){
 4506:       eip=0;
 4507:       for(j=1; j<=nlstate;j++){
 4508: 	eip +=eij[i][j][(int)age];
 4509: 	fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
 4510:       }
 4511:       fprintf(ficreseij,"%9.4f", eip );
 4512:     }
 4513:     fprintf(ficreseij,"\n");
 4514:     
 4515:   }
 4516:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4517:   printf("\n");
 4518:   fprintf(ficlog,"\n");
 4519:   
 4520: }
 4521: 
 4522: 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[] )
 4523: 
 4524: {
 4525:   /* Covariances of health expectancies eij and of total life expectancies according
 4526:      to initial status i, ei. .
 4527:   */
 4528:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
 4529:   int nhstepma, nstepma; /* Decreasing with age */
 4530:   double age, agelim, hf;
 4531:   double ***p3matp, ***p3matm, ***varhe;
 4532:   double **dnewm,**doldm;
 4533:   double *xp, *xm;
 4534:   double **gp, **gm;
 4535:   double ***gradg, ***trgradg;
 4536:   int theta;
 4537: 
 4538:   double eip, vip;
 4539: 
 4540:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
 4541:   xp=vector(1,npar);
 4542:   xm=vector(1,npar);
 4543:   dnewm=matrix(1,nlstate*nlstate,1,npar);
 4544:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
 4545:   
 4546:   pstamp(ficresstdeij);
 4547:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
 4548:   fprintf(ficresstdeij,"# Age");
 4549:   for(i=1; i<=nlstate;i++){
 4550:     for(j=1; j<=nlstate;j++)
 4551:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
 4552:     fprintf(ficresstdeij," e%1d. ",i);
 4553:   }
 4554:   fprintf(ficresstdeij,"\n");
 4555: 
 4556:   pstamp(ficrescveij);
 4557:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
 4558:   fprintf(ficrescveij,"# Age");
 4559:   for(i=1; i<=nlstate;i++)
 4560:     for(j=1; j<=nlstate;j++){
 4561:       cptj= (j-1)*nlstate+i;
 4562:       for(i2=1; i2<=nlstate;i2++)
 4563: 	for(j2=1; j2<=nlstate;j2++){
 4564: 	  cptj2= (j2-1)*nlstate+i2;
 4565: 	  if(cptj2 <= cptj)
 4566: 	    fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
 4567: 	}
 4568:     }
 4569:   fprintf(ficrescveij,"\n");
 4570:   
 4571:   if(estepm < stepm){
 4572:     printf ("Problem %d lower than %d\n",estepm, stepm);
 4573:   }
 4574:   else  hstepm=estepm;   
 4575:   /* We compute the life expectancy from trapezoids spaced every estepm months
 4576:    * This is mainly to measure the difference between two models: for example
 4577:    * if stepm=24 months pijx are given only every 2 years and by summing them
 4578:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 4579:    * progression in between and thus overestimating or underestimating according
 4580:    * to the curvature of the survival function. If, for the same date, we 
 4581:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 4582:    * to compare the new estimate of Life expectancy with the same linear 
 4583:    * hypothesis. A more precise result, taking into account a more precise
 4584:    * curvature will be obtained if estepm is as small as stepm. */
 4585: 
 4586:   /* For example we decided to compute the life expectancy with the smallest unit */
 4587:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 4588:      nhstepm is the number of hstepm from age to agelim 
 4589:      nstepm is the number of stepm from age to agelin. 
 4590:      Look at hpijx to understand the reason of that which relies in memory size
 4591:      and note for a fixed period like estepm months */
 4592:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 4593:      survival function given by stepm (the optimization length). Unfortunately it
 4594:      means that if the survival funtion is printed only each two years of age and if
 4595:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 4596:      results. So we changed our mind and took the option of the best precision.
 4597:   */
 4598:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 4599: 
 4600:   /* If stepm=6 months */
 4601:   /* nhstepm age range expressed in number of stepm */
 4602:   agelim=AGESUP;
 4603:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
 4604:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 4605:   /* if (stepm >= YEARM) hstepm=1;*/
 4606:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 4607:   
 4608:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4609:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4610:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
 4611:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
 4612:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
 4613:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
 4614: 
 4615:   for (age=bage; age<=fage; age ++){ 
 4616:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 4617:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 4618:     /* if (stepm >= YEARM) hstepm=1;*/
 4619:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 4620: 		
 4621:     /* If stepm=6 months */
 4622:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 4623:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 4624:     
 4625:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 4626: 		
 4627:     /* Computing  Variances of health expectancies */
 4628:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
 4629:        decrease memory allocation */
 4630:     for(theta=1; theta <=npar; theta++){
 4631:       for(i=1; i<=npar; i++){ 
 4632: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 4633: 	xm[i] = x[i] - (i==theta ?delti[theta]:0);
 4634:       }
 4635:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
 4636:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
 4637: 			
 4638:       for(j=1; j<= nlstate; j++){
 4639: 	for(i=1; i<=nlstate; i++){
 4640: 	  for(h=0; h<=nhstepm-1; h++){
 4641: 	    gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
 4642: 	    gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
 4643: 	  }
 4644: 	}
 4645:       }
 4646: 			
 4647:       for(ij=1; ij<= nlstate*nlstate; ij++)
 4648: 	for(h=0; h<=nhstepm-1; h++){
 4649: 	  gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
 4650: 	}
 4651:     }/* End theta */
 4652:     
 4653:     
 4654:     for(h=0; h<=nhstepm-1; h++)
 4655:       for(j=1; j<=nlstate*nlstate;j++)
 4656: 	for(theta=1; theta <=npar; theta++)
 4657: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 4658:     
 4659: 		
 4660:     for(ij=1;ij<=nlstate*nlstate;ij++)
 4661:       for(ji=1;ji<=nlstate*nlstate;ji++)
 4662: 	varhe[ij][ji][(int)age] =0.;
 4663: 		
 4664:     printf("%d|",(int)age);fflush(stdout);
 4665:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 4666:     for(h=0;h<=nhstepm-1;h++){
 4667:       for(k=0;k<=nhstepm-1;k++){
 4668: 	matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
 4669: 	matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
 4670: 	for(ij=1;ij<=nlstate*nlstate;ij++)
 4671: 	  for(ji=1;ji<=nlstate*nlstate;ji++)
 4672: 	    varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
 4673:       }
 4674:     }
 4675: 		
 4676:     /* Computing expectancies */
 4677:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 4678:     for(i=1; i<=nlstate;i++)
 4679:       for(j=1; j<=nlstate;j++)
 4680: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 4681: 	  eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
 4682: 					
 4683: 	  /* 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]);*/
 4684: 					
 4685: 	}
 4686: 		
 4687:     fprintf(ficresstdeij,"%3.0f",age );
 4688:     for(i=1; i<=nlstate;i++){
 4689:       eip=0.;
 4690:       vip=0.;
 4691:       for(j=1; j<=nlstate;j++){
 4692: 	eip += eij[i][j][(int)age];
 4693: 	for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
 4694: 	  vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
 4695: 	fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
 4696:       }
 4697:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
 4698:     }
 4699:     fprintf(ficresstdeij,"\n");
 4700: 		
 4701:     fprintf(ficrescveij,"%3.0f",age );
 4702:     for(i=1; i<=nlstate;i++)
 4703:       for(j=1; j<=nlstate;j++){
 4704: 	cptj= (j-1)*nlstate+i;
 4705: 	for(i2=1; i2<=nlstate;i2++)
 4706: 	  for(j2=1; j2<=nlstate;j2++){
 4707: 	    cptj2= (j2-1)*nlstate+i2;
 4708: 	    if(cptj2 <= cptj)
 4709: 	      fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
 4710: 	  }
 4711:       }
 4712:     fprintf(ficrescveij,"\n");
 4713: 		
 4714:   }
 4715:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
 4716:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
 4717:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
 4718:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
 4719:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4720:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4721:   printf("\n");
 4722:   fprintf(ficlog,"\n");
 4723: 	
 4724:   free_vector(xm,1,npar);
 4725:   free_vector(xp,1,npar);
 4726:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
 4727:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
 4728:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
 4729: }
 4730:  
 4731: /************ Variance ******************/
 4732:  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[])
 4733:  {
 4734:    /* Variance of health expectancies */
 4735:    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
 4736:    /* double **newm;*/
 4737:    /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
 4738:   
 4739:    /* int movingaverage(); */
 4740:    double **dnewm,**doldm;
 4741:    double **dnewmp,**doldmp;
 4742:    int i, j, nhstepm, hstepm, h, nstepm ;
 4743:    int k;
 4744:    double *xp;
 4745:    double **gp, **gm;  /* for var eij */
 4746:    double ***gradg, ***trgradg; /*for var eij */
 4747:    double **gradgp, **trgradgp; /* for var p point j */
 4748:    double *gpp, *gmp; /* for var p point j */
 4749:    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
 4750:    double ***p3mat;
 4751:    double age,agelim, hf;
 4752:    /* double ***mobaverage; */
 4753:    int theta;
 4754:    char digit[4];
 4755:    char digitp[25];
 4756: 
 4757:    char fileresprobmorprev[FILENAMELENGTH];
 4758: 
 4759:    if(popbased==1){
 4760:      if(mobilav!=0)
 4761:        strcpy(digitp,"-POPULBASED-MOBILAV_");
 4762:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
 4763:    }
 4764:    else 
 4765:      strcpy(digitp,"-STABLBASED_");
 4766: 
 4767:    /* if (mobilav!=0) { */
 4768:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 4769:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
 4770:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
 4771:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
 4772:    /*   } */
 4773:    /* } */
 4774: 
 4775:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
 4776:    sprintf(digit,"%-d",ij);
 4777:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
 4778:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
 4779:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
 4780:    strcat(fileresprobmorprev,fileresu);
 4781:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
 4782:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
 4783:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
 4784:    }
 4785:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 4786:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 4787:    pstamp(ficresprobmorprev);
 4788:    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);
 4789:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
 4790:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 4791:      fprintf(ficresprobmorprev," p.%-d SE",j);
 4792:      for(i=1; i<=nlstate;i++)
 4793:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 4794:    }  
 4795:    fprintf(ficresprobmorprev,"\n");
 4796:   
 4797:    fprintf(ficgp,"\n# Routine varevsij");
 4798:    fprintf(ficgp,"\nunset title \n");
 4799:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
 4800:    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");
 4801:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
 4802:    /*   } */
 4803:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 4804:    pstamp(ficresvij);
 4805:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
 4806:    if(popbased==1)
 4807:      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);
 4808:    else
 4809:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
 4810:    fprintf(ficresvij,"# Age");
 4811:    for(i=1; i<=nlstate;i++)
 4812:      for(j=1; j<=nlstate;j++)
 4813:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
 4814:    fprintf(ficresvij,"\n");
 4815: 
 4816:    xp=vector(1,npar);
 4817:    dnewm=matrix(1,nlstate,1,npar);
 4818:    doldm=matrix(1,nlstate,1,nlstate);
 4819:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
 4820:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 4821: 
 4822:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
 4823:    gpp=vector(nlstate+1,nlstate+ndeath);
 4824:    gmp=vector(nlstate+1,nlstate+ndeath);
 4825:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 4826:   
 4827:    if(estepm < stepm){
 4828:      printf ("Problem %d lower than %d\n",estepm, stepm);
 4829:    }
 4830:    else  hstepm=estepm;   
 4831:    /* For example we decided to compute the life expectancy with the smallest unit */
 4832:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 4833:       nhstepm is the number of hstepm from age to agelim 
 4834:       nstepm is the number of stepm from age to agelim. 
 4835:       Look at function hpijx to understand why because of memory size limitations, 
 4836:       we decided (b) to get a life expectancy respecting the most precise curvature of the
 4837:       survival function given by stepm (the optimization length). Unfortunately it
 4838:       means that if the survival funtion is printed every two years of age and if
 4839:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 4840:       results. So we changed our mind and took the option of the best precision.
 4841:    */
 4842:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 4843:    agelim = AGESUP;
 4844:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 4845:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 4846:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 4847:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4848:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
 4849:      gp=matrix(0,nhstepm,1,nlstate);
 4850:      gm=matrix(0,nhstepm,1,nlstate);
 4851: 		
 4852: 		
 4853:      for(theta=1; theta <=npar; theta++){
 4854:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
 4855: 	 xp[i] = x[i] + (i==theta ?delti[theta]:0);
 4856:        }
 4857: 			
 4858:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 4859: 			
 4860:        if (popbased==1) {
 4861: 	 if(mobilav ==0){
 4862: 	   for(i=1; i<=nlstate;i++)
 4863: 	     prlim[i][i]=probs[(int)age][i][ij];
 4864: 	 }else{ /* mobilav */ 
 4865: 	   for(i=1; i<=nlstate;i++)
 4866: 	     prlim[i][i]=mobaverage[(int)age][i][ij];
 4867: 	 }
 4868:        }
 4869: 			
 4870:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
 4871:        for(j=1; j<= nlstate; j++){
 4872: 	 for(h=0; h<=nhstepm; h++){
 4873: 	   for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 4874: 	     gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 4875: 	 }
 4876:        }
 4877:        /* Next for computing probability of death (h=1 means
 4878: 	  computed over hstepm matrices product = hstepm*stepm months) 
 4879: 	  as a weighted average of prlim.
 4880:        */
 4881:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
 4882: 	 for(i=1,gpp[j]=0.; i<= nlstate; i++)
 4883: 	   gpp[j] += prlim[i][i]*p3mat[i][j][1];
 4884:        }    
 4885:        /* end probability of death */
 4886: 			
 4887:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
 4888: 	 xp[i] = x[i] - (i==theta ?delti[theta]:0);
 4889: 			
 4890:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
 4891: 			
 4892:        if (popbased==1) {
 4893: 	 if(mobilav ==0){
 4894: 	   for(i=1; i<=nlstate;i++)
 4895: 	     prlim[i][i]=probs[(int)age][i][ij];
 4896: 	 }else{ /* mobilav */ 
 4897: 	   for(i=1; i<=nlstate;i++)
 4898: 	     prlim[i][i]=mobaverage[(int)age][i][ij];
 4899: 	 }
 4900:        }
 4901: 			
 4902:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 4903: 			
 4904:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
 4905: 	 for(h=0; h<=nhstepm; h++){
 4906: 	   for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 4907: 	     gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 4908: 	 }
 4909:        }
 4910:        /* This for computing probability of death (h=1 means
 4911: 	  computed over hstepm matrices product = hstepm*stepm months) 
 4912: 	  as a weighted average of prlim.
 4913:        */
 4914:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
 4915: 	 for(i=1,gmp[j]=0.; i<= nlstate; i++)
 4916: 	   gmp[j] += prlim[i][i]*p3mat[i][j][1];
 4917:        }    
 4918:        /* end probability of death */
 4919: 			
 4920:        for(j=1; j<= nlstate; j++) /* vareij */
 4921: 	 for(h=0; h<=nhstepm; h++){
 4922: 	   gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 4923: 	 }
 4924: 			
 4925:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
 4926: 	 gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
 4927:        }
 4928: 			
 4929:      } /* End theta */
 4930: 		
 4931:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
 4932: 		
 4933:      for(h=0; h<=nhstepm; h++) /* veij */
 4934:        for(j=1; j<=nlstate;j++)
 4935: 	 for(theta=1; theta <=npar; theta++)
 4936: 	   trgradg[h][j][theta]=gradg[h][theta][j];
 4937: 		
 4938:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
 4939:        for(theta=1; theta <=npar; theta++)
 4940: 	 trgradgp[j][theta]=gradgp[theta][j];
 4941: 		
 4942: 		
 4943:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 4944:      for(i=1;i<=nlstate;i++)
 4945:        for(j=1;j<=nlstate;j++)
 4946: 	 vareij[i][j][(int)age] =0.;
 4947: 		
 4948:      for(h=0;h<=nhstepm;h++){
 4949:        for(k=0;k<=nhstepm;k++){
 4950: 	 matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 4951: 	 matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
 4952: 	 for(i=1;i<=nlstate;i++)
 4953: 	   for(j=1;j<=nlstate;j++)
 4954: 	     vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
 4955:        }
 4956:      }
 4957: 		
 4958:      /* pptj */
 4959:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
 4960:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
 4961:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
 4962:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
 4963: 	 varppt[j][i]=doldmp[j][i];
 4964:      /* end ppptj */
 4965:      /*  x centered again */
 4966: 		
 4967:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
 4968: 		
 4969:      if (popbased==1) {
 4970:        if(mobilav ==0){
 4971: 	 for(i=1; i<=nlstate;i++)
 4972: 	   prlim[i][i]=probs[(int)age][i][ij];
 4973:        }else{ /* mobilav */ 
 4974: 	 for(i=1; i<=nlstate;i++)
 4975: 	   prlim[i][i]=mobaverage[(int)age][i][ij];
 4976:        }
 4977:      }
 4978: 		
 4979:      /* This for computing probability of death (h=1 means
 4980: 	computed over hstepm (estepm) matrices product = hstepm*stepm months) 
 4981: 	as a weighted average of prlim.
 4982:      */
 4983:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
 4984:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
 4985:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
 4986: 	 gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
 4987:      }    
 4988:      /* end probability of death */
 4989: 		
 4990:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
 4991:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 4992:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
 4993:        for(i=1; i<=nlstate;i++){
 4994: 	 fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 4995:        }
 4996:      } 
 4997:      fprintf(ficresprobmorprev,"\n");
 4998: 		
 4999:      fprintf(ficresvij,"%.0f ",age );
 5000:      for(i=1; i<=nlstate;i++)
 5001:        for(j=1; j<=nlstate;j++){
 5002: 	 fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
 5003:        }
 5004:      fprintf(ficresvij,"\n");
 5005:      free_matrix(gp,0,nhstepm,1,nlstate);
 5006:      free_matrix(gm,0,nhstepm,1,nlstate);
 5007:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 5008:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 5009:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5010:    } /* End age */
 5011:    free_vector(gpp,nlstate+1,nlstate+ndeath);
 5012:    free_vector(gmp,nlstate+1,nlstate+ndeath);
 5013:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
 5014:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 5015:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
 5016:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
 5017:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
 5018:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
 5019:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
 5020:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
 5021:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
 5022:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
 5023:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
 5024:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
 5025:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
 5026:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
 5027:    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);
 5028:    /*  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);
 5029:     */
 5030:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
 5031:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
 5032: 
 5033:    free_vector(xp,1,npar);
 5034:    free_matrix(doldm,1,nlstate,1,nlstate);
 5035:    free_matrix(dnewm,1,nlstate,1,npar);
 5036:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 5037:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
 5038:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 5039:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 5040:    fclose(ficresprobmorprev);
 5041:    fflush(ficgp);
 5042:    fflush(fichtm); 
 5043:  }  /* end varevsij */
 5044: 
 5045: /************ Variance of prevlim ******************/
 5046:  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[])
 5047: {
 5048:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
 5049:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 5050: 
 5051:   double **dnewm,**doldm;
 5052:   int i, j, nhstepm, hstepm;
 5053:   double *xp;
 5054:   double *gp, *gm;
 5055:   double **gradg, **trgradg;
 5056:   double **mgm, **mgp;
 5057:   double age,agelim;
 5058:   int theta;
 5059:   
 5060:   pstamp(ficresvpl);
 5061:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
 5062:   fprintf(ficresvpl,"# Age");
 5063:   for(i=1; i<=nlstate;i++)
 5064:       fprintf(ficresvpl," %1d-%1d",i,i);
 5065:   fprintf(ficresvpl,"\n");
 5066: 
 5067:   xp=vector(1,npar);
 5068:   dnewm=matrix(1,nlstate,1,npar);
 5069:   doldm=matrix(1,nlstate,1,nlstate);
 5070:   
 5071:   hstepm=1*YEARM; /* Every year of age */
 5072:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 5073:   agelim = AGESUP;
 5074:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 5075:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 5076:     if (stepm >= YEARM) hstepm=1;
 5077:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 5078:     gradg=matrix(1,npar,1,nlstate);
 5079:     mgp=matrix(1,npar,1,nlstate);
 5080:     mgm=matrix(1,npar,1,nlstate);
 5081:     gp=vector(1,nlstate);
 5082:     gm=vector(1,nlstate);
 5083: 
 5084:     for(theta=1; theta <=npar; theta++){
 5085:       for(i=1; i<=npar; i++){ /* Computes gradient */
 5086: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 5087:       }
 5088:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
 5089: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 5090:       else
 5091: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 5092:       for(i=1;i<=nlstate;i++){
 5093: 	gp[i] = prlim[i][i];
 5094: 	mgp[theta][i] = prlim[i][i];
 5095:       }
 5096:       for(i=1; i<=npar; i++) /* Computes gradient */
 5097: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 5098:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
 5099: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 5100:       else
 5101: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 5102:       for(i=1;i<=nlstate;i++){
 5103: 	gm[i] = prlim[i][i];
 5104: 	mgm[theta][i] = prlim[i][i];
 5105:       }
 5106:       for(i=1;i<=nlstate;i++)
 5107: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 5108:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
 5109:     } /* End theta */
 5110: 
 5111:     trgradg =matrix(1,nlstate,1,npar);
 5112: 
 5113:     for(j=1; j<=nlstate;j++)
 5114:       for(theta=1; theta <=npar; theta++)
 5115: 	trgradg[j][theta]=gradg[theta][j];
 5116:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
 5117:     /*   printf("\nmgm mgp %d ",(int)age); */
 5118:     /*   for(j=1; j<=nlstate;j++){ */
 5119:     /* 	printf(" %d ",j); */
 5120:     /* 	for(theta=1; theta <=npar; theta++) */
 5121:     /* 	  printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
 5122:     /* 	printf("\n "); */
 5123:     /*   } */
 5124:     /* } */
 5125:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
 5126:     /*   printf("\n gradg %d ",(int)age); */
 5127:     /*   for(j=1; j<=nlstate;j++){ */
 5128:     /* 	printf("%d ",j); */
 5129:     /* 	for(theta=1; theta <=npar; theta++) */
 5130:     /* 	  printf("%d %lf ",theta,gradg[theta][j]); */
 5131:     /* 	printf("\n "); */
 5132:     /*   } */
 5133:     /* } */
 5134: 
 5135:     for(i=1;i<=nlstate;i++)
 5136:       varpl[i][(int)age] =0.;
 5137:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
 5138:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 5139:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 5140:     }else{
 5141:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 5142:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 5143:     }
 5144:     for(i=1;i<=nlstate;i++)
 5145:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 5146: 
 5147:     fprintf(ficresvpl,"%.0f ",age );
 5148:     for(i=1; i<=nlstate;i++)
 5149:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
 5150:     fprintf(ficresvpl,"\n");
 5151:     free_vector(gp,1,nlstate);
 5152:     free_vector(gm,1,nlstate);
 5153:     free_matrix(mgm,1,npar,1,nlstate);
 5154:     free_matrix(mgp,1,npar,1,nlstate);
 5155:     free_matrix(gradg,1,npar,1,nlstate);
 5156:     free_matrix(trgradg,1,nlstate,1,npar);
 5157:   } /* End age */
 5158: 
 5159:   free_vector(xp,1,npar);
 5160:   free_matrix(doldm,1,nlstate,1,npar);
 5161:   free_matrix(dnewm,1,nlstate,1,nlstate);
 5162: 
 5163: }
 5164: 
 5165: /************ Variance of one-step probabilities  ******************/
 5166: 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[])
 5167:  {
 5168:    int i, j=0,  k1, l1, tj;
 5169:    int k2, l2, j1,  z1;
 5170:    int k=0, l;
 5171:    int first=1, first1, first2;
 5172:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
 5173:    double **dnewm,**doldm;
 5174:    double *xp;
 5175:    double *gp, *gm;
 5176:    double **gradg, **trgradg;
 5177:    double **mu;
 5178:    double age, cov[NCOVMAX+1];
 5179:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
 5180:    int theta;
 5181:    char fileresprob[FILENAMELENGTH];
 5182:    char fileresprobcov[FILENAMELENGTH];
 5183:    char fileresprobcor[FILENAMELENGTH];
 5184:    double ***varpij;
 5185: 
 5186:    strcpy(fileresprob,"PROB_"); 
 5187:    strcat(fileresprob,fileres);
 5188:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
 5189:      printf("Problem with resultfile: %s\n", fileresprob);
 5190:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
 5191:    }
 5192:    strcpy(fileresprobcov,"PROBCOV_"); 
 5193:    strcat(fileresprobcov,fileresu);
 5194:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
 5195:      printf("Problem with resultfile: %s\n", fileresprobcov);
 5196:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 5197:    }
 5198:    strcpy(fileresprobcor,"PROBCOR_"); 
 5199:    strcat(fileresprobcor,fileresu);
 5200:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 5201:      printf("Problem with resultfile: %s\n", fileresprobcor);
 5202:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 5203:    }
 5204:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 5205:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 5206:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 5207:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 5208:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 5209:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 5210:    pstamp(ficresprob);
 5211:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
 5212:    fprintf(ficresprob,"# Age");
 5213:    pstamp(ficresprobcov);
 5214:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
 5215:    fprintf(ficresprobcov,"# Age");
 5216:    pstamp(ficresprobcor);
 5217:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 5218:    fprintf(ficresprobcor,"# Age");
 5219: 
 5220: 
 5221:    for(i=1; i<=nlstate;i++)
 5222:      for(j=1; j<=(nlstate+ndeath);j++){
 5223:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
 5224:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
 5225:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
 5226:      }  
 5227:    /* fprintf(ficresprob,"\n");
 5228:       fprintf(ficresprobcov,"\n");
 5229:       fprintf(ficresprobcor,"\n");
 5230:    */
 5231:    xp=vector(1,npar);
 5232:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 5233:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 5234:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
 5235:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 5236:    first=1;
 5237:    fprintf(ficgp,"\n# Routine varprob");
 5238:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
 5239:    fprintf(fichtm,"\n");
 5240: 
 5241:    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);
 5242:    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);
 5243:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
 5244: and drawn. It helps understanding how is the covariance between two incidences.\
 5245:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
 5246:    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. \
 5247: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
 5248: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
 5249: standard deviations wide on each axis. <br>\
 5250:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
 5251:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 5252: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
 5253: 
 5254:    cov[1]=1;
 5255:    /* tj=cptcoveff; */
 5256:    tj = (int) pow(2,cptcoveff);
 5257:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
 5258:    j1=0;
 5259:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates */
 5260:      if  (cptcovn>0) {
 5261:        fprintf(ficresprob, "\n#********** Variable "); 
 5262:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5263:        fprintf(ficresprob, "**********\n#\n");
 5264:        fprintf(ficresprobcov, "\n#********** Variable "); 
 5265:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5266:        fprintf(ficresprobcov, "**********\n#\n");
 5267: 			
 5268:        fprintf(ficgp, "\n#********** Variable "); 
 5269:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5270:        fprintf(ficgp, "**********\n#\n");
 5271: 			
 5272: 			
 5273:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
 5274:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5275:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
 5276: 			
 5277:        fprintf(ficresprobcor, "\n#********** Variable ");    
 5278:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5279:        fprintf(ficresprobcor, "**********\n#");    
 5280:        if(invalidvarcomb[j1]){
 5281: 	 fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
 5282: 	 fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
 5283: 	 continue;
 5284:        }
 5285:      }
 5286:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
 5287:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 5288:      gp=vector(1,(nlstate)*(nlstate+ndeath));
 5289:      gm=vector(1,(nlstate)*(nlstate+ndeath));
 5290:      for (age=bage; age<=fage; age ++){ 
 5291:        cov[2]=age;
 5292:        if(nagesqr==1)
 5293: 	 cov[3]= age*age;
 5294:        for (k=1; k<=cptcovn;k++) {
 5295: 	 cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
 5296: 	 /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
 5297: 								    * 1  1 1 1 1
 5298: 								    * 2  2 1 1 1
 5299: 								    * 3  1 2 1 1
 5300: 								    */
 5301: 	 /* nbcode[1][1]=0 nbcode[1][2]=1;*/
 5302:        }
 5303:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 5304:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 5305:        for (k=1; k<=cptcovprod;k++)
 5306: 	 cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
 5307: 			
 5308: 			
 5309:        for(theta=1; theta <=npar; theta++){
 5310: 	 for(i=1; i<=npar; i++)
 5311: 	   xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
 5312: 				
 5313: 	 pmij(pmmij,cov,ncovmodel,xp,nlstate);
 5314: 				
 5315: 	 k=0;
 5316: 	 for(i=1; i<= (nlstate); i++){
 5317: 	   for(j=1; j<=(nlstate+ndeath);j++){
 5318: 	     k=k+1;
 5319: 	     gp[k]=pmmij[i][j];
 5320: 	   }
 5321: 	 }
 5322: 				
 5323: 	 for(i=1; i<=npar; i++)
 5324: 	   xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
 5325: 				
 5326: 	 pmij(pmmij,cov,ncovmodel,xp,nlstate);
 5327: 	 k=0;
 5328: 	 for(i=1; i<=(nlstate); i++){
 5329: 	   for(j=1; j<=(nlstate+ndeath);j++){
 5330: 	     k=k+1;
 5331: 	     gm[k]=pmmij[i][j];
 5332: 	   }
 5333: 	 }
 5334: 				
 5335: 	 for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
 5336: 	   gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
 5337:        }
 5338: 
 5339:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
 5340: 	 for(theta=1; theta <=npar; theta++)
 5341: 	   trgradg[j][theta]=gradg[theta][j];
 5342: 			
 5343:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
 5344:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
 5345: 			
 5346:        pmij(pmmij,cov,ncovmodel,x,nlstate);
 5347: 			
 5348:        k=0;
 5349:        for(i=1; i<=(nlstate); i++){
 5350: 	 for(j=1; j<=(nlstate+ndeath);j++){
 5351: 	   k=k+1;
 5352: 	   mu[k][(int) age]=pmmij[i][j];
 5353: 	 }
 5354:        }
 5355:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 5356: 	 for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 5357: 	   varpij[i][j][(int)age] = doldm[i][j];
 5358: 			
 5359:        /*printf("\n%d ",(int)age);
 5360: 	 for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 5361: 	 printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 5362: 	 fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 5363: 	 }*/
 5364: 			
 5365:        fprintf(ficresprob,"\n%d ",(int)age);
 5366:        fprintf(ficresprobcov,"\n%d ",(int)age);
 5367:        fprintf(ficresprobcor,"\n%d ",(int)age);
 5368: 			
 5369:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
 5370: 	 fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
 5371:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 5372: 	 fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
 5373: 	 fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
 5374:        }
 5375:        i=0;
 5376:        for (k=1; k<=(nlstate);k++){
 5377: 	 for (l=1; l<=(nlstate+ndeath);l++){ 
 5378: 	   i++;
 5379: 	   fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 5380: 	   fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
 5381: 	   for (j=1; j<=i;j++){
 5382: 	     /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
 5383: 	     fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
 5384: 	     fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
 5385: 	   }
 5386: 	 }
 5387:        }/* end of loop for state */
 5388:      } /* end of loop for age */
 5389:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
 5390:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 5391:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 5392:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 5393:     
 5394:      /* Confidence intervalle of pij  */
 5395:      /*
 5396:        fprintf(ficgp,"\nunset parametric;unset label");
 5397:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
 5398:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 5399:        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);
 5400:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
 5401:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
 5402:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
 5403:      */
 5404: 		
 5405:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
 5406:      first1=1;first2=2;
 5407:      for (k2=1; k2<=(nlstate);k2++){
 5408:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
 5409: 	 if(l2==k2) continue;
 5410: 	 j=(k2-1)*(nlstate+ndeath)+l2;
 5411: 	 for (k1=1; k1<=(nlstate);k1++){
 5412: 	   for (l1=1; l1<=(nlstate+ndeath);l1++){ 
 5413: 	     if(l1==k1) continue;
 5414: 	     i=(k1-1)*(nlstate+ndeath)+l1;
 5415: 	     if(i<=j) continue;
 5416: 	     for (age=bage; age<=fage; age ++){ 
 5417: 	       if ((int)age %5==0){
 5418: 		 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
 5419: 		 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
 5420: 		 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
 5421: 		 mu1=mu[i][(int) age]/stepm*YEARM ;
 5422: 		 mu2=mu[j][(int) age]/stepm*YEARM;
 5423: 		 c12=cv12/sqrt(v1*v2);
 5424: 		 /* Computing eigen value of matrix of covariance */
 5425: 		 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 5426: 		 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 5427: 		 if ((lc2 <0) || (lc1 <0) ){
 5428: 		   if(first2==1){
 5429: 		     first1=0;
 5430: 		     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);
 5431: 		   }
 5432: 		   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);
 5433: 		   /* lc1=fabs(lc1); */ /* If we want to have them positive */
 5434: 		   /* lc2=fabs(lc2); */
 5435: 		 }
 5436: 								
 5437: 		 /* Eigen vectors */
 5438: 		 v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
 5439: 		 /*v21=sqrt(1.-v11*v11); *//* error */
 5440: 		 v21=(lc1-v1)/cv12*v11;
 5441: 		 v12=-v21;
 5442: 		 v22=v11;
 5443: 		 tnalp=v21/v11;
 5444: 		 if(first1==1){
 5445: 		   first1=0;
 5446: 		   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);
 5447: 		 }
 5448: 		 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);
 5449: 		 /*printf(fignu*/
 5450: 		 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
 5451: 		 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
 5452: 		 if(first==1){
 5453: 		   first=0;
 5454: 		   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
 5455: 		   fprintf(ficgp,"\nset parametric;unset label");
 5456: 		   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);
 5457: 		   fprintf(ficgp,"\nset ter svg size 640, 480");
 5458: 		   fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
 5459:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">																		\
 5460: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
 5461: 			   subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,	\
 5462: 			   subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 5463: 		   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 5464: 		   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
 5465: 		   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 5466: 		   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 5467: 		   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 5468: 		   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",	\
 5469: 			   mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),										\
 5470: 			   mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 5471: 		 }else{
 5472: 		   first=0;
 5473: 		   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
 5474: 		   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 5475: 		   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 5476: 		   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", \
 5477: 			   mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),					\
 5478: 			   mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 5479: 		 }/* if first */
 5480: 	       } /* age mod 5 */
 5481: 	     } /* end loop age */
 5482: 	     fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 5483: 	     first=1;
 5484: 	   } /*l12 */
 5485: 	 } /* k12 */
 5486:        } /*l1 */
 5487:      }/* k1 */
 5488:    }  /* loop on combination of covariates j1 */
 5489:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 5490:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
 5491:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 5492:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
 5493:    free_vector(xp,1,npar);
 5494:    fclose(ficresprob);
 5495:    fclose(ficresprobcov);
 5496:    fclose(ficresprobcor);
 5497:    fflush(ficgp);
 5498:    fflush(fichtmcov);
 5499:  }
 5500: 
 5501: 
 5502: /******************* Printing html file ***********/
 5503: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
 5504: 		  int lastpass, int stepm, int weightopt, char model[],\
 5505: 		  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 5506: 		  int popforecast, int prevfcast, int backcast, int estepm , \
 5507: 		  double jprev1, double mprev1,double anprev1, double dateprev1, \
 5508: 		  double jprev2, double mprev2,double anprev2, double dateprev2){
 5509:   int jj1, k1, i1, cpt;
 5510: 
 5511:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
 5512:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
 5513: </ul>");
 5514:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
 5515:    fprintf(fichtm,"<li>- Observed frequency between two states (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> (html file)<br/>\n",
 5516: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
 5517:    fprintf(fichtm,"<li> - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> (html file) ",
 5518: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
 5519:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
 5520:    fprintf(fichtm,"\
 5521:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 5522: 	   stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
 5523:    fprintf(fichtm,"\
 5524:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 5525: 	   stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
 5526:    fprintf(fichtm,"\
 5527:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 5528: 	   subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
 5529:    fprintf(fichtm,"\
 5530:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 5531: 	   subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
 5532:    fprintf(fichtm,"\
 5533:  - (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): \
 5534:    <a href=\"%s\">%s</a> <br>\n",
 5535: 	   estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
 5536:    if(prevfcast==1){
 5537:      fprintf(fichtm,"\
 5538:  - Prevalence projections by age and states:				\
 5539:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
 5540:    }
 5541: 
 5542:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
 5543: 
 5544:    m=pow(2,cptcoveff);
 5545:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 5546: 
 5547:    jj1=0;
 5548:    for(k1=1; k1<=m;k1++){
 5549: 
 5550:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
 5551:      jj1++;
 5552:      if (cptcovn > 0) {
 5553:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 5554:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
 5555: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
 5556: 	 printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
 5557:        }
 5558:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 5559:        if(invalidvarcomb[k1]){
 5560: 	 fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
 5561: 	 printf("\nCombination (%d) ignored because no cases \n",k1); 
 5562: 	 continue;
 5563:        }
 5564:      }
 5565:      /* aij, bij */
 5566:      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> \
 5567: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
 5568:      /* Pij */
 5569:      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> \
 5570: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
 5571:      /* Quasi-incidences */
 5572:      fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
 5573:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
 5574:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
 5575: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
 5576: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
 5577:      /* Survival functions (period) in state j */
 5578:      for(cpt=1; cpt<=nlstate;cpt++){
 5579:        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> \
 5580: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
 5581:      }
 5582:      /* State specific survival functions (period) */
 5583:      for(cpt=1; cpt<=nlstate;cpt++){
 5584:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
 5585:  Or probability to survive in various states (1 to %d) being in state %d at different ages.	\
 5586:  <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);
 5587:      }
 5588:      /* Period (stable) prevalence in each health state */
 5589:      for(cpt=1; cpt<=nlstate;cpt++){
 5590:        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> \
 5591: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
 5592:      }
 5593:      if(backcast==1){
 5594:        /* Period (stable) back prevalence in each health state */
 5595:        for(cpt=1; cpt<=nlstate;cpt++){
 5596: 	 fprintf(fichtm,"<br>\n- Convergence to period (stable) back 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> \
 5597: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1);
 5598:        }
 5599:      }
 5600:      if(prevfcast==1){
 5601:        /* Projection of prevalence up to period (stable) prevalence in each health state */
 5602:        for(cpt=1; cpt<=nlstate;cpt++){
 5603: 	 fprintf(fichtm,"<br>\n- Projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f) 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> \
 5604: <img src=\"%s_%d-%d.svg\">", dateprev1, dateprev2, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1);
 5605:        }
 5606:      }
 5607: 	 
 5608:      for(cpt=1; cpt<=nlstate;cpt++) {
 5609:        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> \
 5610: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
 5611:      }
 5612:      /* } /\* end i1 *\/ */
 5613:    }/* End k1 */
 5614:    fprintf(fichtm,"</ul>");
 5615: 
 5616:    fprintf(fichtm,"\
 5617: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
 5618:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
 5619:  - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
 5620: But because parameters are usually highly correlated (a higher incidence of disability \
 5621: and a higher incidence of recovery can give very close observed transition) it might \
 5622: be very useful to look not only at linear confidence intervals estimated from the \
 5623: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
 5624: (parameters) of the logistic regression, it might be more meaningful to visualize the \
 5625: covariance matrix of the one-step probabilities. \
 5626: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
 5627: 
 5628:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 5629: 	   subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
 5630:    fprintf(fichtm,"\
 5631:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 5632: 	   subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
 5633: 
 5634:    fprintf(fichtm,"\
 5635:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 5636: 	   subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
 5637:    fprintf(fichtm,"\
 5638:  - 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): \
 5639:    <a href=\"%s\">%s</a> <br>\n</li>",
 5640: 	   estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
 5641:    fprintf(fichtm,"\
 5642:  - (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): \
 5643:    <a href=\"%s\">%s</a> <br>\n</li>",
 5644: 	   estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
 5645:    fprintf(fichtm,"\
 5646:  - 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",
 5647: 	   estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
 5648:    fprintf(fichtm,"\
 5649:  - 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",
 5650: 	   estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
 5651:    fprintf(fichtm,"\
 5652:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
 5653: 	   subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
 5654: 
 5655: /*  if(popforecast==1) fprintf(fichtm,"\n */
 5656: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
 5657: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
 5658: /* 	<br>",fileres,fileres,fileres,fileres); */
 5659: /*  else  */
 5660: /*    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); */
 5661:    fflush(fichtm);
 5662:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
 5663: 
 5664:    m=pow(2,cptcoveff);
 5665:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 5666: 
 5667:    jj1=0;
 5668:    for(k1=1; k1<=m;k1++){
 5669:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
 5670:      jj1++;
 5671:      if (cptcovn > 0) {
 5672:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 5673:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 5674: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
 5675:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 5676: 
 5677:        if(invalidvarcomb[k1]){
 5678: 	 fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
 5679: 	 continue;
 5680:        }
 5681:      }
 5682:      for(cpt=1; cpt<=nlstate;cpt++) {
 5683:        fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
 5684: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d.svg\"> %s_%d-%d.svg</a>\n <br>\
 5685: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);  
 5686:      }
 5687:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
 5688: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
 5689: true period expectancies (those weighted with period prevalences are also\
 5690:  drawn in addition to the population based expectancies computed using\
 5691:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg</a>\n<br>\
 5692: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
 5693:      /* } /\* end i1 *\/ */
 5694:    }/* End k1 */
 5695:    fprintf(fichtm,"</ul>");
 5696:    fflush(fichtm);
 5697: }
 5698: 
 5699: /******************* Gnuplot file **************/
 5700:  void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
 5701: 
 5702:   char dirfileres[132],optfileres[132];
 5703: 	char gplotcondition[132];
 5704:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
 5705:   int lv=0, vlv=0, kl=0;
 5706:   int ng=0;
 5707:   int vpopbased;
 5708: 	int ioffset; /* variable offset for columns */
 5709: 
 5710: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
 5711: /*     printf("Problem with file %s",optionfilegnuplot); */
 5712: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
 5713: /*   } */
 5714: 
 5715:   /*#ifdef windows */
 5716:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 5717:     /*#endif */
 5718:   m=pow(2,cptcoveff);
 5719: 
 5720:   /* Contribution to likelihood */
 5721:   /* Plot the probability implied in the likelihood */
 5722:     fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
 5723:     fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
 5724:     /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
 5725:     fprintf(ficgp,"\nset ter pngcairo size 640, 480");
 5726: /* nice for mle=4 plot by number of matrix products.
 5727:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
 5728: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
 5729:     /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
 5730:     fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
 5731:     fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$13):6 t \"All sample, transitions colored by destination\" with dots lc variable; set out;\n",subdirf(fileresilk));
 5732:     fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
 5733:     fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$13):5 t \"All sample, transitions colored by origin\" with dots lc variable; set out;\n\n",subdirf(fileresilk));
 5734:     for (i=1; i<= nlstate ; i ++) {
 5735:       fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
 5736:       fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
 5737:       fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($12/4.):6 t \"p%d%d\" with points pointtype 7 ps variable lc variable \\\n",i,1,i,1);
 5738:       for (j=2; j<= nlstate+ndeath ; j ++) {
 5739: 				fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($12/4.):6 t \"p%d%d\" with points pointtype 7 ps variable lc variable ",i,j,i,j);
 5740:       }
 5741:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
 5742:     }
 5743:     /* 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 */		 
 5744:     /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
 5745:     /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
 5746:     fprintf(ficgp,"\nset out;unset log\n");
 5747:     /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
 5748: 
 5749:   strcpy(dirfileres,optionfilefiname);
 5750:   strcpy(optfileres,"vpl");
 5751:  /* 1eme*/
 5752:   for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
 5753:     for (k1=1; k1<= m ; k1 ++) { /* For each valid combination of covariate */
 5754:       /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
 5755:       fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
 5756:       for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 5757: 				lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
 5758: 				/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5759: 				/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5760: 				/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5761: 				vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
 5762: 			/* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
 5763: 				fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 5764:       }
 5765:       fprintf(ficgp,"\n#\n");
 5766: 			if(invalidvarcomb[k1]){
 5767: 						fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 5768: 						continue;
 5769: 			}
 5770: 
 5771: 			fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
 5772: 			fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
 5773: 			fprintf(ficgp,"set xlabel \"Age\" \n\
 5774: set ylabel \"Probability\" \n	\
 5775: set ter svg size 640, 480\n	\
 5776: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
 5777: 			
 5778: 			for (i=1; i<= nlstate ; i ++) {
 5779: 				if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 5780: 				else        fprintf(ficgp," %%*lf (%%*lf)");
 5781: 			}
 5782: 			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);
 5783: 			for (i=1; i<= nlstate ; i ++) {
 5784: 				if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 5785: 				else fprintf(ficgp," %%*lf (%%*lf)");
 5786: 			} 
 5787: 			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); 
 5788: 			for (i=1; i<= nlstate ; i ++) {
 5789: 				if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 5790: 				else fprintf(ficgp," %%*lf (%%*lf)");
 5791: 			}  
 5792: 			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));
 5793: 			if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
 5794: 				/* fprintf(ficgp,",\"%s\" every :::%d::%d u 1:($%d) t\"Backward stable prevalence\" w l lt 3",subdirf2(fileresu,"PLB_"),k1-1,k1-1,1+cpt); */
 5795: 				fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1 */
 5796: 				kl=0;
 5797: 				for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
 5798: 					lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
 5799: 					/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5800: 					/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5801: 					/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5802: 					vlv= nbcode[Tvaraff[k]][lv];
 5803: 					kl++;
 5804: 					/* 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 *\/ */
 5805: 					/*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
 5806: 					/*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
 5807: 					/* ''  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*/
 5808: 					if(k==cptcoveff){
 5809: 							fprintf(ficgp,"$%d==%d && $%d==%d)? $%d : 1/0) t 'Backward prevalence in state %d' with line ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv], \
 5810: 											6+(cpt-1),  cpt );
 5811: 					}else{
 5812: 						fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
 5813: 						kl++;
 5814: 					}
 5815: 				} /* end covariate */
 5816: 			}
 5817: 			fprintf(ficgp,"\nset out \n");
 5818:     } /* k1 */
 5819:   } /* cpt */
 5820:   /*2 eme*/
 5821:   for (k1=1; k1<= m ; k1 ++) { 
 5822: 
 5823:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
 5824:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 5825: 				lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 5826: 				/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5827: 				/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5828: 				/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5829: 				vlv= nbcode[Tvaraff[k]][lv];
 5830: 				fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 5831:       }
 5832:       fprintf(ficgp,"\n#\n");
 5833: 			if(invalidvarcomb[k1]){
 5834: 						fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 5835: 						continue;
 5836: 			}
 5837: 			
 5838: 			fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
 5839: 			for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 5840: 				if(vpopbased==0)
 5841: 					fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
 5842: 				else
 5843: 					fprintf(ficgp,"\nreplot ");
 5844: 				for (i=1; i<= nlstate+1 ; i ++) {
 5845: 					k=2*i;
 5846: 					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);
 5847: 					for (j=1; j<= nlstate+1 ; j ++) {
 5848: 						if (j==i) fprintf(ficgp," %%lf (%%lf)");
 5849: 						else fprintf(ficgp," %%*lf (%%*lf)");
 5850: 					}   
 5851: 					if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
 5852: 					else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
 5853: 					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);
 5854: 					for (j=1; j<= nlstate+1 ; j ++) {
 5855: 						if (j==i) fprintf(ficgp," %%lf (%%lf)");
 5856: 						else fprintf(ficgp," %%*lf (%%*lf)");
 5857: 					}   
 5858: 					fprintf(ficgp,"\" t\"\" w l lt 0,");
 5859: 					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);
 5860: 					for (j=1; j<= nlstate+1 ; j ++) {
 5861: 						if (j==i) fprintf(ficgp," %%lf (%%lf)");
 5862: 						else fprintf(ficgp," %%*lf (%%*lf)");
 5863: 					}   
 5864: 					if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
 5865: 					else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
 5866: 				} /* state */
 5867: 			} /* vpopbased */
 5868: 			fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
 5869:   } /* k1 */
 5870: 	
 5871: 	
 5872:   /*3eme*/
 5873:   for (k1=1; k1<= m ; k1 ++) { 
 5874: 
 5875:     for (cpt=1; cpt<= nlstate ; cpt ++) {
 5876:       fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  cov=%d state=%d",k1, cpt);
 5877:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 5878: 				lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 5879: 				/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5880: 				/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5881: 				/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5882: 				vlv= nbcode[Tvaraff[k]][lv];
 5883: 				fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 5884:       }
 5885:       fprintf(ficgp,"\n#\n");
 5886: 			if(invalidvarcomb[k1]){
 5887: 						fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 5888: 						continue;
 5889: 			}
 5890: 			
 5891:       /*       k=2+nlstate*(2*cpt-2); */
 5892:       k=2+(nlstate+1)*(cpt-1);
 5893:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
 5894:       fprintf(ficgp,"set ter svg size 640, 480\n\
 5895: 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);
 5896:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 5897: 				for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 5898: 				fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 5899: 				fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 5900: 				for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 5901: 				fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 5902: 				
 5903:       */
 5904:       for (i=1; i< nlstate ; i ++) {
 5905: 				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);
 5906: 				/*	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);*/
 5907: 				
 5908:       } 
 5909:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
 5910:     }
 5911:   }
 5912:   
 5913: 	/* 4eme */
 5914:   /* Survival functions (period) from state i in state j by initial state i */
 5915:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
 5916: 
 5917:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 5918:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
 5919:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 5920: 				lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 5921: 				/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5922: 				/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5923: 				/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5924: 				vlv= nbcode[Tvaraff[k]][lv];
 5925: 				fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 5926:       }
 5927:       fprintf(ficgp,"\n#\n");
 5928: 			if(invalidvarcomb[k1]){
 5929: 							fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 5930: 							continue;
 5931: 			}
 5932: 			
 5933:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
 5934:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
 5935: set ter svg size 640, 480\n																							\
 5936: unset log y\n																														\
 5937: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 5938:       k=3;
 5939:       for (i=1; i<= nlstate ; i ++){
 5940: 				if(i==1){
 5941: 					fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 5942: 				}else{
 5943: 					fprintf(ficgp,", '' ");
 5944: 				}
 5945: 				l=(nlstate+ndeath)*(i-1)+1;
 5946: 				fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 5947: 				for (j=2; j<= nlstate+ndeath ; j ++)
 5948: 					fprintf(ficgp,"+$%d",k+l+j-1);
 5949: 				fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
 5950:       } /* nlstate */
 5951:       fprintf(ficgp,"\nset out\n");
 5952:     } /* end cpt state*/ 
 5953:   } /* end covariate */  
 5954: 	
 5955: /* 5eme */
 5956:   /* Survival functions (period) from state i in state j by final state j */
 5957:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
 5958:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
 5959: 
 5960:       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);
 5961:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 5962: 				lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 5963: 				/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5964: 				/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5965: 				/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5966: 				vlv= nbcode[Tvaraff[k]][lv];
 5967: 				fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 5968:       }
 5969:       fprintf(ficgp,"\n#\n");
 5970: 			if(invalidvarcomb[k1]){
 5971: 						fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 5972: 						continue;
 5973: 			}
 5974: 			
 5975:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
 5976:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
 5977: set ter svg size 640, 480\n																							\
 5978: unset log y\n																														\
 5979: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 5980:       k=3;
 5981:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
 5982: 				if(j==1)
 5983: 					fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 5984: 				else
 5985: 					fprintf(ficgp,", '' ");
 5986: 				l=(nlstate+ndeath)*(cpt-1) +j;
 5987: 				fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
 5988: 				/* for (i=2; i<= nlstate+ndeath ; i ++) */
 5989: 				/*   fprintf(ficgp,"+$%d",k+l+i-1); */
 5990: 				fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
 5991:       } /* nlstate */
 5992:       fprintf(ficgp,", '' ");
 5993:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
 5994:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
 5995: 				l=(nlstate+ndeath)*(cpt-1) +j;
 5996: 				if(j < nlstate)
 5997: 					fprintf(ficgp,"$%d +",k+l);
 5998: 				else
 5999: 					fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
 6000:       }
 6001:       fprintf(ficgp,"\nset out\n");
 6002:     } /* end cpt state*/ 
 6003:   } /* end covariate */  
 6004: 	
 6005: /* 6eme */
 6006:   /* CV preval stable (period) for each covariate */
 6007:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
 6008:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 6009: 
 6010:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
 6011:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 6012: 				lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 6013: 				/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6014: 				/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6015: 				/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6016: 				vlv= nbcode[Tvaraff[k]][lv];
 6017: 				fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6018:       }
 6019:       fprintf(ficgp,"\n#\n");
 6020: 			if(invalidvarcomb[k1]){
 6021: 						fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6022: 						continue;
 6023: 			}
 6024: 
 6025:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
 6026:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 6027: set ter svg size 640, 480\n\
 6028: unset log y\n\
 6029: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 6030:       k=3; /* Offset */
 6031:       for (i=1; i<= nlstate ; i ++){
 6032: 				if(i==1)
 6033: 					fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 6034: 				else
 6035: 					fprintf(ficgp,", '' ");
 6036: 				l=(nlstate+ndeath)*(i-1)+1;
 6037: 				fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 6038: 				for (j=2; j<= nlstate ; j ++)
 6039: 					fprintf(ficgp,"+$%d",k+l+j-1);
 6040: 				fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
 6041:       } /* nlstate */
 6042:       fprintf(ficgp,"\nset out\n");
 6043:     } /* end cpt state*/ 
 6044:   } /* end covariate */  
 6045: 
 6046: 
 6047: /* 7eme */
 6048:   if(backcast == 1){
 6049:     /* CV back preval stable (period) for each covariate */
 6050:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
 6051:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 6052: 				fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
 6053: 				for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 6054: 					lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 6055: 					/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6056: 					/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6057: 					/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6058: 					vlv= nbcode[Tvaraff[k]][lv];
 6059: 					fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6060: 				}
 6061: 				fprintf(ficgp,"\n#\n");
 6062: 				if(invalidvarcomb[k1]){
 6063: 								fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6064: 								continue;
 6065: 				}
 6066: 				
 6067: 				fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1);
 6068: 				fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 6069: set ter svg size 640, 480\n																							\
 6070: unset log y\n																														\
 6071: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 6072: 				k=3; /* Offset */
 6073: 				for (i=1; i<= nlstate ; i ++){
 6074: 					if(i==1)
 6075: 						fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
 6076: 					else
 6077: 						fprintf(ficgp,", '' ");
 6078: 					/* l=(nlstate+ndeath)*(i-1)+1; */
 6079: 					l=(nlstate+ndeath)*(cpt-1)+1;
 6080: 					/* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
 6081: 					/* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
 6082: 					fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */
 6083: 					/* for (j=2; j<= nlstate ; j ++) */
 6084: 					/* 	fprintf(ficgp,"+$%d",k+l+j-1); */
 6085: 					/* 	/\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
 6086: 					fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
 6087: 				} /* nlstate */
 6088: 				fprintf(ficgp,"\nset out\n");
 6089:       } /* end cpt state*/ 
 6090:     } /* end covariate */  
 6091:   } /* End if backcast */
 6092:   
 6093: 	/* 8eme */
 6094:   if(prevfcast==1){
 6095:     /* Projection from cross-sectional to stable (period) for each covariate */
 6096:     
 6097:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
 6098:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 6099: 				fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
 6100: 				for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
 6101: 					lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
 6102: 					/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6103: 					/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6104: 					/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6105: 					vlv= nbcode[Tvaraff[k]][lv];
 6106: 					fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6107: 				}
 6108: 				fprintf(ficgp,"\n#\n");
 6109: 				if(invalidvarcomb[k1]){
 6110: 								fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6111: 								continue;
 6112: 				}
 6113: 				
 6114: 				fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
 6115: 				fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
 6116: 				fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
 6117: set ter svg size 640, 480\n	\
 6118: unset log y\n	\
 6119: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 6120: 				for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
 6121: 					/*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 6122: 					/*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 6123: 					/*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 6124: 					/*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 6125: 					if(i==1){
 6126: 						fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
 6127: 					}else{
 6128: 						fprintf(ficgp,",\\\n '' ");
 6129: 					}
 6130: 					if(cptcoveff ==0){ /* No covariate */
 6131: 						ioffset=2; /* Age is in 2 */
 6132: 						/*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
 6133: 						/*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
 6134: 						/*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
 6135: 						/*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
 6136: 						fprintf(ficgp," u %d:(", ioffset); 
 6137: 						if(i==nlstate+1)
 6138: 							fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ",			\
 6139: 											ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
 6140: 						else
 6141: 							fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",			\
 6142: 											ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
 6143: 					}else{ /* more than 2 covariates */
 6144: 						if(cptcoveff ==1){
 6145: 							ioffset=4; /* Age is in 4 */
 6146: 						}else{
 6147: 							ioffset=6; /* Age is in 6 */
 6148: 						/*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 6149: 						/*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
 6150: 						}   
 6151: 						fprintf(ficgp," u %d:(",ioffset); 
 6152: 						kl=0;
 6153: 						strcpy(gplotcondition,"(");
 6154: 						for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
 6155: 							lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
 6156: 							/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6157: 							/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6158: 							/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6159: 							vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
 6160: 							kl++;
 6161: 							sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
 6162: 							kl++;
 6163: 							if(k <cptcoveff && cptcoveff>1)
 6164: 								sprintf(gplotcondition+strlen(gplotcondition)," && ");
 6165: 						}
 6166: 						strcpy(gplotcondition+strlen(gplotcondition),")");
 6167: 						/* 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 *\/ */
 6168: 						/*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
 6169: 						/*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
 6170: 						/* ''  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*/
 6171: 						if(i==nlstate+1){
 6172: 							fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ", gplotcondition, \
 6173: 											ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
 6174: 						}else{
 6175: 								fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
 6176: 												ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
 6177: 						}
 6178: 					} /* end if covariate */
 6179: 				} /* nlstate */
 6180: 				fprintf(ficgp,"\nset out\n");
 6181: 			} /* end cpt state*/
 6182: 		} /* end covariate */
 6183: 	} /* End if prevfcast */
 6184: 	
 6185: 	
 6186: 	/* proba elementaires */
 6187: 	fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
 6188:   for(i=1,jk=1; i <=nlstate; i++){
 6189:     fprintf(ficgp,"# initial state %d\n",i);
 6190:     for(k=1; k <=(nlstate+ndeath); k++){
 6191:       if (k != i) {
 6192: 	fprintf(ficgp,"#   current state %d\n",k);
 6193: 	for(j=1; j <=ncovmodel; j++){
 6194: 	  fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
 6195: 	  jk++; 
 6196: 	}
 6197: 	fprintf(ficgp,"\n");
 6198:       }
 6199:     }
 6200:    }
 6201:   fprintf(ficgp,"##############\n#\n");
 6202: 
 6203:   /*goto avoid;*/
 6204:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
 6205:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
 6206:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
 6207:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
 6208:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
 6209:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 6210:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 6211:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 6212:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 6213:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
 6214:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 6215:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
 6216:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
 6217:   fprintf(ficgp,"#\n");
 6218:    for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
 6219:      fprintf(ficgp,"# ng=%d\n",ng);
 6220:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
 6221:      for(jk=1; jk <=m; jk++) {
 6222:        fprintf(ficgp,"#    jk=%d\n",jk);
 6223:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
 6224:        fprintf(ficgp,"\nset ter svg size 640, 480 ");
 6225:        if (ng==1){
 6226: 	 fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
 6227: 	 fprintf(ficgp,"\nunset log y");
 6228:        }else if (ng==2){
 6229: 	 fprintf(ficgp,"\nset ylabel \"Probability\"\n");
 6230: 	 fprintf(ficgp,"\nset log y");
 6231:        }else if (ng==3){
 6232: 	 fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
 6233: 	 fprintf(ficgp,"\nset log y");
 6234:        }else
 6235: 	 fprintf(ficgp,"\nunset title ");
 6236:        fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
 6237:        i=1;
 6238:        for(k2=1; k2<=nlstate; k2++) {
 6239: 	 k3=i;
 6240: 	 for(k=1; k<=(nlstate+ndeath); k++) {
 6241: 	   if (k != k2){
 6242: 	     switch( ng) {
 6243: 	     case 1:
 6244: 	       if(nagesqr==0)
 6245: 		 fprintf(ficgp," p%d+p%d*x",i,i+1);
 6246: 	       else /* nagesqr =1 */
 6247: 		 fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
 6248: 	       break;
 6249: 	     case 2: /* ng=2 */
 6250: 	       if(nagesqr==0)
 6251: 		 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
 6252: 	       else /* nagesqr =1 */
 6253: 		   fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
 6254: 	       break;
 6255: 	     case 3:
 6256: 	       if(nagesqr==0)
 6257: 		 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
 6258: 	       else /* nagesqr =1 */
 6259: 		 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
 6260: 	       break;
 6261: 	     }
 6262: 	     ij=1;/* To be checked else nbcode[0][0] wrong */
 6263: 	     for(j=3; j <=ncovmodel-nagesqr; j++) {
 6264: 	       /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
 6265: 	       if(ij <=cptcovage) { /* Bug valgrind */
 6266: 		 if((j-2)==Tage[ij]) { /* Bug valgrind */
 6267: 		   fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
 6268: 		   /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
 6269: 		   ij++;
 6270: 		 }
 6271: 	       }
 6272: 	       else
 6273: 		 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
 6274: 	     }
 6275: 	   }else{
 6276: 	     i=i-ncovmodel;
 6277: 	     if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
 6278: 	       fprintf(ficgp," (1.");
 6279: 	   }
 6280: 	   
 6281: 	   if(ng != 1){
 6282: 	     fprintf(ficgp,")/(1");
 6283: 	     
 6284: 	     for(k1=1; k1 <=nlstate; k1++){ 
 6285: 	       if(nagesqr==0)
 6286: 		 fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
 6287: 	       else /* nagesqr =1 */
 6288: 		 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);
 6289: 	       
 6290: 	       ij=1;
 6291: 	       for(j=3; j <=ncovmodel-nagesqr; j++){
 6292: 		 if(ij <=cptcovage) { /* Bug valgrind */
 6293: 		   if((j-2)==Tage[ij]) { /* Bug valgrind */
 6294: 		     fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
 6295: 		     /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
 6296: 		     ij++;
 6297: 		   }
 6298: 		 }
 6299: 		 else
 6300: 		   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
 6301: 	       }
 6302: 	       fprintf(ficgp,")");
 6303: 	     }
 6304: 	     fprintf(ficgp,")");
 6305: 	     if(ng ==2)
 6306: 	       fprintf(ficgp," t \"p%d%d\" ", k2,k);
 6307: 	     else /* ng= 3 */
 6308: 	       fprintf(ficgp," t \"i%d%d\" ", k2,k);
 6309: 	   }else{ /* end ng <> 1 */
 6310: 	     if( k !=k2) /* logit p11 is hard to draw */
 6311: 	       fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
 6312: 	   }
 6313: 	   if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
 6314: 	     fprintf(ficgp,",");
 6315: 	   if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
 6316: 	     fprintf(ficgp,",");
 6317: 	   i=i+ncovmodel;
 6318: 	 } /* end k */
 6319:        } /* end k2 */
 6320:        fprintf(ficgp,"\n set out\n");
 6321:      } /* end jk */
 6322:    } /* end ng */
 6323:  /* avoid: */
 6324:    fflush(ficgp); 
 6325: }  /* end gnuplot */
 6326: 
 6327: 
 6328: /*************** Moving average **************/
 6329: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
 6330:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
 6331:    
 6332:    int i, cpt, cptcod;
 6333:    int modcovmax =1;
 6334:    int mobilavrange, mob;
 6335:    int iage=0;
 6336: 
 6337:    double sum=0.;
 6338:    double age;
 6339:    double *sumnewp, *sumnewm;
 6340:    double *agemingood, *agemaxgood; /* Currently identical for all covariates */
 6341:   
 6342:   
 6343:    /* modcovmax=2*cptcoveff;/\* Max number of modalities. We suppose  */
 6344:    /* 		   a covariate has 2 modalities, should be equal to ncovcombmax  *\/ */
 6345: 
 6346:    sumnewp = vector(1,ncovcombmax);
 6347:    sumnewm = vector(1,ncovcombmax);
 6348:    agemingood = vector(1,ncovcombmax);	
 6349:    agemaxgood = vector(1,ncovcombmax);
 6350: 
 6351:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
 6352:      sumnewm[cptcod]=0.;
 6353:      sumnewp[cptcod]=0.;
 6354:      agemingood[cptcod]=0;
 6355:      agemaxgood[cptcod]=0;
 6356:    }
 6357:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
 6358:   
 6359:    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
 6360:      if(mobilav==1) mobilavrange=5; /* default */
 6361:      else mobilavrange=mobilav;
 6362:      for (age=bage; age<=fage; age++)
 6363:        for (i=1; i<=nlstate;i++)
 6364: 	 for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
 6365: 	   mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 6366:      /* We keep the original values on the extreme ages bage, fage and for 
 6367: 	fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
 6368: 	we use a 5 terms etc. until the borders are no more concerned. 
 6369:      */ 
 6370:      for (mob=3;mob <=mobilavrange;mob=mob+2){
 6371:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
 6372: 	 for (i=1; i<=nlstate;i++){
 6373: 	   for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
 6374: 	     mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
 6375: 	     for (cpt=1;cpt<=(mob-1)/2;cpt++){
 6376: 	       mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
 6377: 	       mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
 6378: 	     }
 6379: 	     mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
 6380: 	   }
 6381: 	 }
 6382:        }/* end age */
 6383:      }/* end mob */
 6384:    }else
 6385:      return -1;
 6386:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
 6387:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
 6388:      if(invalidvarcomb[cptcod]){
 6389:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
 6390:        continue;
 6391:      }
 6392: 
 6393:      agemingood[cptcod]=fage-(mob-1)/2;
 6394:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
 6395:        sumnewm[cptcod]=0.;
 6396:        for (i=1; i<=nlstate;i++){
 6397: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 6398:        }
 6399:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
 6400: 	 agemingood[cptcod]=age;
 6401:        }else{ /* bad */
 6402: 	 for (i=1; i<=nlstate;i++){
 6403: 	   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
 6404: 	 } /* i */
 6405:        } /* end bad */
 6406:      }/* age */
 6407:      sum=0.;
 6408:      for (i=1; i<=nlstate;i++){
 6409:        sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
 6410:      }
 6411:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
 6412:        printf("For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one at any descending age!\n",cptcod);
 6413:        /* for (i=1; i<=nlstate;i++){ */
 6414:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
 6415:        /* } /\* i *\/ */
 6416:      } /* end bad */
 6417:      /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
 6418:      /* From youngest, finding the oldest wrong */
 6419:      agemaxgood[cptcod]=bage+(mob-1)/2;
 6420:      for (age=bage+(mob-1)/2; age<=fage; age++){
 6421:        sumnewm[cptcod]=0.;
 6422:        for (i=1; i<=nlstate;i++){
 6423: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 6424:        }
 6425:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
 6426: 	 agemaxgood[cptcod]=age;
 6427:        }else{ /* bad */
 6428: 	 for (i=1; i<=nlstate;i++){
 6429: 	   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
 6430: 	 } /* i */
 6431:        } /* end bad */
 6432:      }/* age */
 6433:      sum=0.;
 6434:      for (i=1; i<=nlstate;i++){
 6435:        sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
 6436:      }
 6437:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
 6438:        printf("For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one at any ascending age!\n",cptcod);
 6439:        /* for (i=1; i<=nlstate;i++){ */
 6440:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
 6441:        /* } /\* i *\/ */
 6442:      } /* end bad */
 6443: 		
 6444:      for (age=bage; age<=fage; age++){
 6445:        printf("%d %d ", cptcod, (int)age);
 6446:        sumnewp[cptcod]=0.;
 6447:        sumnewm[cptcod]=0.;
 6448:        for (i=1; i<=nlstate;i++){
 6449: 	 sumnewp[cptcod]+=probs[(int)age][i][cptcod];
 6450: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 6451: 	 /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
 6452:        }
 6453:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
 6454:      }
 6455:      /* printf("\n"); */
 6456:      /* } */
 6457:      /* brutal averaging */
 6458:      for (i=1; i<=nlstate;i++){
 6459:        for (age=1; age<=bage; age++){
 6460: 	 mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
 6461: 	 /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
 6462:        }	
 6463:        for (age=fage; age<=AGESUP; age++){
 6464: 	 mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
 6465: 	 /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
 6466:        }
 6467:      } /* end i status */
 6468:      for (i=nlstate+1; i<=nlstate+ndeath;i++){
 6469:        for (age=1; age<=AGESUP; age++){
 6470: 	 /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
 6471: 	 mobaverage[(int)age][i][cptcod]=0.;
 6472:        }
 6473:      }
 6474:    }/* end cptcod */
 6475:    free_vector(sumnewm,1, ncovcombmax);
 6476:    free_vector(sumnewp,1, ncovcombmax);
 6477:    free_vector(agemaxgood,1, ncovcombmax);
 6478:    free_vector(agemingood,1, ncovcombmax);
 6479:    return 0;
 6480:  }/* End movingaverage */
 6481:  
 6482: 
 6483: /************** Forecasting ******************/
 6484: 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){
 6485:   /* proj1, year, month, day of starting projection 
 6486:      agemin, agemax range of age
 6487:      dateprev1 dateprev2 range of dates during which prevalence is computed
 6488:      anproj2 year of en of projection (same day and month as proj1).
 6489:   */
 6490:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
 6491:   double agec; /* generic age */
 6492:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
 6493:   double *popeffectif,*popcount;
 6494:   double ***p3mat;
 6495:   /* double ***mobaverage; */
 6496:   char fileresf[FILENAMELENGTH];
 6497: 
 6498:   agelim=AGESUP;
 6499:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 6500:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 6501:      We still use firstpass and lastpass as another selection.
 6502:   */
 6503:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
 6504:   /* 	      firstpass, lastpass,  stepm,  weightopt, model); */
 6505:  
 6506:   strcpy(fileresf,"F_"); 
 6507:   strcat(fileresf,fileresu);
 6508:   if((ficresf=fopen(fileresf,"w"))==NULL) {
 6509:     printf("Problem with forecast resultfile: %s\n", fileresf);
 6510:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
 6511:   }
 6512:   printf("Computing forecasting: result on file '%s', please wait... \n", fileresf);
 6513:   fprintf(ficlog,"Computing forecasting: result on file '%s', please wait... \n", fileresf);
 6514: 
 6515:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 6516: 
 6517: 
 6518:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 6519:   if (stepm<=12) stepsize=1;
 6520:   if(estepm < stepm){
 6521:     printf ("Problem %d lower than %d\n",estepm, stepm);
 6522:   }
 6523:   else  hstepm=estepm;   
 6524: 
 6525:   hstepm=hstepm/stepm; 
 6526:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
 6527:                                fractional in yp1 */
 6528:   anprojmean=yp;
 6529:   yp2=modf((yp1*12),&yp);
 6530:   mprojmean=yp;
 6531:   yp1=modf((yp2*30.5),&yp);
 6532:   jprojmean=yp;
 6533:   if(jprojmean==0) jprojmean=1;
 6534:   if(mprojmean==0) jprojmean=1;
 6535: 
 6536:   i1=cptcoveff;
 6537:   if (cptcovn < 1){i1=1;}
 6538:   
 6539:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
 6540:   
 6541:   fprintf(ficresf,"#****** Routine prevforecast **\n");
 6542: 
 6543: /* 	      if (h==(int)(YEARM*yearp)){ */
 6544:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
 6545:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 6546:       k=k+1;
 6547:       fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
 6548:       for(j=1;j<=cptcoveff;j++) {
 6549: 				fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 6550:       }
 6551:       fprintf(ficresf," yearproj age");
 6552:       for(j=1; j<=nlstate+ndeath;j++){ 
 6553: 				for(i=1; i<=nlstate;i++) 	      
 6554:           fprintf(ficresf," p%d%d",i,j);
 6555: 				fprintf(ficresf," wp.%d",j);
 6556:       }
 6557:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
 6558: 				fprintf(ficresf,"\n");
 6559: 				fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
 6560: 				for (agec=fage; agec>=(ageminpar-1); agec--){ 
 6561: 					nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
 6562: 					nhstepm = nhstepm/hstepm; 
 6563: 					p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6564: 					oldm=oldms;savm=savms;
 6565: 					hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
 6566: 					
 6567: 					for (h=0; h<=nhstepm; h++){
 6568: 						if (h*hstepm/YEARM*stepm ==yearp) {
 6569:               fprintf(ficresf,"\n");
 6570:               for(j=1;j<=cptcoveff;j++) 
 6571:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 6572: 							fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
 6573: 						} 
 6574: 						for(j=1; j<=nlstate+ndeath;j++) {
 6575: 							ppij=0.;
 6576: 							for(i=1; i<=nlstate;i++) {
 6577: 								if (mobilav==1) 
 6578: 									ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
 6579: 								else {
 6580: 									ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
 6581: 								}
 6582: 								if (h*hstepm/YEARM*stepm== yearp) {
 6583: 									fprintf(ficresf," %.3f", p3mat[i][j][h]);
 6584: 								}
 6585: 							} /* end i */
 6586: 							if (h*hstepm/YEARM*stepm==yearp) {
 6587: 								fprintf(ficresf," %.3f", ppij);
 6588: 							}
 6589: 						}/* end j */
 6590: 					} /* end h */
 6591: 					free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6592: 				} /* end agec */
 6593:       } /* end yearp */
 6594:     } /* end cptcod */
 6595:   } /* end  cptcov */
 6596: 	
 6597:   fclose(ficresf);
 6598:   printf("End of Computing forecasting \n");
 6599:   fprintf(ficlog,"End of Computing forecasting\n");
 6600: 
 6601: }
 6602: 
 6603: /* /\************** Back Forecasting ******************\/ */
 6604: /* void prevbackforecast(char fileres[], double anback1, double mback1, double jback1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anback2, double p[], int cptcoveff){ */
 6605: /*   /\* back1, year, month, day of starting backection  */
 6606: /*      agemin, agemax range of age */
 6607: /*      dateprev1 dateprev2 range of dates during which prevalence is computed */
 6608: /*      anback2 year of en of backection (same day and month as back1). */
 6609: /*   *\/ */
 6610: /*   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
 6611: /*   double agec; /\* generic age *\/ */
 6612: /*   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
 6613: /*   double *popeffectif,*popcount; */
 6614: /*   double ***p3mat; */
 6615: /*   /\* double ***mobaverage; *\/ */
 6616: /*   char fileresfb[FILENAMELENGTH]; */
 6617: 	
 6618: /*   agelim=AGESUP; */
 6619: /*   /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
 6620: /*      in each health status at the date of interview (if between dateprev1 and dateprev2). */
 6621: /*      We still use firstpass and lastpass as another selection. */
 6622: /*   *\/ */
 6623: /*   /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
 6624: /*   /\* 	      firstpass, lastpass,  stepm,  weightopt, model); *\/ */
 6625: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
 6626: 	
 6627: /*   strcpy(fileresfb,"FB_");  */
 6628: /*   strcat(fileresfb,fileresu); */
 6629: /*   if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
 6630: /*     printf("Problem with back forecast resultfile: %s\n", fileresfb); */
 6631: /*     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
 6632: /*   } */
 6633: /*   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
 6634: /*   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
 6635: 	
 6636: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
 6637: 	
 6638: /*   /\* if (mobilav!=0) { *\/ */
 6639: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
 6640: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
 6641: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
 6642: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
 6643: /*   /\*   } *\/ */
 6644: /*   /\* } *\/ */
 6645: 	
 6646: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
 6647: /*   if (stepm<=12) stepsize=1; */
 6648: /*   if(estepm < stepm){ */
 6649: /*     printf ("Problem %d lower than %d\n",estepm, stepm); */
 6650: /*   } */
 6651: /*   else  hstepm=estepm;    */
 6652: 	
 6653: /*   hstepm=hstepm/stepm;  */
 6654: /*   yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
 6655: /*                                fractional in yp1 *\/ */
 6656: /*   anprojmean=yp; */
 6657: /*   yp2=modf((yp1*12),&yp); */
 6658: /*   mprojmean=yp; */
 6659: /*   yp1=modf((yp2*30.5),&yp); */
 6660: /*   jprojmean=yp; */
 6661: /*   if(jprojmean==0) jprojmean=1; */
 6662: /*   if(mprojmean==0) jprojmean=1; */
 6663: 	
 6664: /*   i1=cptcoveff; */
 6665: /*   if (cptcovn < 1){i1=1;} */
 6666:   
 6667: /*   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);  */
 6668:   
 6669: /*   fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
 6670: 	
 6671: /* 	/\* 	      if (h==(int)(YEARM*yearp)){ *\/ */
 6672: /*   for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
 6673: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
 6674: /*       k=k+1; */
 6675: /*       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
 6676: /*       for(j=1;j<=cptcoveff;j++) { */
 6677: /* 				fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
 6678: /*       } */
 6679: /*       fprintf(ficresfb," yearbproj age"); */
 6680: /*       for(j=1; j<=nlstate+ndeath;j++){  */
 6681: /* 				for(i=1; i<=nlstate;i++) 	       */
 6682: /*           fprintf(ficresfb," p%d%d",i,j); */
 6683: /* 				fprintf(ficresfb," p.%d",j); */
 6684: /*       } */
 6685: /*       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {  */
 6686: /* 				/\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  *\/ */
 6687: /* 				fprintf(ficresfb,"\n"); */
 6688: /* 				fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);    */
 6689: /* 				for (agec=fage; agec>=(ageminpar-1); agec--){  */
 6690: /* 					nhstepm=(int) rint((agelim-agec)*YEARM/stepm);  */
 6691: /* 					nhstepm = nhstepm/hstepm;  */
 6692: /* 					p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
 6693: /* 					oldm=oldms;savm=savms; */
 6694: /* 					hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k); 	 */
 6695: /* 					for (h=0; h<=nhstepm; h++){ */
 6696: /* 						if (h*hstepm/YEARM*stepm ==yearp) { */
 6697: /*               fprintf(ficresfb,"\n"); */
 6698: /*               for(j=1;j<=cptcoveff;j++)  */
 6699: /*                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
 6700: /* 							fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
 6701: /* 						}  */
 6702: /* 						for(j=1; j<=nlstate+ndeath;j++) { */
 6703: /* 							ppij=0.; */
 6704: /* 							for(i=1; i<=nlstate;i++) { */
 6705: /* 								if (mobilav==1)  */
 6706: /* 									ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
 6707: /* 								else { */
 6708: /* 									ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
 6709: /* 								} */
 6710: /* 								if (h*hstepm/YEARM*stepm== yearp) { */
 6711: /* 									fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
 6712: /* 								} */
 6713: /* 							} /\* end i *\/ */
 6714: /* 							if (h*hstepm/YEARM*stepm==yearp) { */
 6715: /* 								fprintf(ficresfb," %.3f", ppij); */
 6716: /* 							} */
 6717: /* 						}/\* end j *\/ */
 6718: /* 					} /\* end h *\/ */
 6719: /* 					free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
 6720: /* 				} /\* end agec *\/ */
 6721: /*       } /\* end yearp *\/ */
 6722: /*     } /\* end cptcod *\/ */
 6723: /*   } /\* end  cptcov *\/ */
 6724: 	
 6725: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
 6726: 	
 6727: /*   fclose(ficresfb); */
 6728: /*   printf("End of Computing Back forecasting \n"); */
 6729: /*   fprintf(ficlog,"End of Computing Back forecasting\n"); */
 6730: 	
 6731: /* } */
 6732: 
 6733: /************** Forecasting *****not tested NB*************/
 6734: 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){
 6735:   
 6736:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
 6737:   int *popage;
 6738:   double calagedatem, agelim, kk1, kk2;
 6739:   double *popeffectif,*popcount;
 6740:   double ***p3mat,***tabpop,***tabpopprev;
 6741:   /* double ***mobaverage; */
 6742:   char filerespop[FILENAMELENGTH];
 6743: 
 6744:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6745:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6746:   agelim=AGESUP;
 6747:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
 6748:   
 6749:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 6750:   
 6751:   
 6752:   strcpy(filerespop,"POP_"); 
 6753:   strcat(filerespop,fileresu);
 6754:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
 6755:     printf("Problem with forecast resultfile: %s\n", filerespop);
 6756:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
 6757:   }
 6758:   printf("Computing forecasting: result on file '%s' \n", filerespop);
 6759:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
 6760: 
 6761:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 6762: 
 6763:   /* if (mobilav!=0) { */
 6764:   /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 6765:   /*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ */
 6766:   /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
 6767:   /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
 6768:   /*   } */
 6769:   /* } */
 6770: 
 6771:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 6772:   if (stepm<=12) stepsize=1;
 6773:   
 6774:   agelim=AGESUP;
 6775:   
 6776:   hstepm=1;
 6777:   hstepm=hstepm/stepm; 
 6778: 	
 6779:   if (popforecast==1) {
 6780:     if((ficpop=fopen(popfile,"r"))==NULL) {
 6781:       printf("Problem with population file : %s\n",popfile);exit(0);
 6782:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
 6783:     } 
 6784:     popage=ivector(0,AGESUP);
 6785:     popeffectif=vector(0,AGESUP);
 6786:     popcount=vector(0,AGESUP);
 6787:     
 6788:     i=1;   
 6789:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
 6790:     
 6791:     imx=i;
 6792:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
 6793:   }
 6794:   
 6795:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
 6796:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 6797:       k=k+1;
 6798:       fprintf(ficrespop,"\n#******");
 6799:       for(j=1;j<=cptcoveff;j++) {
 6800: 	fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 6801:       }
 6802:       fprintf(ficrespop,"******\n");
 6803:       fprintf(ficrespop,"# Age");
 6804:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
 6805:       if (popforecast==1)  fprintf(ficrespop," [Population]");
 6806:       
 6807:       for (cpt=0; cpt<=0;cpt++) { 
 6808: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 6809: 	
 6810: 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 6811: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 6812: 	  nhstepm = nhstepm/hstepm; 
 6813: 	  
 6814: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6815: 	  oldm=oldms;savm=savms;
 6816: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 6817: 	  
 6818: 	  for (h=0; h<=nhstepm; h++){
 6819: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 6820: 	      fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 6821: 	    } 
 6822: 	    for(j=1; j<=nlstate+ndeath;j++) {
 6823: 	      kk1=0.;kk2=0;
 6824: 	      for(i=1; i<=nlstate;i++) {	      
 6825: 		if (mobilav==1) 
 6826: 		  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
 6827: 		else {
 6828: 		  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
 6829: 		}
 6830: 	      }
 6831: 	      if (h==(int)(calagedatem+12*cpt)){
 6832: 		tabpop[(int)(agedeb)][j][cptcod]=kk1;
 6833: 		/*fprintf(ficrespop," %.3f", kk1);
 6834: 		  if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
 6835: 	      }
 6836: 	    }
 6837: 	    for(i=1; i<=nlstate;i++){
 6838: 	      kk1=0.;
 6839: 	      for(j=1; j<=nlstate;j++){
 6840: 		kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
 6841: 	      }
 6842: 	      tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
 6843: 	    }
 6844: 	    
 6845: 	    if (h==(int)(calagedatem+12*cpt))
 6846: 	      for(j=1; j<=nlstate;j++) 
 6847: 		fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
 6848: 	  }
 6849: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6850: 	}
 6851:       }
 6852:       
 6853:       /******/
 6854:       
 6855:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
 6856: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 6857: 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 6858: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 6859: 	  nhstepm = nhstepm/hstepm; 
 6860: 	  
 6861: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6862: 	  oldm=oldms;savm=savms;
 6863: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 6864: 	  for (h=0; h<=nhstepm; h++){
 6865: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 6866: 	      fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 6867: 	    } 
 6868: 	    for(j=1; j<=nlstate+ndeath;j++) {
 6869: 	      kk1=0.;kk2=0;
 6870: 	      for(i=1; i<=nlstate;i++) {	      
 6871: 		kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];	
 6872: 	      }
 6873: 	      if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);	
 6874: 	    }
 6875: 	  }
 6876: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6877: 	}
 6878:       }
 6879:     } 
 6880:   }
 6881:   
 6882:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 6883:   
 6884:   if (popforecast==1) {
 6885:     free_ivector(popage,0,AGESUP);
 6886:     free_vector(popeffectif,0,AGESUP);
 6887:     free_vector(popcount,0,AGESUP);
 6888:   }
 6889:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6890:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6891:   fclose(ficrespop);
 6892: } /* End of popforecast */
 6893:  
 6894: int fileappend(FILE *fichier, char *optionfich)
 6895: {
 6896:   if((fichier=fopen(optionfich,"a"))==NULL) {
 6897:     printf("Problem with file: %s\n", optionfich);
 6898:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
 6899:     return (0);
 6900:   }
 6901:   fflush(fichier);
 6902:   return (1);
 6903: }
 6904: 
 6905: 
 6906: /**************** function prwizard **********************/
 6907: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
 6908: {
 6909: 
 6910:   /* Wizard to print covariance matrix template */
 6911: 
 6912:   char ca[32], cb[32];
 6913:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
 6914:   int numlinepar;
 6915: 
 6916:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 6917:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 6918:   for(i=1; i <=nlstate; i++){
 6919:     jj=0;
 6920:     for(j=1; j <=nlstate+ndeath; j++){
 6921:       if(j==i) continue;
 6922:       jj++;
 6923:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
 6924:       printf("%1d%1d",i,j);
 6925:       fprintf(ficparo,"%1d%1d",i,j);
 6926:       for(k=1; k<=ncovmodel;k++){
 6927: 	/* 	  printf(" %lf",param[i][j][k]); */
 6928: 	/* 	  fprintf(ficparo," %lf",param[i][j][k]); */
 6929: 	printf(" 0.");
 6930: 	fprintf(ficparo," 0.");
 6931:       }
 6932:       printf("\n");
 6933:       fprintf(ficparo,"\n");
 6934:     }
 6935:   }
 6936:   printf("# Scales (for hessian or gradient estimation)\n");
 6937:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
 6938:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
 6939:   for(i=1; i <=nlstate; i++){
 6940:     jj=0;
 6941:     for(j=1; j <=nlstate+ndeath; j++){
 6942:       if(j==i) continue;
 6943:       jj++;
 6944:       fprintf(ficparo,"%1d%1d",i,j);
 6945:       printf("%1d%1d",i,j);
 6946:       fflush(stdout);
 6947:       for(k=1; k<=ncovmodel;k++){
 6948: 	/* 	printf(" %le",delti3[i][j][k]); */
 6949: 	/* 	fprintf(ficparo," %le",delti3[i][j][k]); */
 6950: 	printf(" 0.");
 6951: 	fprintf(ficparo," 0.");
 6952:       }
 6953:       numlinepar++;
 6954:       printf("\n");
 6955:       fprintf(ficparo,"\n");
 6956:     }
 6957:   }
 6958:   printf("# Covariance matrix\n");
 6959: /* # 121 Var(a12)\n\ */
 6960: /* # 122 Cov(b12,a12) Var(b12)\n\ */
 6961: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 6962: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 6963: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 6964: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 6965: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 6966: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 6967:   fflush(stdout);
 6968:   fprintf(ficparo,"# Covariance matrix\n");
 6969:   /* # 121 Var(a12)\n\ */
 6970:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
 6971:   /* #   ...\n\ */
 6972:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
 6973:   
 6974:   for(itimes=1;itimes<=2;itimes++){
 6975:     jj=0;
 6976:     for(i=1; i <=nlstate; i++){
 6977:       for(j=1; j <=nlstate+ndeath; j++){
 6978: 	if(j==i) continue;
 6979: 	for(k=1; k<=ncovmodel;k++){
 6980: 	  jj++;
 6981: 	  ca[0]= k+'a'-1;ca[1]='\0';
 6982: 	  if(itimes==1){
 6983: 	    printf("#%1d%1d%d",i,j,k);
 6984: 	    fprintf(ficparo,"#%1d%1d%d",i,j,k);
 6985: 	  }else{
 6986: 	    printf("%1d%1d%d",i,j,k);
 6987: 	    fprintf(ficparo,"%1d%1d%d",i,j,k);
 6988: 	    /* 	printf(" %.5le",matcov[i][j]); */
 6989: 	  }
 6990: 	  ll=0;
 6991: 	  for(li=1;li <=nlstate; li++){
 6992: 	    for(lj=1;lj <=nlstate+ndeath; lj++){
 6993: 	      if(lj==li) continue;
 6994: 	      for(lk=1;lk<=ncovmodel;lk++){
 6995: 		ll++;
 6996: 		if(ll<=jj){
 6997: 		  cb[0]= lk +'a'-1;cb[1]='\0';
 6998: 		  if(ll<jj){
 6999: 		    if(itimes==1){
 7000: 		      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 7001: 		      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 7002: 		    }else{
 7003: 		      printf(" 0.");
 7004: 		      fprintf(ficparo," 0.");
 7005: 		    }
 7006: 		  }else{
 7007: 		    if(itimes==1){
 7008: 		      printf(" Var(%s%1d%1d)",ca,i,j);
 7009: 		      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
 7010: 		    }else{
 7011: 		      printf(" 0.");
 7012: 		      fprintf(ficparo," 0.");
 7013: 		    }
 7014: 		  }
 7015: 		}
 7016: 	      } /* end lk */
 7017: 	    } /* end lj */
 7018: 	  } /* end li */
 7019: 	  printf("\n");
 7020: 	  fprintf(ficparo,"\n");
 7021: 	  numlinepar++;
 7022: 	} /* end k*/
 7023:       } /*end j */
 7024:     } /* end i */
 7025:   } /* end itimes */
 7026: 
 7027: } /* end of prwizard */
 7028: /******************* Gompertz Likelihood ******************************/
 7029: double gompertz(double x[])
 7030: { 
 7031:   double A,B,L=0.0,sump=0.,num=0.;
 7032:   int i,n=0; /* n is the size of the sample */
 7033: 
 7034:   for (i=1;i<=imx ; i++) {
 7035:     sump=sump+weight[i];
 7036:     /*    sump=sump+1;*/
 7037:     num=num+1;
 7038:   }
 7039:  
 7040:  
 7041:   /* for (i=0; i<=imx; i++) 
 7042:      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]);*/
 7043: 
 7044:   for (i=1;i<=imx ; i++)
 7045:     {
 7046:       if (cens[i] == 1 && wav[i]>1)
 7047: 	A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
 7048:       
 7049:       if (cens[i] == 0 && wav[i]>1)
 7050: 	A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
 7051: 	     +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
 7052:       
 7053:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 7054:       if (wav[i] > 1 ) { /* ??? */
 7055: 	L=L+A*weight[i];
 7056: 	/* 	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]);*/
 7057:       }
 7058:     }
 7059: 
 7060:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 7061:  
 7062:   return -2*L*num/sump;
 7063: }
 7064: 
 7065: #ifdef GSL
 7066: /******************* Gompertz_f Likelihood ******************************/
 7067: double gompertz_f(const gsl_vector *v, void *params)
 7068: { 
 7069:   double A,B,LL=0.0,sump=0.,num=0.;
 7070:   double *x= (double *) v->data;
 7071:   int i,n=0; /* n is the size of the sample */
 7072: 
 7073:   for (i=0;i<=imx-1 ; i++) {
 7074:     sump=sump+weight[i];
 7075:     /*    sump=sump+1;*/
 7076:     num=num+1;
 7077:   }
 7078:  
 7079:  
 7080:   /* for (i=0; i<=imx; i++) 
 7081:      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]);*/
 7082:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
 7083:   for (i=1;i<=imx ; i++)
 7084:     {
 7085:       if (cens[i] == 1 && wav[i]>1)
 7086: 	A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
 7087:       
 7088:       if (cens[i] == 0 && wav[i]>1)
 7089: 	A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
 7090: 	     +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
 7091:       
 7092:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 7093:       if (wav[i] > 1 ) { /* ??? */
 7094: 	LL=LL+A*weight[i];
 7095: 	/* 	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]);*/
 7096:       }
 7097:     }
 7098: 
 7099:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 7100:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
 7101:  
 7102:   return -2*LL*num/sump;
 7103: }
 7104: #endif
 7105: 
 7106: /******************* Printing html file ***********/
 7107: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
 7108: 		  int lastpass, int stepm, int weightopt, char model[],\
 7109: 		  int imx,  double p[],double **matcov,double agemortsup){
 7110:   int i,k;
 7111: 
 7112:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
 7113:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
 7114:   for (i=1;i<=2;i++) 
 7115:     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]));
 7116:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
 7117:   fprintf(fichtm,"</ul>");
 7118: 
 7119: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
 7120: 
 7121:  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>");
 7122: 
 7123:  for (k=agegomp;k<(agemortsup-2);k++) 
 7124:    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]);
 7125: 
 7126:  
 7127:   fflush(fichtm);
 7128: }
 7129: 
 7130: /******************* Gnuplot file **************/
 7131: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 7132: 
 7133:   char dirfileres[132],optfileres[132];
 7134: 
 7135:   int ng;
 7136: 
 7137: 
 7138:   /*#ifdef windows */
 7139:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 7140:     /*#endif */
 7141: 
 7142: 
 7143:   strcpy(dirfileres,optionfilefiname);
 7144:   strcpy(optfileres,"vpl");
 7145:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
 7146:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
 7147:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
 7148:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
 7149:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
 7150: 
 7151: } 
 7152: 
 7153: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
 7154: {
 7155: 
 7156:   /*-------- data file ----------*/
 7157:   FILE *fic;
 7158:   char dummy[]="                         ";
 7159:   int i=0, j=0, n=0;
 7160:   int linei, month, year,iout;
 7161:   char line[MAXLINE], linetmp[MAXLINE];
 7162:   char stra[MAXLINE], strb[MAXLINE];
 7163:   char *stratrunc;
 7164:   int lstra;
 7165: 
 7166: 
 7167:   if((fic=fopen(datafile,"r"))==NULL)    {
 7168:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
 7169:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
 7170:   }
 7171: 
 7172:   i=1;
 7173:   linei=0;
 7174:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
 7175:     linei=linei+1;
 7176:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
 7177:       if(line[j] == '\t')
 7178: 	line[j] = ' ';
 7179:     }
 7180:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
 7181:       ;
 7182:     };
 7183:     line[j+1]=0;  /* Trims blanks at end of line */
 7184:     if(line[0]=='#'){
 7185:       fprintf(ficlog,"Comment line\n%s\n",line);
 7186:       printf("Comment line\n%s\n",line);
 7187:       continue;
 7188:     }
 7189:     trimbb(linetmp,line); /* Trims multiple blanks in line */
 7190:     strcpy(line, linetmp);
 7191:   
 7192: 
 7193:     for (j=maxwav;j>=1;j--){
 7194:       cutv(stra, strb, line, ' '); 
 7195:       if(strb[0]=='.') { /* Missing status */
 7196: 	lval=-1;
 7197:       }else{
 7198: 	errno=0;
 7199: 	lval=strtol(strb,&endptr,10); 
 7200:       /*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
 7201: 	if( strb[0]=='\0' || (*endptr != '\0')){
 7202: 	  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);
 7203: 	  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);
 7204: 	  return 1;
 7205: 	}
 7206:       }
 7207:       s[j][i]=lval;
 7208:       
 7209:       strcpy(line,stra);
 7210:       cutv(stra, strb,line,' ');
 7211:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 7212:       }
 7213:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 7214: 	month=99;
 7215: 	year=9999;
 7216:       }else{
 7217: 	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);
 7218: 	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);
 7219: 	return 1;
 7220:       }
 7221:       anint[j][i]= (double) year; 
 7222:       mint[j][i]= (double)month; 
 7223:       strcpy(line,stra);
 7224:     } /* ENd Waves */
 7225:     
 7226:     cutv(stra, strb,line,' '); 
 7227:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 7228:     }
 7229:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 7230:       month=99;
 7231:       year=9999;
 7232:     }else{
 7233:       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);
 7234: 	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);
 7235: 	return 1;
 7236:     }
 7237:     andc[i]=(double) year; 
 7238:     moisdc[i]=(double) month; 
 7239:     strcpy(line,stra);
 7240:     
 7241:     cutv(stra, strb,line,' '); 
 7242:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 7243:     }
 7244:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
 7245:       month=99;
 7246:       year=9999;
 7247:     }else{
 7248:       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);
 7249:       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);
 7250: 	return 1;
 7251:     }
 7252:     if (year==9999) {
 7253:       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);
 7254:       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);
 7255: 	return 1;
 7256: 
 7257:     }
 7258:     annais[i]=(double)(year);
 7259:     moisnais[i]=(double)(month); 
 7260:     strcpy(line,stra);
 7261:     
 7262:     cutv(stra, strb,line,' '); 
 7263:     errno=0;
 7264:     dval=strtod(strb,&endptr); 
 7265:     if( strb[0]=='\0' || (*endptr != '\0')){
 7266:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
 7267:       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);
 7268:       fflush(ficlog);
 7269:       return 1;
 7270:     }
 7271:     weight[i]=dval; 
 7272:     strcpy(line,stra);
 7273:     
 7274:     for (j=ncovcol;j>=1;j--){
 7275:       cutv(stra, strb,line,' '); 
 7276:       if(strb[0]=='.') { /* Missing status */
 7277: 	lval=-1;
 7278:       }else{
 7279: 	errno=0;
 7280: 	lval=strtol(strb,&endptr,10); 
 7281: 	if( strb[0]=='\0' || (*endptr != '\0')){
 7282: 	  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);
 7283: 	  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);
 7284: 	  return 1;
 7285: 	}
 7286:       }
 7287:       if(lval <-1 || lval >1){
 7288: 	printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 7289:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 7290:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 7291:  For example, for multinomial values like 1, 2 and 3,\n \
 7292:  build V1=0 V2=0 for the reference value (1),\n \
 7293:         V1=1 V2=0 for (2) \n \
 7294:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 7295:  output of IMaCh is often meaningless.\n \
 7296:  Exiting.\n",lval,linei, i,line,j);
 7297: 	fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 7298:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 7299:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 7300:  For example, for multinomial values like 1, 2 and 3,\n \
 7301:  build V1=0 V2=0 for the reference value (1),\n \
 7302:         V1=1 V2=0 for (2) \n \
 7303:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 7304:  output of IMaCh is often meaningless.\n \
 7305:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
 7306: 	return 1;
 7307:       }
 7308:       covar[j][i]=(double)(lval);
 7309:       strcpy(line,stra);
 7310:     }  
 7311:     lstra=strlen(stra);
 7312:      
 7313:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
 7314:       stratrunc = &(stra[lstra-9]);
 7315:       num[i]=atol(stratrunc);
 7316:     }
 7317:     else
 7318:       num[i]=atol(stra);
 7319:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
 7320:       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;}*/
 7321:     
 7322:     i=i+1;
 7323:   } /* End loop reading  data */
 7324: 
 7325:   *imax=i-1; /* Number of individuals */
 7326:   fclose(fic);
 7327:  
 7328:   return (0);
 7329:   /* endread: */
 7330:     printf("Exiting readdata: ");
 7331:     fclose(fic);
 7332:     return (1);
 7333: 
 7334: 
 7335: 
 7336: }
 7337: void removespace(char *str) {
 7338:   char *p1 = str, *p2 = str;
 7339:   do
 7340:     while (*p2 == ' ')
 7341:       p2++;
 7342:   while (*p1++ == *p2++);
 7343: }
 7344: 
 7345: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
 7346:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
 7347:    * - nagesqr = 1 if age*age in the model, otherwise 0.
 7348:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
 7349:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
 7350:    * - cptcovage number of covariates with age*products =2
 7351:    * - cptcovs number of simple covariates
 7352:    * - 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
 7353:    *     which is a new column after the 9 (ncovcol) variables. 
 7354:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
 7355:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
 7356:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
 7357:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
 7358:  */
 7359: {
 7360:   int i, j, k, ks;
 7361:   int  j1, k1, k2;
 7362:   char modelsav[80];
 7363:   char stra[80], strb[80], strc[80], strd[80],stre[80];
 7364:   char *strpt;
 7365: 
 7366:   /*removespace(model);*/
 7367:   if (strlen(model) >1){ /* If there is at least 1 covariate */
 7368:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
 7369:     if (strstr(model,"AGE") !=0){
 7370:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
 7371:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
 7372:       return 1;
 7373:     }
 7374:     if (strstr(model,"v") !=0){
 7375:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
 7376:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
 7377:       return 1;
 7378:     }
 7379:     strcpy(modelsav,model); 
 7380:     if ((strpt=strstr(model,"age*age")) !=0){
 7381:       printf(" strpt=%s, model=%s\n",strpt, model);
 7382:       if(strpt != model){
 7383:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
 7384:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
 7385:  corresponding column of parameters.\n",model);
 7386:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
 7387:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
 7388:  corresponding column of parameters.\n",model); fflush(ficlog);
 7389:       return 1;
 7390:     }
 7391: 
 7392:       nagesqr=1;
 7393:       if (strstr(model,"+age*age") !=0)
 7394: 	substrchaine(modelsav, model, "+age*age");
 7395:       else if (strstr(model,"age*age+") !=0)
 7396: 	substrchaine(modelsav, model, "age*age+");
 7397:       else 
 7398: 	substrchaine(modelsav, model, "age*age");
 7399:     }else
 7400:       nagesqr=0;
 7401:     if (strlen(modelsav) >1){
 7402:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
 7403:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
 7404:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
 7405:       cptcovt= j+1; /* Number of total covariates in the model, not including
 7406: 		   * cst, age and age*age 
 7407: 		   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
 7408:                   /* including age products which are counted in cptcovage.
 7409: 		  * but the covariates which are products must be treated 
 7410: 		  * separately: ncovn=4- 2=2 (V1+V3). */
 7411:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
 7412:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
 7413: 
 7414:     
 7415:       /*   Design
 7416:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
 7417:        *  <          ncovcol=8                >
 7418:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
 7419:        *   k=  1    2      3       4     5       6      7        8
 7420:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
 7421:        *  covar[k,i], value of kth covariate if not including age for individual i:
 7422:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
 7423:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
 7424:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
 7425:        *  Tage[++cptcovage]=k
 7426:        *       if products, new covar are created after ncovcol with k1
 7427:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
 7428:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
 7429:        *  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
 7430:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
 7431:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
 7432:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
 7433:        *  <          ncovcol=8                >
 7434:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
 7435:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
 7436:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
 7437:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 7438:        * p Tprod[1]@2={                         6, 5}
 7439:        *p Tvard[1][1]@4= {7, 8, 5, 6}
 7440:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
 7441:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 7442:        *How to reorganize?
 7443:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
 7444:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 7445:        *       {2,   1,     4,      8,    5,      6,     3,       7}
 7446:        * Struct []
 7447:        */
 7448: 
 7449:       /* This loop fills the array Tvar from the string 'model'.*/
 7450:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
 7451:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
 7452:       /* 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
 7453:       /* 	k=3 V4 Tvar[k=3]= 4 (from V4) */
 7454:       /* 	k=2 V1 Tvar[k=2]= 1 (from V1) */
 7455:       /* 	k=1 Tvar[1]=2 (from V2) */
 7456:       /* 	k=5 Tvar[5] */
 7457:       /* for (k=1; k<=cptcovn;k++) { */
 7458:       /* 	cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 7459:       /* 	} */
 7460:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
 7461:       /*
 7462:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
 7463:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
 7464:         Tvar[k]=0;
 7465:       cptcovage=0;
 7466:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
 7467: 	cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
 7468: 					 modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
 7469: 	if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
 7470: 	/*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
 7471: 	/*scanf("%d",i);*/
 7472: 	if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
 7473: 	  cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
 7474: 	  if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
 7475: 	    /* covar is not filled and then is empty */
 7476: 	    cptcovprod--;
 7477: 	    cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
 7478: 	    Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
 7479: 	    cptcovage++; /* Sums the number of covariates which include age as a product */
 7480: 	    Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
 7481: 	    /*printf("stre=%s ", stre);*/
 7482: 	  } else if (strcmp(strd,"age")==0) { /* or age*Vn */
 7483: 	    cptcovprod--;
 7484: 	    cutl(stre,strb,strc,'V');
 7485: 	    Tvar[k]=atoi(stre);
 7486: 	    cptcovage++;
 7487: 	    Tage[cptcovage]=k;
 7488: 	  } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
 7489: 	    /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
 7490: 	    cptcovn++;
 7491: 	    cptcovprodnoage++;k1++;
 7492: 	    cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
 7493: 	    Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
 7494: 				   because this model-covariate is a construction we invent a new column
 7495: 				   ncovcol + k1
 7496: 				   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
 7497: 				   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
 7498: 	    cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
 7499: 	    Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
 7500: 	    Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
 7501: 	    Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
 7502: 	    k2=k2+2;
 7503: 	    Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
 7504: 	    Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
 7505: 	    for (i=1; i<=lastobs;i++){
 7506: 	      /* Computes the new covariate which is a product of
 7507: 		 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
 7508: 	      covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
 7509: 	    }
 7510: 	  } /* End age is not in the model */
 7511: 	} /* End if model includes a product */
 7512: 	else { /* no more sum */
 7513: 	  /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
 7514: 	  /*  scanf("%d",i);*/
 7515: 	  cutl(strd,strc,strb,'V');
 7516: 	  ks++; /**< Number of simple covariates */
 7517: 	  cptcovn++;
 7518: 	  Tvar[k]=atoi(strd);
 7519: 	}
 7520: 	strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
 7521: 	/*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
 7522: 	  scanf("%d",i);*/
 7523:       } /* end of loop + on total covariates */
 7524:     } /* end if strlen(modelsave == 0) age*age might exist */
 7525:   } /* end if strlen(model == 0) */
 7526:   
 7527:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
 7528:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
 7529: 
 7530:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
 7531:   printf("cptcovprod=%d ", cptcovprod);
 7532:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
 7533: 
 7534:   scanf("%d ",i);*/
 7535: 
 7536: 
 7537:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
 7538:   /*endread:*/
 7539:     printf("Exiting decodemodel: ");
 7540:     return (1);
 7541: }
 7542: 
 7543: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
 7544: {
 7545:   int i, m;
 7546:   int firstone=0;
 7547:   
 7548:   for (i=1; i<=imx; i++) {
 7549:     for(m=2; (m<= maxwav); m++) {
 7550:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
 7551: 	anint[m][i]=9999;
 7552: 	if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
 7553: 	  s[m][i]=-1;
 7554:       }
 7555:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
 7556: 	*nberr = *nberr + 1;
 7557: 	if(firstone == 0){
 7558: 	  firstone=1;
 7559: 	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 can be biased (%d) because status is a death state %d at wave %d. Wave dropped.\nOther similar cases in log file\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr,s[m][i],m);
 7560: 	}
 7561: 	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 can be biased (%d) because status is a death state %d at wave %d. Wave dropped.\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr,s[m][i],m);
 7562: 	s[m][i]=-1;
 7563:       }
 7564:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
 7565: 	(*nberr)++;
 7566: 	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]); 
 7567: 	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]); 
 7568: 	s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
 7569:       }
 7570:     }
 7571:   }
 7572: 
 7573:   for (i=1; i<=imx; i++)  {
 7574:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
 7575:     for(m=firstpass; (m<= lastpass); m++){
 7576:       if(s[m][i] >0  || s[m][i]==-1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){ /* What if s[m][i]=-1 */
 7577: 	if (s[m][i] >= nlstate+1) {
 7578: 	  if(agedc[i]>0){
 7579: 	    if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
 7580: 	      agev[m][i]=agedc[i];
 7581: 	      /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
 7582: 	    }else {
 7583: 	      if ((int)andc[i]!=9999){
 7584: 		nbwarn++;
 7585: 		printf("Warning negative age at death: %ld line:%d\n",num[i],i);
 7586: 		fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
 7587: 		agev[m][i]=-1;
 7588: 	      }
 7589: 	    }
 7590: 	  } /* agedc > 0 */
 7591: 	} /* end if */
 7592: 	else if(s[m][i] !=9){ /* Standard case, age in fractional
 7593: 				 years but with the precision of a month */
 7594: 	  agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
 7595: 	  if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
 7596: 	    agev[m][i]=1;
 7597: 	  else if(agev[m][i] < *agemin){ 
 7598: 	    *agemin=agev[m][i];
 7599: 	    printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
 7600: 	  }
 7601: 	  else if(agev[m][i] >*agemax){
 7602: 	    *agemax=agev[m][i];
 7603: 	    /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
 7604: 	  }
 7605: 	  /*agev[m][i]=anint[m][i]-annais[i];*/
 7606: 	  /*	 agev[m][i] = age[i]+2*m;*/
 7607: 	} /* en if 9*/
 7608: 	else { /* =9 */
 7609: 	  /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
 7610: 	  agev[m][i]=1;
 7611: 	  s[m][i]=-1;
 7612: 	}
 7613:       }
 7614:       else if(s[m][i]==0) /*= 0 Unknown */
 7615: 	agev[m][i]=1;
 7616:       else{
 7617: 	printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
 7618: 	fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
 7619: 	agev[m][i]=0;
 7620:       }
 7621:     } /* End for lastpass */
 7622:   }
 7623:     
 7624:   for (i=1; i<=imx; i++)  {
 7625:     for(m=firstpass; (m<=lastpass); m++){
 7626:       if (s[m][i] > (nlstate+ndeath)) {
 7627: 	(*nberr)++;
 7628: 	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);	
 7629: 	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);	
 7630: 	return 1;
 7631:       }
 7632:     }
 7633:   }
 7634: 
 7635:   /*for (i=1; i<=imx; i++){
 7636:   for (m=firstpass; (m<lastpass); m++){
 7637:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
 7638: }
 7639: 
 7640: }*/
 7641: 
 7642: 
 7643:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
 7644:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
 7645: 
 7646:   return (0);
 7647:  /* endread:*/
 7648:     printf("Exiting calandcheckages: ");
 7649:     return (1);
 7650: }
 7651: 
 7652: #if defined(_MSC_VER)
 7653: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 7654: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 7655: //#include "stdafx.h"
 7656: //#include <stdio.h>
 7657: //#include <tchar.h>
 7658: //#include <windows.h>
 7659: //#include <iostream>
 7660: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
 7661: 
 7662: LPFN_ISWOW64PROCESS fnIsWow64Process;
 7663: 
 7664: BOOL IsWow64()
 7665: {
 7666: 	BOOL bIsWow64 = FALSE;
 7667: 
 7668: 	//typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
 7669: 	//  (HANDLE, PBOOL);
 7670: 
 7671: 	//LPFN_ISWOW64PROCESS fnIsWow64Process;
 7672: 
 7673: 	HMODULE module = GetModuleHandle(_T("kernel32"));
 7674: 	const char funcName[] = "IsWow64Process";
 7675: 	fnIsWow64Process = (LPFN_ISWOW64PROCESS)
 7676: 		GetProcAddress(module, funcName);
 7677: 
 7678: 	if (NULL != fnIsWow64Process)
 7679: 	{
 7680: 		if (!fnIsWow64Process(GetCurrentProcess(),
 7681: 			&bIsWow64))
 7682: 			//throw std::exception("Unknown error");
 7683: 			printf("Unknown error\n");
 7684: 	}
 7685: 	return bIsWow64 != FALSE;
 7686: }
 7687: #endif
 7688: 
 7689: void syscompilerinfo(int logged)
 7690:  {
 7691:    /* #include "syscompilerinfo.h"*/
 7692:    /* command line Intel compiler 32bit windows, XP compatible:*/
 7693:    /* /GS /W3 /Gy
 7694:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
 7695:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
 7696:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
 7697:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
 7698:    */ 
 7699:    /* 64 bits */
 7700:    /*
 7701:      /GS /W3 /Gy
 7702:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
 7703:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
 7704:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
 7705:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
 7706:    /* Optimization are useless and O3 is slower than O2 */
 7707:    /*
 7708:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
 7709:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
 7710:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
 7711:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
 7712:    */
 7713:    /* Link is */ /* /OUT:"visual studio
 7714:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
 7715:       /PDB:"visual studio
 7716:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
 7717:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
 7718:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
 7719:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
 7720:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
 7721:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
 7722:       uiAccess='false'"
 7723:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
 7724:       /NOLOGO /TLBID:1
 7725:    */
 7726: #if defined __INTEL_COMPILER
 7727: #if defined(__GNUC__)
 7728: 	struct utsname sysInfo;  /* For Intel on Linux and OS/X */
 7729: #endif
 7730: #elif defined(__GNUC__) 
 7731: #ifndef  __APPLE__
 7732: #include <gnu/libc-version.h>  /* Only on gnu */
 7733: #endif
 7734:    struct utsname sysInfo;
 7735:    int cross = CROSS;
 7736:    if (cross){
 7737: 	   printf("Cross-");
 7738: 	   if(logged) fprintf(ficlog, "Cross-");
 7739:    }
 7740: #endif
 7741: 
 7742: #include <stdint.h>
 7743: 
 7744:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
 7745: #if defined(__clang__)
 7746:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");	/* Clang/LLVM. ---------------------------------------------- */
 7747: #endif
 7748: #if defined(__ICC) || defined(__INTEL_COMPILER)
 7749:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
 7750: #endif
 7751: #if defined(__GNUC__) || defined(__GNUG__)
 7752:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
 7753: #endif
 7754: #if defined(__HP_cc) || defined(__HP_aCC)
 7755:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
 7756: #endif
 7757: #if defined(__IBMC__) || defined(__IBMCPP__)
 7758:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
 7759: #endif
 7760: #if defined(_MSC_VER)
 7761:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
 7762: #endif
 7763: #if defined(__PGI)
 7764:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
 7765: #endif
 7766: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
 7767:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
 7768: #endif
 7769:    printf(" for "); if (logged) fprintf(ficlog, " for ");
 7770:    
 7771: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
 7772: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
 7773:     // Windows (x64 and x86)
 7774:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
 7775: #elif __unix__ // all unices, not all compilers
 7776:     // Unix
 7777:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
 7778: #elif __linux__
 7779:     // linux
 7780:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
 7781: #elif __APPLE__
 7782:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
 7783:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
 7784: #endif
 7785: 
 7786: /*  __MINGW32__	  */
 7787: /*  __CYGWIN__	 */
 7788: /* __MINGW64__  */
 7789: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
 7790: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
 7791: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
 7792: /* _WIN64  // Defined for applications for Win64. */
 7793: /* _M_X64 // Defined for compilations that target x64 processors. */
 7794: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
 7795: 
 7796: #if UINTPTR_MAX == 0xffffffff
 7797:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
 7798: #elif UINTPTR_MAX == 0xffffffffffffffff
 7799:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
 7800: #else
 7801:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
 7802: #endif
 7803: 
 7804: #if defined(__GNUC__)
 7805: # if defined(__GNUC_PATCHLEVEL__)
 7806: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 7807:                             + __GNUC_MINOR__ * 100 \
 7808:                             + __GNUC_PATCHLEVEL__)
 7809: # else
 7810: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 7811:                             + __GNUC_MINOR__ * 100)
 7812: # endif
 7813:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
 7814:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
 7815: 
 7816:    if (uname(&sysInfo) != -1) {
 7817:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 7818: 	 if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 7819:    }
 7820:    else
 7821:       perror("uname() error");
 7822:    //#ifndef __INTEL_COMPILER 
 7823: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
 7824:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
 7825:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
 7826: #endif
 7827: #endif
 7828: 
 7829:    //   void main()
 7830:    //   {
 7831: #if defined(_MSC_VER)
 7832:    if (IsWow64()){
 7833: 	   printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 7834: 	   if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 7835:    }
 7836:    else{
 7837: 	   printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 7838: 	   if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 7839:    }
 7840:    //	   printf("\nPress Enter to continue...");
 7841:    //	   getchar();
 7842:    //   }
 7843: 
 7844: #endif
 7845:    
 7846: 
 7847: }
 7848: 
 7849: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
 7850:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 7851:   int i, j, k, i1 ;
 7852:   /* double ftolpl = 1.e-10; */
 7853:   double age, agebase, agelim;
 7854:   double tot;
 7855: 
 7856:   strcpy(filerespl,"PL_");
 7857:   strcat(filerespl,fileresu);
 7858:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
 7859:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
 7860:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
 7861:   }
 7862:   printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
 7863:   fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
 7864:   pstamp(ficrespl);
 7865:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
 7866:   fprintf(ficrespl,"#Age ");
 7867:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
 7868:   fprintf(ficrespl,"\n");
 7869:   
 7870:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
 7871: 
 7872:   agebase=ageminpar;
 7873:   agelim=agemaxpar;
 7874: 
 7875:   i1=pow(2,cptcoveff);
 7876:   if (cptcovn < 1){i1=1;}
 7877: 
 7878:   for(k=1; k<=i1;k++){
 7879:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 7880:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
 7881:     //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 7882:     /* k=k+1; */
 7883:     /* to clean */
 7884:     //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
 7885:     fprintf(ficrespl,"#******");
 7886:     printf("#******");
 7887:     fprintf(ficlog,"#******");
 7888:     for(j=1;j<=cptcoveff;j++) {
 7889:       fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7890:       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7891:       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7892:     }
 7893:     fprintf(ficrespl,"******\n");
 7894:     printf("******\n");
 7895:     fprintf(ficlog,"******\n");
 7896: 		if(invalidvarcomb[k]){
 7897: 						printf("\nCombination (%d) ignored because no cases \n",k); 
 7898: 						fprintf(ficrespl,"#Combination (%d) ignored because no cases \n",k); 
 7899: 						fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
 7900: 						continue;
 7901: 		}
 7902: 
 7903:     fprintf(ficrespl,"#Age ");
 7904:     for(j=1;j<=cptcoveff;j++) {
 7905:       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7906:     }
 7907:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
 7908:     fprintf(ficrespl,"Total Years_to_converge\n");
 7909: 	
 7910:     for (age=agebase; age<=agelim; age++){
 7911:       /* for (age=agebase; age<=agebase; age++){ */
 7912:       prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
 7913:       fprintf(ficrespl,"%.0f ",age );
 7914:       for(j=1;j<=cptcoveff;j++)
 7915: 							fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7916:       tot=0.;
 7917:       for(i=1; i<=nlstate;i++){
 7918: 							tot +=  prlim[i][i];
 7919: 							fprintf(ficrespl," %.5f", prlim[i][i]);
 7920:       }
 7921:       fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
 7922:     } /* Age */
 7923:     /* was end of cptcod */
 7924:   } /* cptcov */
 7925:   return 0;
 7926: }
 7927: 
 7928: int back_prevalence_limit(double *p, double **bprlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp, double dateprev1,double dateprev2, int firstpass, int lastpass, int mobilavproj){
 7929: 	/*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
 7930: 	
 7931: 	/* Computes the back prevalence limit  for any combination	of covariate values 
 7932:    * at any age between ageminpar and agemaxpar
 7933: 	 */
 7934:   int i, j, k, i1 ;
 7935:   /* double ftolpl = 1.e-10; */
 7936:   double age, agebase, agelim;
 7937:   double tot;
 7938:   /* double ***mobaverage; */
 7939:   /* double	 **dnewm, **doldm, **dsavm;  /\* for use *\/ */
 7940: 
 7941:   strcpy(fileresplb,"PLB_");
 7942:   strcat(fileresplb,fileresu);
 7943:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
 7944:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
 7945:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
 7946:   }
 7947:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
 7948:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
 7949:   pstamp(ficresplb);
 7950:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
 7951:   fprintf(ficresplb,"#Age ");
 7952:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
 7953:   fprintf(ficresplb,"\n");
 7954:   
 7955:   
 7956:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
 7957:   
 7958:   agebase=ageminpar;
 7959:   agelim=agemaxpar;
 7960:   
 7961:   
 7962:   i1=pow(2,cptcoveff);
 7963:   if (cptcovn < 1){i1=1;}
 7964: 
 7965: 	for(k=1; k<=i1;k++){ 
 7966:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 7967:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
 7968:     //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 7969:     /* k=k+1; */
 7970:     /* to clean */
 7971:     //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
 7972:     fprintf(ficresplb,"#******");
 7973:     printf("#******");
 7974:     fprintf(ficlog,"#******");
 7975:     for(j=1;j<=cptcoveff;j++) {
 7976:       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7977:       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7978:       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7979:     }
 7980:     fprintf(ficresplb,"******\n");
 7981:     printf("******\n");
 7982:     fprintf(ficlog,"******\n");
 7983: 		if(invalidvarcomb[k]){
 7984: 						printf("\nCombination (%d) ignored because no cases \n",k); 
 7985: 						fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
 7986: 						fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
 7987: 						continue;
 7988: 		}
 7989:     
 7990:     fprintf(ficresplb,"#Age ");
 7991:     for(j=1;j<=cptcoveff;j++) {
 7992:       fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7993:     }
 7994:     for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
 7995:     fprintf(ficresplb,"Total Years_to_converge\n");
 7996:     
 7997:     
 7998:     for (age=agebase; age<=agelim; age++){
 7999:       /* for (age=agebase; age<=agebase; age++){ */
 8000:       if(mobilavproj > 0){
 8001: 	/* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
 8002: 	/* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
 8003: 				bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k);
 8004:       }else if (mobilavproj == 0){
 8005: 				printf("There is no chance to get back prevalence limit if data aren't non zero and summing to 1, please try a non null mobil_average(=%d) parameter or mobil_average=-1 if you want to try at your own risk.\n",mobilavproj);
 8006: 				fprintf(ficlog,"There is no chance to get back prevalence limit if data aren't non zero and summing to 1, please try a non null mobil_average(=%d) parameter or mobil_average=-1 if you want to try at your own risk.\n",mobilavproj);
 8007: 				exit(1);
 8008:       }else{
 8009: 				/* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
 8010: 				bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k);
 8011:       }
 8012:       fprintf(ficresplb,"%.0f ",age );
 8013:       for(j=1;j<=cptcoveff;j++)
 8014: 				fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8015:       tot=0.;
 8016:       for(i=1; i<=nlstate;i++){
 8017: 				tot +=  bprlim[i][i];
 8018: 				fprintf(ficresplb," %.5f", bprlim[i][i]);
 8019:       }
 8020:       fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
 8021:     } /* Age */
 8022:     /* was end of cptcod */
 8023:   } /* cptcov */
 8024:   
 8025:   /* hBijx(p, bage, fage); */
 8026:   /* fclose(ficrespijb); */
 8027:   
 8028:   return 0;
 8029: }
 8030:  
 8031: int hPijx(double *p, int bage, int fage){
 8032:     /*------------- h Pij x at various ages ------------*/
 8033: 
 8034:   int stepsize;
 8035:   int agelim;
 8036:   int hstepm;
 8037:   int nhstepm;
 8038:   int h, i, i1, j, k;
 8039: 
 8040:   double agedeb;
 8041:   double ***p3mat;
 8042: 
 8043:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
 8044:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
 8045:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
 8046:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
 8047:     }
 8048:     printf("Computing pij: result on file '%s' \n", filerespij);
 8049:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
 8050:   
 8051:     stepsize=(int) (stepm+YEARM-1)/YEARM;
 8052:     /*if (stepm<=24) stepsize=2;*/
 8053: 
 8054:     agelim=AGESUP;
 8055:     hstepm=stepsize*YEARM; /* Every year of age */
 8056:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
 8057: 		
 8058:     /* hstepm=1;   aff par mois*/
 8059:     pstamp(ficrespij);
 8060:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
 8061:     i1= pow(2,cptcoveff);
 8062: 		/* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 8063: 		/*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
 8064: 		/*  	k=k+1;  */
 8065:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 8066:       fprintf(ficrespij,"\n#****** ");
 8067:       for(j=1;j<=cptcoveff;j++) 
 8068: 	fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8069:       fprintf(ficrespij,"******\n");
 8070:       
 8071:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
 8072: 	nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 8073: 	nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 8074: 	
 8075: 	/*	  nhstepm=nhstepm*YEARM; aff par mois*/
 8076: 	
 8077: 	p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 8078: 	oldm=oldms;savm=savms;
 8079: 	hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 8080: 	fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
 8081: 	for(i=1; i<=nlstate;i++)
 8082: 	  for(j=1; j<=nlstate+ndeath;j++)
 8083: 	    fprintf(ficrespij," %1d-%1d",i,j);
 8084: 	fprintf(ficrespij,"\n");
 8085: 	for (h=0; h<=nhstepm; h++){
 8086: 	  /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
 8087: 	  fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
 8088: 	  for(i=1; i<=nlstate;i++)
 8089: 	    for(j=1; j<=nlstate+ndeath;j++)
 8090: 	      fprintf(ficrespij," %.5f", p3mat[i][j][h]);
 8091: 	  fprintf(ficrespij,"\n");
 8092: 	}
 8093: 	free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 8094: 	fprintf(ficrespij,"\n");
 8095:       }
 8096:       /*}*/
 8097:     }
 8098:     return 0;
 8099: }
 8100:  
 8101:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
 8102:     /*------------- h Bij x at various ages ------------*/
 8103: 
 8104:   int stepsize;
 8105:   /* int agelim; */
 8106: 	int ageminl;
 8107:   int hstepm;
 8108:   int nhstepm;
 8109:   int h, i, i1, j, k;
 8110: 	
 8111:   double agedeb;
 8112:   double ***p3mat;
 8113: 	
 8114:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
 8115:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
 8116:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
 8117:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
 8118:   }
 8119:   printf("Computing pij back: result on file '%s' \n", filerespijb);
 8120:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
 8121:   
 8122:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 8123:   /*if (stepm<=24) stepsize=2;*/
 8124:   
 8125:   /* agelim=AGESUP; */
 8126:   ageminl=30;
 8127:   hstepm=stepsize*YEARM; /* Every year of age */
 8128:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
 8129:   
 8130:   /* hstepm=1;   aff par mois*/
 8131:   pstamp(ficrespijb);
 8132:   fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
 8133:   i1= pow(2,cptcoveff);
 8134:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 8135:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
 8136:   /*  	k=k+1;  */
 8137:   for (k=1; k <= (int) pow(2,cptcoveff); k++){
 8138:     fprintf(ficrespijb,"\n#****** ");
 8139:     for(j=1;j<=cptcoveff;j++)
 8140:       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8141:     fprintf(ficrespijb,"******\n");
 8142:     if(invalidvarcomb[k]){
 8143:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
 8144:       continue;
 8145:     }
 8146:     
 8147:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
 8148:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
 8149:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
 8150:       nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
 8151:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
 8152:       
 8153:       /*	  nhstepm=nhstepm*YEARM; aff par mois*/
 8154:       
 8155:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 8156:       /* oldm=oldms;savm=savms; */
 8157:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
 8158:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
 8159:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
 8160:       fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
 8161:       for(i=1; i<=nlstate;i++)
 8162: 	for(j=1; j<=nlstate+ndeath;j++)
 8163: 	  fprintf(ficrespijb," %1d-%1d",i,j);
 8164:       fprintf(ficrespijb,"\n");
 8165:       for (h=0; h<=nhstepm; h++){
 8166: 	/*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
 8167: 	fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
 8168: 	/* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
 8169: 	for(i=1; i<=nlstate;i++)
 8170: 	  for(j=1; j<=nlstate+ndeath;j++)
 8171: 	    fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
 8172: 	fprintf(ficrespijb,"\n");
 8173:       }
 8174:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 8175:       fprintf(ficrespijb,"\n");
 8176:     }
 8177:     /*}*/
 8178:   }
 8179:   return 0;
 8180:  } /*  hBijx */
 8181: 
 8182: 
 8183: /***********************************************/
 8184: /**************** Main Program *****************/
 8185: /***********************************************/
 8186: 
 8187: int main(int argc, char *argv[])
 8188: {
 8189: #ifdef GSL
 8190:   const gsl_multimin_fminimizer_type *T;
 8191:   size_t iteri = 0, it;
 8192:   int rval = GSL_CONTINUE;
 8193:   int status = GSL_SUCCESS;
 8194:   double ssval;
 8195: #endif
 8196:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
 8197:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
 8198:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
 8199:   int jj, ll, li, lj, lk;
 8200:   int numlinepar=0; /* Current linenumber of parameter file */
 8201:   int num_filled;
 8202:   int itimes;
 8203:   int NDIM=2;
 8204:   int vpopbased=0;
 8205: 
 8206:   char ca[32], cb[32];
 8207:   /*  FILE *fichtm; *//* Html File */
 8208:   /* FILE *ficgp;*/ /*Gnuplot File */
 8209:   struct stat info;
 8210:   double agedeb=0.;
 8211: 
 8212:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
 8213:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
 8214: 
 8215:   double fret;
 8216:   double dum=0.; /* Dummy variable */
 8217:   double ***p3mat;
 8218:   /* double ***mobaverage; */
 8219: 
 8220:   char line[MAXLINE];
 8221:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
 8222: 
 8223:   char model[MAXLINE], modeltemp[MAXLINE];
 8224:   char pathr[MAXLINE], pathimach[MAXLINE]; 
 8225:   char *tok, *val; /* pathtot */
 8226:   int firstobs=1, lastobs=10;
 8227:   int c,  h , cpt, c2;
 8228:   int jl=0;
 8229:   int i1, j1, jk, stepsize=0;
 8230:   int count=0;
 8231: 
 8232:   int *tab; 
 8233:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
 8234:   int backcast=0;
 8235:   int mobilav=0,popforecast=0;
 8236:   int hstepm=0, nhstepm=0;
 8237:   int agemortsup;
 8238:   float  sumlpop=0.;
 8239:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
 8240:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
 8241: 
 8242:   double bage=0, fage=110., age, agelim=0., agebase=0.;
 8243:   double ftolpl=FTOL;
 8244:   double **prlim;
 8245:   double **bprlim;
 8246:   double ***param; /* Matrix of parameters */
 8247:   double  *p;
 8248:   double **matcov; /* Matrix of covariance */
 8249:   double **hess; /* Hessian matrix */
 8250:   double ***delti3; /* Scale */
 8251:   double *delti; /* Scale */
 8252:   double ***eij, ***vareij;
 8253:   double **varpl; /* Variances of prevalence limits by age */
 8254:   double *epj, vepp;
 8255: 
 8256:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
 8257:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
 8258: 
 8259:   double **ximort;
 8260:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
 8261:   int *dcwave;
 8262: 
 8263:   char z[1]="c";
 8264: 
 8265:   /*char  *strt;*/
 8266:   char strtend[80];
 8267: 
 8268: 
 8269: /*   setlocale (LC_ALL, ""); */
 8270: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
 8271: /*   textdomain (PACKAGE); */
 8272: /*   setlocale (LC_CTYPE, ""); */
 8273: /*   setlocale (LC_MESSAGES, ""); */
 8274: 
 8275:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
 8276:   rstart_time = time(NULL);  
 8277:   /*  (void) gettimeofday(&start_time,&tzp);*/
 8278:   start_time = *localtime(&rstart_time);
 8279:   curr_time=start_time;
 8280:   /*tml = *localtime(&start_time.tm_sec);*/
 8281:   /* strcpy(strstart,asctime(&tml)); */
 8282:   strcpy(strstart,asctime(&start_time));
 8283: 
 8284: /*  printf("Localtime (at start)=%s",strstart); */
 8285: /*  tp.tm_sec = tp.tm_sec +86400; */
 8286: /*  tm = *localtime(&start_time.tm_sec); */
 8287: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
 8288: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
 8289: /*   tmg.tm_hour=tmg.tm_hour + 1; */
 8290: /*   tp.tm_sec = mktime(&tmg); */
 8291: /*   strt=asctime(&tmg); */
 8292: /*   printf("Time(after) =%s",strstart);  */
 8293: /*  (void) time (&time_value);
 8294: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
 8295: *  tm = *localtime(&time_value);
 8296: *  strstart=asctime(&tm);
 8297: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
 8298: */
 8299: 
 8300:   nberr=0; /* Number of errors and warnings */
 8301:   nbwarn=0;
 8302: #ifdef WIN32
 8303:   _getcwd(pathcd, size);
 8304: #else
 8305:   getcwd(pathcd, size);
 8306: #endif
 8307:   syscompilerinfo(0);
 8308:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
 8309:   if(argc <=1){
 8310:     printf("\nEnter the parameter file name: ");
 8311:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
 8312:       printf("ERROR Empty parameter file name\n");
 8313:       goto end;
 8314:     }
 8315:     i=strlen(pathr);
 8316:     if(pathr[i-1]=='\n')
 8317:       pathr[i-1]='\0';
 8318:     i=strlen(pathr);
 8319:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
 8320:       pathr[i-1]='\0';
 8321:     }
 8322:     i=strlen(pathr);
 8323:     if( i==0 ){
 8324:       printf("ERROR Empty parameter file name\n");
 8325:       goto end;
 8326:     }
 8327:     for (tok = pathr; tok != NULL; ){
 8328:       printf("Pathr |%s|\n",pathr);
 8329:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
 8330:       printf("val= |%s| pathr=%s\n",val,pathr);
 8331:       strcpy (pathtot, val);
 8332:       if(pathr[0] == '\0') break; /* Dirty */
 8333:     }
 8334:   }
 8335:   else{
 8336:     strcpy(pathtot,argv[1]);
 8337:   }
 8338:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
 8339:   /*cygwin_split_path(pathtot,path,optionfile);
 8340:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
 8341:   /* cutv(path,optionfile,pathtot,'\\');*/
 8342: 
 8343:   /* Split argv[0], imach program to get pathimach */
 8344:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
 8345:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 8346:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 8347:  /*   strcpy(pathimach,argv[0]); */
 8348:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
 8349:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
 8350:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
 8351: #ifdef WIN32
 8352:   _chdir(path); /* Can be a relative path */
 8353:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
 8354: #else
 8355:   chdir(path); /* Can be a relative path */
 8356:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
 8357: #endif
 8358:   printf("Current directory %s!\n",pathcd);
 8359:   strcpy(command,"mkdir ");
 8360:   strcat(command,optionfilefiname);
 8361:   if((outcmd=system(command)) != 0){
 8362:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
 8363:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
 8364:     /* fclose(ficlog); */
 8365: /*     exit(1); */
 8366:   }
 8367: /*   if((imk=mkdir(optionfilefiname))<0){ */
 8368: /*     perror("mkdir"); */
 8369: /*   } */
 8370: 
 8371:   /*-------- arguments in the command line --------*/
 8372: 
 8373:   /* Main Log file */
 8374:   strcat(filelog, optionfilefiname);
 8375:   strcat(filelog,".log");    /* */
 8376:   if((ficlog=fopen(filelog,"w"))==NULL)    {
 8377:     printf("Problem with logfile %s\n",filelog);
 8378:     goto end;
 8379:   }
 8380:   fprintf(ficlog,"Log filename:%s\n",filelog);
 8381:   fprintf(ficlog,"Version %s %s",version,fullversion);
 8382:   fprintf(ficlog,"\nEnter the parameter file name: \n");
 8383:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
 8384:  path=%s \n\
 8385:  optionfile=%s\n\
 8386:  optionfilext=%s\n\
 8387:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
 8388: 
 8389:   syscompilerinfo(1);
 8390: 
 8391:   printf("Local time (at start):%s",strstart);
 8392:   fprintf(ficlog,"Local time (at start): %s",strstart);
 8393:   fflush(ficlog);
 8394: /*   (void) gettimeofday(&curr_time,&tzp); */
 8395: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
 8396: 
 8397:   /* */
 8398:   strcpy(fileres,"r");
 8399:   strcat(fileres, optionfilefiname);
 8400:   strcat(fileresu, optionfilefiname); /* Without r in front */
 8401:   strcat(fileres,".txt");    /* Other files have txt extension */
 8402:   strcat(fileresu,".txt");    /* Other files have txt extension */
 8403: 
 8404:   /* Main ---------arguments file --------*/
 8405: 
 8406:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
 8407:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 8408:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 8409:     fflush(ficlog);
 8410:     /* goto end; */
 8411:     exit(70); 
 8412:   }
 8413: 
 8414: 
 8415: 
 8416:   strcpy(filereso,"o");
 8417:   strcat(filereso,fileresu);
 8418:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
 8419:     printf("Problem with Output resultfile: %s\n", filereso);
 8420:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
 8421:     fflush(ficlog);
 8422:     goto end;
 8423:   }
 8424: 
 8425:   /* Reads comments: lines beginning with '#' */
 8426:   numlinepar=0;
 8427: 
 8428:     /* First parameter line */
 8429:   while(fgets(line, MAXLINE, ficpar)) {
 8430:     /* If line starts with a # it is a comment */
 8431:     if (line[0] == '#') {
 8432:       numlinepar++;
 8433:       fputs(line,stdout);
 8434:       fputs(line,ficparo);
 8435:       fputs(line,ficlog);
 8436:       continue;
 8437:     }else
 8438:       break;
 8439:   }
 8440:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
 8441: 			title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
 8442:     if (num_filled != 5) {
 8443:       printf("Should be 5 parameters\n");
 8444:     }
 8445:     numlinepar++;
 8446:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
 8447:   }
 8448:   /* Second parameter line */
 8449:   while(fgets(line, MAXLINE, ficpar)) {
 8450:     /* If line starts with a # it is a comment */
 8451:     if (line[0] == '#') {
 8452:       numlinepar++;
 8453:       fputs(line,stdout);
 8454:       fputs(line,ficparo);
 8455:       fputs(line,ficlog);
 8456:       continue;
 8457:     }else
 8458:       break;
 8459:   }
 8460:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
 8461: 			&ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
 8462:     if (num_filled != 8) {
 8463:       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");
 8464:       printf("but line=%s\n",line);
 8465:     }
 8466:     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);
 8467:   }
 8468:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
 8469:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
 8470:   /* Third parameter line */
 8471:   while(fgets(line, MAXLINE, ficpar)) {
 8472:     /* If line starts with a # it is a comment */
 8473:     if (line[0] == '#') {
 8474:       numlinepar++;
 8475:       fputs(line,stdout);
 8476:       fputs(line,ficparo);
 8477:       fputs(line,ficlog);
 8478:       continue;
 8479:     }else
 8480:       break;
 8481:   }
 8482:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
 8483:     if (num_filled == 0)
 8484:             model[0]='\0';
 8485:     else if (num_filled != 1){
 8486:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
 8487:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
 8488:       model[0]='\0';
 8489:       goto end;
 8490:     }
 8491:     else{
 8492:       if (model[0]=='+'){
 8493: 	for(i=1; i<=strlen(model);i++)
 8494: 	  modeltemp[i-1]=model[i];
 8495: 	strcpy(model,modeltemp); 
 8496:       }
 8497:     }
 8498:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
 8499:     printf("model=1+age+%s\n",model);fflush(stdout);
 8500:   }
 8501:   /* 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); */
 8502:   /* numlinepar=numlinepar+3; /\* In general *\/ */
 8503:   /* 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); */
 8504:   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);
 8505:   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);
 8506:   fflush(ficlog);
 8507:   /* if(model[0]=='#'|| model[0]== '\0'){ */
 8508:   if(model[0]=='#'){
 8509:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
 8510:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
 8511:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");		\
 8512:     if(mle != -1){
 8513:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
 8514:       exit(1);
 8515:     }
 8516:   }
 8517:   while((c=getc(ficpar))=='#' && c!= EOF){
 8518:     ungetc(c,ficpar);
 8519:     fgets(line, MAXLINE, ficpar);
 8520:     numlinepar++;
 8521:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
 8522:       z[0]=line[1];
 8523:     }
 8524:     /* printf("****line [1] = %c \n",line[1]); */
 8525:     fputs(line, stdout);
 8526:     //puts(line);
 8527:     fputs(line,ficparo);
 8528:     fputs(line,ficlog);
 8529:   }
 8530:   ungetc(c,ficpar);
 8531: 
 8532:    
 8533:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
 8534:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
 8535:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
 8536:      v1+v2*age+v2*v3 makes cptcovn = 3
 8537:   */
 8538:   if (strlen(model)>1) 
 8539:     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*/
 8540:   else
 8541:     ncovmodel=2; /* Constant and age */
 8542:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
 8543:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
 8544:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
 8545:     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);
 8546:     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);
 8547:     fflush(stdout);
 8548:     fclose (ficlog);
 8549:     goto end;
 8550:   }
 8551:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 8552:   delti=delti3[1][1];
 8553:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
 8554:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
 8555:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 8556:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 8557:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 8558:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 8559:     fclose (ficparo);
 8560:     fclose (ficlog);
 8561:     goto end;
 8562:     exit(0);
 8563:   }  else if(mle==-5) { /* Main Wizard */
 8564:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 8565:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 8566:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 8567:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 8568:     matcov=matrix(1,npar,1,npar);
 8569:     hess=matrix(1,npar,1,npar);
 8570:   }  else{ /* Begin of mle != -1 or -5 */
 8571:     /* Read guessed parameters */
 8572:     /* Reads comments: lines beginning with '#' */
 8573:     while((c=getc(ficpar))=='#' && c!= EOF){
 8574:       ungetc(c,ficpar);
 8575:       fgets(line, MAXLINE, ficpar);
 8576:       numlinepar++;
 8577:       fputs(line,stdout);
 8578:       fputs(line,ficparo);
 8579:       fputs(line,ficlog);
 8580:     }
 8581:     ungetc(c,ficpar);
 8582:     
 8583:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 8584:     for(i=1; i <=nlstate; i++){
 8585: 			j=0;
 8586:       for(jj=1; jj <=nlstate+ndeath; jj++){
 8587: 				if(jj==i) continue;
 8588: 				j++;
 8589: 				fscanf(ficpar,"%1d%1d",&i1,&j1);
 8590: 				if ((i1 != i) || (j1 != jj)){
 8591: 					printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
 8592: It might be a problem of design; if ncovcol and the model are correct\n \
 8593: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
 8594: 					exit(1);
 8595: 				}
 8596: 				fprintf(ficparo,"%1d%1d",i1,j1);
 8597: 				if(mle==1)
 8598: 					printf("%1d%1d",i,jj);
 8599: 				fprintf(ficlog,"%1d%1d",i,jj);
 8600: 				for(k=1; k<=ncovmodel;k++){
 8601: 					fscanf(ficpar," %lf",&param[i][j][k]);
 8602: 					if(mle==1){
 8603: 						printf(" %lf",param[i][j][k]);
 8604: 						fprintf(ficlog," %lf",param[i][j][k]);
 8605: 					}
 8606: 					else
 8607: 						fprintf(ficlog," %lf",param[i][j][k]);
 8608: 					fprintf(ficparo," %lf",param[i][j][k]);
 8609: 				}
 8610: 				fscanf(ficpar,"\n");
 8611: 				numlinepar++;
 8612: 				if(mle==1)
 8613: 					printf("\n");
 8614: 				fprintf(ficlog,"\n");
 8615: 				fprintf(ficparo,"\n");
 8616:       }
 8617:     }  
 8618:     fflush(ficlog);
 8619: 
 8620:     /* Reads scales values */
 8621:     p=param[1][1];
 8622:     
 8623:     /* Reads comments: lines beginning with '#' */
 8624:     while((c=getc(ficpar))=='#' && c!= EOF){
 8625:       ungetc(c,ficpar);
 8626:       fgets(line, MAXLINE, ficpar);
 8627:       numlinepar++;
 8628:       fputs(line,stdout);
 8629:       fputs(line,ficparo);
 8630:       fputs(line,ficlog);
 8631:     }
 8632:     ungetc(c,ficpar);
 8633: 
 8634:     for(i=1; i <=nlstate; i++){
 8635:       for(j=1; j <=nlstate+ndeath-1; j++){
 8636: 				fscanf(ficpar,"%1d%1d",&i1,&j1);
 8637: 				if ( (i1-i) * (j1-j) != 0){
 8638: 					printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
 8639: 					exit(1);
 8640: 				}
 8641: 				printf("%1d%1d",i,j);
 8642: 				fprintf(ficparo,"%1d%1d",i1,j1);
 8643: 				fprintf(ficlog,"%1d%1d",i1,j1);
 8644: 				for(k=1; k<=ncovmodel;k++){
 8645: 					fscanf(ficpar,"%le",&delti3[i][j][k]);
 8646: 					printf(" %le",delti3[i][j][k]);
 8647: 					fprintf(ficparo," %le",delti3[i][j][k]);
 8648: 					fprintf(ficlog," %le",delti3[i][j][k]);
 8649: 				}
 8650: 				fscanf(ficpar,"\n");
 8651: 				numlinepar++;
 8652: 				printf("\n");
 8653: 				fprintf(ficparo,"\n");
 8654: 				fprintf(ficlog,"\n");
 8655:       }
 8656:     }
 8657:     fflush(ficlog);
 8658: 		
 8659:     /* Reads covariance matrix */
 8660:     delti=delti3[1][1];
 8661: 		
 8662: 		
 8663:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
 8664: 		
 8665:     /* Reads comments: lines beginning with '#' */
 8666:     while((c=getc(ficpar))=='#' && c!= EOF){
 8667:       ungetc(c,ficpar);
 8668:       fgets(line, MAXLINE, ficpar);
 8669:       numlinepar++;
 8670:       fputs(line,stdout);
 8671:       fputs(line,ficparo);
 8672:       fputs(line,ficlog);
 8673:     }
 8674:     ungetc(c,ficpar);
 8675: 		
 8676:     matcov=matrix(1,npar,1,npar);
 8677:     hess=matrix(1,npar,1,npar);
 8678:     for(i=1; i <=npar; i++)
 8679:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
 8680: 		
 8681:     /* Scans npar lines */
 8682:     for(i=1; i <=npar; i++){
 8683:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
 8684:       if(count != 3){
 8685: 				printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
 8686: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
 8687: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
 8688: 				fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
 8689: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
 8690: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
 8691: 				exit(1);
 8692:       }else{
 8693: 				if(mle==1)
 8694: 					printf("%1d%1d%1d",i1,j1,jk);
 8695: 			}
 8696:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
 8697:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
 8698:       for(j=1; j <=i; j++){
 8699: 				fscanf(ficpar," %le",&matcov[i][j]);
 8700: 				if(mle==1){
 8701: 					printf(" %.5le",matcov[i][j]);
 8702: 				}
 8703: 				fprintf(ficlog," %.5le",matcov[i][j]);
 8704: 				fprintf(ficparo," %.5le",matcov[i][j]);
 8705:       }
 8706:       fscanf(ficpar,"\n");
 8707:       numlinepar++;
 8708:       if(mle==1)
 8709: 				printf("\n");
 8710:       fprintf(ficlog,"\n");
 8711:       fprintf(ficparo,"\n");
 8712:     }
 8713:     /* End of read covariance matrix npar lines */
 8714:     for(i=1; i <=npar; i++)
 8715:       for(j=i+1;j<=npar;j++)
 8716: 				matcov[i][j]=matcov[j][i];
 8717:     
 8718:     if(mle==1)
 8719:       printf("\n");
 8720:     fprintf(ficlog,"\n");
 8721:     
 8722:     fflush(ficlog);
 8723:     
 8724:     /*-------- Rewriting parameter file ----------*/
 8725:     strcpy(rfileres,"r");    /* "Rparameterfile */
 8726:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
 8727:     strcat(rfileres,".");    /* */
 8728:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
 8729:     if((ficres =fopen(rfileres,"w"))==NULL) {
 8730:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
 8731:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
 8732:     }
 8733:     fprintf(ficres,"#%s\n",version);
 8734:   }    /* End of mle != -3 */
 8735:   
 8736:   /*  Main data
 8737:    */
 8738:   n= lastobs;
 8739:   num=lvector(1,n);
 8740:   moisnais=vector(1,n);
 8741:   annais=vector(1,n);
 8742:   moisdc=vector(1,n);
 8743:   andc=vector(1,n);
 8744:   weight=vector(1,n);
 8745:   agedc=vector(1,n);
 8746:   cod=ivector(1,n);
 8747:   for(i=1;i<=n;i++){
 8748: 		num[i]=0;
 8749: 		moisnais[i]=0;
 8750: 		annais[i]=0;
 8751: 		moisdc[i]=0;
 8752: 		andc[i]=0;
 8753: 		agedc[i]=0;
 8754: 		cod[i]=0;
 8755: 		weight[i]=1.0; /* Equal weights, 1 by default */
 8756: 	}
 8757:   mint=matrix(1,maxwav,1,n);
 8758:   anint=matrix(1,maxwav,1,n);
 8759:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
 8760:   tab=ivector(1,NCOVMAX);
 8761:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
 8762:   ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
 8763: 
 8764:   /* Reads data from file datafile */
 8765:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
 8766:     goto end;
 8767: 
 8768:   /* Calculation of the number of parameters from char model */
 8769:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
 8770: 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
 8771: 	k=3 V4 Tvar[k=3]= 4 (from V4)
 8772: 	k=2 V1 Tvar[k=2]= 1 (from V1)
 8773: 	k=1 Tvar[1]=2 (from V2)
 8774:     */
 8775:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
 8776:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
 8777:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
 8778:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
 8779:   */
 8780:   /* For model-covariate k tells which data-covariate to use but
 8781:     because this model-covariate is a construction we invent a new column
 8782:     ncovcol + k1
 8783:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
 8784:     Tvar[3=V1*V4]=4+1 etc */
 8785:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
 8786:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
 8787:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
 8788:   */
 8789:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
 8790:   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
 8791: 			    * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
 8792: 			    * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
 8793:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
 8794: 			 4 covariates (3 plus signs)
 8795: 			 Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
 8796: 		      */  
 8797: 
 8798: /* Main decodemodel */
 8799: 
 8800: 
 8801:   if(decodemodel(model, lastobs) == 1)
 8802:     goto end;
 8803: 
 8804:   if((double)(lastobs-imx)/(double)imx > 1.10){
 8805:     nbwarn++;
 8806:     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); 
 8807:     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); 
 8808:   }
 8809:     /*  if(mle==1){*/
 8810:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
 8811:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
 8812:   }
 8813: 
 8814:     /*-calculation of age at interview from date of interview and age at death -*/
 8815:   agev=matrix(1,maxwav,1,imx);
 8816: 
 8817:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
 8818:     goto end;
 8819: 
 8820: 
 8821:   agegomp=(int)agemin;
 8822:   free_vector(moisnais,1,n);
 8823:   free_vector(annais,1,n);
 8824:   /* free_matrix(mint,1,maxwav,1,n);
 8825:      free_matrix(anint,1,maxwav,1,n);*/
 8826:   /* free_vector(moisdc,1,n); */
 8827:   /* free_vector(andc,1,n); */
 8828:   /* */
 8829:   
 8830:   wav=ivector(1,imx);
 8831:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
 8832:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
 8833:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
 8834:   dh=imatrix(1,lastpass-firstpass+2,1,imx); /* We are adding a wave if status is unknown at last wave but death occurs after last wave.*/
 8835:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
 8836:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
 8837:    
 8838:   /* Concatenates waves */
 8839:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 8840:      Death is a valid wave (if date is known).
 8841:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
 8842:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 8843:      and mw[mi+1][i]. dh depends on stepm.
 8844:   */
 8845: 
 8846:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
 8847:   /* */
 8848:  
 8849:   free_vector(moisdc,1,n);
 8850:   free_vector(andc,1,n);
 8851: 
 8852:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
 8853:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
 8854:   ncodemax[1]=1;
 8855:   Ndum =ivector(-1,NCOVMAX);  
 8856: 	cptcoveff=0;
 8857:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
 8858:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
 8859: 	}
 8860: 	
 8861: 	ncovcombmax=pow(2,cptcoveff);
 8862: 	invalidvarcomb=ivector(1, ncovcombmax); 
 8863: 	for(i=1;i<ncovcombmax;i++)
 8864: 		invalidvarcomb[i]=0;
 8865: 
 8866:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
 8867:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
 8868:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
 8869: 
 8870:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
 8871:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
 8872:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
 8873:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
 8874:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
 8875:    * (currently 0 or 1) in the data.
 8876:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
 8877:    * corresponding modality (h,j).
 8878:    */
 8879: 
 8880:   h=0;
 8881:   /*if (cptcovn > 0) */
 8882:   m=pow(2,cptcoveff);
 8883:  
 8884: 	  /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
 8885: 	   * For k=4 covariates, h goes from 1 to m=2**k
 8886: 	   * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
 8887:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
 8888: 	   *     h\k   1     2     3     4
 8889: 	   *______________________________  
 8890: 	   *     1 i=1 1 i=1 1 i=1 1 i=1 1
 8891: 	   *     2     2     1     1     1
 8892: 	   *     3 i=2 1     2     1     1
 8893: 	   *     4     2     2     1     1
 8894: 	   *     5 i=3 1 i=2 1     2     1
 8895: 	   *     6     2     1     2     1
 8896: 	   *     7 i=4 1     2     2     1
 8897: 	   *     8     2     2     2     1
 8898: 	   *     9 i=5 1 i=3 1 i=2 1     2
 8899: 	   *    10     2     1     1     2
 8900: 	   *    11 i=6 1     2     1     2
 8901: 	   *    12     2     2     1     2
 8902: 	   *    13 i=7 1 i=4 1     2     2    
 8903: 	   *    14     2     1     2     2
 8904: 	   *    15 i=8 1     2     2     2
 8905: 	   *    16     2     2     2     2
 8906: 	   */
 8907:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
 8908:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
 8909:      * and the value of each covariate?
 8910:      * V1=1, V2=1, V3=2, V4=1 ?
 8911:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
 8912:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
 8913:      * In order to get the real value in the data, we use nbcode
 8914:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
 8915:      * We are keeping this crazy system in order to be able (in the future?) 
 8916:      * to have more than 2 values (0 or 1) for a covariate.
 8917:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
 8918:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
 8919:      *              bbbbbbbb
 8920:      *              76543210     
 8921:      *   h-1        00000101 (6-1=5)
 8922:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
 8923:      *           &
 8924:      *     1        00000001 (1)
 8925:      *              00000000        = 1 & ((h-1) >> (k-1))
 8926:      *          +1= 00000001 =1 
 8927:      *
 8928:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
 8929:      *          h'      1101 =2^3+2^2+0x2^1+2^0
 8930:      *    >>k'            11
 8931:      *          &   00000001
 8932:      *            = 00000001
 8933:      *      +1    = 00000010=2    =  codtabm(14,3)   
 8934:      * Reverse h=6 and m=16?
 8935:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
 8936:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
 8937:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
 8938:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
 8939:      * V3=decodtabm(14,3,2**4)=2
 8940:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
 8941:      *(h-1) >> (j-1)    0011 =13 >> 2
 8942:      *          &1 000000001
 8943:      *           = 000000001
 8944:      *         +1= 000000010 =2
 8945:      *                  2211
 8946:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
 8947:      *                  V3=2
 8948: 		 * codtabm and decodtabm are identical
 8949:      */
 8950: 
 8951: 
 8952:  free_ivector(Ndum,-1,NCOVMAX);
 8953: 
 8954: 
 8955:     
 8956:   /* Initialisation of ----------- gnuplot -------------*/
 8957:   strcpy(optionfilegnuplot,optionfilefiname);
 8958:   if(mle==-3)
 8959:     strcat(optionfilegnuplot,"-MORT_");
 8960:   strcat(optionfilegnuplot,".gp");
 8961: 
 8962:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
 8963:     printf("Problem with file %s",optionfilegnuplot);
 8964:   }
 8965:   else{
 8966:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
 8967:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
 8968:     //fprintf(ficgp,"set missing 'NaNq'\n");
 8969:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
 8970:   }
 8971:   /*  fclose(ficgp);*/
 8972: 
 8973: 
 8974:   /* Initialisation of --------- index.htm --------*/
 8975: 
 8976:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
 8977:   if(mle==-3)
 8978:     strcat(optionfilehtm,"-MORT_");
 8979:   strcat(optionfilehtm,".htm");
 8980:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
 8981:     printf("Problem with %s \n",optionfilehtm);
 8982:     exit(0);
 8983:   }
 8984: 
 8985:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
 8986:   strcat(optionfilehtmcov,"-cov.htm");
 8987:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
 8988:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
 8989:   }
 8990:   else{
 8991:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 8992: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 8993: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
 8994: 	  optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 8995:   }
 8996: 
 8997:   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é-2013-2016-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-2018</a></font><br>  \
 8998: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 8999: <font size=\"2\">IMaCh-%s <br> %s</font> \
 9000: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 9001: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
 9002: \n\
 9003: <hr  size=\"2\" color=\"#EC5E5E\">\
 9004:  <ul><li><h4>Parameter files</h4>\n\
 9005:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
 9006:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
 9007:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
 9008:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
 9009:  - Date and time at start: %s</ul>\n",\
 9010: 	  optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
 9011: 	  optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
 9012: 	  fileres,fileres,\
 9013: 	  filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
 9014:   fflush(fichtm);
 9015: 
 9016:   strcpy(pathr,path);
 9017:   strcat(pathr,optionfilefiname);
 9018: #ifdef WIN32
 9019:   _chdir(optionfilefiname); /* Move to directory named optionfile */
 9020: #else
 9021:   chdir(optionfilefiname); /* Move to directory named optionfile */
 9022: #endif
 9023: 	  
 9024:   
 9025:   /* Calculates basic frequencies. Computes observed prevalence at single age 
 9026: 		 and for any valid combination of covariates
 9027:      and prints on file fileres'p'. */
 9028:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart,	\
 9029: 	      firstpass, lastpass,  stepm,  weightopt, model);
 9030: 
 9031:   fprintf(fichtm,"\n");
 9032:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
 9033: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
 9034: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
 9035: 	  imx,agemin,agemax,jmin,jmax,jmean);
 9036:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 9037: 	oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 9038: 	newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 9039: 	savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 9040: 	oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
 9041: 
 9042:   /* For Powell, parameters are in a vector p[] starting at p[1]
 9043:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
 9044:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
 9045: 
 9046:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
 9047:   /* For mortality only */
 9048:   if (mle==-3){
 9049:     ximort=matrix(1,NDIM,1,NDIM); 
 9050: 		for(i=1;i<=NDIM;i++)
 9051: 			for(j=1;j<=NDIM;j++)
 9052: 				ximort[i][j]=0.;
 9053:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
 9054:     cens=ivector(1,n);
 9055:     ageexmed=vector(1,n);
 9056:     agecens=vector(1,n);
 9057:     dcwave=ivector(1,n);
 9058:  
 9059:     for (i=1; i<=imx; i++){
 9060:       dcwave[i]=-1;
 9061:       for (m=firstpass; m<=lastpass; m++)
 9062: 				if (s[m][i]>nlstate) {
 9063: 					dcwave[i]=m;
 9064: 					/*	printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
 9065: 					break;
 9066: 				}
 9067:     }
 9068: 		
 9069:     for (i=1; i<=imx; i++) {
 9070:       if (wav[i]>0){
 9071: 				ageexmed[i]=agev[mw[1][i]][i];
 9072: 				j=wav[i];
 9073: 				agecens[i]=1.; 
 9074: 				
 9075: 				if (ageexmed[i]> 1 && wav[i] > 0){
 9076: 					agecens[i]=agev[mw[j][i]][i];
 9077: 					cens[i]= 1;
 9078: 				}else if (ageexmed[i]< 1) 
 9079: 					cens[i]= -1;
 9080: 				if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
 9081: 					cens[i]=0 ;
 9082:       }
 9083:       else cens[i]=-1;
 9084:     }
 9085:     
 9086:     for (i=1;i<=NDIM;i++) {
 9087:       for (j=1;j<=NDIM;j++)
 9088: 				ximort[i][j]=(i == j ? 1.0 : 0.0);
 9089:     }
 9090:     
 9091:     /*p[1]=0.0268; p[NDIM]=0.083;*/
 9092:     /*printf("%lf %lf", p[1], p[2]);*/
 9093:     
 9094:     
 9095: #ifdef GSL
 9096:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
 9097: #else
 9098:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
 9099: #endif
 9100:     strcpy(filerespow,"POW-MORT_"); 
 9101:     strcat(filerespow,fileresu);
 9102:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
 9103:       printf("Problem with resultfile: %s\n", filerespow);
 9104:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 9105:     }
 9106: #ifdef GSL
 9107:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
 9108: #else
 9109:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
 9110: #endif
 9111:     /*  for (i=1;i<=nlstate;i++)
 9112: 	for(j=1;j<=nlstate+ndeath;j++)
 9113: 	if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 9114:     */
 9115:     fprintf(ficrespow,"\n");
 9116: #ifdef GSL
 9117:     /* gsl starts here */ 
 9118:     T = gsl_multimin_fminimizer_nmsimplex;
 9119:     gsl_multimin_fminimizer *sfm = NULL;
 9120:     gsl_vector *ss, *x;
 9121:     gsl_multimin_function minex_func;
 9122: 
 9123:     /* Initial vertex size vector */
 9124:     ss = gsl_vector_alloc (NDIM);
 9125:     
 9126:     if (ss == NULL){
 9127:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
 9128:     }
 9129:     /* Set all step sizes to 1 */
 9130:     gsl_vector_set_all (ss, 0.001);
 9131: 
 9132:     /* Starting point */
 9133:     
 9134:     x = gsl_vector_alloc (NDIM);
 9135:     
 9136:     if (x == NULL){
 9137:       gsl_vector_free(ss);
 9138:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
 9139:     }
 9140:   
 9141:     /* Initialize method and iterate */
 9142:     /*     p[1]=0.0268; p[NDIM]=0.083; */
 9143:     /*     gsl_vector_set(x, 0, 0.0268); */
 9144:     /*     gsl_vector_set(x, 1, 0.083); */
 9145:     gsl_vector_set(x, 0, p[1]);
 9146:     gsl_vector_set(x, 1, p[2]);
 9147: 
 9148:     minex_func.f = &gompertz_f;
 9149:     minex_func.n = NDIM;
 9150:     minex_func.params = (void *)&p; /* ??? */
 9151:     
 9152:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
 9153:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
 9154:     
 9155:     printf("Iterations beginning .....\n\n");
 9156:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
 9157: 
 9158:     iteri=0;
 9159:     while (rval == GSL_CONTINUE){
 9160:       iteri++;
 9161:       status = gsl_multimin_fminimizer_iterate(sfm);
 9162:       
 9163:       if (status) printf("error: %s\n", gsl_strerror (status));
 9164:       fflush(0);
 9165:       
 9166:       if (status) 
 9167:         break;
 9168:       
 9169:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
 9170:       ssval = gsl_multimin_fminimizer_size (sfm);
 9171:       
 9172:       if (rval == GSL_SUCCESS)
 9173:         printf ("converged to a local maximum at\n");
 9174:       
 9175:       printf("%5d ", iteri);
 9176:       for (it = 0; it < NDIM; it++){
 9177: 	printf ("%10.5f ", gsl_vector_get (sfm->x, it));
 9178:       }
 9179:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
 9180:     }
 9181:     
 9182:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
 9183:     
 9184:     gsl_vector_free(x); /* initial values */
 9185:     gsl_vector_free(ss); /* inital step size */
 9186:     for (it=0; it<NDIM; it++){
 9187:       p[it+1]=gsl_vector_get(sfm->x,it);
 9188:       fprintf(ficrespow," %.12lf", p[it]);
 9189:     }
 9190:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
 9191: #endif
 9192: #ifdef POWELL
 9193:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
 9194: #endif  
 9195:     fclose(ficrespow);
 9196:     
 9197:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
 9198: 
 9199:     for(i=1; i <=NDIM; i++)
 9200:       for(j=i+1;j<=NDIM;j++)
 9201: 				matcov[i][j]=matcov[j][i];
 9202:     
 9203:     printf("\nCovariance matrix\n ");
 9204:     fprintf(ficlog,"\nCovariance matrix\n ");
 9205:     for(i=1; i <=NDIM; i++) {
 9206:       for(j=1;j<=NDIM;j++){ 
 9207: 				printf("%f ",matcov[i][j]);
 9208: 				fprintf(ficlog,"%f ",matcov[i][j]);
 9209:       }
 9210:       printf("\n ");  fprintf(ficlog,"\n ");
 9211:     }
 9212:     
 9213:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
 9214:     for (i=1;i<=NDIM;i++) {
 9215:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
 9216:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
 9217:     }
 9218:     lsurv=vector(1,AGESUP);
 9219:     lpop=vector(1,AGESUP);
 9220:     tpop=vector(1,AGESUP);
 9221:     lsurv[agegomp]=100000;
 9222:     
 9223:     for (k=agegomp;k<=AGESUP;k++) {
 9224:       agemortsup=k;
 9225:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
 9226:     }
 9227:     
 9228:     for (k=agegomp;k<agemortsup;k++)
 9229:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
 9230:     
 9231:     for (k=agegomp;k<agemortsup;k++){
 9232:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
 9233:       sumlpop=sumlpop+lpop[k];
 9234:     }
 9235:     
 9236:     tpop[agegomp]=sumlpop;
 9237:     for (k=agegomp;k<(agemortsup-3);k++){
 9238:       /*  tpop[k+1]=2;*/
 9239:       tpop[k+1]=tpop[k]-lpop[k];
 9240:     }
 9241:     
 9242:     
 9243:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
 9244:     for (k=agegomp;k<(agemortsup-2);k++) 
 9245:       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]);
 9246:     
 9247:     
 9248:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 9249: 		ageminpar=50;
 9250: 		agemaxpar=100;
 9251:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
 9252:       	printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
 9253: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
 9254: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
 9255:       	fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
 9256: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
 9257: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
 9258:     }else{
 9259: 			printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
 9260: 			fprintf(ficlog,"Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
 9261:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 9262: 		}
 9263:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
 9264: 		     stepm, weightopt,\
 9265: 		     model,imx,p,matcov,agemortsup);
 9266:     
 9267:     free_vector(lsurv,1,AGESUP);
 9268:     free_vector(lpop,1,AGESUP);
 9269:     free_vector(tpop,1,AGESUP);
 9270:     free_matrix(ximort,1,NDIM,1,NDIM);
 9271:     free_ivector(cens,1,n);
 9272:     free_vector(agecens,1,n);
 9273:     free_ivector(dcwave,1,n);
 9274: #ifdef GSL
 9275: #endif
 9276:   } /* Endof if mle==-3 mortality only */
 9277:   /* Standard  */
 9278:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
 9279:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
 9280:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
 9281:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 9282:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 9283:     for (k=1; k<=npar;k++)
 9284:       printf(" %d %8.5f",k,p[k]);
 9285:     printf("\n");
 9286:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
 9287:       /* mlikeli uses func not funcone */
 9288:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
 9289:     }
 9290:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
 9291:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
 9292:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
 9293:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 9294:     }
 9295:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
 9296:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 9297:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 9298:     for (k=1; k<=npar;k++)
 9299:       printf(" %d %8.5f",k,p[k]);
 9300:     printf("\n");
 9301:     
 9302:     /*--------- results files --------------*/
 9303:     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);
 9304:     
 9305:     
 9306:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 9307:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 9308:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 9309:     for(i=1,jk=1; i <=nlstate; i++){
 9310:       for(k=1; k <=(nlstate+ndeath); k++){
 9311: 				if (k != i) {
 9312: 					printf("%d%d ",i,k);
 9313: 					fprintf(ficlog,"%d%d ",i,k);
 9314: 					fprintf(ficres,"%1d%1d ",i,k);
 9315: 					for(j=1; j <=ncovmodel; j++){
 9316: 						printf("%12.7f ",p[jk]);
 9317: 						fprintf(ficlog,"%12.7f ",p[jk]);
 9318: 						fprintf(ficres,"%12.7f ",p[jk]);
 9319: 						jk++; 
 9320: 					}
 9321: 					printf("\n");
 9322: 					fprintf(ficlog,"\n");
 9323: 					fprintf(ficres,"\n");
 9324: 				}
 9325:       }
 9326:     }
 9327:     if(mle != 0){
 9328:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
 9329:       ftolhess=ftol; /* Usually correct */
 9330:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
 9331:       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");
 9332:       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");
 9333:       for(i=1,jk=1; i <=nlstate; i++){
 9334: 				for(k=1; k <=(nlstate+ndeath); k++){
 9335: 					if (k != i) {
 9336: 						printf("%d%d ",i,k);
 9337: 						fprintf(ficlog,"%d%d ",i,k);
 9338: 						for(j=1; j <=ncovmodel; j++){
 9339: 							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]));
 9340: 							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]));
 9341: 							jk++; 
 9342: 						}
 9343: 						printf("\n");
 9344: 						fprintf(ficlog,"\n");
 9345: 					}
 9346: 				}
 9347:       }
 9348:     } /* end of hesscov and Wald tests */
 9349: 		
 9350:     /*  */
 9351:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
 9352:     printf("# Scales (for hessian or gradient estimation)\n");
 9353:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
 9354:     for(i=1,jk=1; i <=nlstate; i++){
 9355:       for(j=1; j <=nlstate+ndeath; j++){
 9356: 				if (j!=i) {
 9357: 					fprintf(ficres,"%1d%1d",i,j);
 9358: 					printf("%1d%1d",i,j);
 9359: 					fprintf(ficlog,"%1d%1d",i,j);
 9360: 					for(k=1; k<=ncovmodel;k++){
 9361: 						printf(" %.5e",delti[jk]);
 9362: 						fprintf(ficlog," %.5e",delti[jk]);
 9363: 						fprintf(ficres," %.5e",delti[jk]);
 9364: 						jk++;
 9365: 					}
 9366: 					printf("\n");
 9367: 					fprintf(ficlog,"\n");
 9368: 					fprintf(ficres,"\n");
 9369: 				}
 9370:       }
 9371:     }
 9372:     
 9373:     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");
 9374:     if(mle >= 1) /* To big for the screen */
 9375:       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");
 9376:     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");
 9377:     /* # 121 Var(a12)\n\ */
 9378:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
 9379:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 9380:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 9381:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 9382:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 9383:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 9384:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 9385:     
 9386:     
 9387:     /* Just to have a covariance matrix which will be more understandable
 9388:        even is we still don't want to manage dictionary of variables
 9389:     */
 9390:     for(itimes=1;itimes<=2;itimes++){
 9391:       jj=0;
 9392:       for(i=1; i <=nlstate; i++){
 9393: 				for(j=1; j <=nlstate+ndeath; j++){
 9394: 					if(j==i) continue;
 9395: 					for(k=1; k<=ncovmodel;k++){
 9396: 						jj++;
 9397: 						ca[0]= k+'a'-1;ca[1]='\0';
 9398: 						if(itimes==1){
 9399: 							if(mle>=1)
 9400: 								printf("#%1d%1d%d",i,j,k);
 9401: 							fprintf(ficlog,"#%1d%1d%d",i,j,k);
 9402: 							fprintf(ficres,"#%1d%1d%d",i,j,k);
 9403: 						}else{
 9404: 							if(mle>=1)
 9405: 								printf("%1d%1d%d",i,j,k);
 9406: 							fprintf(ficlog,"%1d%1d%d",i,j,k);
 9407: 							fprintf(ficres,"%1d%1d%d",i,j,k);
 9408: 						}
 9409: 						ll=0;
 9410: 						for(li=1;li <=nlstate; li++){
 9411: 							for(lj=1;lj <=nlstate+ndeath; lj++){
 9412: 								if(lj==li) continue;
 9413: 								for(lk=1;lk<=ncovmodel;lk++){
 9414: 									ll++;
 9415: 									if(ll<=jj){
 9416: 										cb[0]= lk +'a'-1;cb[1]='\0';
 9417: 										if(ll<jj){
 9418: 											if(itimes==1){
 9419: 												if(mle>=1)
 9420: 													printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 9421: 												fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 9422: 												fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 9423: 											}else{
 9424: 												if(mle>=1)
 9425: 													printf(" %.5e",matcov[jj][ll]); 
 9426: 												fprintf(ficlog," %.5e",matcov[jj][ll]); 
 9427: 												fprintf(ficres," %.5e",matcov[jj][ll]); 
 9428: 											}
 9429: 										}else{
 9430: 											if(itimes==1){
 9431: 												if(mle>=1)
 9432: 													printf(" Var(%s%1d%1d)",ca,i,j);
 9433: 												fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
 9434: 												fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
 9435: 											}else{
 9436: 												if(mle>=1)
 9437: 													printf(" %.7e",matcov[jj][ll]); 
 9438: 												fprintf(ficlog," %.7e",matcov[jj][ll]); 
 9439: 												fprintf(ficres," %.7e",matcov[jj][ll]); 
 9440: 											}
 9441: 										}
 9442: 									}
 9443: 								} /* end lk */
 9444: 							} /* end lj */
 9445: 						} /* end li */
 9446: 						if(mle>=1)
 9447: 							printf("\n");
 9448: 						fprintf(ficlog,"\n");
 9449: 						fprintf(ficres,"\n");
 9450: 						numlinepar++;
 9451: 					} /* end k*/
 9452: 				} /*end j */
 9453:       } /* end i */
 9454:     } /* end itimes */
 9455:     
 9456:     fflush(ficlog);
 9457:     fflush(ficres);
 9458: 		while(fgets(line, MAXLINE, ficpar)) {
 9459: 			/* If line starts with a # it is a comment */
 9460: 			if (line[0] == '#') {
 9461: 				numlinepar++;
 9462: 				fputs(line,stdout);
 9463: 				fputs(line,ficparo);
 9464: 				fputs(line,ficlog);
 9465: 				continue;
 9466: 			}else
 9467: 				break;
 9468: 		}
 9469: 		
 9470:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
 9471:     /*   ungetc(c,ficpar); */
 9472:     /*   fgets(line, MAXLINE, ficpar); */
 9473:     /*   fputs(line,stdout); */
 9474:     /*   fputs(line,ficparo); */
 9475:     /* } */
 9476:     /* ungetc(c,ficpar); */
 9477:     
 9478:     estepm=0;
 9479:     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){
 9480: 			
 9481: 			if (num_filled != 6) {
 9482: 				printf("Error: Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n, your line=%s . Probably you are running an older format.\n",line);
 9483: 				fprintf(ficlog,"Error: Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n, your line=%s . Probably you are running an older format.\n",line);
 9484: 				goto end;
 9485: 			}
 9486: 			printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
 9487: 		}
 9488: 		/* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
 9489: 		/*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
 9490: 		
 9491:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
 9492:     if (estepm==0 || estepm < stepm) estepm=stepm;
 9493:     if (fage <= 2) {
 9494:       bage = ageminpar;
 9495:       fage = agemaxpar;
 9496:     }
 9497:     
 9498:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
 9499:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
 9500:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
 9501: 		
 9502:     /* Other stuffs, more or less useful */    
 9503:     while((c=getc(ficpar))=='#' && c!= EOF){
 9504:       ungetc(c,ficpar);
 9505:       fgets(line, MAXLINE, ficpar);
 9506:       fputs(line,stdout);
 9507:       fputs(line,ficparo);
 9508:     }
 9509:     ungetc(c,ficpar);
 9510:     
 9511:     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);
 9512:     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);
 9513:     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);
 9514:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
 9515:     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);
 9516:     
 9517:     while((c=getc(ficpar))=='#' && c!= EOF){
 9518:       ungetc(c,ficpar);
 9519:       fgets(line, MAXLINE, ficpar);
 9520:       fputs(line,stdout);
 9521:       fputs(line,ficparo);
 9522:     }
 9523:     ungetc(c,ficpar);
 9524:     
 9525:     
 9526:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
 9527:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
 9528:     
 9529:     fscanf(ficpar,"pop_based=%d\n",&popbased);
 9530:     fprintf(ficlog,"pop_based=%d\n",popbased);
 9531:     fprintf(ficparo,"pop_based=%d\n",popbased);   
 9532:     fprintf(ficres,"pop_based=%d\n",popbased);   
 9533:     
 9534:     while((c=getc(ficpar))=='#' && c!= EOF){
 9535:       ungetc(c,ficpar);
 9536:       fgets(line, MAXLINE, ficpar);
 9537:       fputs(line,stdout);
 9538:       fputs(line,ficparo);
 9539:     }
 9540:     ungetc(c,ficpar);
 9541:     
 9542:     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);
 9543:     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);
 9544:     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);
 9545:     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);
 9546:     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);
 9547:     /* day and month of proj2 are not used but only year anproj2.*/
 9548:     
 9549:     while((c=getc(ficpar))=='#' && c!= EOF){
 9550:       ungetc(c,ficpar);
 9551:       fgets(line, MAXLINE, ficpar);
 9552:       fputs(line,stdout);
 9553:       fputs(line,ficparo);
 9554:     }
 9555:     ungetc(c,ficpar);
 9556:     
 9557:     fscanf(ficpar,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",&backcast,&jback1,&mback1,&anback1,&jback2,&mback2,&anback2,&mobilavproj);
 9558:     fprintf(ficparo,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
 9559:     fprintf(ficlog,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
 9560:     fprintf(ficres,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
 9561:     /* day and month of proj2 are not used but only year anproj2.*/
 9562:     
 9563:     
 9564: 		/* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
 9565:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
 9566:     
 9567:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 9568:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
 9569: 			printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
 9570: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
 9571: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
 9572: 			fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
 9573: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
 9574: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
 9575:     }else{
 9576:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
 9577:     }
 9578:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
 9579: 								 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
 9580: 								 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
 9581: 		
 9582: 		/*------------ free_vector  -------------*/
 9583: 		/*  chdir(path); */
 9584: 		
 9585:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
 9586:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
 9587:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
 9588:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
 9589:     free_lvector(num,1,n);
 9590:     free_vector(agedc,1,n);
 9591:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
 9592:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
 9593:     fclose(ficparo);
 9594:     fclose(ficres);
 9595: 		
 9596: 		
 9597:     /* Other results (useful)*/
 9598: 		
 9599: 		
 9600:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 9601:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
 9602:     prlim=matrix(1,nlstate,1,nlstate);
 9603:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
 9604:     fclose(ficrespl);
 9605: 
 9606:     /*------------- h Pij x at various ages ------------*/
 9607:     /*#include "hpijx.h"*/
 9608:     hPijx(p, bage, fage);
 9609:     fclose(ficrespij);
 9610: 
 9611:     /* ncovcombmax=  pow(2,cptcoveff); */
 9612:     /*-------------- Variance of one-step probabilities---*/
 9613:     k=1;
 9614:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
 9615: 
 9616:     /* Prevalence for each covariates in probs[age][status][cov] */
 9617:     probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
 9618:     for(i=1;i<=AGESUP;i++)
 9619:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
 9620: 				for(k=1;k<=ncovcombmax;k++)
 9621: 					probs[i][j][k]=0.;
 9622:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 9623:     if (mobilav!=0 ||mobilavproj !=0 ) {
 9624:       mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
 9625: 			for(i=1;i<=AGESUP;i++)
 9626: 				for(j=1;j<=nlstate;j++)
 9627: 					for(k=1;k<=ncovcombmax;k++)
 9628: 						mobaverages[i][j][k]=0.;
 9629:       mobaverage=mobaverages;
 9630:       if (mobilav!=0) {
 9631: 				if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
 9632: 					fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 9633: 					printf(" Error in movingaverage mobilav=%d\n",mobilav);
 9634: 				}
 9635:       }
 9636:       /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
 9637:       /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
 9638:       else if (mobilavproj !=0) {
 9639: 				if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
 9640: 					fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
 9641: 					printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
 9642: 				}
 9643:       }
 9644:     }/* end if moving average */
 9645: 		
 9646:     /*---------- Forecasting ------------------*/
 9647:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
 9648:     if(prevfcast==1){
 9649:       /*    if(stepm ==1){*/
 9650:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
 9651:     }
 9652:     if(backcast==1){
 9653:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath); 	
 9654:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath); 	
 9655:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
 9656: 
 9657:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
 9658: 
 9659:       bprlim=matrix(1,nlstate,1,nlstate);
 9660:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
 9661:       fclose(ficresplb);
 9662: 
 9663:       hBijx(p, bage, fage, mobaverage);
 9664:       fclose(ficrespijb);
 9665:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
 9666: 
 9667:       /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
 9668: 	 bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
 9669:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
 9670:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
 9671:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
 9672:     }
 9673:     
 9674:  
 9675:     /* ------ Other prevalence ratios------------ */
 9676: 
 9677:     free_ivector(wav,1,imx);
 9678:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
 9679:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
 9680:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
 9681: 		
 9682: 		
 9683:     /*---------- Health expectancies, no variances ------------*/
 9684: 		
 9685:     strcpy(filerese,"E_");
 9686:     strcat(filerese,fileresu);
 9687:     if((ficreseij=fopen(filerese,"w"))==NULL) {
 9688:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 9689:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 9690:     }
 9691:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
 9692:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
 9693:  		
 9694:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 9695:       fprintf(ficreseij,"\n#****** ");
 9696:       for(j=1;j<=cptcoveff;j++) {
 9697: 				fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9698:       }
 9699:       fprintf(ficreseij,"******\n");
 9700:       
 9701:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 9702:       oldm=oldms;savm=savms;
 9703:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
 9704:       
 9705:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 9706:     }
 9707:     fclose(ficreseij);
 9708:     printf("done evsij\n");fflush(stdout);
 9709:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
 9710: 		
 9711:     /*---------- Health expectancies and variances ------------*/
 9712: 		
 9713: 		
 9714:     strcpy(filerest,"T_");
 9715:     strcat(filerest,fileresu);
 9716:     if((ficrest=fopen(filerest,"w"))==NULL) {
 9717:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
 9718:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
 9719:     }
 9720:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
 9721:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
 9722: 		
 9723: 
 9724:     strcpy(fileresstde,"STDE_");
 9725:     strcat(fileresstde,fileresu);
 9726:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
 9727:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 9728:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 9729:     }
 9730:     printf("  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 9731:     fprintf(ficlog,"  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 9732: 
 9733:     strcpy(filerescve,"CVE_");
 9734:     strcat(filerescve,fileresu);
 9735:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
 9736:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 9737:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 9738:     }
 9739:     printf("    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 9740:     fprintf(ficlog,"    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 9741: 
 9742:     strcpy(fileresv,"V_");
 9743:     strcat(fileresv,fileresu);
 9744:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
 9745:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
 9746:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
 9747:     }
 9748:     printf("      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
 9749:     fprintf(ficlog,"      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
 9750: 
 9751:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 9752:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 9753:           
 9754:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 9755:       fprintf(ficrest,"\n#****** ");
 9756:       for(j=1;j<=cptcoveff;j++) 
 9757: 				fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9758:       fprintf(ficrest,"******\n");
 9759:       
 9760:       fprintf(ficresstdeij,"\n#****** ");
 9761:       fprintf(ficrescveij,"\n#****** ");
 9762:       for(j=1;j<=cptcoveff;j++) {
 9763: 				fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9764: 				fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9765:       }
 9766:       fprintf(ficresstdeij,"******\n");
 9767:       fprintf(ficrescveij,"******\n");
 9768:       
 9769:       fprintf(ficresvij,"\n#****** ");
 9770:       for(j=1;j<=cptcoveff;j++) 
 9771: 				fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9772:       fprintf(ficresvij,"******\n");
 9773:       
 9774:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 9775:       oldm=oldms;savm=savms;
 9776:       printf(" cvevsij %d, ",k);
 9777:       fprintf(ficlog, " cvevsij %d, ",k);
 9778:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
 9779:       printf(" end cvevsij \n ");
 9780:       fprintf(ficlog, " end cvevsij \n ");
 9781:       
 9782:       /*
 9783:        */
 9784:       /* goto endfree; */
 9785:       
 9786:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 9787:       pstamp(ficrest);
 9788:       
 9789:       
 9790:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 9791: 				oldm=oldms;savm=savms; /* ZZ Segmentation fault */
 9792: 				cptcod= 0; /* To be deleted */
 9793: 				printf("varevsij %d \n",vpopbased);
 9794: 				fprintf(ficlog, "varevsij %d \n",vpopbased);
 9795: 				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 */
 9796: 				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 ");
 9797: 				if(vpopbased==1)
 9798: 					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);
 9799: 				else
 9800: 					fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
 9801: 				fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
 9802: 				for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
 9803: 				fprintf(ficrest,"\n");
 9804: 				/* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
 9805: 				epj=vector(1,nlstate+1);
 9806: 				printf("Computing age specific period (stable) prevalences in each health state \n");
 9807: 				fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
 9808: 				for(age=bage; age <=fage ;age++){
 9809: 					prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
 9810: 					if (vpopbased==1) {
 9811: 						if(mobilav ==0){
 9812: 							for(i=1; i<=nlstate;i++)
 9813: 								prlim[i][i]=probs[(int)age][i][k];
 9814: 						}else{ /* mobilav */ 
 9815: 							for(i=1; i<=nlstate;i++)
 9816: 								prlim[i][i]=mobaverage[(int)age][i][k];
 9817: 						}
 9818: 					}
 9819: 	  
 9820: 					fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
 9821: 					/* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
 9822: 					/* printf(" age %4.0f ",age); */
 9823: 					for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
 9824: 						for(i=1, epj[j]=0.;i <=nlstate;i++) {
 9825: 							epj[j] += prlim[i][i]*eij[i][j][(int)age];
 9826: 							/*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
 9827: 							/* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
 9828: 						}
 9829: 						epj[nlstate+1] +=epj[j];
 9830: 					}
 9831: 					/* printf(" age %4.0f \n",age); */
 9832: 	  
 9833: 					for(i=1, vepp=0.;i <=nlstate;i++)
 9834: 						for(j=1;j <=nlstate;j++)
 9835: 							vepp += vareij[i][j][(int)age];
 9836: 					fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
 9837: 					for(j=1;j <=nlstate;j++){
 9838: 						fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
 9839: 					}
 9840: 					fprintf(ficrest,"\n");
 9841: 				}
 9842:       } /* End vpopbased */
 9843:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 9844:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 9845:       free_vector(epj,1,nlstate+1);
 9846:       printf("done \n");fflush(stdout);
 9847:       fprintf(ficlog,"done\n");fflush(ficlog);
 9848:       
 9849:       /*}*/
 9850:     } /* End k */
 9851:     free_vector(weight,1,n);
 9852:     free_imatrix(Tvard,1,NCOVMAX,1,2);
 9853:     free_imatrix(s,1,maxwav+1,1,n);
 9854:     free_matrix(anint,1,maxwav,1,n); 
 9855:     free_matrix(mint,1,maxwav,1,n);
 9856:     free_ivector(cod,1,n);
 9857:     free_ivector(tab,1,NCOVMAX);
 9858:     fclose(ficresstdeij);
 9859:     fclose(ficrescveij);
 9860:     fclose(ficresvij);
 9861:     fclose(ficrest);
 9862:     printf("done Health expectancies\n");fflush(stdout);
 9863:     fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
 9864:     fclose(ficpar);
 9865:   
 9866:     /*------- Variance of period (stable) prevalence------*/   
 9867: 
 9868:     strcpy(fileresvpl,"VPL_");
 9869:     strcat(fileresvpl,fileresu);
 9870:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
 9871:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
 9872:       exit(0);
 9873:     }
 9874:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
 9875:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
 9876: 
 9877:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 9878:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 9879:           
 9880:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 9881:     	fprintf(ficresvpl,"\n#****** ");
 9882: 			for(j=1;j<=cptcoveff;j++) 
 9883: 				fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9884: 			fprintf(ficresvpl,"******\n");
 9885:       
 9886: 			varpl=matrix(1,nlstate,(int) bage, (int) fage);
 9887: 			oldm=oldms;savm=savms;
 9888: 			varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
 9889: 			free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
 9890:       /*}*/
 9891:     }
 9892: 		
 9893:     fclose(ficresvpl);
 9894:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
 9895:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
 9896: 
 9897:     /*---------- End : free ----------------*/
 9898:     if (mobilav!=0 ||mobilavproj !=0)
 9899:       free_ma3x(mobaverages,1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
 9900:     free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
 9901:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
 9902:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
 9903:   }  /* mle==-3 arrives here for freeing */
 9904:  /* endfree:*/
 9905:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
 9906:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
 9907:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
 9908:     free_matrix(covar,0,NCOVMAX,1,n);
 9909:     free_matrix(matcov,1,npar,1,npar);
 9910:     free_matrix(hess,1,npar,1,npar);
 9911:     /*free_vector(delti,1,npar);*/
 9912:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 9913:     free_matrix(agev,1,maxwav,1,imx);
 9914:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
 9915: 
 9916:     free_ivector(ncodemax,1,NCOVMAX);
 9917:     free_ivector(ncodemaxwundef,1,NCOVMAX);
 9918:     free_ivector(Tvar,1,NCOVMAX);
 9919:     free_ivector(Tprod,1,NCOVMAX);
 9920:     free_ivector(Tvaraff,1,NCOVMAX);
 9921:     free_ivector(invalidvarcomb,1,ncovcombmax);
 9922:     free_ivector(Tage,1,NCOVMAX);
 9923: 
 9924:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
 9925:     /* free_imatrix(codtab,1,100,1,10); */
 9926:   fflush(fichtm);
 9927:   fflush(ficgp);
 9928:   
 9929: 
 9930:   if((nberr >0) || (nbwarn>0)){
 9931:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
 9932:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d. Please look at the log file for details.\n",nberr,nbwarn);
 9933:   }else{
 9934:     printf("End of Imach\n");
 9935:     fprintf(ficlog,"End of Imach\n");
 9936:   }
 9937:   printf("See log file on %s\n",filelog);
 9938:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
 9939:   /*(void) gettimeofday(&end_time,&tzp);*/
 9940:   rend_time = time(NULL);  
 9941:   end_time = *localtime(&rend_time);
 9942:   /* tml = *localtime(&end_time.tm_sec); */
 9943:   strcpy(strtend,asctime(&end_time));
 9944:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
 9945:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
 9946:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 9947: 
 9948:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 9949:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 9950:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 9951:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
 9952: /*   if(fileappend(fichtm,optionfilehtm)){ */
 9953:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 9954:   fclose(fichtm);
 9955:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 9956:   fclose(fichtmcov);
 9957:   fclose(ficgp);
 9958:   fclose(ficlog);
 9959:   /*------ End -----------*/
 9960: 
 9961: 
 9962:    printf("Before Current directory %s!\n",pathcd);
 9963: #ifdef WIN32
 9964:    if (_chdir(pathcd) != 0)
 9965: 	   printf("Can't move to directory %s!\n",path);
 9966:    if(_getcwd(pathcd,MAXLINE) > 0)
 9967: #else
 9968:    if(chdir(pathcd) != 0)
 9969: 	   printf("Can't move to directory %s!\n", path);
 9970:    if (getcwd(pathcd, MAXLINE) > 0)
 9971: #endif 
 9972:     printf("Current directory %s!\n",pathcd);
 9973:   /*strcat(plotcmd,CHARSEPARATOR);*/
 9974:   sprintf(plotcmd,"gnuplot");
 9975: #ifdef _WIN32
 9976:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
 9977: #endif
 9978:   if(!stat(plotcmd,&info)){
 9979:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 9980:     if(!stat(getenv("GNUPLOTBIN"),&info)){
 9981:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
 9982:     }else
 9983:       strcpy(pplotcmd,plotcmd);
 9984: #ifdef __unix
 9985:     strcpy(plotcmd,GNUPLOTPROGRAM);
 9986:     if(!stat(plotcmd,&info)){
 9987:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 9988:     }else
 9989:       strcpy(pplotcmd,plotcmd);
 9990: #endif
 9991:   }else
 9992:     strcpy(pplotcmd,plotcmd);
 9993:   
 9994:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
 9995:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
 9996: 
 9997:   if((outcmd=system(plotcmd)) != 0){
 9998:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
 9999:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
10000:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
10001:     if((outcmd=system(plotcmd)) != 0)
10002:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
10003:   }
10004:   printf(" Successful, please wait...");
10005:   while (z[0] != 'q') {
10006:     /* chdir(path); */
10007:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
10008:     scanf("%s",z);
10009: /*     if (z[0] == 'c') system("./imach"); */
10010:     if (z[0] == 'e') {
10011: #ifdef __APPLE__
10012:       sprintf(pplotcmd, "open %s", optionfilehtm);
10013: #elif __linux
10014:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
10015: #else
10016:       sprintf(pplotcmd, "%s", optionfilehtm);
10017: #endif
10018:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
10019:       system(pplotcmd);
10020:     }
10021:     else if (z[0] == 'g') system(plotcmd);
10022:     else if (z[0] == 'q') exit(0);
10023:   }
10024:   end:
10025:   while (z[0] != 'q') {
10026:     printf("\nType  q for exiting: "); fflush(stdout);
10027:     scanf("%s",z);
10028:   }
10029: }

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