File:  [Local Repository] / imach / src / imach.c
Revision 1.239: download - view: text, annotated - select for diffs
Fri Aug 26 15:51:03 2016 UTC (7 years, 8 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
Summary: Improvement in Powell output in order to copy and paste

Author:

    1: /* $Id: imach.c,v 1.239 2016/08/26 15:51:03 brouard Exp $
    2:   $State: Exp $
    3:   $Log: imach.c,v $
    4:   Revision 1.239  2016/08/26 15:51:03  brouard
    5:   Summary: Improvement in Powell output in order to copy and paste
    6: 
    7:   Author:
    8: 
    9:   Revision 1.238  2016/08/26 14:23:35  brouard
   10:   Summary: Starting tests of 0.99
   11: 
   12:   Revision 1.237  2016/08/26 09:20:19  brouard
   13:   Summary: to valgrind
   14: 
   15:   Revision 1.236  2016/08/25 10:50:18  brouard
   16:   *** empty log message ***
   17: 
   18:   Revision 1.235  2016/08/25 06:59:23  brouard
   19:   *** empty log message ***
   20: 
   21:   Revision 1.234  2016/08/23 16:51:20  brouard
   22:   *** empty log message ***
   23: 
   24:   Revision 1.233  2016/08/23 07:40:50  brouard
   25:   Summary: not working
   26: 
   27:   Revision 1.232  2016/08/22 14:20:21  brouard
   28:   Summary: not working
   29: 
   30:   Revision 1.231  2016/08/22 07:17:15  brouard
   31:   Summary: not working
   32: 
   33:   Revision 1.230  2016/08/22 06:55:53  brouard
   34:   Summary: Not working
   35: 
   36:   Revision 1.229  2016/07/23 09:45:53  brouard
   37:   Summary: Completing for func too
   38: 
   39:   Revision 1.228  2016/07/22 17:45:30  brouard
   40:   Summary: Fixing some arrays, still debugging
   41: 
   42:   Revision 1.226  2016/07/12 18:42:34  brouard
   43:   Summary: temp
   44: 
   45:   Revision 1.225  2016/07/12 08:40:03  brouard
   46:   Summary: saving but not running
   47: 
   48:   Revision 1.224  2016/07/01 13:16:01  brouard
   49:   Summary: Fixes
   50: 
   51:   Revision 1.223  2016/02/19 09:23:35  brouard
   52:   Summary: temporary
   53: 
   54:   Revision 1.222  2016/02/17 08:14:50  brouard
   55:   Summary: Probably last 0.98 stable version 0.98r6
   56: 
   57:   Revision 1.221  2016/02/15 23:35:36  brouard
   58:   Summary: minor bug
   59: 
   60:   Revision 1.219  2016/02/15 00:48:12  brouard
   61:   *** empty log message ***
   62: 
   63:   Revision 1.218  2016/02/12 11:29:23  brouard
   64:   Summary: 0.99 Back projections
   65: 
   66:   Revision 1.217  2015/12/23 17:18:31  brouard
   67:   Summary: Experimental backcast
   68: 
   69:   Revision 1.216  2015/12/18 17:32:11  brouard
   70:   Summary: 0.98r4 Warning and status=-2
   71: 
   72:   Version 0.98r4 is now:
   73:    - displaying an error when status is -1, date of interview unknown and date of death known;
   74:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
   75:   Older changes concerning s=-2, dating from 2005 have been supersed.
   76: 
   77:   Revision 1.215  2015/12/16 08:52:24  brouard
   78:   Summary: 0.98r4 working
   79: 
   80:   Revision 1.214  2015/12/16 06:57:54  brouard
   81:   Summary: temporary not working
   82: 
   83:   Revision 1.213  2015/12/11 18:22:17  brouard
   84:   Summary: 0.98r4
   85: 
   86:   Revision 1.212  2015/11/21 12:47:24  brouard
   87:   Summary: minor typo
   88: 
   89:   Revision 1.211  2015/11/21 12:41:11  brouard
   90:   Summary: 0.98r3 with some graph of projected cross-sectional
   91: 
   92:   Author: Nicolas Brouard
   93: 
   94:   Revision 1.210  2015/11/18 17:41:20  brouard
   95:   Summary: Start working on projected prevalences
   96: 
   97:   Revision 1.209  2015/11/17 22:12:03  brouard
   98:   Summary: Adding ftolpl parameter
   99:   Author: N Brouard
  100: 
  101:   We had difficulties to get smoothed confidence intervals. It was due
  102:   to the period prevalence which wasn't computed accurately. The inner
  103:   parameter ftolpl is now an outer parameter of the .imach parameter
  104:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
  105:   computation are long.
  106: 
  107:   Revision 1.208  2015/11/17 14:31:57  brouard
  108:   Summary: temporary
  109: 
  110:   Revision 1.207  2015/10/27 17:36:57  brouard
  111:   *** empty log message ***
  112: 
  113:   Revision 1.206  2015/10/24 07:14:11  brouard
  114:   *** empty log message ***
  115: 
  116:   Revision 1.205  2015/10/23 15:50:53  brouard
  117:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
  118: 
  119:   Revision 1.204  2015/10/01 16:20:26  brouard
  120:   Summary: Some new graphs of contribution to likelihood
  121: 
  122:   Revision 1.203  2015/09/30 17:45:14  brouard
  123:   Summary: looking at better estimation of the hessian
  124: 
  125:   Also a better criteria for convergence to the period prevalence And
  126:   therefore adding the number of years needed to converge. (The
  127:   prevalence in any alive state shold sum to one
  128: 
  129:   Revision 1.202  2015/09/22 19:45:16  brouard
  130:   Summary: Adding some overall graph on contribution to likelihood. Might change
  131: 
  132:   Revision 1.201  2015/09/15 17:34:58  brouard
  133:   Summary: 0.98r0
  134: 
  135:   - Some new graphs like suvival functions
  136:   - Some bugs fixed like model=1+age+V2.
  137: 
  138:   Revision 1.200  2015/09/09 16:53:55  brouard
  139:   Summary: Big bug thanks to Flavia
  140: 
  141:   Even model=1+age+V2. did not work anymore
  142: 
  143:   Revision 1.199  2015/09/07 14:09:23  brouard
  144:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
  145: 
  146:   Revision 1.198  2015/09/03 07:14:39  brouard
  147:   Summary: 0.98q5 Flavia
  148: 
  149:   Revision 1.197  2015/09/01 18:24:39  brouard
  150:   *** empty log message ***
  151: 
  152:   Revision 1.196  2015/08/18 23:17:52  brouard
  153:   Summary: 0.98q5
  154: 
  155:   Revision 1.195  2015/08/18 16:28:39  brouard
  156:   Summary: Adding a hack for testing purpose
  157: 
  158:   After reading the title, ftol and model lines, if the comment line has
  159:   a q, starting with #q, the answer at the end of the run is quit. It
  160:   permits to run test files in batch with ctest. The former workaround was
  161:   $ echo q | imach foo.imach
  162: 
  163:   Revision 1.194  2015/08/18 13:32:00  brouard
  164:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
  165: 
  166:   Revision 1.193  2015/08/04 07:17:42  brouard
  167:   Summary: 0.98q4
  168: 
  169:   Revision 1.192  2015/07/16 16:49:02  brouard
  170:   Summary: Fixing some outputs
  171: 
  172:   Revision 1.191  2015/07/14 10:00:33  brouard
  173:   Summary: Some fixes
  174: 
  175:   Revision 1.190  2015/05/05 08:51:13  brouard
  176:   Summary: Adding digits in output parameters (7 digits instead of 6)
  177: 
  178:   Fix 1+age+.
  179: 
  180:   Revision 1.189  2015/04/30 14:45:16  brouard
  181:   Summary: 0.98q2
  182: 
  183:   Revision 1.188  2015/04/30 08:27:53  brouard
  184:   *** empty log message ***
  185: 
  186:   Revision 1.187  2015/04/29 09:11:15  brouard
  187:   *** empty log message ***
  188: 
  189:   Revision 1.186  2015/04/23 12:01:52  brouard
  190:   Summary: V1*age is working now, version 0.98q1
  191: 
  192:   Some codes had been disabled in order to simplify and Vn*age was
  193:   working in the optimization phase, ie, giving correct MLE parameters,
  194:   but, as usual, outputs were not correct and program core dumped.
  195: 
  196:   Revision 1.185  2015/03/11 13:26:42  brouard
  197:   Summary: Inclusion of compile and links command line for Intel Compiler
  198: 
  199:   Revision 1.184  2015/03/11 11:52:39  brouard
  200:   Summary: Back from Windows 8. Intel Compiler
  201: 
  202:   Revision 1.183  2015/03/10 20:34:32  brouard
  203:   Summary: 0.98q0, trying with directest, mnbrak fixed
  204: 
  205:   We use directest instead of original Powell test; probably no
  206:   incidence on the results, but better justifications;
  207:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
  208:   wrong results.
  209: 
  210:   Revision 1.182  2015/02/12 08:19:57  brouard
  211:   Summary: Trying to keep directest which seems simpler and more general
  212:   Author: Nicolas Brouard
  213: 
  214:   Revision 1.181  2015/02/11 23:22:24  brouard
  215:   Summary: Comments on Powell added
  216: 
  217:   Author:
  218: 
  219:   Revision 1.180  2015/02/11 17:33:45  brouard
  220:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
  221: 
  222:   Revision 1.179  2015/01/04 09:57:06  brouard
  223:   Summary: back to OS/X
  224: 
  225:   Revision 1.178  2015/01/04 09:35:48  brouard
  226:   *** empty log message ***
  227: 
  228:   Revision 1.177  2015/01/03 18:40:56  brouard
  229:   Summary: Still testing ilc32 on OSX
  230: 
  231:   Revision 1.176  2015/01/03 16:45:04  brouard
  232:   *** empty log message ***
  233: 
  234:   Revision 1.175  2015/01/03 16:33:42  brouard
  235:   *** empty log message ***
  236: 
  237:   Revision 1.174  2015/01/03 16:15:49  brouard
  238:   Summary: Still in cross-compilation
  239: 
  240:   Revision 1.173  2015/01/03 12:06:26  brouard
  241:   Summary: trying to detect cross-compilation
  242: 
  243:   Revision 1.172  2014/12/27 12:07:47  brouard
  244:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
  245: 
  246:   Revision 1.171  2014/12/23 13:26:59  brouard
  247:   Summary: Back from Visual C
  248: 
  249:   Still problem with utsname.h on Windows
  250: 
  251:   Revision 1.170  2014/12/23 11:17:12  brouard
  252:   Summary: Cleaning some \%% back to %%
  253: 
  254:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
  255: 
  256:   Revision 1.169  2014/12/22 23:08:31  brouard
  257:   Summary: 0.98p
  258: 
  259:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
  260: 
  261:   Revision 1.168  2014/12/22 15:17:42  brouard
  262:   Summary: update
  263: 
  264:   Revision 1.167  2014/12/22 13:50:56  brouard
  265:   Summary: Testing uname and compiler version and if compiled 32 or 64
  266: 
  267:   Testing on Linux 64
  268: 
  269:   Revision 1.166  2014/12/22 11:40:47  brouard
  270:   *** empty log message ***
  271: 
  272:   Revision 1.165  2014/12/16 11:20:36  brouard
  273:   Summary: After compiling on Visual C
  274: 
  275:   * imach.c (Module): Merging 1.61 to 1.162
  276: 
  277:   Revision 1.164  2014/12/16 10:52:11  brouard
  278:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
  279: 
  280:   * imach.c (Module): Merging 1.61 to 1.162
  281: 
  282:   Revision 1.163  2014/12/16 10:30:11  brouard
  283:   * imach.c (Module): Merging 1.61 to 1.162
  284: 
  285:   Revision 1.162  2014/09/25 11:43:39  brouard
  286:   Summary: temporary backup 0.99!
  287: 
  288:   Revision 1.1  2014/09/16 11:06:58  brouard
  289:   Summary: With some code (wrong) for nlopt
  290: 
  291:   Author:
  292: 
  293:   Revision 1.161  2014/09/15 20:41:41  brouard
  294:   Summary: Problem with macro SQR on Intel compiler
  295: 
  296:   Revision 1.160  2014/09/02 09:24:05  brouard
  297:   *** empty log message ***
  298: 
  299:   Revision 1.159  2014/09/01 10:34:10  brouard
  300:   Summary: WIN32
  301:   Author: Brouard
  302: 
  303:   Revision 1.158  2014/08/27 17:11:51  brouard
  304:   *** empty log message ***
  305: 
  306:   Revision 1.157  2014/08/27 16:26:55  brouard
  307:   Summary: Preparing windows Visual studio version
  308:   Author: Brouard
  309: 
  310:   In order to compile on Visual studio, time.h is now correct and time_t
  311:   and tm struct should be used. difftime should be used but sometimes I
  312:   just make the differences in raw time format (time(&now).
  313:   Trying to suppress #ifdef LINUX
  314:   Add xdg-open for __linux in order to open default browser.
  315: 
  316:   Revision 1.156  2014/08/25 20:10:10  brouard
  317:   *** empty log message ***
  318: 
  319:   Revision 1.155  2014/08/25 18:32:34  brouard
  320:   Summary: New compile, minor changes
  321:   Author: Brouard
  322: 
  323:   Revision 1.154  2014/06/20 17:32:08  brouard
  324:   Summary: Outputs now all graphs of convergence to period prevalence
  325: 
  326:   Revision 1.153  2014/06/20 16:45:46  brouard
  327:   Summary: If 3 live state, convergence to period prevalence on same graph
  328:   Author: Brouard
  329: 
  330:   Revision 1.152  2014/06/18 17:54:09  brouard
  331:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
  332: 
  333:   Revision 1.151  2014/06/18 16:43:30  brouard
  334:   *** empty log message ***
  335: 
  336:   Revision 1.150  2014/06/18 16:42:35  brouard
  337:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
  338:   Author: brouard
  339: 
  340:   Revision 1.149  2014/06/18 15:51:14  brouard
  341:   Summary: Some fixes in parameter files errors
  342:   Author: Nicolas Brouard
  343: 
  344:   Revision 1.148  2014/06/17 17:38:48  brouard
  345:   Summary: Nothing new
  346:   Author: Brouard
  347: 
  348:   Just a new packaging for OS/X version 0.98nS
  349: 
  350:   Revision 1.147  2014/06/16 10:33:11  brouard
  351:   *** empty log message ***
  352: 
  353:   Revision 1.146  2014/06/16 10:20:28  brouard
  354:   Summary: Merge
  355:   Author: Brouard
  356: 
  357:   Merge, before building revised version.
  358: 
  359:   Revision 1.145  2014/06/10 21:23:15  brouard
  360:   Summary: Debugging with valgrind
  361:   Author: Nicolas Brouard
  362: 
  363:   Lot of changes in order to output the results with some covariates
  364:   After the Edimburgh REVES conference 2014, it seems mandatory to
  365:   improve the code.
  366:   No more memory valgrind error but a lot has to be done in order to
  367:   continue the work of splitting the code into subroutines.
  368:   Also, decodemodel has been improved. Tricode is still not
  369:   optimal. nbcode should be improved. Documentation has been added in
  370:   the source code.
  371: 
  372:   Revision 1.143  2014/01/26 09:45:38  brouard
  373:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
  374: 
  375:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  376:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
  377: 
  378:   Revision 1.142  2014/01/26 03:57:36  brouard
  379:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
  380: 
  381:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  382: 
  383:   Revision 1.141  2014/01/26 02:42:01  brouard
  384:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  385: 
  386:   Revision 1.140  2011/09/02 10:37:54  brouard
  387:   Summary: times.h is ok with mingw32 now.
  388: 
  389:   Revision 1.139  2010/06/14 07:50:17  brouard
  390:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
  391:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
  392: 
  393:   Revision 1.138  2010/04/30 18:19:40  brouard
  394:   *** empty log message ***
  395: 
  396:   Revision 1.137  2010/04/29 18:11:38  brouard
  397:   (Module): Checking covariates for more complex models
  398:   than V1+V2. A lot of change to be done. Unstable.
  399: 
  400:   Revision 1.136  2010/04/26 20:30:53  brouard
  401:   (Module): merging some libgsl code. Fixing computation
  402:   of likelione (using inter/intrapolation if mle = 0) in order to
  403:   get same likelihood as if mle=1.
  404:   Some cleaning of code and comments added.
  405: 
  406:   Revision 1.135  2009/10/29 15:33:14  brouard
  407:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  408: 
  409:   Revision 1.134  2009/10/29 13:18:53  brouard
  410:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  411: 
  412:   Revision 1.133  2009/07/06 10:21:25  brouard
  413:   just nforces
  414: 
  415:   Revision 1.132  2009/07/06 08:22:05  brouard
  416:   Many tings
  417: 
  418:   Revision 1.131  2009/06/20 16:22:47  brouard
  419:   Some dimensions resccaled
  420: 
  421:   Revision 1.130  2009/05/26 06:44:34  brouard
  422:   (Module): Max Covariate is now set to 20 instead of 8. A
  423:   lot of cleaning with variables initialized to 0. Trying to make
  424:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
  425: 
  426:   Revision 1.129  2007/08/31 13:49:27  lievre
  427:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
  428: 
  429:   Revision 1.128  2006/06/30 13:02:05  brouard
  430:   (Module): Clarifications on computing e.j
  431: 
  432:   Revision 1.127  2006/04/28 18:11:50  brouard
  433:   (Module): Yes the sum of survivors was wrong since
  434:   imach-114 because nhstepm was no more computed in the age
  435:   loop. Now we define nhstepma in the age loop.
  436:   (Module): In order to speed up (in case of numerous covariates) we
  437:   compute health expectancies (without variances) in a first step
  438:   and then all the health expectancies with variances or standard
  439:   deviation (needs data from the Hessian matrices) which slows the
  440:   computation.
  441:   In the future we should be able to stop the program is only health
  442:   expectancies and graph are needed without standard deviations.
  443: 
  444:   Revision 1.126  2006/04/28 17:23:28  brouard
  445:   (Module): Yes the sum of survivors was wrong since
  446:   imach-114 because nhstepm was no more computed in the age
  447:   loop. Now we define nhstepma in the age loop.
  448:   Version 0.98h
  449: 
  450:   Revision 1.125  2006/04/04 15:20:31  lievre
  451:   Errors in calculation of health expectancies. Age was not initialized.
  452:   Forecasting file added.
  453: 
  454:   Revision 1.124  2006/03/22 17:13:53  lievre
  455:   Parameters are printed with %lf instead of %f (more numbers after the comma).
  456:   The log-likelihood is printed in the log file
  457: 
  458:   Revision 1.123  2006/03/20 10:52:43  brouard
  459:   * imach.c (Module): <title> changed, corresponds to .htm file
  460:   name. <head> headers where missing.
  461: 
  462:   * imach.c (Module): Weights can have a decimal point as for
  463:   English (a comma might work with a correct LC_NUMERIC environment,
  464:   otherwise the weight is truncated).
  465:   Modification of warning when the covariates values are not 0 or
  466:   1.
  467:   Version 0.98g
  468: 
  469:   Revision 1.122  2006/03/20 09:45:41  brouard
  470:   (Module): Weights can have a decimal point as for
  471:   English (a comma might work with a correct LC_NUMERIC environment,
  472:   otherwise the weight is truncated).
  473:   Modification of warning when the covariates values are not 0 or
  474:   1.
  475:   Version 0.98g
  476: 
  477:   Revision 1.121  2006/03/16 17:45:01  lievre
  478:   * imach.c (Module): Comments concerning covariates added
  479: 
  480:   * imach.c (Module): refinements in the computation of lli if
  481:   status=-2 in order to have more reliable computation if stepm is
  482:   not 1 month. Version 0.98f
  483: 
  484:   Revision 1.120  2006/03/16 15:10:38  lievre
  485:   (Module): refinements in the computation of lli if
  486:   status=-2 in order to have more reliable computation if stepm is
  487:   not 1 month. Version 0.98f
  488: 
  489:   Revision 1.119  2006/03/15 17:42:26  brouard
  490:   (Module): Bug if status = -2, the loglikelihood was
  491:   computed as likelihood omitting the logarithm. Version O.98e
  492: 
  493:   Revision 1.118  2006/03/14 18:20:07  brouard
  494:   (Module): varevsij Comments added explaining the second
  495:   table of variances if popbased=1 .
  496:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  497:   (Module): Function pstamp added
  498:   (Module): Version 0.98d
  499: 
  500:   Revision 1.117  2006/03/14 17:16:22  brouard
  501:   (Module): varevsij Comments added explaining the second
  502:   table of variances if popbased=1 .
  503:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  504:   (Module): Function pstamp added
  505:   (Module): Version 0.98d
  506: 
  507:   Revision 1.116  2006/03/06 10:29:27  brouard
  508:   (Module): Variance-covariance wrong links and
  509:   varian-covariance of ej. is needed (Saito).
  510: 
  511:   Revision 1.115  2006/02/27 12:17:45  brouard
  512:   (Module): One freematrix added in mlikeli! 0.98c
  513: 
  514:   Revision 1.114  2006/02/26 12:57:58  brouard
  515:   (Module): Some improvements in processing parameter
  516:   filename with strsep.
  517: 
  518:   Revision 1.113  2006/02/24 14:20:24  brouard
  519:   (Module): Memory leaks checks with valgrind and:
  520:   datafile was not closed, some imatrix were not freed and on matrix
  521:   allocation too.
  522: 
  523:   Revision 1.112  2006/01/30 09:55:26  brouard
  524:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
  525: 
  526:   Revision 1.111  2006/01/25 20:38:18  brouard
  527:   (Module): Lots of cleaning and bugs added (Gompertz)
  528:   (Module): Comments can be added in data file. Missing date values
  529:   can be a simple dot '.'.
  530: 
  531:   Revision 1.110  2006/01/25 00:51:50  brouard
  532:   (Module): Lots of cleaning and bugs added (Gompertz)
  533: 
  534:   Revision 1.109  2006/01/24 19:37:15  brouard
  535:   (Module): Comments (lines starting with a #) are allowed in data.
  536: 
  537:   Revision 1.108  2006/01/19 18:05:42  lievre
  538:   Gnuplot problem appeared...
  539:   To be fixed
  540: 
  541:   Revision 1.107  2006/01/19 16:20:37  brouard
  542:   Test existence of gnuplot in imach path
  543: 
  544:   Revision 1.106  2006/01/19 13:24:36  brouard
  545:   Some cleaning and links added in html output
  546: 
  547:   Revision 1.105  2006/01/05 20:23:19  lievre
  548:   *** empty log message ***
  549: 
  550:   Revision 1.104  2005/09/30 16:11:43  lievre
  551:   (Module): sump fixed, loop imx fixed, and simplifications.
  552:   (Module): If the status is missing at the last wave but we know
  553:   that the person is alive, then we can code his/her status as -2
  554:   (instead of missing=-1 in earlier versions) and his/her
  555:   contributions to the likelihood is 1 - Prob of dying from last
  556:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
  557:   the healthy state at last known wave). Version is 0.98
  558: 
  559:   Revision 1.103  2005/09/30 15:54:49  lievre
  560:   (Module): sump fixed, loop imx fixed, and simplifications.
  561: 
  562:   Revision 1.102  2004/09/15 17:31:30  brouard
  563:   Add the possibility to read data file including tab characters.
  564: 
  565:   Revision 1.101  2004/09/15 10:38:38  brouard
  566:   Fix on curr_time
  567: 
  568:   Revision 1.100  2004/07/12 18:29:06  brouard
  569:   Add version for Mac OS X. Just define UNIX in Makefile
  570: 
  571:   Revision 1.99  2004/06/05 08:57:40  brouard
  572:   *** empty log message ***
  573: 
  574:   Revision 1.98  2004/05/16 15:05:56  brouard
  575:   New version 0.97 . First attempt to estimate force of mortality
  576:   directly from the data i.e. without the need of knowing the health
  577:   state at each age, but using a Gompertz model: log u =a + b*age .
  578:   This is the basic analysis of mortality and should be done before any
  579:   other analysis, in order to test if the mortality estimated from the
  580:   cross-longitudinal survey is different from the mortality estimated
  581:   from other sources like vital statistic data.
  582: 
  583:   The same imach parameter file can be used but the option for mle should be -3.
  584: 
  585:   Agnès, who wrote this part of the code, tried to keep most of the
  586:   former routines in order to include the new code within the former code.
  587: 
  588:   The output is very simple: only an estimate of the intercept and of
  589:   the slope with 95% confident intervals.
  590: 
  591:   Current limitations:
  592:   A) Even if you enter covariates, i.e. with the
  593:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
  594:   B) There is no computation of Life Expectancy nor Life Table.
  595: 
  596:   Revision 1.97  2004/02/20 13:25:42  lievre
  597:   Version 0.96d. Population forecasting command line is (temporarily)
  598:   suppressed.
  599: 
  600:   Revision 1.96  2003/07/15 15:38:55  brouard
  601:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
  602:   rewritten within the same printf. Workaround: many printfs.
  603: 
  604:   Revision 1.95  2003/07/08 07:54:34  brouard
  605:   * imach.c (Repository):
  606:   (Repository): Using imachwizard code to output a more meaningful covariance
  607:   matrix (cov(a12,c31) instead of numbers.
  608: 
  609:   Revision 1.94  2003/06/27 13:00:02  brouard
  610:   Just cleaning
  611: 
  612:   Revision 1.93  2003/06/25 16:33:55  brouard
  613:   (Module): On windows (cygwin) function asctime_r doesn't
  614:   exist so I changed back to asctime which exists.
  615:   (Module): Version 0.96b
  616: 
  617:   Revision 1.92  2003/06/25 16:30:45  brouard
  618:   (Module): On windows (cygwin) function asctime_r doesn't
  619:   exist so I changed back to asctime which exists.
  620: 
  621:   Revision 1.91  2003/06/25 15:30:29  brouard
  622:   * imach.c (Repository): Duplicated warning errors corrected.
  623:   (Repository): Elapsed time after each iteration is now output. It
  624:   helps to forecast when convergence will be reached. Elapsed time
  625:   is stamped in powell.  We created a new html file for the graphs
  626:   concerning matrix of covariance. It has extension -cov.htm.
  627: 
  628:   Revision 1.90  2003/06/24 12:34:15  brouard
  629:   (Module): Some bugs corrected for windows. Also, when
  630:   mle=-1 a template is output in file "or"mypar.txt with the design
  631:   of the covariance matrix to be input.
  632: 
  633:   Revision 1.89  2003/06/24 12:30:52  brouard
  634:   (Module): Some bugs corrected for windows. Also, when
  635:   mle=-1 a template is output in file "or"mypar.txt with the design
  636:   of the covariance matrix to be input.
  637: 
  638:   Revision 1.88  2003/06/23 17:54:56  brouard
  639:   * 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.
  640: 
  641:   Revision 1.87  2003/06/18 12:26:01  brouard
  642:   Version 0.96
  643: 
  644:   Revision 1.86  2003/06/17 20:04:08  brouard
  645:   (Module): Change position of html and gnuplot routines and added
  646:   routine fileappend.
  647: 
  648:   Revision 1.85  2003/06/17 13:12:43  brouard
  649:   * imach.c (Repository): Check when date of death was earlier that
  650:   current date of interview. It may happen when the death was just
  651:   prior to the death. In this case, dh was negative and likelihood
  652:   was wrong (infinity). We still send an "Error" but patch by
  653:   assuming that the date of death was just one stepm after the
  654:   interview.
  655:   (Repository): Because some people have very long ID (first column)
  656:   we changed int to long in num[] and we added a new lvector for
  657:   memory allocation. But we also truncated to 8 characters (left
  658:   truncation)
  659:   (Repository): No more line truncation errors.
  660: 
  661:   Revision 1.84  2003/06/13 21:44:43  brouard
  662:   * imach.c (Repository): Replace "freqsummary" at a correct
  663:   place. It differs from routine "prevalence" which may be called
  664:   many times. Probs is memory consuming and must be used with
  665:   parcimony.
  666:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
  667: 
  668:   Revision 1.83  2003/06/10 13:39:11  lievre
  669:   *** empty log message ***
  670: 
  671:   Revision 1.82  2003/06/05 15:57:20  brouard
  672:   Add log in  imach.c and  fullversion number is now printed.
  673: 
  674: */
  675: /*
  676:    Interpolated Markov Chain
  677: 
  678:   Short summary of the programme:
  679:   
  680:   This program computes Healthy Life Expectancies or State-specific
  681:   (if states aren't health statuses) Expectancies from
  682:   cross-longitudinal data. Cross-longitudinal data consist in: 
  683: 
  684:   -1- a first survey ("cross") where individuals from different ages
  685:   are interviewed on their health status or degree of disability (in
  686:   the case of a health survey which is our main interest)
  687: 
  688:   -2- at least a second wave of interviews ("longitudinal") which
  689:   measure each change (if any) in individual health status.  Health
  690:   expectancies are computed from the time spent in each health state
  691:   according to a model. More health states you consider, more time is
  692:   necessary to reach the Maximum Likelihood of the parameters involved
  693:   in the model.  The simplest model is the multinomial logistic model
  694:   where pij is the probability to be observed in state j at the second
  695:   wave conditional to be observed in state i at the first
  696:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
  697:   etc , where 'age' is age and 'sex' is a covariate. If you want to
  698:   have a more complex model than "constant and age", you should modify
  699:   the program where the markup *Covariates have to be included here
  700:   again* invites you to do it.  More covariates you add, slower the
  701:   convergence.
  702: 
  703:   The advantage of this computer programme, compared to a simple
  704:   multinomial logistic model, is clear when the delay between waves is not
  705:   identical for each individual. Also, if a individual missed an
  706:   intermediate interview, the information is lost, but taken into
  707:   account using an interpolation or extrapolation.  
  708: 
  709:   hPijx is the probability to be observed in state i at age x+h
  710:   conditional to the observed state i at age x. The delay 'h' can be
  711:   split into an exact number (nh*stepm) of unobserved intermediate
  712:   states. This elementary transition (by month, quarter,
  713:   semester or year) is modelled as a multinomial logistic.  The hPx
  714:   matrix is simply the matrix product of nh*stepm elementary matrices
  715:   and the contribution of each individual to the likelihood is simply
  716:   hPijx.
  717: 
  718:   Also this programme outputs the covariance matrix of the parameters but also
  719:   of the life expectancies. It also computes the period (stable) prevalence.
  720: 
  721: Back prevalence and projections:
  722: 
  723:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
  724:    double agemaxpar, double ftolpl, int *ncvyearp, double
  725:    dateprev1,double dateprev2, int firstpass, int lastpass, int
  726:    mobilavproj)
  727: 
  728:     Computes the back prevalence limit for any combination of
  729:     covariate values k at any age between ageminpar and agemaxpar and
  730:     returns it in **bprlim. In the loops,
  731: 
  732:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
  733:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
  734: 
  735:    - hBijx Back Probability to be in state i at age x-h being in j at x
  736:    Computes for any combination of covariates k and any age between bage and fage 
  737:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
  738:  			oldm=oldms;savm=savms;
  739: 
  740:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
  741:      Computes the transition matrix starting at age 'age' over
  742:      'nhstepm*hstepm*stepm' months (i.e. until
  743:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
  744:      nhstepm*hstepm matrices. 
  745: 
  746:      Returns p3mat[i][j][h] after calling
  747:      p3mat[i][j][h]=matprod2(newm,
  748:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
  749:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
  750:      oldm);
  751: 
  752: Important routines
  753: 
  754: - func (or funcone), computes logit (pij) distinguishing
  755:   o fixed variables (single or product dummies or quantitative);
  756:   o varying variables by:
  757:    (1) wave (single, product dummies, quantitative), 
  758:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
  759:        % fixed dummy (treated) or quantitative (not done because time-consuming);
  760:        % varying dummy (not done) or quantitative (not done);
  761: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
  762:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
  763: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
  764:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
  765:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
  766: 
  767: 
  768:   
  769:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
  770:            Institut national d'études démographiques, Paris.
  771:   This software have been partly granted by Euro-REVES, a concerted action
  772:   from the European Union.
  773:   It is copyrighted identically to a GNU software product, ie programme and
  774:   software can be distributed freely for non commercial use. Latest version
  775:   can be accessed at http://euroreves.ined.fr/imach .
  776: 
  777:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
  778:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
  779:   
  780:   **********************************************************************/
  781: /*
  782:   main
  783:   read parameterfile
  784:   read datafile
  785:   concatwav
  786:   freqsummary
  787:   if (mle >= 1)
  788:     mlikeli
  789:   print results files
  790:   if mle==1 
  791:      computes hessian
  792:   read end of parameter file: agemin, agemax, bage, fage, estepm
  793:       begin-prev-date,...
  794:   open gnuplot file
  795:   open html file
  796:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
  797:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
  798:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
  799:     freexexit2 possible for memory heap.
  800: 
  801:   h Pij x                         | pij_nom  ficrestpij
  802:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
  803:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
  804:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
  805: 
  806:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
  807:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
  808:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
  809:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
  810:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
  811: 
  812:   forecasting if prevfcast==1 prevforecast call prevalence()
  813:   health expectancies
  814:   Variance-covariance of DFLE
  815:   prevalence()
  816:    movingaverage()
  817:   varevsij() 
  818:   if popbased==1 varevsij(,popbased)
  819:   total life expectancies
  820:   Variance of period (stable) prevalence
  821:  end
  822: */
  823: 
  824: /* #define DEBUG */
  825: /* #define DEBUGBRENT */
  826: /* #define DEBUGLINMIN */
  827: /* #define DEBUGHESS */
  828: #define DEBUGHESSIJ
  829: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
  830: #define POWELL /* Instead of NLOPT */
  831: #define POWELLNOF3INFF1TEST /* Skip test */
  832: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
  833: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
  834: 
  835: #include <math.h>
  836: #include <stdio.h>
  837: #include <stdlib.h>
  838: #include <string.h>
  839: #include <ctype.h>
  840: 
  841: #ifdef _WIN32
  842: #include <io.h>
  843: #include <windows.h>
  844: #include <tchar.h>
  845: #else
  846: #include <unistd.h>
  847: #endif
  848: 
  849: #include <limits.h>
  850: #include <sys/types.h>
  851: 
  852: #if defined(__GNUC__)
  853: #include <sys/utsname.h> /* Doesn't work on Windows */
  854: #endif
  855: 
  856: #include <sys/stat.h>
  857: #include <errno.h>
  858: /* extern int errno; */
  859: 
  860: /* #ifdef LINUX */
  861: /* #include <time.h> */
  862: /* #include "timeval.h" */
  863: /* #else */
  864: /* #include <sys/time.h> */
  865: /* #endif */
  866: 
  867: #include <time.h>
  868: 
  869: #ifdef GSL
  870: #include <gsl/gsl_errno.h>
  871: #include <gsl/gsl_multimin.h>
  872: #endif
  873: 
  874: 
  875: #ifdef NLOPT
  876: #include <nlopt.h>
  877: typedef struct {
  878:   double (* function)(double [] );
  879: } myfunc_data ;
  880: #endif
  881: 
  882: /* #include <libintl.h> */
  883: /* #define _(String) gettext (String) */
  884: 
  885: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
  886: 
  887: #define GNUPLOTPROGRAM "gnuplot"
  888: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
  889: #define FILENAMELENGTH 132
  890: 
  891: #define	GLOCK_ERROR_NOPATH		-1	/* empty path */
  892: #define	GLOCK_ERROR_GETCWD		-2	/* cannot get cwd */
  893: 
  894: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
  895: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
  896: 
  897: #define NINTERVMAX 8
  898: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
  899: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
  900: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
  901: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
  902: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
  903: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
  904: #define MAXN 20000
  905: #define YEARM 12. /**< Number of months per year */
  906: /* #define AGESUP 130 */
  907: #define AGESUP 150
  908: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
  909: #define AGEBASE 40
  910: #define AGEOVERFLOW 1.e20
  911: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
  912: #ifdef _WIN32
  913: #define DIRSEPARATOR '\\'
  914: #define CHARSEPARATOR "\\"
  915: #define ODIRSEPARATOR '/'
  916: #else
  917: #define DIRSEPARATOR '/'
  918: #define CHARSEPARATOR "/"
  919: #define ODIRSEPARATOR '\\'
  920: #endif
  921: 
  922: /* $Id: imach.c,v 1.239 2016/08/26 15:51:03 brouard Exp $ */
  923: /* $State: Exp $ */
  924: #include "version.h"
  925: char version[]=__IMACH_VERSION__;
  926: char copyright[]="February 2016,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015-2018";
  927: char fullversion[]="$Revision: 1.239 $ $Date: 2016/08/26 15:51:03 $"; 
  928: char strstart[80];
  929: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
  930: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
  931: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
  932: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
  933: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
  934: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
  935: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
  936: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
  937: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
  938: int cptcovprodnoage=0; /**< Number of covariate products without age */   
  939: int cptcoveff=0; /* Total number of covariates to vary for printing results */
  940: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
  941: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
  942: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
  943: int nsd=0; /**< Total number of single dummy variables (output) */
  944: int nsq=0; /**< Total number of single quantitative variables (output) */
  945: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
  946: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
  947: int ntveff=0; /**< ntveff number of effective time varying variables */
  948: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
  949: int cptcov=0; /* Working variable */
  950: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
  951: int npar=NPARMAX;
  952: int nlstate=2; /* Number of live states */
  953: int ndeath=1; /* Number of dead states */
  954: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
  955: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
  956: int popbased=0;
  957: 
  958: int *wav; /* Number of waves for this individuual 0 is possible */
  959: int maxwav=0; /* Maxim number of waves */
  960: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
  961: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
  962: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
  963: 		   to the likelihood and the sum of weights (done by funcone)*/
  964: int mle=1, weightopt=0;
  965: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
  966: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
  967: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
  968: 	   * wave mi and wave mi+1 is not an exact multiple of stepm. */
  969: int countcallfunc=0;  /* Count the number of calls to func */
  970: int selected(int kvar); /* Is covariate kvar selected for printing results */
  971: 
  972: double jmean=1; /* Mean space between 2 waves */
  973: double **matprod2(); /* test */
  974: double **oldm, **newm, **savm; /* Working pointers to matrices */
  975: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
  976: double	 **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
  977: 
  978: /*FILE *fic ; */ /* Used in readdata only */
  979: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
  980: FILE *ficlog, *ficrespow;
  981: int globpr=0; /* Global variable for printing or not */
  982: double fretone; /* Only one call to likelihood */
  983: long ipmx=0; /* Number of contributions */
  984: double sw; /* Sum of weights */
  985: char filerespow[FILENAMELENGTH];
  986: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
  987: FILE *ficresilk;
  988: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
  989: FILE *ficresprobmorprev;
  990: FILE *fichtm, *fichtmcov; /* Html File */
  991: FILE *ficreseij;
  992: char filerese[FILENAMELENGTH];
  993: FILE *ficresstdeij;
  994: char fileresstde[FILENAMELENGTH];
  995: FILE *ficrescveij;
  996: char filerescve[FILENAMELENGTH];
  997: FILE  *ficresvij;
  998: char fileresv[FILENAMELENGTH];
  999: FILE  *ficresvpl;
 1000: char fileresvpl[FILENAMELENGTH];
 1001: char title[MAXLINE];
 1002: char model[MAXLINE]; /**< The model line */
 1003: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
 1004: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
 1005: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
 1006: char command[FILENAMELENGTH];
 1007: int  outcmd=0;
 1008: 
 1009: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
 1010: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
 1011: char filelog[FILENAMELENGTH]; /* Log file */
 1012: char filerest[FILENAMELENGTH];
 1013: char fileregp[FILENAMELENGTH];
 1014: char popfile[FILENAMELENGTH];
 1015: 
 1016: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
 1017: 
 1018: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
 1019: /* struct timezone tzp; */
 1020: /* extern int gettimeofday(); */
 1021: struct tm tml, *gmtime(), *localtime();
 1022: 
 1023: extern time_t time();
 1024: 
 1025: struct tm start_time, end_time, curr_time, last_time, forecast_time;
 1026: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
 1027: struct tm tm;
 1028: 
 1029: char strcurr[80], strfor[80];
 1030: 
 1031: char *endptr;
 1032: long lval;
 1033: double dval;
 1034: 
 1035: #define NR_END 1
 1036: #define FREE_ARG char*
 1037: #define FTOL 1.0e-10
 1038: 
 1039: #define NRANSI 
 1040: #define ITMAX 200 
 1041: 
 1042: #define TOL 2.0e-4 
 1043: 
 1044: #define CGOLD 0.3819660 
 1045: #define ZEPS 1.0e-10 
 1046: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
 1047: 
 1048: #define GOLD 1.618034 
 1049: #define GLIMIT 100.0 
 1050: #define TINY 1.0e-20 
 1051: 
 1052: static double maxarg1,maxarg2;
 1053: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
 1054: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
 1055:   
 1056: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
 1057: #define rint(a) floor(a+0.5)
 1058: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
 1059: #define mytinydouble 1.0e-16
 1060: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
 1061: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
 1062: /* static double dsqrarg; */
 1063: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
 1064: static double sqrarg;
 1065: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
 1066: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
 1067: int agegomp= AGEGOMP;
 1068: 
 1069: int imx; 
 1070: int stepm=1;
 1071: /* Stepm, step in month: minimum step interpolation*/
 1072: 
 1073: int estepm;
 1074: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
 1075: 
 1076: int m,nb;
 1077: long *num;
 1078: int firstpass=0, lastpass=4,*cod, *cens;
 1079: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
 1080: 		   covariate for which somebody answered excluding 
 1081: 		   undefined. Usually 2: 0 and 1. */
 1082: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
 1083: 			     covariate for which somebody answered including 
 1084: 			     undefined. Usually 3: -1, 0 and 1. */
 1085: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
 1086: double **pmmij, ***probs; /* Global pointer */
 1087: double ***mobaverage, ***mobaverages; /* New global variable */
 1088: double *ageexmed,*agecens;
 1089: double dateintmean=0;
 1090: 
 1091: double *weight;
 1092: int **s; /* Status */
 1093: double *agedc;
 1094: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
 1095: 		  * covar=matrix(0,NCOVMAX,1,n); 
 1096: 		  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
 1097: double **coqvar; /* Fixed quantitative covariate iqv */
 1098: double ***cotvar; /* Time varying covariate itv */
 1099: double ***cotqvar; /* Time varying quantitative covariate itqv */
 1100: double  idx; 
 1101: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
 1102: /*           V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1103: /*k          1  2   3   4     5    6    7     8    9 */
 1104: /*Tvar[k]=   5  4   3   6     5    2    7     1    1 */
 1105: /* Tndvar[k]    1   2   3               4          5 */
 1106: /*TDvar         4   3   6               7          1 */ /* For outputs only; combination of dummies fixed or varying */
 1107: /* Tns[k]    1  2   2              4               5 */ /* Number of single cova */
 1108: /* TvarsD[k]    1   2                              3 */ /* Number of single dummy cova */
 1109: /* TvarsDind    2   3                              9 */ /* position K of single dummy cova */
 1110: /* TvarsQ[k] 1                     2                 */ /* Number of single quantitative cova */
 1111: /* TvarsQind 1                     6                 */ /* position K of single quantitative cova */
 1112: /* Tprod[i]=k           4               7            */
 1113: /* Tage[i]=k                  5               8      */
 1114: /* */
 1115: /* Type                    */
 1116: /* V         1  2  3  4  5 */
 1117: /*           F  F  V  V  V */
 1118: /*           D  Q  D  D  Q */
 1119: /*                         */
 1120: int *TvarsD;
 1121: int *TvarsDind;
 1122: int *TvarsQ;
 1123: int *TvarsQind;
 1124: 
 1125: #define MAXRESULTLINES 10
 1126: int nresult=0;
 1127: int TKresult[MAXRESULTLINES];
 1128: int Tresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
 1129: int Tinvresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
 1130: int Tvresult[MAXRESULTLINES][NCOVMAX]; /* For dummy variable , variable # (output) */
 1131: double Tqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
 1132: double Tqinvresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
 1133: int Tvqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , variable # (output) */
 1134: 
 1135: /* int *TDvar; /\**< TDvar[1]=4,  TDvarF[2]=3, TDvar[3]=6  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
 1136: int *TvarF; /**< TvarF[1]=Tvar[6]=2,  TvarF[2]=Tvar[7]=7, TvarF[3]=Tvar[9]=1  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1137: int *TvarFind; /**< TvarFind[1]=6,  TvarFind[2]=7, Tvarind[3]=9  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1138: int *TvarV; /**< TvarV[1]=Tvar[1]=5, TvarV[2]=Tvar[2]=4  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1139: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1140: int *TvarA; /**< TvarA[1]=Tvar[5]=5, TvarA[2]=Tvar[8]=1  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1141: int *TvarAind; /**< TvarindA[1]=5, TvarAind[2]=8  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1142: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1143: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1144: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
 1145: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
 1146: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
 1147: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
 1148: int *TvarVQ; /* TvarVQ[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying quantitative variable */
 1149: int *TvarVQind; /* TvarVQind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying quantitative variable */
 1150: 
 1151: int *Tvarsel; /**< Selected covariates for output */
 1152: double *Tvalsel; /**< Selected modality value of covariate for output */
 1153: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
 1154: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
 1155: int *Dummy; /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
 1156: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
 1157: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
 1158: int *Tage;
 1159: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
 1160: int *Tmodelind; /** Tmodelind[Tvaraff[3]]=9 for V1 position,Tvaraff[1]@9={4, 3, 1, 0, 0, 0, 0, 0, 0}, model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
 1161: int *TmodelInvind; /** Tmodelind[Tvaraff[3]]=9 for V1 position,Tvaraff[1]@9={4, 3, 1, 0, 0, 0, 0, 0, 0}, model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/ 
 1162: int *TmodelInvQind; /** Tmodelqind[1]=1 for V5(quantitative varying) position,Tvaraff[1]@9={4, 3, 1, 0, 0, 0, 0, 0, 0}, model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1  */
 1163: int *Ndum; /** Freq of modality (tricode */
 1164: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
 1165: int **Tvard;
 1166: int *Tprod;/**< Gives the k position of the k1 product */
 1167: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
 1168: int *Tposprod; /**< Gives the k1 product from the k position */
 1169:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
 1170:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
 1171: int cptcovprod, *Tvaraff, *invalidvarcomb;
 1172: double *lsurv, *lpop, *tpop;
 1173: 
 1174: #define FD 1; /* Fixed dummy covariate */
 1175: #define FQ 2; /* Fixed quantitative covariate */
 1176: #define FP 3; /* Fixed product covariate */
 1177: #define FPDD 7; /* Fixed product dummy*dummy covariate */
 1178: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
 1179: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
 1180: #define VD 10; /* Varying dummy covariate */
 1181: #define VQ 11; /* Varying quantitative covariate */
 1182: #define VP 12; /* Varying product covariate */
 1183: #define VPDD 13; /* Varying product dummy*dummy covariate */
 1184: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
 1185: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
 1186: #define APFD 16; /* Age product * fixed dummy covariate */
 1187: #define APFQ 17; /* Age product * fixed quantitative covariate */
 1188: #define APVD 18; /* Age product * varying dummy covariate */
 1189: #define APVQ 19; /* Age product * varying quantitative covariate */
 1190: 
 1191: #define FTYPE 1; /* Fixed covariate */
 1192: #define VTYPE 2; /* Varying covariate (loop in wave) */
 1193: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
 1194: 
 1195: struct kmodel{
 1196: 	int maintype; /* main type */
 1197: 	int subtype; /* subtype */
 1198: };
 1199: struct kmodel modell[NCOVMAX];
 1200: 
 1201: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
 1202: double ftolhess; /**< Tolerance for computing hessian */
 1203: 
 1204: /**************** split *************************/
 1205: static	int split( char *path, char *dirc, char *name, char *ext, char *finame )
 1206: {
 1207:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
 1208:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
 1209:   */ 
 1210:   char	*ss;				/* pointer */
 1211:   int	l1=0, l2=0;				/* length counters */
 1212: 
 1213:   l1 = strlen(path );			/* length of path */
 1214:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
 1215:   ss= strrchr( path, DIRSEPARATOR );		/* find last / */
 1216:   if ( ss == NULL ) {			/* no directory, so determine current directory */
 1217:     strcpy( name, path );		/* we got the fullname name because no directory */
 1218:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
 1219:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
 1220:     /* get current working directory */
 1221:     /*    extern  char* getcwd ( char *buf , int len);*/
 1222: #ifdef WIN32
 1223:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
 1224: #else
 1225: 	if (getcwd(dirc, FILENAME_MAX) == NULL) {
 1226: #endif
 1227:       return( GLOCK_ERROR_GETCWD );
 1228:     }
 1229:     /* got dirc from getcwd*/
 1230:     printf(" DIRC = %s \n",dirc);
 1231:   } else {				/* strip directory from path */
 1232:     ss++;				/* after this, the filename */
 1233:     l2 = strlen( ss );			/* length of filename */
 1234:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
 1235:     strcpy( name, ss );		/* save file name */
 1236:     strncpy( dirc, path, l1 - l2 );	/* now the directory */
 1237:     dirc[l1-l2] = '\0';			/* add zero */
 1238:     printf(" DIRC2 = %s \n",dirc);
 1239:   }
 1240:   /* We add a separator at the end of dirc if not exists */
 1241:   l1 = strlen( dirc );			/* length of directory */
 1242:   if( dirc[l1-1] != DIRSEPARATOR ){
 1243:     dirc[l1] =  DIRSEPARATOR;
 1244:     dirc[l1+1] = 0; 
 1245:     printf(" DIRC3 = %s \n",dirc);
 1246:   }
 1247:   ss = strrchr( name, '.' );		/* find last / */
 1248:   if (ss >0){
 1249:     ss++;
 1250:     strcpy(ext,ss);			/* save extension */
 1251:     l1= strlen( name);
 1252:     l2= strlen(ss)+1;
 1253:     strncpy( finame, name, l1-l2);
 1254:     finame[l1-l2]= 0;
 1255:   }
 1256: 
 1257:   return( 0 );				/* we're done */
 1258: }
 1259: 
 1260: 
 1261: /******************************************/
 1262: 
 1263: void replace_back_to_slash(char *s, char*t)
 1264: {
 1265:   int i;
 1266:   int lg=0;
 1267:   i=0;
 1268:   lg=strlen(t);
 1269:   for(i=0; i<= lg; i++) {
 1270:     (s[i] = t[i]);
 1271:     if (t[i]== '\\') s[i]='/';
 1272:   }
 1273: }
 1274: 
 1275: char *trimbb(char *out, char *in)
 1276: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
 1277:   char *s;
 1278:   s=out;
 1279:   while (*in != '\0'){
 1280:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
 1281:       in++;
 1282:     }
 1283:     *out++ = *in++;
 1284:   }
 1285:   *out='\0';
 1286:   return s;
 1287: }
 1288: 
 1289: /* char *substrchaine(char *out, char *in, char *chain) */
 1290: /* { */
 1291: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
 1292: /*   char *s, *t; */
 1293: /*   t=in;s=out; */
 1294: /*   while ((*in != *chain) && (*in != '\0')){ */
 1295: /*     *out++ = *in++; */
 1296: /*   } */
 1297: 
 1298: /*   /\* *in matches *chain *\/ */
 1299: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
 1300: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1301: /*   } */
 1302: /*   in--; chain--; */
 1303: /*   while ( (*in != '\0')){ */
 1304: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1305: /*     *out++ = *in++; */
 1306: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1307: /*   } */
 1308: /*   *out='\0'; */
 1309: /*   out=s; */
 1310: /*   return out; */
 1311: /* } */
 1312: char *substrchaine(char *out, char *in, char *chain)
 1313: {
 1314:   /* Substract chain 'chain' from 'in', return and output 'out' */
 1315:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
 1316: 
 1317:   char *strloc;
 1318: 
 1319:   strcpy (out, in); 
 1320:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
 1321:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
 1322:   if(strloc != NULL){ 
 1323:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
 1324:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
 1325:     /* strcpy (strloc, strloc +strlen(chain));*/
 1326:   }
 1327:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
 1328:   return out;
 1329: }
 1330: 
 1331: 
 1332: char *cutl(char *blocc, char *alocc, char *in, char occ)
 1333: {
 1334:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
 1335:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
 1336:      gives blocc="abcdef" and alocc="ghi2j".
 1337:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
 1338:   */
 1339:   char *s, *t;
 1340:   t=in;s=in;
 1341:   while ((*in != occ) && (*in != '\0')){
 1342:     *alocc++ = *in++;
 1343:   }
 1344:   if( *in == occ){
 1345:     *(alocc)='\0';
 1346:     s=++in;
 1347:   }
 1348:  
 1349:   if (s == t) {/* occ not found */
 1350:     *(alocc-(in-s))='\0';
 1351:     in=s;
 1352:   }
 1353:   while ( *in != '\0'){
 1354:     *blocc++ = *in++;
 1355:   }
 1356: 
 1357:   *blocc='\0';
 1358:   return t;
 1359: }
 1360: char *cutv(char *blocc, char *alocc, char *in, char occ)
 1361: {
 1362:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
 1363:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
 1364:      gives blocc="abcdef2ghi" and alocc="j".
 1365:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
 1366:   */
 1367:   char *s, *t;
 1368:   t=in;s=in;
 1369:   while (*in != '\0'){
 1370:     while( *in == occ){
 1371:       *blocc++ = *in++;
 1372:       s=in;
 1373:     }
 1374:     *blocc++ = *in++;
 1375:   }
 1376:   if (s == t) /* occ not found */
 1377:     *(blocc-(in-s))='\0';
 1378:   else
 1379:     *(blocc-(in-s)-1)='\0';
 1380:   in=s;
 1381:   while ( *in != '\0'){
 1382:     *alocc++ = *in++;
 1383:   }
 1384: 
 1385:   *alocc='\0';
 1386:   return s;
 1387: }
 1388: 
 1389: int nbocc(char *s, char occ)
 1390: {
 1391:   int i,j=0;
 1392:   int lg=20;
 1393:   i=0;
 1394:   lg=strlen(s);
 1395:   for(i=0; i<= lg; i++) {
 1396:     if  (s[i] == occ ) j++;
 1397:   }
 1398:   return j;
 1399: }
 1400: 
 1401: /* void cutv(char *u,char *v, char*t, char occ) */
 1402: /* { */
 1403: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
 1404: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
 1405: /*      gives u="abcdef2ghi" and v="j" *\/ */
 1406: /*   int i,lg,j,p=0; */
 1407: /*   i=0; */
 1408: /*   lg=strlen(t); */
 1409: /*   for(j=0; j<=lg-1; j++) { */
 1410: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
 1411: /*   } */
 1412: 
 1413: /*   for(j=0; j<p; j++) { */
 1414: /*     (u[j] = t[j]); */
 1415: /*   } */
 1416: /*      u[p]='\0'; */
 1417: 
 1418: /*    for(j=0; j<= lg; j++) { */
 1419: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
 1420: /*   } */
 1421: /* } */
 1422: 
 1423: #ifdef _WIN32
 1424: char * strsep(char **pp, const char *delim)
 1425: {
 1426:   char *p, *q;
 1427:          
 1428:   if ((p = *pp) == NULL)
 1429:     return 0;
 1430:   if ((q = strpbrk (p, delim)) != NULL)
 1431:   {
 1432:     *pp = q + 1;
 1433:     *q = '\0';
 1434:   }
 1435:   else
 1436:     *pp = 0;
 1437:   return p;
 1438: }
 1439: #endif
 1440: 
 1441: /********************** nrerror ********************/
 1442: 
 1443: void nrerror(char error_text[])
 1444: {
 1445:   fprintf(stderr,"ERREUR ...\n");
 1446:   fprintf(stderr,"%s\n",error_text);
 1447:   exit(EXIT_FAILURE);
 1448: }
 1449: /*********************** vector *******************/
 1450: double *vector(int nl, int nh)
 1451: {
 1452:   double *v;
 1453:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
 1454:   if (!v) nrerror("allocation failure in vector");
 1455:   return v-nl+NR_END;
 1456: }
 1457: 
 1458: /************************ free vector ******************/
 1459: void free_vector(double*v, int nl, int nh)
 1460: {
 1461:   free((FREE_ARG)(v+nl-NR_END));
 1462: }
 1463: 
 1464: /************************ivector *******************************/
 1465: int *ivector(long nl,long nh)
 1466: {
 1467:   int *v;
 1468:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
 1469:   if (!v) nrerror("allocation failure in ivector");
 1470:   return v-nl+NR_END;
 1471: }
 1472: 
 1473: /******************free ivector **************************/
 1474: void free_ivector(int *v, long nl, long nh)
 1475: {
 1476:   free((FREE_ARG)(v+nl-NR_END));
 1477: }
 1478: 
 1479: /************************lvector *******************************/
 1480: long *lvector(long nl,long nh)
 1481: {
 1482:   long *v;
 1483:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
 1484:   if (!v) nrerror("allocation failure in ivector");
 1485:   return v-nl+NR_END;
 1486: }
 1487: 
 1488: /******************free lvector **************************/
 1489: void free_lvector(long *v, long nl, long nh)
 1490: {
 1491:   free((FREE_ARG)(v+nl-NR_END));
 1492: }
 1493: 
 1494: /******************* imatrix *******************************/
 1495: int **imatrix(long nrl, long nrh, long ncl, long nch) 
 1496:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
 1497: { 
 1498:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
 1499:   int **m; 
 1500:   
 1501:   /* allocate pointers to rows */ 
 1502:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
 1503:   if (!m) nrerror("allocation failure 1 in matrix()"); 
 1504:   m += NR_END; 
 1505:   m -= nrl; 
 1506:   
 1507:   
 1508:   /* allocate rows and set pointers to them */ 
 1509:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
 1510:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
 1511:   m[nrl] += NR_END; 
 1512:   m[nrl] -= ncl; 
 1513:   
 1514:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
 1515:   
 1516:   /* return pointer to array of pointers to rows */ 
 1517:   return m; 
 1518: } 
 1519: 
 1520: /****************** free_imatrix *************************/
 1521: void free_imatrix(m,nrl,nrh,ncl,nch)
 1522:       int **m;
 1523:       long nch,ncl,nrh,nrl; 
 1524:      /* free an int matrix allocated by imatrix() */ 
 1525: { 
 1526:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
 1527:   free((FREE_ARG) (m+nrl-NR_END)); 
 1528: } 
 1529: 
 1530: /******************* matrix *******************************/
 1531: double **matrix(long nrl, long nrh, long ncl, long nch)
 1532: {
 1533:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
 1534:   double **m;
 1535: 
 1536:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1537:   if (!m) nrerror("allocation failure 1 in matrix()");
 1538:   m += NR_END;
 1539:   m -= nrl;
 1540: 
 1541:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1542:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1543:   m[nrl] += NR_END;
 1544:   m[nrl] -= ncl;
 1545: 
 1546:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1547:   return m;
 1548:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
 1549: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
 1550: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
 1551:    */
 1552: }
 1553: 
 1554: /*************************free matrix ************************/
 1555: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
 1556: {
 1557:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1558:   free((FREE_ARG)(m+nrl-NR_END));
 1559: }
 1560: 
 1561: /******************* ma3x *******************************/
 1562: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
 1563: {
 1564:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
 1565:   double ***m;
 1566: 
 1567:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1568:   if (!m) nrerror("allocation failure 1 in matrix()");
 1569:   m += NR_END;
 1570:   m -= nrl;
 1571: 
 1572:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1573:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1574:   m[nrl] += NR_END;
 1575:   m[nrl] -= ncl;
 1576: 
 1577:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1578: 
 1579:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
 1580:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
 1581:   m[nrl][ncl] += NR_END;
 1582:   m[nrl][ncl] -= nll;
 1583:   for (j=ncl+1; j<=nch; j++) 
 1584:     m[nrl][j]=m[nrl][j-1]+nlay;
 1585:   
 1586:   for (i=nrl+1; i<=nrh; i++) {
 1587:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
 1588:     for (j=ncl+1; j<=nch; j++) 
 1589:       m[i][j]=m[i][j-1]+nlay;
 1590:   }
 1591:   return m; 
 1592:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
 1593:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
 1594:   */
 1595: }
 1596: 
 1597: /*************************free ma3x ************************/
 1598: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
 1599: {
 1600:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
 1601:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1602:   free((FREE_ARG)(m+nrl-NR_END));
 1603: }
 1604: 
 1605: /*************** function subdirf ***********/
 1606: char *subdirf(char fileres[])
 1607: {
 1608:   /* Caution optionfilefiname is hidden */
 1609:   strcpy(tmpout,optionfilefiname);
 1610:   strcat(tmpout,"/"); /* Add to the right */
 1611:   strcat(tmpout,fileres);
 1612:   return tmpout;
 1613: }
 1614: 
 1615: /*************** function subdirf2 ***********/
 1616: char *subdirf2(char fileres[], char *preop)
 1617: {
 1618:   
 1619:   /* Caution optionfilefiname is hidden */
 1620:   strcpy(tmpout,optionfilefiname);
 1621:   strcat(tmpout,"/");
 1622:   strcat(tmpout,preop);
 1623:   strcat(tmpout,fileres);
 1624:   return tmpout;
 1625: }
 1626: 
 1627: /*************** function subdirf3 ***********/
 1628: char *subdirf3(char fileres[], char *preop, char *preop2)
 1629: {
 1630:   
 1631:   /* Caution optionfilefiname is hidden */
 1632:   strcpy(tmpout,optionfilefiname);
 1633:   strcat(tmpout,"/");
 1634:   strcat(tmpout,preop);
 1635:   strcat(tmpout,preop2);
 1636:   strcat(tmpout,fileres);
 1637:   return tmpout;
 1638: }
 1639:  
 1640: /*************** function subdirfext ***********/
 1641: char *subdirfext(char fileres[], char *preop, char *postop)
 1642: {
 1643:   
 1644:   strcpy(tmpout,preop);
 1645:   strcat(tmpout,fileres);
 1646:   strcat(tmpout,postop);
 1647:   return tmpout;
 1648: }
 1649: 
 1650: /*************** function subdirfext3 ***********/
 1651: char *subdirfext3(char fileres[], char *preop, char *postop)
 1652: {
 1653:   
 1654:   /* Caution optionfilefiname is hidden */
 1655:   strcpy(tmpout,optionfilefiname);
 1656:   strcat(tmpout,"/");
 1657:   strcat(tmpout,preop);
 1658:   strcat(tmpout,fileres);
 1659:   strcat(tmpout,postop);
 1660:   return tmpout;
 1661: }
 1662:  
 1663: char *asc_diff_time(long time_sec, char ascdiff[])
 1664: {
 1665:   long sec_left, days, hours, minutes;
 1666:   days = (time_sec) / (60*60*24);
 1667:   sec_left = (time_sec) % (60*60*24);
 1668:   hours = (sec_left) / (60*60) ;
 1669:   sec_left = (sec_left) %(60*60);
 1670:   minutes = (sec_left) /60;
 1671:   sec_left = (sec_left) % (60);
 1672:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
 1673:   return ascdiff;
 1674: }
 1675: 
 1676: /***************** f1dim *************************/
 1677: extern int ncom; 
 1678: extern double *pcom,*xicom;
 1679: extern double (*nrfunc)(double []); 
 1680:  
 1681: double f1dim(double x) 
 1682: { 
 1683:   int j; 
 1684:   double f;
 1685:   double *xt; 
 1686:  
 1687:   xt=vector(1,ncom); 
 1688:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
 1689:   f=(*nrfunc)(xt); 
 1690:   free_vector(xt,1,ncom); 
 1691:   return f; 
 1692: } 
 1693: 
 1694: /*****************brent *************************/
 1695: double brent(double ax, double bx, double cx, double (*f)(double), double tol, 	double *xmin) 
 1696: {
 1697:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
 1698:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
 1699:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
 1700:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
 1701:    * returned function value. 
 1702:   */
 1703:   int iter; 
 1704:   double a,b,d,etemp;
 1705:   double fu=0,fv,fw,fx;
 1706:   double ftemp=0.;
 1707:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
 1708:   double e=0.0; 
 1709:  
 1710:   a=(ax < cx ? ax : cx); 
 1711:   b=(ax > cx ? ax : cx); 
 1712:   x=w=v=bx; 
 1713:   fw=fv=fx=(*f)(x); 
 1714:   for (iter=1;iter<=ITMAX;iter++) { 
 1715:     xm=0.5*(a+b); 
 1716:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
 1717:     /*		if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
 1718:     printf(".");fflush(stdout);
 1719:     fprintf(ficlog,".");fflush(ficlog);
 1720: #ifdef DEBUGBRENT
 1721:     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);
 1722:     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);
 1723:     /*		if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
 1724: #endif
 1725:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
 1726:       *xmin=x; 
 1727:       return fx; 
 1728:     } 
 1729:     ftemp=fu;
 1730:     if (fabs(e) > tol1) { 
 1731:       r=(x-w)*(fx-fv); 
 1732:       q=(x-v)*(fx-fw); 
 1733:       p=(x-v)*q-(x-w)*r; 
 1734:       q=2.0*(q-r); 
 1735:       if (q > 0.0) p = -p; 
 1736:       q=fabs(q); 
 1737:       etemp=e; 
 1738:       e=d; 
 1739:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
 1740: 				d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1741:       else { 
 1742: 				d=p/q; 
 1743: 				u=x+d; 
 1744: 				if (u-a < tol2 || b-u < tol2) 
 1745: 					d=SIGN(tol1,xm-x); 
 1746:       } 
 1747:     } else { 
 1748:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1749:     } 
 1750:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
 1751:     fu=(*f)(u); 
 1752:     if (fu <= fx) { 
 1753:       if (u >= x) a=x; else b=x; 
 1754:       SHFT(v,w,x,u) 
 1755:       SHFT(fv,fw,fx,fu) 
 1756:     } else { 
 1757:       if (u < x) a=u; else b=u; 
 1758:       if (fu <= fw || w == x) { 
 1759: 				v=w; 
 1760: 				w=u; 
 1761: 				fv=fw; 
 1762: 				fw=fu; 
 1763:       } else if (fu <= fv || v == x || v == w) { 
 1764: 				v=u; 
 1765: 				fv=fu; 
 1766:       } 
 1767:     } 
 1768:   } 
 1769:   nrerror("Too many iterations in brent"); 
 1770:   *xmin=x; 
 1771:   return fx; 
 1772: } 
 1773: 
 1774: /****************** mnbrak ***********************/
 1775: 
 1776: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
 1777: 	    double (*func)(double)) 
 1778: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
 1779: the downhill direction (defined by the function as evaluated at the initial points) and returns
 1780: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
 1781: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
 1782:    */
 1783:   double ulim,u,r,q, dum;
 1784:   double fu; 
 1785: 
 1786:   double scale=10.;
 1787:   int iterscale=0;
 1788: 
 1789:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
 1790:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
 1791: 
 1792: 
 1793:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
 1794:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
 1795:   /*   *bx = *ax - (*ax - *bx)/scale; */
 1796:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
 1797:   /* } */
 1798: 
 1799:   if (*fb > *fa) { 
 1800:     SHFT(dum,*ax,*bx,dum) 
 1801:     SHFT(dum,*fb,*fa,dum) 
 1802:   } 
 1803:   *cx=(*bx)+GOLD*(*bx-*ax); 
 1804:   *fc=(*func)(*cx); 
 1805: #ifdef DEBUG
 1806:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
 1807:   fprintf(ficlog,"mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
 1808: #endif
 1809:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc. If fc=inf it exits and if flat fb=fc it exits too.*/
 1810:     r=(*bx-*ax)*(*fb-*fc); 
 1811:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
 1812:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
 1813:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
 1814:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
 1815:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
 1816:       fu=(*func)(u); 
 1817: #ifdef DEBUG
 1818:       /* f(x)=A(x-u)**2+f(u) */
 1819:       double A, fparabu; 
 1820:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 1821:       fparabu= *fa - A*(*ax-u)*(*ax-u);
 1822:       printf("\nmnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf, fparabu=%.12f, q=%lf < %lf=r)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu,q,r);
 1823:       fprintf(ficlog,"\nmnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf, fparabu=%.12f, q=%lf < %lf=r)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu,q,r);
 1824:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
 1825:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
 1826:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
 1827:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
 1828: #endif 
 1829: #ifdef MNBRAKORIGINAL
 1830: #else
 1831: /*       if (fu > *fc) { */
 1832: /* #ifdef DEBUG */
 1833: /*       printf("mnbrak4  fu > fc \n"); */
 1834: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
 1835: /* #endif */
 1836: /* 	/\* 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 *\\/  *\/ */
 1837: /* 	/\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
 1838: /* 	dum=u; /\* Shifting c and u *\/ */
 1839: /* 	u = *cx; */
 1840: /* 	*cx = dum; */
 1841: /* 	dum = fu; */
 1842: /* 	fu = *fc; */
 1843: /* 	*fc =dum; */
 1844: /*       } else { /\* end *\/ */
 1845: /* #ifdef DEBUG */
 1846: /*       printf("mnbrak3  fu < fc \n"); */
 1847: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
 1848: /* #endif */
 1849: /* 	dum=u; /\* Shifting c and u *\/ */
 1850: /* 	u = *cx; */
 1851: /* 	*cx = dum; */
 1852: /* 	dum = fu; */
 1853: /* 	fu = *fc; */
 1854: /* 	*fc =dum; */
 1855: /*       } */
 1856: #ifdef DEBUGMNBRAK
 1857: 		 double A, fparabu; 
 1858:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 1859:      fparabu= *fa - A*(*ax-u)*(*ax-u);
 1860:      printf("\nmnbrak35 ax=%lf fa=%lf bx=%lf fb=%lf, u=%lf fp=%lf fu=%lf < or >= fc=%lf cx=%lf, q=%lf < %lf=r \n",*ax, *fa, *bx,*fb,u,fparabu,fu,*fc,*cx,q,r);
 1861:      fprintf(ficlog,"\nmnbrak35 ax=%lf fa=%lf bx=%lf fb=%lf, u=%lf fp=%lf fu=%lf < or >= fc=%lf cx=%lf, q=%lf < %lf=r \n",*ax, *fa, *bx,*fb,u,fparabu,fu,*fc,*cx,q,r);
 1862: #endif
 1863:       dum=u; /* Shifting c and u */
 1864:       u = *cx;
 1865:       *cx = dum;
 1866:       dum = fu;
 1867:       fu = *fc;
 1868:       *fc =dum;
 1869: #endif
 1870:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
 1871: #ifdef DEBUG
 1872:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
 1873:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
 1874: #endif
 1875:       fu=(*func)(u); 
 1876:       if (fu < *fc) { 
 1877: #ifdef DEBUG
 1878: 				printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
 1879: 			  fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
 1880: #endif
 1881: 			  SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
 1882: 				SHFT(*fb,*fc,fu,(*func)(u)) 
 1883: #ifdef DEBUG
 1884: 					printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
 1885: #endif
 1886:       } 
 1887:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
 1888: #ifdef DEBUG
 1889:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
 1890:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
 1891: #endif
 1892:       u=ulim; 
 1893:       fu=(*func)(u); 
 1894:     } else { /* u could be left to b (if r > q parabola has a maximum) */
 1895: #ifdef DEBUG
 1896:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
 1897:       fprintf(ficlog,"\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
 1898: #endif
 1899:       u=(*cx)+GOLD*(*cx-*bx); 
 1900:       fu=(*func)(u); 
 1901: #ifdef DEBUG
 1902:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
 1903:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
 1904: #endif
 1905:     } /* end tests */
 1906:     SHFT(*ax,*bx,*cx,u) 
 1907:     SHFT(*fa,*fb,*fc,fu) 
 1908: #ifdef DEBUG
 1909:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
 1910:       fprintf(ficlog, "\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
 1911: #endif
 1912:   } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
 1913: } 
 1914: 
 1915: /*************** linmin ************************/
 1916: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
 1917: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
 1918: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
 1919: the value of func at the returned location p . This is actually all accomplished by calling the
 1920: routines mnbrak and brent .*/
 1921: int ncom; 
 1922: double *pcom,*xicom;
 1923: double (*nrfunc)(double []); 
 1924:  
 1925: #ifdef LINMINORIGINAL
 1926: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
 1927: #else
 1928: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
 1929: #endif
 1930: { 
 1931:   double brent(double ax, double bx, double cx, 
 1932: 	       double (*f)(double), double tol, double *xmin); 
 1933:   double f1dim(double x); 
 1934:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
 1935: 	      double *fc, double (*func)(double)); 
 1936:   int j; 
 1937:   double xx,xmin,bx,ax; 
 1938:   double fx,fb,fa;
 1939: 
 1940: #ifdef LINMINORIGINAL
 1941: #else
 1942:   double scale=10., axs, xxs; /* Scale added for infinity */
 1943: #endif
 1944:   
 1945:   ncom=n; 
 1946:   pcom=vector(1,n); 
 1947:   xicom=vector(1,n); 
 1948:   nrfunc=func; 
 1949:   for (j=1;j<=n;j++) { 
 1950:     pcom[j]=p[j]; 
 1951:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
 1952:   } 
 1953: 
 1954: #ifdef LINMINORIGINAL
 1955:   xx=1.;
 1956: #else
 1957:   axs=0.0;
 1958:   xxs=1.;
 1959:   do{
 1960:     xx= xxs;
 1961: #endif
 1962:     ax=0.;
 1963:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
 1964:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
 1965:     /* 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))   */
 1966:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
 1967:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
 1968:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
 1969:     /* 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]]*/
 1970: #ifdef LINMINORIGINAL
 1971: #else
 1972:     if (fx != fx){
 1973: 			xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
 1974: 			printf("|");
 1975: 			fprintf(ficlog,"|");
 1976: #ifdef DEBUGLINMIN
 1977: 			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);
 1978: #endif
 1979:     }
 1980:   }while(fx != fx && xxs > 1.e-5);
 1981: #endif
 1982:   
 1983: #ifdef DEBUGLINMIN
 1984:   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);
 1985:   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);
 1986: #endif
 1987: #ifdef LINMINORIGINAL
 1988: #else
 1989: 	if(fb == fx){ /* Flat function in the direction */
 1990: 		xmin=xx;
 1991:     *flat=1;
 1992: 	}else{
 1993:     *flat=0;
 1994: #endif
 1995: 		/*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
 1996:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
 1997:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
 1998:   /* fmin = f(p[j] + xmin * xi[j]) */
 1999:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
 2000:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
 2001: #ifdef DEBUG
 2002:   printf("retour brent from bracket (a=%lf fa=%lf, xx=%lf fx=%lf, b=%lf fb=%lf): fret=%lf xmin=%lf\n",ax,fa,xx,fx,bx,fb,*fret,xmin);
 2003:   fprintf(ficlog,"retour brent from bracket (a=%lf fa=%lf, xx=%lf fx=%lf, b=%lf fb=%lf): fret=%lf xmin=%lf\n",ax,fa,xx,fx,bx,fb,*fret,xmin);
 2004: #endif
 2005: #ifdef LINMINORIGINAL
 2006: #else
 2007: 			}
 2008: #endif
 2009: #ifdef DEBUGLINMIN
 2010:   printf("linmin end ");
 2011:   fprintf(ficlog,"linmin end ");
 2012: #endif
 2013:   for (j=1;j<=n;j++) { 
 2014: #ifdef LINMINORIGINAL
 2015:     xi[j] *= xmin; 
 2016: #else
 2017: #ifdef DEBUGLINMIN
 2018:     if(xxs <1.0)
 2019:       printf(" before xi[%d]=%12.8f", j,xi[j]);
 2020: #endif
 2021:     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) */
 2022: #ifdef DEBUGLINMIN
 2023:     if(xxs <1.0)
 2024:       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 );
 2025: #endif
 2026: #endif
 2027:     p[j] += xi[j]; /* Parameters values are updated accordingly */
 2028:   } 
 2029: #ifdef DEBUGLINMIN
 2030:   printf("\n");
 2031:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
 2032:   fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
 2033:   for (j=1;j<=n;j++) { 
 2034:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
 2035:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
 2036:     if(j % ncovmodel == 0){
 2037:       printf("\n");
 2038:       fprintf(ficlog,"\n");
 2039:     }
 2040:   }
 2041: #else
 2042: #endif
 2043:   free_vector(xicom,1,n); 
 2044:   free_vector(pcom,1,n); 
 2045: } 
 2046: 
 2047: 
 2048: /*************** powell ************************/
 2049: /*
 2050: Minimization of a function func of n variables. Input consists of an initial starting point
 2051: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
 2052: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
 2053: such that failure to decrease by more than this amount on one iteration signals doneness. On
 2054: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
 2055: function value at p , and iter is the number of iterations taken. The routine linmin is used.
 2056:  */
 2057: #ifdef LINMINORIGINAL
 2058: #else
 2059: 	int *flatdir; /* Function is vanishing in that direction */
 2060: 	int flat=0, flatd=0; /* Function is vanishing in that direction */
 2061: #endif
 2062: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
 2063: 	    double (*func)(double [])) 
 2064: { 
 2065: #ifdef LINMINORIGINAL
 2066:  void linmin(double p[], double xi[], int n, double *fret, 
 2067: 	      double (*func)(double [])); 
 2068: #else 
 2069:  void linmin(double p[], double xi[], int n, double *fret, 
 2070: 						 double (*func)(double []),int *flat); 
 2071: #endif
 2072:  int i,ibig,j,jk,k; 
 2073:   double del,t,*pt,*ptt,*xit;
 2074:   double directest;
 2075:   double fp,fptt;
 2076:   double *xits;
 2077:   int niterf, itmp;
 2078: #ifdef LINMINORIGINAL
 2079: #else
 2080: 
 2081:   flatdir=ivector(1,n); 
 2082:   for (j=1;j<=n;j++) flatdir[j]=0; 
 2083: #endif
 2084: 
 2085:   pt=vector(1,n); 
 2086:   ptt=vector(1,n); 
 2087:   xit=vector(1,n); 
 2088:   xits=vector(1,n); 
 2089:   *fret=(*func)(p); 
 2090:   for (j=1;j<=n;j++) pt[j]=p[j]; 
 2091:   rcurr_time = time(NULL);  
 2092:   for (*iter=1;;++(*iter)) { 
 2093:     fp=(*fret); /* From former iteration or initial value */
 2094:     ibig=0; 
 2095:     del=0.0; 
 2096:     rlast_time=rcurr_time;
 2097:     /* (void) gettimeofday(&curr_time,&tzp); */
 2098:     rcurr_time = time(NULL);  
 2099:     curr_time = *localtime(&rcurr_time);
 2100:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
 2101:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
 2102: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
 2103:     for (i=1;i<=n;i++) {
 2104:       fprintf(ficrespow," %.12lf", p[i]);
 2105:     }
 2106:     fprintf(ficrespow,"\n");fflush(ficrespow);
 2107:     printf("\n#model=  1      +     age ");
 2108:     fprintf(ficlog,"\n#model=  1      +     age ");
 2109:     if(nagesqr==1){
 2110: 	printf("  + age*age  ",Tvar[j]);
 2111: 	fprintf(ficlog,"  + age*age  ",Tvar[j]);
 2112:     }
 2113:     for(j=1;j <=ncovmodel-2;j++){
 2114:       if(Typevar[j]==0) {
 2115: 	printf("  +      V%d  ",Tvar[j]);
 2116: 	fprintf(ficlog,"  +      V%d  ",Tvar[j]);
 2117:       }else if(Typevar[j]==1) {
 2118: 	printf("  +    V%d*age ",Tvar[j]);
 2119: 	fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
 2120:       }else if(Typevar[j]==2) {
 2121: 	printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
 2122: 	fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
 2123:       }
 2124:     }
 2125:     printf("\n");
 2126: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
 2127: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
 2128:     fprintf(ficlog,"\n");
 2129:     for(i=1,jk=1; i <=nlstate; i++){
 2130:       for(k=1; k <=(nlstate+ndeath); k++){
 2131: 	if (k != i) {
 2132: 	  printf("%d%d ",i,k);
 2133: 	  fprintf(ficlog,"%d%d ",i,k);
 2134: 	  fprintf(ficres,"%1d%1d ",i,k);
 2135: 	  for(j=1; j <=ncovmodel; j++){
 2136: 	    printf("%12.7f ",p[jk]);
 2137: 	    fprintf(ficlog,"%12.7f ",p[jk]);
 2138: 	    fprintf(ficres,"%12.7f ",p[jk]);
 2139: 	    jk++; 
 2140: 	  }
 2141: 	  printf("\n");
 2142: 	  fprintf(ficlog,"\n");
 2143: 	  fprintf(ficres,"\n");
 2144: 	}
 2145:       }
 2146:     }
 2147:     if(*iter <=3){
 2148:       tml = *localtime(&rcurr_time);
 2149:       strcpy(strcurr,asctime(&tml));
 2150:       rforecast_time=rcurr_time; 
 2151:       itmp = strlen(strcurr);
 2152:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
 2153: 				strcurr[itmp-1]='\0';
 2154:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 2155:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 2156:       for(niterf=10;niterf<=30;niterf+=10){
 2157: 				rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
 2158: 				forecast_time = *localtime(&rforecast_time);
 2159: 				strcpy(strfor,asctime(&forecast_time));
 2160: 				itmp = strlen(strfor);
 2161: 				if(strfor[itmp-1]=='\n')
 2162: 					strfor[itmp-1]='\0';
 2163: 				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);
 2164: 				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);
 2165:       }
 2166:     }
 2167:     for (i=1;i<=n;i++) { /* For each direction i */
 2168:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
 2169:       fptt=(*fret); 
 2170: #ifdef DEBUG
 2171:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 2172:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 2173: #endif
 2174:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
 2175:       fprintf(ficlog,"%d",i);fflush(ficlog);
 2176: #ifdef LINMINORIGINAL
 2177:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
 2178: #else
 2179:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
 2180: 			flatdir[i]=flat; /* Function is vanishing in that direction i */
 2181: #endif
 2182: 			/* Outputs are fret(new point p) p is updated and xit rescaled */
 2183:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
 2184: 				/* because that direction will be replaced unless the gain del is small */
 2185: 				/* in comparison with the 'probable' gain, mu^2, with the last average direction. */
 2186: 				/* Unless the n directions are conjugate some gain in the determinant may be obtained */
 2187: 				/* with the new direction. */
 2188: 				del=fabs(fptt-(*fret)); 
 2189: 				ibig=i; 
 2190:       } 
 2191: #ifdef DEBUG
 2192:       printf("%d %.12e",i,(*fret));
 2193:       fprintf(ficlog,"%d %.12e",i,(*fret));
 2194:       for (j=1;j<=n;j++) {
 2195: 				xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
 2196: 				printf(" x(%d)=%.12e",j,xit[j]);
 2197: 				fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
 2198:       }
 2199:       for(j=1;j<=n;j++) {
 2200: 				printf(" p(%d)=%.12e",j,p[j]);
 2201: 				fprintf(ficlog," p(%d)=%.12e",j,p[j]);
 2202:       }
 2203:       printf("\n");
 2204:       fprintf(ficlog,"\n");
 2205: #endif
 2206:     } /* end loop on each direction i */
 2207:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
 2208:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
 2209:     /* New value of last point Pn is not computed, P(n-1) */
 2210:       for(j=1;j<=n;j++) {
 2211: 				if(flatdir[j] >0){
 2212: 					printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
 2213: 					fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
 2214: 				}
 2215: 				/* printf("\n"); */
 2216: 				/* fprintf(ficlog,"\n"); */
 2217: 			}
 2218:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
 2219:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
 2220:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
 2221:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
 2222:       /* decreased of more than 3.84  */
 2223:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
 2224:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
 2225:       /* By adding 10 parameters more the gain should be 18.31 */
 2226: 			
 2227:       /* Starting the program with initial values given by a former maximization will simply change */
 2228:       /* the scales of the directions and the directions, because the are reset to canonical directions */
 2229:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
 2230:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
 2231: #ifdef DEBUG
 2232:       int k[2],l;
 2233:       k[0]=1;
 2234:       k[1]=-1;
 2235:       printf("Max: %.12e",(*func)(p));
 2236:       fprintf(ficlog,"Max: %.12e",(*func)(p));
 2237:       for (j=1;j<=n;j++) {
 2238: 	printf(" %.12e",p[j]);
 2239: 	fprintf(ficlog," %.12e",p[j]);
 2240:       }
 2241:       printf("\n");
 2242:       fprintf(ficlog,"\n");
 2243:       for(l=0;l<=1;l++) {
 2244: 	for (j=1;j<=n;j++) {
 2245: 	  ptt[j]=p[j]+(p[j]-pt[j])*k[l];
 2246: 	  printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 2247: 	  fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 2248: 	}
 2249: 	printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 2250: 	fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 2251:       }
 2252: #endif
 2253: 
 2254: #ifdef LINMINORIGINAL
 2255: #else
 2256:       free_ivector(flatdir,1,n); 
 2257: #endif
 2258:       free_vector(xit,1,n); 
 2259:       free_vector(xits,1,n); 
 2260:       free_vector(ptt,1,n); 
 2261:       free_vector(pt,1,n); 
 2262:       return; 
 2263:     } /* enough precision */ 
 2264:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
 2265:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
 2266:       ptt[j]=2.0*p[j]-pt[j]; 
 2267:       xit[j]=p[j]-pt[j]; 
 2268:       pt[j]=p[j]; 
 2269:     } 
 2270:     fptt=(*func)(ptt); /* f_3 */
 2271: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
 2272: 		if (*iter <=4) {
 2273: #else
 2274: #endif
 2275: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
 2276: #else
 2277:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
 2278: #endif
 2279:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
 2280:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
 2281:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
 2282:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
 2283:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
 2284:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
 2285:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
 2286:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
 2287:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
 2288:       /*  Even if f3 <f1, directest can be negative and t >0 */
 2289:       /* mu² and del² are equal when f3=f1 */
 2290: 			/* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
 2291: 			/* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
 2292: 			/* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
 2293: 			/* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
 2294: #ifdef NRCORIGINAL
 2295:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
 2296: #else
 2297:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
 2298:       t= t- del*SQR(fp-fptt);
 2299: #endif
 2300:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
 2301: #ifdef DEBUG
 2302:       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);
 2303:       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);
 2304:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 2305: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 2306:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 2307: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 2308:       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);
 2309:       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);
 2310: #endif
 2311: #ifdef POWELLORIGINAL
 2312:       if (t < 0.0) { /* Then we use it for new direction */
 2313: #else
 2314:       if (directest*t < 0.0) { /* Contradiction between both tests */
 2315: 				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);
 2316:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 2317:         fprintf(ficlog,"directest= %.12lf (if directest<0 or t<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);
 2318:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 2319:       } 
 2320:       if (directest < 0.0) { /* Then we use it for new direction */
 2321: #endif
 2322: #ifdef DEBUGLINMIN
 2323: 	printf("Before linmin in direction P%d-P0\n",n);
 2324: 	for (j=1;j<=n;j++) {
 2325: 	  printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2326: 	  fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2327: 	  if(j % ncovmodel == 0){
 2328: 	    printf("\n");
 2329: 	    fprintf(ficlog,"\n");
 2330: 	  }
 2331: 	}
 2332: #endif
 2333: #ifdef LINMINORIGINAL
 2334: 	linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
 2335: #else
 2336: 	linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
 2337: 	flatdir[i]=flat; /* Function is vanishing in that direction i */
 2338: #endif
 2339: 	
 2340: #ifdef DEBUGLINMIN
 2341: 	for (j=1;j<=n;j++) { 
 2342: 	  printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2343: 	  fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2344: 	  if(j % ncovmodel == 0){
 2345: 	    printf("\n");
 2346: 	    fprintf(ficlog,"\n");
 2347: 	  }
 2348: 	}
 2349: #endif
 2350: 	for (j=1;j<=n;j++) { 
 2351: 	  xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
 2352: 	  xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
 2353: 	}
 2354: #ifdef LINMINORIGINAL
 2355: #else
 2356: 	for (j=1, flatd=0;j<=n;j++) {
 2357: 	  if(flatdir[j]>0)
 2358: 	    flatd++;
 2359: 	}
 2360: 	if(flatd >0){
 2361: 	  printf("%d flat directions\n",flatd);
 2362: 	  fprintf(ficlog,"%d flat directions\n",flatd);
 2363: 	  for (j=1;j<=n;j++) { 
 2364: 	    if(flatdir[j]>0){
 2365: 	      printf("%d ",j);
 2366: 	      fprintf(ficlog,"%d ",j);
 2367: 	    }
 2368: 	  }
 2369: 	  printf("\n");
 2370: 	  fprintf(ficlog,"\n");
 2371: 	}
 2372: #endif
 2373: 	printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 2374: 	fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 2375: 	
 2376: #ifdef DEBUG
 2377: 	printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 2378: 	fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 2379: 	for(j=1;j<=n;j++){
 2380: 	  printf(" %lf",xit[j]);
 2381: 	  fprintf(ficlog," %lf",xit[j]);
 2382: 	}
 2383: 	printf("\n");
 2384: 	fprintf(ficlog,"\n");
 2385: #endif
 2386:       } /* end of t or directest negative */
 2387: #ifdef POWELLNOF3INFF1TEST
 2388: #else
 2389:       } /* end if (fptt < fp)  */
 2390: #endif
 2391: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
 2392:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
 2393: #else
 2394: #endif
 2395: 		} /* loop iteration */ 
 2396: } 
 2397:   
 2398: /**** Prevalence limit (stable or period prevalence)  ****************/
 2399:   
 2400:   double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij, int nres)
 2401:   {
 2402:     /* Computes the prevalence limit in each live state at age x and for covariate combination ij 
 2403:        (and selected quantitative values in nres)
 2404:        by left multiplying the unit
 2405:        matrix by transitions matrix until convergence is reached with precision ftolpl */
 2406:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
 2407:   /* Wx is row vector: population in state 1, population in state 2, population dead */
 2408:   /* or prevalence in state 1, prevalence in state 2, 0 */
 2409:   /* newm is the matrix after multiplications, its rows are identical at a factor */
 2410:   /* Initial matrix pimij */
 2411:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
 2412:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
 2413:   /*  0,                   0                  , 1} */
 2414:   /*
 2415:    * and after some iteration: */
 2416:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
 2417:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
 2418:   /*  0,                   0                  , 1} */
 2419:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
 2420:   /* {0.51571254859325999, 0.4842874514067399, */
 2421:   /*  0.51326036147820708, 0.48673963852179264} */
 2422:   /* If we start from prlim again, prlim tends to a constant matrix */
 2423:     
 2424:   int i, ii,j,k;
 2425:   double *min, *max, *meandiff, maxmax,sumnew=0.;
 2426:   /* double **matprod2(); */ /* test */
 2427:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
 2428:   double **newm;
 2429:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
 2430:   int ncvloop=0;
 2431:   
 2432:   min=vector(1,nlstate);
 2433:   max=vector(1,nlstate);
 2434:   meandiff=vector(1,nlstate);
 2435: 
 2436: 	/* Starting with matrix unity */
 2437:   for (ii=1;ii<=nlstate+ndeath;ii++)
 2438:     for (j=1;j<=nlstate+ndeath;j++){
 2439:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2440:     }
 2441:   
 2442:   cov[1]=1.;
 2443:   
 2444:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2445:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
 2446:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
 2447:     ncvloop++;
 2448:     newm=savm;
 2449:     /* Covariates have to be included here again */
 2450:     cov[2]=agefin;
 2451:     if(nagesqr==1)
 2452:       cov[3]= agefin*agefin;;
 2453:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
 2454:  			/* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
 2455:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
 2456:       /* printf("prevalim Dummy combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov=%lf codtabm(%d,Tvar[%d])=%d \n",ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,k)],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,k)); */
 2457:     }
 2458:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
 2459:  			/* Here comes the value of quantitative after renumbering k with single quantitative covariates */
 2460:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
 2461:       /* printf("prevalim Quantitative k=%d  TvarsQind[%d]=%d, TvarsQ[%d]=V%d,Tqresult[%d][%d]=%f\n",k,k,TvarsQind[k],k,TvarsQ[k],nres,k,Tqresult[nres][k]); */
 2462:     }
 2463:     for (k=1; k<=cptcovage;k++){  /* For product with age */
 2464:       if(Dummy[Tvar[Tage[k]]]){
 2465: 	cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 2466:       } else{
 2467: 	cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
 2468:       }
 2469:       /* printf("prevalim Age combi=%d k=%d  Tage[%d]=V%d Tqresult[%d][%d]=%f\n",ij,k,k,Tage[k],nres,k,Tqresult[nres][k]); */
 2470:     }
 2471:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
 2472:       /* printf("prevalim Prod ij=%d k=%d  Tprod[%d]=%d Tvard[%d][1]=V%d, Tvard[%d][2]=V%d\n",ij,k,k,Tprod[k], k,Tvard[k][1], k,Tvard[k][2]); */
 2473:       if(Dummy[Tvard[k][1]==0]){
 2474: 	if(Dummy[Tvard[k][2]==0]){
 2475: 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
 2476: 	}else{
 2477: 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
 2478: 	}
 2479:       }else{
 2480: 	if(Dummy[Tvard[k][2]==0]){
 2481: 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
 2482: 	}else{
 2483: 	  cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
 2484: 	}
 2485:       }
 2486:     }
 2487:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 2488:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 2489:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 2490:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2491:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 2492: 		/* age and covariate values of ij are in 'cov' */
 2493:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
 2494:     
 2495:     savm=oldm;
 2496:     oldm=newm;
 2497: 
 2498:     for(j=1; j<=nlstate; j++){
 2499:       max[j]=0.;
 2500:       min[j]=1.;
 2501:     }
 2502:     for(i=1;i<=nlstate;i++){
 2503:       sumnew=0;
 2504:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
 2505:       for(j=1; j<=nlstate; j++){ 
 2506: 	prlim[i][j]= newm[i][j]/(1-sumnew);
 2507: 	max[j]=FMAX(max[j],prlim[i][j]);
 2508: 	min[j]=FMIN(min[j],prlim[i][j]);
 2509:       }
 2510:     }
 2511: 
 2512:     maxmax=0.;
 2513:     for(j=1; j<=nlstate; j++){
 2514:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
 2515:       maxmax=FMAX(maxmax,meandiff[j]);
 2516:       /* 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); */
 2517:     } /* j loop */
 2518:     *ncvyear= (int)age- (int)agefin;
 2519:     /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
 2520:     if(maxmax < ftolpl){
 2521:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
 2522:       free_vector(min,1,nlstate);
 2523:       free_vector(max,1,nlstate);
 2524:       free_vector(meandiff,1,nlstate);
 2525:       return prlim;
 2526:     }
 2527:   } /* age loop */
 2528:     /* After some age loop it doesn't converge */
 2529:   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\
 2530: 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);
 2531:   /* 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); */
 2532:   free_vector(min,1,nlstate);
 2533:   free_vector(max,1,nlstate);
 2534:   free_vector(meandiff,1,nlstate);
 2535:   
 2536:   return prlim; /* should not reach here */
 2537: }
 2538: 
 2539: 
 2540:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
 2541: 
 2542:  /* 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) */
 2543:  /* 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) */
 2544:  double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij)
 2545: {
 2546:   /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
 2547:      matrix by transitions matrix until convergence is reached with precision ftolpl */
 2548:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
 2549:   /* Wx is row vector: population in state 1, population in state 2, population dead */
 2550:   /* or prevalence in state 1, prevalence in state 2, 0 */
 2551:   /* newm is the matrix after multiplications, its rows are identical at a factor */
 2552:   /* Initial matrix pimij */
 2553:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
 2554:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
 2555:   /*  0,                   0                  , 1} */
 2556:   /*
 2557:    * and after some iteration: */
 2558:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
 2559:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
 2560:   /*  0,                   0                  , 1} */
 2561:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
 2562:   /* {0.51571254859325999, 0.4842874514067399, */
 2563:   /*  0.51326036147820708, 0.48673963852179264} */
 2564:   /* If we start from prlim again, prlim tends to a constant matrix */
 2565: 
 2566:   int i, ii,j,k;
 2567:   double *min, *max, *meandiff, maxmax,sumnew=0.;
 2568:   /* double **matprod2(); */ /* test */
 2569:   double **out, cov[NCOVMAX+1], **bmij();
 2570:   double **newm;
 2571:   double	 **dnewm, **doldm, **dsavm;  /* for use */
 2572:   double	 **oldm, **savm;  /* for use */
 2573: 
 2574:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
 2575:   int ncvloop=0;
 2576:   
 2577:   min=vector(1,nlstate);
 2578:   max=vector(1,nlstate);
 2579:   meandiff=vector(1,nlstate);
 2580: 
 2581: 	dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
 2582: 	oldm=oldms; savm=savms;
 2583: 
 2584: 	/* Starting with matrix unity */
 2585: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2586: 		for (j=1;j<=nlstate+ndeath;j++){
 2587:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2588:     }
 2589:   
 2590:   cov[1]=1.;
 2591:   
 2592:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2593:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
 2594:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
 2595:   for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
 2596:     ncvloop++;
 2597:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
 2598: 		/* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
 2599:     /* Covariates have to be included here again */
 2600:     cov[2]=agefin;
 2601:     if(nagesqr==1)
 2602:       cov[3]= agefin*agefin;;
 2603:     for (k=1; k<=cptcovn;k++) {
 2604:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 2605:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 2606:       /* 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])]); */
 2607:     }
 2608:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
 2609:     for (k=1; k<=cptcovprod;k++) /* Useless */
 2610:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 2611:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
 2612:     
 2613:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 2614:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 2615:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 2616:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2617:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 2618: 		/* ij should be linked to the correct index of cov */
 2619: 		/* age and covariate values ij are in 'cov', but we need to pass
 2620: 		 * ij for the observed prevalence at age and status and covariate
 2621: 		 * number:  prevacurrent[(int)agefin][ii][ij]
 2622: 		 */
 2623:     /* 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 *\/ */
 2624:     /* 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 *\/ */
 2625:     out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij)); /* Bug Valgrind */
 2626:     savm=oldm;
 2627:     oldm=newm;
 2628:     for(j=1; j<=nlstate; j++){
 2629:       max[j]=0.;
 2630:       min[j]=1.;
 2631:     }
 2632:     for(j=1; j<=nlstate; j++){ 
 2633:       for(i=1;i<=nlstate;i++){
 2634: 	/* bprlim[i][j]= newm[i][j]/(1-sumnew); */
 2635: 	bprlim[i][j]= newm[i][j];
 2636: 	max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
 2637: 	min[i]=FMIN(min[i],bprlim[i][j]);
 2638:       }
 2639:     }
 2640: 		
 2641:     maxmax=0.;
 2642:     for(i=1; i<=nlstate; i++){
 2643:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
 2644:       maxmax=FMAX(maxmax,meandiff[i]);
 2645:       /* 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); */
 2646:     } /* j loop */
 2647:     *ncvyear= -( (int)age- (int)agefin);
 2648:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
 2649:     if(maxmax < ftolpl){
 2650:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
 2651:       free_vector(min,1,nlstate);
 2652:       free_vector(max,1,nlstate);
 2653:       free_vector(meandiff,1,nlstate);
 2654:       return bprlim;
 2655:     }
 2656:   } /* age loop */
 2657:     /* After some age loop it doesn't converge */
 2658:   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\
 2659: 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);
 2660:   /* 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); */
 2661:   free_vector(min,1,nlstate);
 2662:   free_vector(max,1,nlstate);
 2663:   free_vector(meandiff,1,nlstate);
 2664:   
 2665:   return bprlim; /* should not reach here */
 2666: }
 2667: 
 2668: /*************** transition probabilities ***************/ 
 2669: 
 2670: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 2671: {
 2672:   /* According to parameters values stored in x and the covariate's values stored in cov,
 2673:      computes the probability to be observed in state j being in state i by appying the
 2674:      model to the ncovmodel covariates (including constant and age).
 2675:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 2676:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 2677:      ncth covariate in the global vector x is given by the formula:
 2678:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 2679:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 2680:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 2681:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 2682:      Outputs ps[i][j] the probability to be observed in j being in j according to
 2683:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 2684:   */
 2685:   double s1, lnpijopii;
 2686:   /*double t34;*/
 2687:   int i,j, nc, ii, jj;
 2688: 
 2689:   for(i=1; i<= nlstate; i++){
 2690:     for(j=1; j<i;j++){
 2691:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2692: 	/*lnpijopii += param[i][j][nc]*cov[nc];*/
 2693: 	lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 2694: 	/* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2695:       }
 2696:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2697:       /* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2698:     }
 2699:     for(j=i+1; j<=nlstate+ndeath;j++){
 2700:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2701: 	/*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 2702: 	lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 2703: 	/* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 2704:       }
 2705:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2706:     }
 2707:   }
 2708:   
 2709:   for(i=1; i<= nlstate; i++){
 2710:     s1=0;
 2711:     for(j=1; j<i; j++){
 2712:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2713:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2714:     }
 2715:     for(j=i+1; j<=nlstate+ndeath; j++){
 2716:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2717:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2718:     }
 2719:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 2720:     ps[i][i]=1./(s1+1.);
 2721:     /* Computing other pijs */
 2722:     for(j=1; j<i; j++)
 2723:       ps[i][j]= exp(ps[i][j])*ps[i][i];
 2724:     for(j=i+1; j<=nlstate+ndeath; j++)
 2725:       ps[i][j]= exp(ps[i][j])*ps[i][i];
 2726:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 2727:   } /* end i */
 2728:   
 2729:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 2730:     for(jj=1; jj<= nlstate+ndeath; jj++){
 2731:       ps[ii][jj]=0;
 2732:       ps[ii][ii]=1;
 2733:     }
 2734:   }
 2735:   
 2736:   
 2737:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 2738:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 2739:   /* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 2740:   /*   } */
 2741:   /*   printf("\n "); */
 2742:   /* } */
 2743:   /* printf("\n ");printf("%lf ",cov[2]);*/
 2744:   /*
 2745:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
 2746: 		goto end;*/
 2747:   return ps;
 2748: }
 2749: 
 2750: /*************** backward transition probabilities ***************/ 
 2751: 
 2752:  /* 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 ) */
 2753: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
 2754:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
 2755: {
 2756:   /* Computes the backward probability at age agefin and covariate ij
 2757:    * and returns in **ps as well as **bmij.
 2758:    */
 2759:   int i, ii, j,k;
 2760:   
 2761:   double **out, **pmij();
 2762:   double sumnew=0.;
 2763:   double agefin;
 2764:   
 2765:   double **dnewm, **dsavm, **doldm;
 2766:   double **bbmij;
 2767:   
 2768:   doldm=ddoldms; /* global pointers */
 2769:   dnewm=ddnewms;
 2770:   dsavm=ddsavms;
 2771:   
 2772:   agefin=cov[2];
 2773:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
 2774:      the observed prevalence (with this covariate ij) */
 2775:   dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
 2776:   /* We do have the matrix Px in savm  and we need pij */
 2777:   for (j=1;j<=nlstate+ndeath;j++){
 2778:     sumnew=0.; /* w1 p11 + w2 p21 only on live states */
 2779:     for (ii=1;ii<=nlstate;ii++){
 2780:       sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
 2781:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
 2782:     for (ii=1;ii<=nlstate+ndeath;ii++){
 2783:       if(sumnew >= 1.e-10){
 2784: 	/* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
 2785: 	/* 	doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
 2786: 	/* }else if(agefin >= agemaxpar+stepm/YEARM){ */
 2787: 	/* 	doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
 2788: 	/* }else */
 2789: 	doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
 2790:       }else{
 2791: 	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);
 2792:       }
 2793:     } /*End ii */
 2794:   } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
 2795:   /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
 2796:   bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
 2797:   /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
 2798:   /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
 2799:   /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
 2800:   /* left Product of this matrix by diag matrix of prevalences (savm) */
 2801:   for (j=1;j<=nlstate+ndeath;j++){
 2802:     for (ii=1;ii<=nlstate+ndeath;ii++){
 2803:       dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
 2804:     }
 2805:   } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
 2806:   ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
 2807:   /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
 2808:   /* end bmij */
 2809:   return ps; 
 2810: }
 2811: /*************** transition probabilities ***************/ 
 2812: 
 2813: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 2814: {
 2815:   /* According to parameters values stored in x and the covariate's values stored in cov,
 2816:      computes the probability to be observed in state j being in state i by appying the
 2817:      model to the ncovmodel covariates (including constant and age).
 2818:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 2819:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 2820:      ncth covariate in the global vector x is given by the formula:
 2821:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 2822:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 2823:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 2824:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 2825:      Outputs ps[i][j] the probability to be observed in j being in j according to
 2826:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 2827:   */
 2828:   double s1, lnpijopii;
 2829:   /*double t34;*/
 2830:   int i,j, nc, ii, jj;
 2831: 
 2832:   for(i=1; i<= nlstate; i++){
 2833:     for(j=1; j<i;j++){
 2834:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2835: 	/*lnpijopii += param[i][j][nc]*cov[nc];*/
 2836: 	lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 2837: 	/* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2838:       }
 2839:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2840:       /* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2841:     }
 2842:     for(j=i+1; j<=nlstate+ndeath;j++){
 2843:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2844: 	/*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 2845: 	lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 2846: 	/* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 2847:       }
 2848:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2849:     }
 2850:   }
 2851:   
 2852:   for(i=1; i<= nlstate; i++){
 2853:     s1=0;
 2854:     for(j=1; j<i; j++){
 2855:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2856:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2857:     }
 2858:     for(j=i+1; j<=nlstate+ndeath; j++){
 2859:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2860:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2861:     }
 2862:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 2863:     ps[i][i]=1./(s1+1.);
 2864:     /* Computing other pijs */
 2865:     for(j=1; j<i; j++)
 2866:       ps[i][j]= exp(ps[i][j])*ps[i][i];
 2867:     for(j=i+1; j<=nlstate+ndeath; j++)
 2868:       ps[i][j]= exp(ps[i][j])*ps[i][i];
 2869:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 2870:   } /* end i */
 2871:   
 2872:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 2873:     for(jj=1; jj<= nlstate+ndeath; jj++){
 2874:       ps[ii][jj]=0;
 2875:       ps[ii][ii]=1;
 2876:     }
 2877:   }
 2878:   /* Added for backcast */ /* Transposed matrix too */
 2879:   for(jj=1; jj<= nlstate+ndeath; jj++){
 2880:     s1=0.;
 2881:     for(ii=1; ii<= nlstate+ndeath; ii++){
 2882:       s1+=ps[ii][jj];
 2883:     }
 2884:     for(ii=1; ii<= nlstate; ii++){
 2885:       ps[ii][jj]=ps[ii][jj]/s1;
 2886:     }
 2887:   }
 2888:   /* Transposition */
 2889:   for(jj=1; jj<= nlstate+ndeath; jj++){
 2890:     for(ii=jj; ii<= nlstate+ndeath; ii++){
 2891:       s1=ps[ii][jj];
 2892:       ps[ii][jj]=ps[jj][ii];
 2893:       ps[jj][ii]=s1;
 2894:     }
 2895:   }
 2896:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 2897:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 2898:   /* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 2899:   /*   } */
 2900:   /*   printf("\n "); */
 2901:   /* } */
 2902:   /* printf("\n ");printf("%lf ",cov[2]);*/
 2903:   /*
 2904:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
 2905:     goto end;*/
 2906:   return ps;
 2907: }
 2908: 
 2909: 
 2910: /**************** Product of 2 matrices ******************/
 2911: 
 2912: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
 2913: {
 2914:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
 2915:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
 2916:   /* in, b, out are matrice of pointers which should have been initialized 
 2917:      before: only the contents of out is modified. The function returns
 2918:      a pointer to pointers identical to out */
 2919:   int i, j, k;
 2920:   for(i=nrl; i<= nrh; i++)
 2921:     for(k=ncolol; k<=ncoloh; k++){
 2922:       out[i][k]=0.;
 2923:       for(j=ncl; j<=nch; j++)
 2924:   	out[i][k] +=in[i][j]*b[j][k];
 2925:     }
 2926:   return out;
 2927: }
 2928: 
 2929: 
 2930: /************* Higher Matrix Product ***************/
 2931: 
 2932: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij, int nres )
 2933: {
 2934:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
 2935:      'nhstepm*hstepm*stepm' months (i.e. until
 2936:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
 2937:      nhstepm*hstepm matrices. 
 2938:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
 2939:      (typically every 2 years instead of every month which is too big 
 2940:      for the memory).
 2941:      Model is determined by parameters x and covariates have to be 
 2942:      included manually here. 
 2943: 
 2944:      */
 2945: 
 2946:   int i, j, d, h, k;
 2947:   double **out, cov[NCOVMAX+1];
 2948:   double **newm;
 2949:   double agexact;
 2950:   double agebegin, ageend;
 2951: 
 2952:   /* Hstepm could be zero and should return the unit matrix */
 2953:   for (i=1;i<=nlstate+ndeath;i++)
 2954:     for (j=1;j<=nlstate+ndeath;j++){
 2955:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 2956:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 2957:     }
 2958:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2959:   for(h=1; h <=nhstepm; h++){
 2960:     for(d=1; d <=hstepm; d++){
 2961:       newm=savm;
 2962:       /* Covariates have to be included here again */
 2963:       cov[1]=1.;
 2964:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
 2965:       cov[2]=agexact;
 2966:       if(nagesqr==1)
 2967: 	cov[3]= agexact*agexact;
 2968:       for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
 2969:  			/* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
 2970: 	cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
 2971: 	/* printf("hpxij Dummy combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov=%lf codtabm(%d,Tvar[%d])=%d \n",ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,k)],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,k)); */
 2972:       }
 2973:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
 2974: 	/* Here comes the value of quantitative after renumbering k with single quantitative covariates */
 2975: 	cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
 2976: 	/* printf("hPxij Quantitative k=%d  TvarsQind[%d]=%d, TvarsQ[%d]=V%d,Tqresult[%d][%d]=%f\n",k,k,TvarsQind[k],k,TvarsQ[k],nres,k,Tqresult[nres][k]); */
 2977:       }
 2978:       for (k=1; k<=cptcovage;k++){
 2979: 	if(Dummy[Tvar[Tage[k]]]){
 2980: 	  cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 2981: 	} else{
 2982: 	  cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
 2983: 	}
 2984: 	/* printf("hPxij Age combi=%d k=%d  Tage[%d]=V%d Tqresult[%d][%d]=%f\n",ij,k,k,Tage[k],nres,k,Tqresult[nres][k]); */
 2985:       }
 2986:       for (k=1; k<=cptcovprod;k++){ /*  */
 2987: 	/* printf("hPxij Prod ij=%d k=%d  Tprod[%d]=%d Tvard[%d][1]=V%d, Tvard[%d][2]=V%d\n",ij,k,k,Tprod[k], k,Tvard[k][1], k,Tvard[k][2]); */
 2988: 	cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
 2989:       }
 2990:       /* for (k=1; k<=cptcovn;k++)  */
 2991:       /* 	cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
 2992:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
 2993:       /* 	cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
 2994:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
 2995:       /* 	cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
 2996:       
 2997:       
 2998:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 2999:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 3000: 			/* right multiplication of oldm by the current matrix */
 3001:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
 3002: 		   pmij(pmmij,cov,ncovmodel,x,nlstate));
 3003:       /* if((int)age == 70){ */
 3004:       /* 	printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
 3005:       /* 	for(i=1; i<=nlstate+ndeath; i++) { */
 3006:       /* 	  printf("%d pmmij ",i); */
 3007:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 3008:       /* 	    printf("%f ",pmmij[i][j]); */
 3009:       /* 	  } */
 3010:       /* 	  printf(" oldm "); */
 3011:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 3012:       /* 	    printf("%f ",oldm[i][j]); */
 3013:       /* 	  } */
 3014:       /* 	  printf("\n"); */
 3015:       /* 	} */
 3016:       /* } */
 3017:       savm=oldm;
 3018:       oldm=newm;
 3019:     }
 3020:     for(i=1; i<=nlstate+ndeath; i++)
 3021:       for(j=1;j<=nlstate+ndeath;j++) {
 3022: 				po[i][j][h]=newm[i][j];
 3023: 				/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 3024:       }
 3025:     /*printf("h=%d ",h);*/
 3026:   } /* end h */
 3027: 	/*     printf("\n H=%d \n",h); */
 3028:   return po;
 3029: }
 3030: 
 3031: /************* Higher Back Matrix Product ***************/
 3032: /* 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 ) */
 3033: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
 3034: {
 3035:   /* Computes the transition matrix starting at age 'age' over
 3036:      'nhstepm*hstepm*stepm' months (i.e. until
 3037:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
 3038:      nhstepm*hstepm matrices.
 3039:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
 3040:      (typically every 2 years instead of every month which is too big
 3041:      for the memory).
 3042:      Model is determined by parameters x and covariates have to be
 3043:      included manually here.
 3044: 
 3045:   */
 3046: 
 3047:   int i, j, d, h, k;
 3048:   double **out, cov[NCOVMAX+1];
 3049:   double **newm;
 3050:   double agexact;
 3051:   double agebegin, ageend;
 3052:   double **oldm, **savm;
 3053: 
 3054:   oldm=oldms;savm=savms;
 3055:   /* Hstepm could be zero and should return the unit matrix */
 3056:   for (i=1;i<=nlstate+ndeath;i++)
 3057:     for (j=1;j<=nlstate+ndeath;j++){
 3058:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 3059:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 3060:     }
 3061:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 3062:   for(h=1; h <=nhstepm; h++){
 3063:     for(d=1; d <=hstepm; d++){
 3064:       newm=savm;
 3065:       /* Covariates have to be included here again */
 3066:       cov[1]=1.;
 3067:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
 3068:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
 3069:       cov[2]=agexact;
 3070:       if(nagesqr==1)
 3071: 	cov[3]= agexact*agexact;
 3072:       for (k=1; k<=cptcovn;k++)
 3073: 	cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 3074:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 3075:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
 3076: 	/* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 3077: 	cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 3078:       /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
 3079:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
 3080: 	cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
 3081:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 3082: 			
 3083: 			
 3084:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 3085:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 3086:       /* Careful transposed matrix */
 3087:       /* age is in cov[2] */
 3088:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
 3089:       /* 						 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
 3090:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
 3091: 		   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
 3092:       /* if((int)age == 70){ */
 3093:       /* 	printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
 3094:       /* 	for(i=1; i<=nlstate+ndeath; i++) { */
 3095:       /* 	  printf("%d pmmij ",i); */
 3096:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 3097:       /* 	    printf("%f ",pmmij[i][j]); */
 3098:       /* 	  } */
 3099:       /* 	  printf(" oldm "); */
 3100:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 3101:       /* 	    printf("%f ",oldm[i][j]); */
 3102:       /* 	  } */
 3103:       /* 	  printf("\n"); */
 3104:       /* 	} */
 3105:       /* } */
 3106:       savm=oldm;
 3107:       oldm=newm;
 3108:     }
 3109:     for(i=1; i<=nlstate+ndeath; i++)
 3110:       for(j=1;j<=nlstate+ndeath;j++) {
 3111: 	po[i][j][h]=newm[i][j];
 3112: 	/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 3113:       }
 3114:     /*printf("h=%d ",h);*/
 3115:   } /* end h */
 3116:   /*     printf("\n H=%d \n",h); */
 3117:   return po;
 3118: }
 3119: 
 3120: 
 3121: #ifdef NLOPT
 3122:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
 3123:   double fret;
 3124:   double *xt;
 3125:   int j;
 3126:   myfunc_data *d2 = (myfunc_data *) pd;
 3127: /* xt = (p1-1); */
 3128:   xt=vector(1,n); 
 3129:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
 3130: 
 3131:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
 3132:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
 3133:   printf("Function = %.12lf ",fret);
 3134:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
 3135:   printf("\n");
 3136:  free_vector(xt,1,n);
 3137:   return fret;
 3138: }
 3139: #endif
 3140: 
 3141: /*************** log-likelihood *************/
 3142: double func( double *x)
 3143: {
 3144:   int i, ii, j, k, mi, d, kk;
 3145:   int ioffset=0;
 3146:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 3147:   double **out;
 3148:   double lli; /* Individual log likelihood */
 3149:   int s1, s2;
 3150:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
 3151:   double bbh, survp;
 3152:   long ipmx;
 3153:   double agexact;
 3154:   /*extern weight */
 3155:   /* We are differentiating ll according to initial status */
 3156:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 3157:   /*for(i=1;i<imx;i++) 
 3158:     printf(" %d\n",s[4][i]);
 3159:   */
 3160: 
 3161:   ++countcallfunc;
 3162: 
 3163:   cov[1]=1.;
 3164: 
 3165:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 3166:   ioffset=0;
 3167:   if(mle==1){
 3168:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3169:       /* Computes the values of the ncovmodel covariates of the model
 3170: 	 depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
 3171: 	 Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
 3172: 	 to be observed in j being in i according to the model.
 3173:       */
 3174:       ioffset=2+nagesqr+cptcovage;
 3175:    /* Fixed */
 3176:       for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
 3177: 	cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (k=6)*/
 3178:       }
 3179:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
 3180: 	 is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
 3181: 	 has been calculated etc */
 3182:       /* For an individual i, wav[i] gives the number of effective waves */
 3183:       /* We compute the contribution to Likelihood of each effective transition
 3184: 	 mw[mi][i] is real wave of the mi th effectve wave */
 3185:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
 3186: 	 s2=s[mw[mi+1][i]][i];
 3187: 	 And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
 3188: 	 But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
 3189: 	 meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
 3190:       */
 3191:       for(mi=1; mi<= wav[i]-1; mi++){
 3192: 	for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
 3193: 	  cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i];
 3194: 	}
 3195: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 3196: 	  for (j=1;j<=nlstate+ndeath;j++){
 3197: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3198: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3199: 	  }
 3200: 	for(d=0; d<dh[mi][i]; d++){
 3201: 	  newm=savm;
 3202: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3203: 	  cov[2]=agexact;
 3204: 	  if(nagesqr==1)
 3205: 	    cov[3]= agexact*agexact;  /* Should be changed here */
 3206: 	  for (kk=1; kk<=cptcovage;kk++) {
 3207: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
 3208: 	  }
 3209: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3210: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3211: 	  savm=oldm;
 3212: 	  oldm=newm;
 3213: 	} /* end mult */
 3214: 	
 3215: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 3216: 	/* But now since version 0.9 we anticipate for bias at large stepm.
 3217: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 3218: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
 3219: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
 3220: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 3221: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
 3222: 	 * probability in order to take into account the bias as a fraction of the way
 3223: 				 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
 3224: 				 * -stepm/2 to stepm/2 .
 3225: 				 * For stepm=1 the results are the same as for previous versions of Imach.
 3226: 				 * For stepm > 1 the results are less biased than in previous versions. 
 3227: 				 */
 3228: 	s1=s[mw[mi][i]][i];
 3229: 	s2=s[mw[mi+1][i]][i];
 3230: 	bbh=(double)bh[mi][i]/(double)stepm; 
 3231: 	/* bias bh is positive if real duration
 3232: 	 * is higher than the multiple of stepm and negative otherwise.
 3233: 	 */
 3234: 	/* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
 3235: 	if( s2 > nlstate){ 
 3236: 	  /* i.e. if s2 is a death state and if the date of death is known 
 3237: 	     then the contribution to the likelihood is the probability to 
 3238: 	     die between last step unit time and current  step unit time, 
 3239: 	     which is also equal to probability to die before dh 
 3240: 	     minus probability to die before dh-stepm . 
 3241: 	     In version up to 0.92 likelihood was computed
 3242: 	     as if date of death was unknown. Death was treated as any other
 3243: 	     health state: the date of the interview describes the actual state
 3244: 	     and not the date of a change in health state. The former idea was
 3245: 	     to consider that at each interview the state was recorded
 3246: 	     (healthy, disable or death) and IMaCh was corrected; but when we
 3247: 	     introduced the exact date of death then we should have modified
 3248: 	     the contribution of an exact death to the likelihood. This new
 3249: 	     contribution is smaller and very dependent of the step unit
 3250: 	     stepm. It is no more the probability to die between last interview
 3251: 	     and month of death but the probability to survive from last
 3252: 	     interview up to one month before death multiplied by the
 3253: 	     probability to die within a month. Thanks to Chris
 3254: 	     Jackson for correcting this bug.  Former versions increased
 3255: 	     mortality artificially. The bad side is that we add another loop
 3256: 	     which slows down the processing. The difference can be up to 10%
 3257: 	     lower mortality.
 3258: 	  */
 3259: 	  /* If, at the beginning of the maximization mostly, the
 3260: 	     cumulative probability or probability to be dead is
 3261: 	     constant (ie = 1) over time d, the difference is equal to
 3262: 	     0.  out[s1][3] = savm[s1][3]: probability, being at state
 3263: 	     s1 at precedent wave, to be dead a month before current
 3264: 	     wave is equal to probability, being at state s1 at
 3265: 	     precedent wave, to be dead at mont of the current
 3266: 	     wave. Then the observed probability (that this person died)
 3267: 	     is null according to current estimated parameter. In fact,
 3268: 	     it should be very low but not zero otherwise the log go to
 3269: 	     infinity.
 3270: 	  */
 3271: /* #ifdef INFINITYORIGINAL */
 3272: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 3273: /* #else */
 3274: /* 	  if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
 3275: /* 	    lli=log(mytinydouble); */
 3276: /* 	  else */
 3277: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 3278: /* #endif */
 3279: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 3280: 	  
 3281: 	} else if  ( s2==-1 ) { /* alive */
 3282: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 3283: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 3284: 	  /*survp += out[s1][j]; */
 3285: 	  lli= log(survp);
 3286: 	}
 3287: 	else if  (s2==-4) { 
 3288: 	  for (j=3,survp=0. ; j<=nlstate; j++)  
 3289: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 3290: 	  lli= log(survp); 
 3291: 	} 
 3292: 	else if  (s2==-5) { 
 3293: 	  for (j=1,survp=0. ; j<=2; j++)  
 3294: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 3295: 	  lli= log(survp); 
 3296: 	} 
 3297: 	else{
 3298: 	  lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 3299: 	  /*  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 */
 3300: 	} 
 3301: 	/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 3302: 	/*if(lli ==000.0)*/
 3303: 	/*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); */
 3304: 	ipmx +=1;
 3305: 	sw += weight[i];
 3306: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3307: 	/* if (lli < log(mytinydouble)){ */
 3308: 	/*   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); */
 3309: 	/*   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]); */
 3310: 	/* } */
 3311:       } /* end of wave */
 3312:     } /* end of individual */
 3313:   }  else if(mle==2){
 3314:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3315:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 3316:       for(mi=1; mi<= wav[i]-1; mi++){
 3317: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 3318: 	  for (j=1;j<=nlstate+ndeath;j++){
 3319: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3320: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3321: 	  }
 3322: 	for(d=0; d<=dh[mi][i]; d++){
 3323: 	  newm=savm;
 3324: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3325: 	  cov[2]=agexact;
 3326: 	  if(nagesqr==1)
 3327: 	    cov[3]= agexact*agexact;
 3328: 	  for (kk=1; kk<=cptcovage;kk++) {
 3329: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3330: 	  }
 3331: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3332: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3333: 	  savm=oldm;
 3334: 	  oldm=newm;
 3335: 	} /* end mult */
 3336:       
 3337: 	s1=s[mw[mi][i]][i];
 3338: 	s2=s[mw[mi+1][i]][i];
 3339: 	bbh=(double)bh[mi][i]/(double)stepm; 
 3340: 	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 */
 3341: 	ipmx +=1;
 3342: 	sw += weight[i];
 3343: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3344:       } /* end of wave */
 3345:     } /* end of individual */
 3346:   }  else if(mle==3){  /* exponential inter-extrapolation */
 3347:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3348:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 3349:       for(mi=1; mi<= wav[i]-1; mi++){
 3350: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 3351: 	  for (j=1;j<=nlstate+ndeath;j++){
 3352: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3353: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3354: 	  }
 3355: 	for(d=0; d<dh[mi][i]; d++){
 3356: 	  newm=savm;
 3357: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3358: 	  cov[2]=agexact;
 3359: 	  if(nagesqr==1)
 3360: 	    cov[3]= agexact*agexact;
 3361: 	  for (kk=1; kk<=cptcovage;kk++) {
 3362: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3363: 	  }
 3364: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3365: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3366: 	  savm=oldm;
 3367: 	  oldm=newm;
 3368: 	} /* end mult */
 3369:       
 3370: 	s1=s[mw[mi][i]][i];
 3371: 	s2=s[mw[mi+1][i]][i];
 3372: 	bbh=(double)bh[mi][i]/(double)stepm; 
 3373: 	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 */
 3374: 	ipmx +=1;
 3375: 	sw += weight[i];
 3376: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3377:       } /* end of wave */
 3378:     } /* end of individual */
 3379:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
 3380:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3381:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 3382:       for(mi=1; mi<= wav[i]-1; mi++){
 3383: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 3384: 	  for (j=1;j<=nlstate+ndeath;j++){
 3385: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3386: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3387: 	  }
 3388: 	for(d=0; d<dh[mi][i]; d++){
 3389: 	  newm=savm;
 3390: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3391: 	  cov[2]=agexact;
 3392: 	  if(nagesqr==1)
 3393: 	    cov[3]= agexact*agexact;
 3394: 	  for (kk=1; kk<=cptcovage;kk++) {
 3395: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3396: 	  }
 3397: 	
 3398: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3399: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3400: 	  savm=oldm;
 3401: 	  oldm=newm;
 3402: 	} /* end mult */
 3403:       
 3404: 	s1=s[mw[mi][i]][i];
 3405: 	s2=s[mw[mi+1][i]][i];
 3406: 	if( s2 > nlstate){ 
 3407: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 3408: 	} else if  ( s2==-1 ) { /* alive */
 3409: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 3410: 	    survp += out[s1][j];
 3411: 	  lli= log(survp);
 3412: 	}else{
 3413: 	  lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 3414: 	}
 3415: 	ipmx +=1;
 3416: 	sw += weight[i];
 3417: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3418: /* 	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]); */
 3419:       } /* end of wave */
 3420:     } /* end of individual */
 3421:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
 3422:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3423:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 3424:       for(mi=1; mi<= wav[i]-1; mi++){
 3425: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 3426: 	  for (j=1;j<=nlstate+ndeath;j++){
 3427: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3428: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3429: 	  }
 3430: 	for(d=0; d<dh[mi][i]; d++){
 3431: 	  newm=savm;
 3432: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3433: 	  cov[2]=agexact;
 3434: 	  if(nagesqr==1)
 3435: 	    cov[3]= agexact*agexact;
 3436: 	  for (kk=1; kk<=cptcovage;kk++) {
 3437: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3438: 	  }
 3439: 	
 3440: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3441: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3442: 	  savm=oldm;
 3443: 	  oldm=newm;
 3444: 	} /* end mult */
 3445:       
 3446: 	s1=s[mw[mi][i]][i];
 3447: 	s2=s[mw[mi+1][i]][i];
 3448: 	lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 3449: 	ipmx +=1;
 3450: 	sw += weight[i];
 3451: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3452: 	/*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]);*/
 3453:       } /* end of wave */
 3454:     } /* end of individual */
 3455:   } /* End of if */
 3456:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 3457:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 3458:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 3459:   return -l;
 3460: }
 3461: 
 3462: /*************** log-likelihood *************/
 3463: double funcone( double *x)
 3464: {
 3465:   /* Same as func but slower because of a lot of printf and if */
 3466:   int i, ii, j, k, mi, d, kk;
 3467:   int ioffset=0;
 3468:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 3469:   double **out;
 3470:   double lli; /* Individual log likelihood */
 3471:   double llt;
 3472:   int s1, s2;
 3473:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
 3474: 
 3475:   double bbh, survp;
 3476:   double agexact;
 3477:   double agebegin, ageend;
 3478:   /*extern weight */
 3479:   /* We are differentiating ll according to initial status */
 3480:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 3481:   /*for(i=1;i<imx;i++) 
 3482:     printf(" %d\n",s[4][i]);
 3483:   */
 3484:   cov[1]=1.;
 3485: 
 3486:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 3487:   ioffset=0;
 3488:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3489:     ioffset=2+nagesqr+cptcovage;
 3490:     /* Fixed */
 3491:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
 3492:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
 3493:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
 3494:       cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (k=6)*/
 3495: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
 3496: /*    cov[2+6]=covar[Tvar[6]][i];  */
 3497: /*    cov[2+6]=covar[2][i]; V2  */
 3498: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
 3499: /*    cov[2+7]=covar[Tvar[7]][i];  */
 3500: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
 3501: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
 3502: /*    cov[2+9]=covar[Tvar[9]][i];  */
 3503: /*    cov[2+9]=covar[1][i]; V1  */
 3504:     }
 3505:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
 3506:     /*   cov[++ioffset]=coqvar[TvarFQ[k]][i];/\* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V2 and V1*V2 is fixed (k=6 and 7?)*\/ */
 3507:     /* } */
 3508:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
 3509:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
 3510:     /* } */
 3511:     
 3512: 
 3513:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
 3514:     /* Wave varying (but not age varying) */
 3515:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
 3516: 				cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i];
 3517: 			}
 3518:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
 3519: 				/* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
 3520: 				/* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
 3521: 				/* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
 3522: 				/* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
 3523: 				/* printf(" i=%d,mi=%d,itv=%d,TmodelInvind[itv]=%d,cotvar[mw[mi][i]][TmodelInvind[itv]][i]=%f\n", i, mi, itv, TmodelInvind[itv],cotvar[mw[mi][i]][TmodelInvind[itv]][i]); */
 3524:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
 3525: 			/* 	iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
 3526: 			/* 	/\* printf(" i=%d,mi=%d,iqtv=%d,TmodelInvQind[iqtv]=%d,cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]=%f\n", i, mi, iqtv, TmodelInvQind[iqtv],cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]); *\/ */
 3527: 			/* 	cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
 3528:       /* } */
 3529:       for (ii=1;ii<=nlstate+ndeath;ii++)
 3530: 				for (j=1;j<=nlstate+ndeath;j++){
 3531: 					oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3532: 					savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3533: 				}
 3534:       
 3535:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
 3536:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
 3537:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
 3538: 				/*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 3539: 					and mw[mi+1][i]. dh depends on stepm.*/
 3540: 				newm=savm;
 3541: 				agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3542: 				cov[2]=agexact;
 3543: 				if(nagesqr==1)
 3544: 					cov[3]= agexact*agexact;
 3545: 				for (kk=1; kk<=cptcovage;kk++) {
 3546: 					cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3547: 				}
 3548: 				/* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
 3549: 				/* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 3550: 				out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3551: 										 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3552: 				/* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
 3553: 				/* 	     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
 3554: 				savm=oldm;
 3555: 				oldm=newm;
 3556:       } /* end mult */
 3557:       
 3558:       s1=s[mw[mi][i]][i];
 3559:       s2=s[mw[mi+1][i]][i];
 3560:       /* if(s2==-1){ */
 3561:       /* 	printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
 3562:       /* 	/\* exit(1); *\/ */
 3563:       /* } */
 3564:       bbh=(double)bh[mi][i]/(double)stepm; 
 3565:       /* bias is positive if real duration
 3566:        * is higher than the multiple of stepm and negative otherwise.
 3567:        */
 3568:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
 3569: 				lli=log(out[s1][s2] - savm[s1][s2]);
 3570:       } else if  ( s2==-1 ) { /* alive */
 3571: 				for (j=1,survp=0. ; j<=nlstate; j++) 
 3572: 					survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 3573: 				lli= log(survp);
 3574:       }else if (mle==1){
 3575: 				lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 3576:       } else if(mle==2){
 3577: 				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 */
 3578:       } else if(mle==3){  /* exponential inter-extrapolation */
 3579: 				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 */
 3580:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
 3581: 				lli=log(out[s1][s2]); /* Original formula */
 3582:       } else{  /* mle=0 back to 1 */
 3583: 				lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 3584: 				/*lli=log(out[s1][s2]); */ /* Original formula */
 3585:       } /* End of if */
 3586:       ipmx +=1;
 3587:       sw += weight[i];
 3588:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3589:       /*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]); */
 3590:       if(globpr){
 3591: 				fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
 3592:  %11.6f %11.6f %11.6f ", \
 3593: 								num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
 3594: 								2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
 3595: 				for(k=1,llt=0.,l=0.; k<=nlstate; k++){
 3596: 					llt +=ll[k]*gipmx/gsw;
 3597: 					fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
 3598: 				}
 3599: 				fprintf(ficresilk," %10.6f\n", -llt);
 3600:       }
 3601: 	} /* end of wave */
 3602: } /* end of individual */
 3603: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 3604: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 3605: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 3606: if(globpr==0){ /* First time we count the contributions and weights */
 3607: 	gipmx=ipmx;
 3608: 	gsw=sw;
 3609: }
 3610: return -l;
 3611: }
 3612: 
 3613: 
 3614: /*************** function likelione ***********/
 3615: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
 3616: {
 3617:   /* This routine should help understanding what is done with 
 3618:      the selection of individuals/waves and
 3619:      to check the exact contribution to the likelihood.
 3620:      Plotting could be done.
 3621:    */
 3622:   int k;
 3623: 
 3624:   if(*globpri !=0){ /* Just counts and sums, no printings */
 3625:     strcpy(fileresilk,"ILK_"); 
 3626:     strcat(fileresilk,fileresu);
 3627:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
 3628:       printf("Problem with resultfile: %s\n", fileresilk);
 3629:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
 3630:     }
 3631:     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");
 3632:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
 3633:     /* 	i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
 3634:     for(k=1; k<=nlstate; k++) 
 3635:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
 3636:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
 3637:   }
 3638: 
 3639:   *fretone=(*funcone)(p);
 3640:   if(*globpri !=0){
 3641:     fclose(ficresilk);
 3642:     if (mle ==0)
 3643:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
 3644:     else if(mle >=1)
 3645:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
 3646:     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));
 3647:     
 3648:       
 3649:     for (k=1; k<= nlstate ; k++) {
 3650:       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> \
 3651: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
 3652:     }
 3653:     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> \
 3654: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
 3655:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
 3656: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
 3657:     fflush(fichtm);
 3658:   }
 3659:   return;
 3660: }
 3661: 
 3662: 
 3663: /*********** Maximum Likelihood Estimation ***************/
 3664: 
 3665: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
 3666: {
 3667:   int i,j, iter=0;
 3668:   double **xi;
 3669:   double fret;
 3670:   double fretone; /* Only one call to likelihood */
 3671:   /*  char filerespow[FILENAMELENGTH];*/
 3672: 
 3673: #ifdef NLOPT
 3674:   int creturn;
 3675:   nlopt_opt opt;
 3676:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
 3677:   double *lb;
 3678:   double minf; /* the minimum objective value, upon return */
 3679:   double * p1; /* Shifted parameters from 0 instead of 1 */
 3680:   myfunc_data dinst, *d = &dinst;
 3681: #endif
 3682: 
 3683: 
 3684:   xi=matrix(1,npar,1,npar);
 3685:   for (i=1;i<=npar;i++)
 3686:     for (j=1;j<=npar;j++)
 3687:       xi[i][j]=(i==j ? 1.0 : 0.0);
 3688:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
 3689:   strcpy(filerespow,"POW_"); 
 3690:   strcat(filerespow,fileres);
 3691:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
 3692:     printf("Problem with resultfile: %s\n", filerespow);
 3693:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 3694:   }
 3695:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
 3696:   for (i=1;i<=nlstate;i++)
 3697:     for(j=1;j<=nlstate+ndeath;j++)
 3698:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 3699:   fprintf(ficrespow,"\n");
 3700: #ifdef POWELL
 3701:   powell(p,xi,npar,ftol,&iter,&fret,func);
 3702: #endif
 3703: 
 3704: #ifdef NLOPT
 3705: #ifdef NEWUOA
 3706:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
 3707: #else
 3708:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
 3709: #endif
 3710:   lb=vector(0,npar-1);
 3711:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
 3712:   nlopt_set_lower_bounds(opt, lb);
 3713:   nlopt_set_initial_step1(opt, 0.1);
 3714:   
 3715:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
 3716:   d->function = func;
 3717:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
 3718:   nlopt_set_min_objective(opt, myfunc, d);
 3719:   nlopt_set_xtol_rel(opt, ftol);
 3720:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
 3721:     printf("nlopt failed! %d\n",creturn); 
 3722:   }
 3723:   else {
 3724:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
 3725:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
 3726:     iter=1; /* not equal */
 3727:   }
 3728:   nlopt_destroy(opt);
 3729: #endif
 3730:   free_matrix(xi,1,npar,1,npar);
 3731:   fclose(ficrespow);
 3732:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 3733:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 3734:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 3735: 
 3736: }
 3737: 
 3738: /**** Computes Hessian and covariance matrix ***/
 3739: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
 3740: {
 3741:   double  **a,**y,*x,pd;
 3742:   /* double **hess; */
 3743:   int i, j;
 3744:   int *indx;
 3745: 
 3746:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
 3747:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
 3748:   void lubksb(double **a, int npar, int *indx, double b[]) ;
 3749:   void ludcmp(double **a, int npar, int *indx, double *d) ;
 3750:   double gompertz(double p[]);
 3751:   /* hess=matrix(1,npar,1,npar); */
 3752: 
 3753:   printf("\nCalculation of the hessian matrix. Wait...\n");
 3754:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
 3755:   for (i=1;i<=npar;i++){
 3756:     printf("%d-",i);fflush(stdout);
 3757:     fprintf(ficlog,"%d-",i);fflush(ficlog);
 3758:    
 3759:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
 3760:     
 3761:     /*  printf(" %f ",p[i]);
 3762: 	printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
 3763:   }
 3764:   
 3765:   for (i=1;i<=npar;i++) {
 3766:     for (j=1;j<=npar;j++)  {
 3767:       if (j>i) { 
 3768: 	printf(".%d-%d",i,j);fflush(stdout);
 3769: 	fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
 3770: 	hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
 3771: 	
 3772: 	hess[j][i]=hess[i][j];    
 3773: 	/*printf(" %lf ",hess[i][j]);*/
 3774:       }
 3775:     }
 3776:   }
 3777:   printf("\n");
 3778:   fprintf(ficlog,"\n");
 3779: 
 3780:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
 3781:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
 3782:   
 3783:   a=matrix(1,npar,1,npar);
 3784:   y=matrix(1,npar,1,npar);
 3785:   x=vector(1,npar);
 3786:   indx=ivector(1,npar);
 3787:   for (i=1;i<=npar;i++)
 3788:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
 3789:   ludcmp(a,npar,indx,&pd);
 3790: 
 3791:   for (j=1;j<=npar;j++) {
 3792:     for (i=1;i<=npar;i++) x[i]=0;
 3793:     x[j]=1;
 3794:     lubksb(a,npar,indx,x);
 3795:     for (i=1;i<=npar;i++){ 
 3796:       matcov[i][j]=x[i];
 3797:     }
 3798:   }
 3799: 
 3800:   printf("\n#Hessian matrix#\n");
 3801:   fprintf(ficlog,"\n#Hessian matrix#\n");
 3802:   for (i=1;i<=npar;i++) { 
 3803:     for (j=1;j<=npar;j++) { 
 3804:       printf("%.6e ",hess[i][j]);
 3805:       fprintf(ficlog,"%.6e ",hess[i][j]);
 3806:     }
 3807:     printf("\n");
 3808:     fprintf(ficlog,"\n");
 3809:   }
 3810: 
 3811:   /* printf("\n#Covariance matrix#\n"); */
 3812:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
 3813:   /* for (i=1;i<=npar;i++) {  */
 3814:   /*   for (j=1;j<=npar;j++) {  */
 3815:   /*     printf("%.6e ",matcov[i][j]); */
 3816:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
 3817:   /*   } */
 3818:   /*   printf("\n"); */
 3819:   /*   fprintf(ficlog,"\n"); */
 3820:   /* } */
 3821: 
 3822:   /* Recompute Inverse */
 3823:   /* for (i=1;i<=npar;i++) */
 3824:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
 3825:   /* ludcmp(a,npar,indx,&pd); */
 3826: 
 3827:   /*  printf("\n#Hessian matrix recomputed#\n"); */
 3828: 
 3829:   /* for (j=1;j<=npar;j++) { */
 3830:   /*   for (i=1;i<=npar;i++) x[i]=0; */
 3831:   /*   x[j]=1; */
 3832:   /*   lubksb(a,npar,indx,x); */
 3833:   /*   for (i=1;i<=npar;i++){  */
 3834:   /*     y[i][j]=x[i]; */
 3835:   /*     printf("%.3e ",y[i][j]); */
 3836:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
 3837:   /*   } */
 3838:   /*   printf("\n"); */
 3839:   /*   fprintf(ficlog,"\n"); */
 3840:   /* } */
 3841: 
 3842:   /* Verifying the inverse matrix */
 3843: #ifdef DEBUGHESS
 3844:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
 3845: 
 3846:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
 3847:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
 3848: 
 3849:   for (j=1;j<=npar;j++) {
 3850:     for (i=1;i<=npar;i++){ 
 3851:       printf("%.2f ",y[i][j]);
 3852:       fprintf(ficlog,"%.2f ",y[i][j]);
 3853:     }
 3854:     printf("\n");
 3855:     fprintf(ficlog,"\n");
 3856:   }
 3857: #endif
 3858: 
 3859:   free_matrix(a,1,npar,1,npar);
 3860:   free_matrix(y,1,npar,1,npar);
 3861:   free_vector(x,1,npar);
 3862:   free_ivector(indx,1,npar);
 3863:   /* free_matrix(hess,1,npar,1,npar); */
 3864: 
 3865: 
 3866: }
 3867: 
 3868: /*************** hessian matrix ****************/
 3869: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
 3870: { /* Around values of x, computes the function func and returns the scales delti and hessian */
 3871:   int i;
 3872:   int l=1, lmax=20;
 3873:   double k1,k2, res, fx;
 3874:   double p2[MAXPARM+1]; /* identical to x */
 3875:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 3876:   int k=0,kmax=10;
 3877:   double l1;
 3878: 
 3879:   fx=func(x);
 3880:   for (i=1;i<=npar;i++) p2[i]=x[i];
 3881:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
 3882:     l1=pow(10,l);
 3883:     delts=delt;
 3884:     for(k=1 ; k <kmax; k=k+1){
 3885:       delt = delta*(l1*k);
 3886:       p2[theta]=x[theta] +delt;
 3887:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
 3888:       p2[theta]=x[theta]-delt;
 3889:       k2=func(p2)-fx;
 3890:       /*res= (k1-2.0*fx+k2)/delt/delt; */
 3891:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
 3892:       
 3893: #ifdef DEBUGHESSII
 3894:       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);
 3895:       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);
 3896: #endif
 3897:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
 3898:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 3899: 	k=kmax;
 3900:       }
 3901:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
 3902: 	k=kmax; l=lmax*10;
 3903:       }
 3904:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
 3905: 	delts=delt;
 3906:       }
 3907:     } /* End loop k */
 3908:   }
 3909:   delti[theta]=delts;
 3910:   return res; 
 3911:   
 3912: }
 3913: 
 3914: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
 3915: {
 3916:   int i;
 3917:   int l=1, lmax=20;
 3918:   double k1,k2,k3,k4,res,fx;
 3919:   double p2[MAXPARM+1];
 3920:   int k, kmax=1;
 3921:   double v1, v2, cv12, lc1, lc2;
 3922: 
 3923:   int firstime=0;
 3924:   
 3925:   fx=func(x);
 3926:   for (k=1; k<=kmax; k=k+10) {
 3927:     for (i=1;i<=npar;i++) p2[i]=x[i];
 3928:     p2[thetai]=x[thetai]+delti[thetai]*k;
 3929:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
 3930:     k1=func(p2)-fx;
 3931:   
 3932:     p2[thetai]=x[thetai]+delti[thetai]*k;
 3933:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
 3934:     k2=func(p2)-fx;
 3935:   
 3936:     p2[thetai]=x[thetai]-delti[thetai]*k;
 3937:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
 3938:     k3=func(p2)-fx;
 3939:   
 3940:     p2[thetai]=x[thetai]-delti[thetai]*k;
 3941:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
 3942:     k4=func(p2)-fx;
 3943:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
 3944:     if(k1*k2*k3*k4 <0.){
 3945:       firstime=1;
 3946:       kmax=kmax+10;
 3947:     }
 3948:     if(kmax >=10 || firstime ==1){
 3949:       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);
 3950:       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);
 3951:       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);
 3952:       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);
 3953:     }
 3954: #ifdef DEBUGHESSIJ
 3955:     v1=hess[thetai][thetai];
 3956:     v2=hess[thetaj][thetaj];
 3957:     cv12=res;
 3958:     /* Computing eigen value of Hessian matrix */
 3959:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3960:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3961:     if ((lc2 <0) || (lc1 <0) ){
 3962:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
 3963:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
 3964:       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);
 3965:       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);
 3966:     }
 3967: #endif
 3968:   }
 3969:   return res;
 3970: }
 3971: 
 3972:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
 3973: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
 3974: /* { */
 3975: /*   int i; */
 3976: /*   int l=1, lmax=20; */
 3977: /*   double k1,k2,k3,k4,res,fx; */
 3978: /*   double p2[MAXPARM+1]; */
 3979: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
 3980: /*   int k=0,kmax=10; */
 3981: /*   double l1; */
 3982:   
 3983: /*   fx=func(x); */
 3984: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
 3985: /*     l1=pow(10,l); */
 3986: /*     delts=delt; */
 3987: /*     for(k=1 ; k <kmax; k=k+1){ */
 3988: /*       delt = delti*(l1*k); */
 3989: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
 3990: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
 3991: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
 3992: /*       k1=func(p2)-fx; */
 3993:       
 3994: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
 3995: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
 3996: /*       k2=func(p2)-fx; */
 3997:       
 3998: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
 3999: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
 4000: /*       k3=func(p2)-fx; */
 4001:       
 4002: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
 4003: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
 4004: /*       k4=func(p2)-fx; */
 4005: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
 4006: /* #ifdef DEBUGHESSIJ */
 4007: /*       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); */
 4008: /*       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); */
 4009: /* #endif */
 4010: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
 4011: /* 	k=kmax; */
 4012: /*       } */
 4013: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
 4014: /* 	k=kmax; l=lmax*10; */
 4015: /*       } */
 4016: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
 4017: /* 	delts=delt; */
 4018: /*       } */
 4019: /*     } /\* End loop k *\/ */
 4020: /*   } */
 4021: /*   delti[theta]=delts; */
 4022: /*   return res;  */
 4023: /* } */
 4024: 
 4025: 
 4026: /************** Inverse of matrix **************/
 4027: void ludcmp(double **a, int n, int *indx, double *d) 
 4028: { 
 4029:   int i,imax,j,k; 
 4030:   double big,dum,sum,temp; 
 4031:   double *vv; 
 4032:  
 4033:   vv=vector(1,n); 
 4034:   *d=1.0; 
 4035:   for (i=1;i<=n;i++) { 
 4036:     big=0.0; 
 4037:     for (j=1;j<=n;j++) 
 4038:       if ((temp=fabs(a[i][j])) > big) big=temp; 
 4039:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
 4040:     vv[i]=1.0/big; 
 4041:   } 
 4042:   for (j=1;j<=n;j++) { 
 4043:     for (i=1;i<j;i++) { 
 4044:       sum=a[i][j]; 
 4045:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
 4046:       a[i][j]=sum; 
 4047:     } 
 4048:     big=0.0; 
 4049:     for (i=j;i<=n;i++) { 
 4050:       sum=a[i][j]; 
 4051:       for (k=1;k<j;k++) 
 4052: 	sum -= a[i][k]*a[k][j]; 
 4053:       a[i][j]=sum; 
 4054:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
 4055: 	big=dum; 
 4056: 	imax=i; 
 4057:       } 
 4058:     } 
 4059:     if (j != imax) { 
 4060:       for (k=1;k<=n;k++) { 
 4061: 	dum=a[imax][k]; 
 4062: 	a[imax][k]=a[j][k]; 
 4063: 	a[j][k]=dum; 
 4064:       } 
 4065:       *d = -(*d); 
 4066:       vv[imax]=vv[j]; 
 4067:     } 
 4068:     indx[j]=imax; 
 4069:     if (a[j][j] == 0.0) a[j][j]=TINY; 
 4070:     if (j != n) { 
 4071:       dum=1.0/(a[j][j]); 
 4072:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
 4073:     } 
 4074:   } 
 4075:   free_vector(vv,1,n);  /* Doesn't work */
 4076: ;
 4077: } 
 4078: 
 4079: void lubksb(double **a, int n, int *indx, double b[]) 
 4080: { 
 4081:   int i,ii=0,ip,j; 
 4082:   double sum; 
 4083:  
 4084:   for (i=1;i<=n;i++) { 
 4085:     ip=indx[i]; 
 4086:     sum=b[ip]; 
 4087:     b[ip]=b[i]; 
 4088:     if (ii) 
 4089:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
 4090:     else if (sum) ii=i; 
 4091:     b[i]=sum; 
 4092:   } 
 4093:   for (i=n;i>=1;i--) { 
 4094:     sum=b[i]; 
 4095:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
 4096:     b[i]=sum/a[i][i]; 
 4097:   } 
 4098: } 
 4099: 
 4100: void pstamp(FILE *fichier)
 4101: {
 4102:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
 4103: }
 4104: 
 4105: /************ Frequencies ********************/
 4106: void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
 4107: 		  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[],	\
 4108: 		  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
 4109: {  /* Some frequencies */
 4110:   
 4111:   int i, m, jk, j1, bool, z1,j, k, iv;
 4112:   int iind=0, iage=0;
 4113:   int mi; /* Effective wave */
 4114:   int first;
 4115:   double ***freq; /* Frequencies */
 4116:   double *meanq;
 4117:   double **meanqt;
 4118:   double *pp, **prop, *posprop, *pospropt;
 4119:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
 4120:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
 4121:   double agebegin, ageend;
 4122:     
 4123:   pp=vector(1,nlstate);
 4124:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
 4125:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
 4126:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
 4127:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
 4128:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
 4129:   meanqt=matrix(1,lastpass,1,nqtveff);
 4130:   strcpy(fileresp,"P_");
 4131:   strcat(fileresp,fileresu);
 4132:   /*strcat(fileresphtm,fileresu);*/
 4133:   if((ficresp=fopen(fileresp,"w"))==NULL) {
 4134:     printf("Problem with prevalence resultfile: %s\n", fileresp);
 4135:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
 4136:     exit(0);
 4137:   }
 4138: 
 4139:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
 4140:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
 4141:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
 4142:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
 4143:     fflush(ficlog);
 4144:     exit(70); 
 4145:   }
 4146:   else{
 4147:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 4148: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 4149: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
 4150: 	    fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 4151:   }
 4152:   fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies and prevalence by age at begin of transition and dummy covariate value at beginning of transition</h4>\n",fileresphtm, fileresphtm);
 4153:     
 4154:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
 4155:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
 4156:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
 4157:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
 4158:     fflush(ficlog);
 4159:     exit(70); 
 4160:   }
 4161:   else{
 4162:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 4163: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 4164: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
 4165: 	    fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 4166:   }
 4167:   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);
 4168: 
 4169:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
 4170:   j1=0;
 4171:   
 4172:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
 4173:   j=cptcoveff;  /* Only dummy covariates of the model */
 4174:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 4175: 
 4176:   first=1;
 4177: 
 4178:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
 4179:      reference=low_education V1=0,V2=0
 4180:      med_educ                V1=1 V2=0, 
 4181:      high_educ               V1=0 V2=1
 4182:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
 4183:   */
 4184: 
 4185:   for (j1 = 1; j1 <= (int) pow(2,j); j1++){ /* Loop on covariates combination in order of model, excluding quantitatives V4=0, V3=0 for example, fixed or varying covariates */
 4186:     posproptt=0.;
 4187:     /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
 4188:       scanf("%d", i);*/
 4189:     for (i=-5; i<=nlstate+ndeath; i++)  
 4190:       for (jk=-5; jk<=nlstate+ndeath; jk++)  
 4191: 				for(m=iagemin; m <= iagemax+3; m++)
 4192: 					freq[i][jk][m]=0;
 4193: 		
 4194:     for (i=1; i<=nlstate; i++)  {
 4195:       for(m=iagemin; m <= iagemax+3; m++)
 4196: 				prop[i][m]=0;
 4197:       posprop[i]=0;
 4198:       pospropt[i]=0;
 4199:     }
 4200:     /* for (z1=1; z1<= nqfveff; z1++) {   */
 4201:     /*   meanq[z1]+=0.; */
 4202:     /*   for(m=1;m<=lastpass;m++){ */
 4203:     /* 	meanqt[m][z1]=0.; */
 4204:     /*   } */
 4205:     /* } */
 4206: 		
 4207:     dateintsum=0;
 4208:     k2cpt=0;
 4209:     /* For that combination of covariate j1, we count and print the frequencies in one pass */
 4210:     for (iind=1; iind<=imx; iind++) { /* For each individual iind */
 4211:       bool=1;
 4212:       if(anyvaryingduminmodel==0){ /* If All fixed covariates */
 4213: 	if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
 4214: 	  /* for (z1=1; z1<= nqfveff; z1++) {   */
 4215: 	  /*   meanq[z1]+=coqvar[Tvar[z1]][iind];  /\* Computes mean of quantitative with selected filter *\/ */
 4216: 	  /* } */
 4217: 	  for (z1=1; z1<=cptcoveff; z1++) {  
 4218: 	    /* if(Tvaraff[z1] ==-20){ */
 4219: 	    /* 	 /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
 4220: 	    /* }else  if(Tvaraff[z1] ==-10){ */
 4221: 	    /* 	 /\* sumnew+=coqvar[z1][iind]; *\/ */
 4222: 	    /* }else  */
 4223: 	    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
 4224: 	      /* Tests if this individual iind responded to j1 (V4=1 V3=0) */
 4225: 	      bool=0;
 4226: 	      /* 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", 
 4227: 		 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
 4228: 		 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
 4229: 	      /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
 4230: 	    } /* Onlyf fixed */
 4231: 	  } /* end z1 */
 4232: 	} /* cptcovn > 0 */
 4233:       } /* end any */
 4234:       if (bool==1){ /* We selected an individual iind satisfying combination j1 or all fixed */
 4235: 	/* for(m=firstpass; m<=lastpass; m++){ */
 4236: 	for(mi=1; mi<wav[iind];mi++){ /* For that wave */
 4237: 	  m=mw[mi][iind];
 4238: 	  if(anyvaryingduminmodel==1){ /* Some are varying covariates */
 4239: 	    for (z1=1; z1<=cptcoveff; z1++) {
 4240: 	      if( Fixed[Tmodelind[z1]]==1){
 4241: 		iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
 4242: 		if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
 4243: 		  bool=0;
 4244: 	      }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
 4245: 		if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
 4246: 		  bool=0;
 4247: 		}
 4248: 	      }
 4249: 	    }
 4250: 	  }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
 4251: 	  /* bool =0 we keep that guy which corresponds to the combination of dummy values */
 4252: 	  if(bool==1){
 4253: 	    /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
 4254: 	       and mw[mi+1][iind]. dh depends on stepm. */
 4255: 	    agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
 4256: 	    ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
 4257: 	    if(m >=firstpass && m <=lastpass){
 4258: 	      k2=anint[m][iind]+(mint[m][iind]/12.);
 4259: 	      /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
 4260: 	      if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
 4261: 	      if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
 4262: 	      if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
 4263: 		prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
 4264: 	      if (m<lastpass) {
 4265: 		/* if(s[m][iind]==4 && s[m+1][iind]==4) */
 4266: 		/*   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]); */
 4267: 		if(s[m][iind]==-1)
 4268: 		  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.));
 4269: 		freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
 4270: 		/* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
 4271: 		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 */
 4272: 	      }
 4273: 	    } /* end if between passes */  
 4274: 	    if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99)) {
 4275: 	      dateintsum=dateintsum+k2;
 4276: 	      k2cpt++;
 4277: 	      /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
 4278: 	    }
 4279: 	  } /* end bool 2 */
 4280: 	} /* end m */
 4281:       } /* end bool */
 4282:     } /* end iind = 1 to imx */
 4283:     /* prop[s][age] is feeded for any initial and valid live state as well as
 4284:        freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
 4285: 		
 4286: 		
 4287:     /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 4288:     pstamp(ficresp);
 4289:     /* if  (ncoveff>0) { */
 4290:     if  (cptcoveff>0) {
 4291:       fprintf(ficresp, "\n#********** Variable "); 
 4292:       fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
 4293:       fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
 4294:       for (z1=1; z1<=cptcoveff; z1++){
 4295: 	fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 4296: 	fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 4297: 	fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 4298:       }
 4299:       fprintf(ficresp, "**********\n#");
 4300:       fprintf(ficresphtm, "**********</h3>\n");
 4301:       fprintf(ficresphtmfr, "**********</h3>\n");
 4302:       fprintf(ficlog, "\n#********** Variable "); 
 4303:       for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 4304:       fprintf(ficlog, "**********\n");
 4305:     }
 4306:     fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
 4307:     for(i=1; i<=nlstate;i++) {
 4308:       fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
 4309:       fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
 4310:     }
 4311:     fprintf(ficresp, "\n");
 4312:     fprintf(ficresphtm, "\n");
 4313: 		
 4314:     /* Header of frequency table by age */
 4315:     fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
 4316:     fprintf(ficresphtmfr,"<th>Age</th> ");
 4317:     for(jk=-1; jk <=nlstate+ndeath; jk++){
 4318:       for(m=-1; m <=nlstate+ndeath; m++){
 4319: 	if(jk!=0 && m!=0)
 4320: 	  fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
 4321:       }
 4322:     }
 4323:     fprintf(ficresphtmfr, "\n");
 4324: 		
 4325:     /* For each age */
 4326:     for(iage=iagemin; iage <= iagemax+3; iage++){
 4327:       fprintf(ficresphtm,"<tr>");
 4328:       if(iage==iagemax+1){
 4329: 				fprintf(ficlog,"1");
 4330: 				fprintf(ficresphtmfr,"<tr><th>0</th> ");
 4331:       }else if(iage==iagemax+2){
 4332: 				fprintf(ficlog,"0");
 4333: 				fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
 4334:       }else if(iage==iagemax+3){
 4335: 				fprintf(ficlog,"Total");
 4336: 				fprintf(ficresphtmfr,"<tr><th>Total</th> ");
 4337:       }else{
 4338: 				if(first==1){
 4339: 					first=0;
 4340: 					printf("See log file for details...\n");
 4341: 				}
 4342: 				fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
 4343: 				fprintf(ficlog,"Age %d", iage);
 4344:       }
 4345:       for(jk=1; jk <=nlstate ; jk++){
 4346: 				for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
 4347: 					pp[jk] += freq[jk][m][iage]; 
 4348:       }
 4349:       for(jk=1; jk <=nlstate ; jk++){
 4350: 				for(m=-1, pos=0; m <=0 ; m++)
 4351: 					pos += freq[jk][m][iage];
 4352: 				if(pp[jk]>=1.e-10){
 4353: 					if(first==1){
 4354: 						printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 4355: 					}
 4356: 					fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 4357: 				}else{
 4358: 					if(first==1)
 4359: 						printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 4360: 					fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 4361: 				}
 4362:       }
 4363: 			
 4364:       for(jk=1; jk <=nlstate ; jk++){ 
 4365: 				/* posprop[jk]=0; */
 4366: 				for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
 4367: 					pp[jk] += freq[jk][m][iage];
 4368:       }	/* pp[jk] is the total number of transitions starting from state jk and any ending status until this age */
 4369: 			
 4370:       for(jk=1,pos=0, pospropta=0.; jk <=nlstate ; jk++){
 4371: 				pos += pp[jk]; /* pos is the total number of transitions until this age */
 4372: 				posprop[jk] += prop[jk][iage]; /* prop is the number of transitions from a live state
 4373: 																					from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
 4374: 				pospropta += prop[jk][iage]; /* prop is the number of transitions from a live state
 4375: 																				from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
 4376:       }
 4377:       for(jk=1; jk <=nlstate ; jk++){
 4378: 				if(pos>=1.e-5){
 4379: 					if(first==1)
 4380: 						printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 4381: 					fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 4382: 				}else{
 4383: 					if(first==1)
 4384: 						printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 4385: 					fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 4386: 				}
 4387: 				if( iage <= iagemax){
 4388: 					if(pos>=1.e-5){
 4389: 						fprintf(ficresp," %d %.5f %.0f %.0f",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
 4390: 						fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
 4391: 						/*probs[iage][jk][j1]= pp[jk]/pos;*/
 4392: 						/*printf("\niage=%d jk=%d j1=%d %.5f %.0f %.0f %f",iage,jk,j1,pp[jk]/pos, pp[jk],pos,probs[iage][jk][j1]);*/
 4393: 					}
 4394: 					else{
 4395: 						fprintf(ficresp," %d NaNq %.0f %.0f",iage,prop[jk][iage],pospropta);
 4396: 						fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[jk][iage],pospropta);
 4397: 					}
 4398: 				}
 4399: 				pospropt[jk] +=posprop[jk];
 4400:       } /* end loop jk */
 4401:       /* pospropt=0.; */
 4402:       for(jk=-1; jk <=nlstate+ndeath; jk++){
 4403: 				for(m=-1; m <=nlstate+ndeath; m++){
 4404: 					if(freq[jk][m][iage] !=0 ) { /* minimizing output */
 4405: 						if(first==1){
 4406: 							printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]);
 4407: 						}
 4408: 						fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iage]);
 4409: 					}
 4410: 					if(jk!=0 && m!=0)
 4411: 						fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][iage]);
 4412: 				}
 4413:       } /* end loop jk */
 4414:       posproptt=0.; 
 4415:       for(jk=1; jk <=nlstate; jk++){
 4416: 				posproptt += pospropt[jk];
 4417:       }
 4418:       fprintf(ficresphtmfr,"</tr>\n ");
 4419:       if(iage <= iagemax){
 4420: 				fprintf(ficresp,"\n");
 4421: 				fprintf(ficresphtm,"</tr>\n");
 4422:       }
 4423:       if(first==1)
 4424: 				printf("Others in log...\n");
 4425:       fprintf(ficlog,"\n");
 4426:     } /* end loop age iage */
 4427:     fprintf(ficresphtm,"<tr><th>Tot</th>");
 4428:     for(jk=1; jk <=nlstate ; jk++){
 4429:       if(posproptt < 1.e-5){
 4430: 				fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[jk],posproptt);	
 4431:       }else{
 4432: 				fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[jk]/posproptt,pospropt[jk],posproptt);	
 4433:       }
 4434:     }
 4435:     fprintf(ficresphtm,"</tr>\n");
 4436:     fprintf(ficresphtm,"</table>\n");
 4437:     fprintf(ficresphtmfr,"</table>\n");
 4438:     if(posproptt < 1.e-5){
 4439:       fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
 4440:       fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
 4441:       fprintf(ficres,"\n  This combination (%d) is not valid and no result will be produced\n\n",j1);
 4442:       invalidvarcomb[j1]=1;
 4443:     }else{
 4444:       fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
 4445:       invalidvarcomb[j1]=0;
 4446:     }
 4447:     fprintf(ficresphtmfr,"</table>\n");
 4448:   } /* end selected combination of covariate j1 */
 4449:   dateintmean=dateintsum/k2cpt; 
 4450: 	
 4451:   fclose(ficresp);
 4452:   fclose(ficresphtm);
 4453:   fclose(ficresphtmfr);
 4454:   free_vector(meanq,1,nqfveff);
 4455:   free_matrix(meanqt,1,lastpass,1,nqtveff);
 4456:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);
 4457:   free_vector(pospropt,1,nlstate);
 4458:   free_vector(posprop,1,nlstate);
 4459:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);
 4460:   free_vector(pp,1,nlstate);
 4461:   /* End of freqsummary */
 4462: }
 4463: 
 4464: /************ Prevalence ********************/
 4465: 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)
 4466: {  
 4467:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 4468:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 4469:      We still use firstpass and lastpass as another selection.
 4470:   */
 4471:  
 4472:   int i, m, jk, j1, bool, z1,j, iv;
 4473:   int mi; /* Effective wave */
 4474:   int iage;
 4475:   double agebegin, ageend;
 4476: 
 4477:   double **prop;
 4478:   double posprop; 
 4479:   double  y2; /* in fractional years */
 4480:   int iagemin, iagemax;
 4481:   int first; /** to stop verbosity which is redirected to log file */
 4482: 
 4483:   iagemin= (int) agemin;
 4484:   iagemax= (int) agemax;
 4485:   /*pp=vector(1,nlstate);*/
 4486:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
 4487:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
 4488:   j1=0;
 4489:   
 4490:   /*j=cptcoveff;*/
 4491:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 4492:   
 4493:   first=1;
 4494:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
 4495:     for (i=1; i<=nlstate; i++)  
 4496:       for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)
 4497: 	prop[i][iage]=0.0;
 4498:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
 4499:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
 4500:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
 4501:     
 4502:     for (i=1; i<=imx; i++) { /* Each individual */
 4503:       bool=1;
 4504:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
 4505:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
 4506: 	m=mw[mi][i];
 4507: 	/* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
 4508: 	/* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
 4509: 	for (z1=1; z1<=cptcoveff; z1++){
 4510: 	  if( Fixed[Tmodelind[z1]]==1){
 4511: 	    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
 4512: 	    if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
 4513: 	      bool=0;
 4514: 	  }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
 4515: 	    if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
 4516: 	      bool=0;
 4517: 	    }
 4518: 	}
 4519: 	if(bool==1){ /* Otherwise we skip that wave/person */
 4520: 	  agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
 4521: 	  /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
 4522: 	  if(m >=firstpass && m <=lastpass){
 4523: 	    y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
 4524: 	    if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
 4525: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 4526: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 4527: 	      if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){
 4528: 		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); 
 4529: 		exit(1);
 4530: 	      }
 4531: 	      if (s[m][i]>0 && s[m][i]<=nlstate) { 
 4532: 		/*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]]);*/
 4533: 		prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
 4534: 		prop[s[m][i]][iagemax+3] += weight[i]; 
 4535: 	      } /* end valid statuses */ 
 4536: 	    } /* end selection of dates */
 4537: 	  } /* end selection of waves */
 4538: 	} /* end bool */
 4539:       } /* end wave */
 4540:     } /* end individual */
 4541:     for(i=iagemin; i <= iagemax+3; i++){  
 4542:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
 4543: 	posprop += prop[jk][i]; 
 4544:       } 
 4545:       
 4546:       for(jk=1; jk <=nlstate ; jk++){	    
 4547: 	if( i <=  iagemax){ 
 4548: 	  if(posprop>=1.e-5){ 
 4549: 	    probs[i][jk][j1]= prop[jk][i]/posprop;
 4550: 	  } else{
 4551: 	    if(first==1){
 4552: 	      first=0;
 4553: 	      printf("Warning Observed prevalence probs[%d][%d][%d]=%lf because of lack of cases\nSee others in log file...\n",jk,i,j1,probs[i][jk][j1]);
 4554: 	    }
 4555: 	  }
 4556: 	} 
 4557:       }/* end jk */ 
 4558:     }/* end i */ 
 4559:      /*} *//* end i1 */
 4560:   } /* end j1 */
 4561:   
 4562:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
 4563:   /*free_vector(pp,1,nlstate);*/
 4564:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);
 4565: }  /* End of prevalence */
 4566: 
 4567: /************* Waves Concatenation ***************/
 4568: 
 4569: 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)
 4570: {
 4571:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 4572:      Death is a valid wave (if date is known).
 4573:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
 4574:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 4575:      and mw[mi+1][i]. dh depends on stepm.
 4576:   */
 4577: 
 4578:   int i=0, mi=0, m=0, mli=0;
 4579:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
 4580:      double sum=0., jmean=0.;*/
 4581:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
 4582:   int j, k=0,jk, ju, jl;
 4583:   double sum=0.;
 4584:   first=0;
 4585:   firstwo=0;
 4586:   firsthree=0;
 4587:   firstfour=0;
 4588:   jmin=100000;
 4589:   jmax=-1;
 4590:   jmean=0.;
 4591: 
 4592: /* Treating live states */
 4593:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
 4594:     mi=0;  /* First valid wave */
 4595:     mli=0; /* Last valid wave */
 4596:     m=firstpass;
 4597:     while(s[m][i] <= nlstate){  /* a live state */
 4598:       if(m >firstpass && s[m][i]==s[m-1][i] && mint[m][i]==mint[m-1][i] && anint[m][i]==anint[m-1][i]){/* Two succesive identical information on wave m */
 4599: 	mli=m-1;/* mw[++mi][i]=m-1; */
 4600:       }else 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 */
 4601: 	mw[++mi][i]=m;
 4602: 	mli=m;
 4603:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
 4604:       if(m < lastpass){ /* m < lastpass, standard case */
 4605: 	m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
 4606:       }
 4607:       else{ /* m >= lastpass, eventual special issue with warning */
 4608: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
 4609: 	break;
 4610: #else
 4611: 	if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
 4612: 	  if(firsthree == 0){
 4613: 	    printf("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 as pi. .\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);
 4614: 	    firsthree=1;
 4615: 	  }
 4616: 	  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 as pi. .\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);
 4617: 	  mw[++mi][i]=m;
 4618: 	  mli=m;
 4619: 	}
 4620: 	if(s[m][i]==-2){ /* Vital status is really unknown */
 4621: 	  nbwarn++;
 4622: 	  if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
 4623: 	    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);
 4624: 	    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.\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], (int) moisdc[i], (int) andc[i], i, m);
 4625: 	  }
 4626: 	  break;
 4627: 	}
 4628: 	break;
 4629: #endif
 4630:       }/* End m >= lastpass */
 4631:     }/* end while */
 4632: 
 4633:     /* mi is the last effective wave, m is lastpass, mw[j][i] gives the # of j-th effective wave for individual i */
 4634:     /* After last pass */
 4635: /* Treating death states */
 4636:     if (s[m][i] > nlstate){  /* In a death state */
 4637:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
 4638:       /* } */
 4639:       mi++;	/* Death is another wave */
 4640:       /* if(mi==0)  never been interviewed correctly before death */
 4641:       /* Only death is a correct wave */
 4642:       mw[mi][i]=m;
 4643:     }
 4644: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
 4645:     else if ((int) andc[i] != 9999) { /* Status is negative. A death occured after lastpass, we can't take it into account because of potential bias */
 4646:       /* m++; */
 4647:       /* mi++; */
 4648:       /* s[m][i]=nlstate+1;  /\* We are setting the status to the last of non live state *\/ */
 4649:       /* mw[mi][i]=m; */
 4650:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
 4651: 	if((andc[i]+moisdc[i]/12.) <=(anint[m][i]+mint[m][i]/12.)){ /* death occured before last wave and status should have been death instead of -1 */
 4652: 	  nbwarn++;
 4653: 	  if(firstfiv==0){
 4654: 	    printf("Warning! Death for individual %ld line=%d occurred at %d/%d before last wave %d interviewed at %d/%d and should have been coded as death instead of '%d'. This case (%d)/wave (%d) is contributing 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], s[m][i], i,m );
 4655: 	    firstfiv=1;
 4656: 	  }else{
 4657: 	    fprintf(ficlog,"Warning! Death for individual %ld line=%d occurred at %d/%d before last wave %d interviewed at %d/%d and should have been coded as death instead of '%d'. This case (%d)/wave (%d) is contributing to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], i,m );
 4658: 	  }
 4659: 	}else{ /* Death occured afer last wave potential bias */
 4660: 	  nberr++;
 4661: 	  if(firstwo==0){
 4662: 	    printf("Error! Death for individual %ld line=%d occurred at %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 );
 4663: 	    firstwo=1;
 4664: 	  }
 4665: 	  fprintf(ficlog,"Error! Death for individual %ld line=%d occurred at %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 );
 4666: 	}
 4667:       }else{ /* end date of interview is known */
 4668: 	/* death is known but not confirmed by death status at any wave */
 4669: 	if(firstfour==0){
 4670: 	  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 );
 4671: 	  firstfour=1;
 4672: 	}
 4673: 	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 );
 4674:       }
 4675:     } /* end if date of death is known */
 4676: #endif
 4677:     wav[i]=mi; /* mi should be the last effective wave (or mli) */
 4678:     /* wav[i]=mw[mi][i]; */
 4679:     if(mi==0){
 4680:       nbwarn++;
 4681:       if(first==0){
 4682: 	printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
 4683: 	first=1;
 4684:       }
 4685:       if(first==1){
 4686: 	fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
 4687:       }
 4688:     } /* end mi==0 */
 4689:   } /* End individuals */
 4690:   /* wav and mw are no more changed */
 4691: 	
 4692:   
 4693:   for(i=1; i<=imx; i++){
 4694:     for(mi=1; mi<wav[i];mi++){
 4695:       if (stepm <=0)
 4696: 	dh[mi][i]=1;
 4697:       else{
 4698: 	if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
 4699: 	  if (agedc[i] < 2*AGESUP) {
 4700: 	    j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
 4701: 	    if(j==0) j=1;  /* Survives at least one month after exam */
 4702: 	    else if(j<0){
 4703: 	      nberr++;
 4704: 	      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]);
 4705: 	      j=1; /* Temporary Dangerous patch */
 4706: 	      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);
 4707: 	      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]);
 4708: 	      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);
 4709: 	    }
 4710: 	    k=k+1;
 4711: 	    if (j >= jmax){
 4712: 	      jmax=j;
 4713: 	      ijmax=i;
 4714: 	    }
 4715: 	    if (j <= jmin){
 4716: 	      jmin=j;
 4717: 	      ijmin=i;
 4718: 	    }
 4719: 	    sum=sum+j;
 4720: 	    /*if (j<0) printf("j=%d num=%d \n",j,i);*/
 4721: 	    /*	  printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
 4722: 	  }
 4723: 	}
 4724: 	else{
 4725: 	  j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 4726: /* 	  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]); */
 4727: 					
 4728: 	  k=k+1;
 4729: 	  if (j >= jmax) {
 4730: 	    jmax=j;
 4731: 	    ijmax=i;
 4732: 	  }
 4733: 	  else if (j <= jmin){
 4734: 	    jmin=j;
 4735: 	    ijmin=i;
 4736: 	  }
 4737: 	  /*	    if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
 4738: 	  /*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]);*/
 4739: 	  if(j<0){
 4740: 	    nberr++;
 4741: 	    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]);
 4742: 	    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]);
 4743: 	  }
 4744: 	  sum=sum+j;
 4745: 	}
 4746: 	jk= j/stepm;
 4747: 	jl= j -jk*stepm;
 4748: 	ju= j -(jk+1)*stepm;
 4749: 	if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
 4750: 	  if(jl==0){
 4751: 	    dh[mi][i]=jk;
 4752: 	    bh[mi][i]=0;
 4753: 	  }else{ /* We want a negative bias in order to only have interpolation ie
 4754: 		  * to avoid the price of an extra matrix product in likelihood */
 4755: 	    dh[mi][i]=jk+1;
 4756: 	    bh[mi][i]=ju;
 4757: 	  }
 4758: 	}else{
 4759: 	  if(jl <= -ju){
 4760: 	    dh[mi][i]=jk;
 4761: 	    bh[mi][i]=jl;	/* bias is positive if real duration
 4762: 				 * is higher than the multiple of stepm and negative otherwise.
 4763: 				 */
 4764: 	  }
 4765: 	  else{
 4766: 	    dh[mi][i]=jk+1;
 4767: 	    bh[mi][i]=ju;
 4768: 	  }
 4769: 	  if(dh[mi][i]==0){
 4770: 	    dh[mi][i]=1; /* At least one step */
 4771: 	    bh[mi][i]=ju; /* At least one step */
 4772: 	    /*  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);*/
 4773: 	  }
 4774: 	} /* end if mle */
 4775:       }
 4776:     } /* end wave */
 4777:   }
 4778:   jmean=sum/k;
 4779:   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);
 4780:   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);
 4781: }
 4782: 
 4783: /*********** Tricode ****************************/
 4784:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
 4785: {
 4786:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
 4787:   /*	  Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
 4788:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
 4789:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
 4790:    * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
 4791:   */
 4792: 
 4793:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
 4794:   int modmaxcovj=0; /* Modality max of covariates j */
 4795:   int cptcode=0; /* Modality max of covariates j */
 4796:   int modmincovj=0; /* Modality min of covariates j */
 4797: 
 4798: 
 4799:   /* cptcoveff=0;  */
 4800: 	/* *cptcov=0; */
 4801:  
 4802:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
 4803: 
 4804:   /* Loop on covariates without age and products and no quantitative variable */
 4805:   /* for (j=1; j<=(cptcovs); j++) { /\* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only *\/ */
 4806:   for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
 4807:     for (j=-1; (j < maxncov); j++) Ndum[j]=0;
 4808:     if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
 4809:       switch(Fixed[k]) {
 4810:       case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
 4811: 				for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the  modality of this covariate Vj*/
 4812: 					ij=(int)(covar[Tvar[k]][i]);
 4813: 					/* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
 4814: 					 * If product of Vn*Vm, still boolean *:
 4815: 					 * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
 4816: 					 * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
 4817: 					/* Finds for covariate j, n=Tvar[j] of Vn . ij is the
 4818: 						 modality of the nth covariate of individual i. */
 4819: 					if (ij > modmaxcovj)
 4820: 						modmaxcovj=ij; 
 4821: 					else if (ij < modmincovj) 
 4822: 						modmincovj=ij; 
 4823: 					if ((ij < -1) && (ij > NCOVMAX)){
 4824: 						printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
 4825: 						exit(1);
 4826: 					}else
 4827: 						Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
 4828: 					/*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
 4829: 					/*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
 4830: 					/* getting the maximum value of the modality of the covariate
 4831: 						 (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
 4832: 						 female ies 1, then modmaxcovj=1.
 4833: 					*/
 4834: 				} /* end for loop on individuals i */
 4835: 				printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
 4836: 				fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
 4837: 				cptcode=modmaxcovj;
 4838: 				/* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
 4839: 				/*for (i=0; i<=cptcode; i++) {*/
 4840: 				for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
 4841: 					printf("Frequencies of covariates %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
 4842: 					fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
 4843: 					if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
 4844: 						if( j != -1){
 4845: 							ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
 4846: 																 covariate for which somebody answered excluding 
 4847: 																 undefined. Usually 2: 0 and 1. */
 4848: 						}
 4849: 						ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
 4850: 																		covariate for which somebody answered including 
 4851: 																		undefined. Usually 3: -1, 0 and 1. */
 4852: 					}	/* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
 4853: 						 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
 4854: 				} /* Ndum[-1] number of undefined modalities */
 4855: 			
 4856: 				/* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
 4857: 				/* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
 4858: 				/* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
 4859: 				/* modmincovj=3; modmaxcovj = 7; */
 4860: 				/* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
 4861: 				/* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
 4862: 			  /*		 defining two dummy variables: variables V1_1 and V1_2.*/
 4863:  	      /* nbcode[Tvar[j]][ij]=k; */
 4864: 	      /* nbcode[Tvar[j]][1]=0; */
 4865: 	      /* nbcode[Tvar[j]][2]=1; */
 4866: 	      /* nbcode[Tvar[j]][3]=2; */
 4867: 	      /* To be continued (not working yet). */
 4868: 	      ij=0; /* ij is similar to i but can jump over null modalities */
 4869: 				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*/
 4870:       	  if (Ndum[i] == 0) { /* If nobody responded to this modality k */
 4871: 	          break;
 4872: 	        }
 4873: 					ij++;
 4874: 					nbcode[Tvar[k]][ij]=i;  /* stores the original value of modality i in an array nbcode, ij modality from 1 to last non-nul modality. nbcode[1][1]=0 nbcode[1][2]=1*/
 4875: 					cptcode = ij; /* New max modality for covar j */
 4876: 				} /* end of loop on modality i=-1 to 1 or more */
 4877: 				break;
 4878:       case 1: /* Testing on varying covariate, could be simple and
 4879: 	       * should look at waves or product of fixed *
 4880: 	       * varying. No time to test -1, assuming 0 and 1 only */
 4881: 				ij=0;
 4882: 				for(i=0; i<=1;i++){
 4883: 					nbcode[Tvar[k]][++ij]=i;
 4884: 				}
 4885: 				break;
 4886:       default:
 4887: 				break;
 4888:       } /* end switch */
 4889:     } /* end dummy test */
 4890:     
 4891:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
 4892:     /* 	/\*recode from 0 *\/ */
 4893:     /* 				     k is a modality. If we have model=V1+V1*sex  */
 4894:     /* 				     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
 4895:     /* 				  But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
 4896:     /* 	} */
 4897:     /* 	/\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
 4898:     /* 	if (ij > ncodemax[j]) { */
 4899:     /* 	  printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
 4900:     /* 	  fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
 4901:     /* 	  break; */
 4902:     /* 	} */
 4903:     /*   }  /\* end of loop on modality k *\/ */
 4904:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
 4905:   
 4906:   for (k=-1; k< maxncov; k++) Ndum[k]=0; 
 4907:   /* Look at fixed dummy (single or product) covariates to check empty modalities */
 4908:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
 4909:     /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
 4910:     ij=Tvar[i]; /* Tvar 5,4,3,6,5,7,1,4 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V4*age */ 
 4911:     Ndum[ij]++; /* Count the # of 1, 2 etc: {1,1,1,2,2,1,1} because V1 once, V2 once, two V4 and V5 in above */
 4912:     /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
 4913:   } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
 4914:   
 4915:   ij=0;
 4916:   /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
 4917:   for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
 4918:     /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
 4919:     /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
 4920:     if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
 4921:       /* If product not in single variable we don't print results */
 4922:       /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
 4923:       ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
 4924:       Tvaraff[ij]=Tvar[k]; /* For printing combination *//* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, Tvar {5, 4, 3, 6, 5, 2, 7, 1, 1} Tvaraff={4, 3, 1} V4, V3, V1*/
 4925:       Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
 4926:       TmodelInvind[ij]=Tvar[k]- ncovcol-nqv; /* Inverse TmodelInvind[2=V4]=2 second dummy varying cov (V4)4-1-1 {0, 2, 1, } TmodelInvind[3]=1 */
 4927:       if(Fixed[k]!=0)
 4928:         anyvaryingduminmodel=1;
 4929: 			/* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
 4930: 			/*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
 4931: 			/* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
 4932: 			/*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
 4933: 			/* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
 4934: 			/*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
 4935:     } 
 4936:   } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
 4937:   /* ij--; */
 4938:   /* cptcoveff=ij; /\*Number of total covariates*\/ */
 4939:   *cptcov=ij; /*Number of total real effective covariates: effective
 4940: 							 * because they can be excluded from the model and real
 4941: 							 * if in the model but excluded because missing values, but how to get k from ij?*/
 4942:   for(j=ij+1; j<= cptcovt; j++){
 4943:     Tvaraff[j]=0;
 4944:     Tmodelind[j]=0;
 4945:   }
 4946:   for(j=ntveff+1; j<= cptcovt; j++){
 4947:     TmodelInvind[j]=0;
 4948:   }
 4949:   /* To be sorted */
 4950:   ;
 4951: }
 4952: 
 4953: 
 4954: /*********** Health Expectancies ****************/
 4955: 
 4956:  void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[], int nres )
 4957: 
 4958: {
 4959:   /* Health expectancies, no variances */
 4960:   int i, j, nhstepm, hstepm, h, nstepm;
 4961:   int nhstepma, nstepma; /* Decreasing with age */
 4962:   double age, agelim, hf;
 4963:   double ***p3mat;
 4964:   double eip;
 4965: 
 4966:   /* pstamp(ficreseij); */
 4967:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
 4968:   fprintf(ficreseij,"# Age");
 4969:   for(i=1; i<=nlstate;i++){
 4970:     for(j=1; j<=nlstate;j++){
 4971:       fprintf(ficreseij," e%1d%1d ",i,j);
 4972:     }
 4973:     fprintf(ficreseij," e%1d. ",i);
 4974:   }
 4975:   fprintf(ficreseij,"\n");
 4976: 
 4977:   
 4978:   if(estepm < stepm){
 4979:     printf ("Problem %d lower than %d\n",estepm, stepm);
 4980:   }
 4981:   else  hstepm=estepm;   
 4982:   /* We compute the life expectancy from trapezoids spaced every estepm months
 4983:    * This is mainly to measure the difference between two models: for example
 4984:    * if stepm=24 months pijx are given only every 2 years and by summing them
 4985:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 4986:    * progression in between and thus overestimating or underestimating according
 4987:    * to the curvature of the survival function. If, for the same date, we 
 4988:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 4989:    * to compare the new estimate of Life expectancy with the same linear 
 4990:    * hypothesis. A more precise result, taking into account a more precise
 4991:    * curvature will be obtained if estepm is as small as stepm. */
 4992: 
 4993:   /* For example we decided to compute the life expectancy with the smallest unit */
 4994:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 4995:      nhstepm is the number of hstepm from age to agelim 
 4996:      nstepm is the number of stepm from age to agelin. 
 4997:      Look at hpijx to understand the reason of that which relies in memory size
 4998:      and note for a fixed period like estepm months */
 4999:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 5000:      survival function given by stepm (the optimization length). Unfortunately it
 5001:      means that if the survival funtion is printed only each two years of age and if
 5002:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 5003:      results. So we changed our mind and took the option of the best precision.
 5004:   */
 5005:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 5006: 
 5007:   agelim=AGESUP;
 5008:   /* If stepm=6 months */
 5009:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
 5010:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 5011:     
 5012: /* nhstepm age range expressed in number of stepm */
 5013:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 5014:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 5015:   /* if (stepm >= YEARM) hstepm=1;*/
 5016:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 5017:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5018: 
 5019:   for (age=bage; age<=fage; age ++){ 
 5020:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 5021:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 5022:     /* if (stepm >= YEARM) hstepm=1;*/
 5023:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 5024: 
 5025:     /* If stepm=6 months */
 5026:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 5027:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 5028:     
 5029:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
 5030:     
 5031:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 5032:     
 5033:     printf("%d|",(int)age);fflush(stdout);
 5034:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 5035:     
 5036:     /* Computing expectancies */
 5037:     for(i=1; i<=nlstate;i++)
 5038:       for(j=1; j<=nlstate;j++)
 5039: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 5040: 	  eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
 5041: 	  
 5042: 	  /* 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]);*/
 5043: 
 5044: 	}
 5045: 
 5046:     fprintf(ficreseij,"%3.0f",age );
 5047:     for(i=1; i<=nlstate;i++){
 5048:       eip=0;
 5049:       for(j=1; j<=nlstate;j++){
 5050: 	eip +=eij[i][j][(int)age];
 5051: 	fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
 5052:       }
 5053:       fprintf(ficreseij,"%9.4f", eip );
 5054:     }
 5055:     fprintf(ficreseij,"\n");
 5056:     
 5057:   }
 5058:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5059:   printf("\n");
 5060:   fprintf(ficlog,"\n");
 5061:   
 5062: }
 5063: 
 5064:  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[], int nres )
 5065: 
 5066: {
 5067:   /* Covariances of health expectancies eij and of total life expectancies according
 5068:      to initial status i, ei. .
 5069:   */
 5070:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
 5071:   int nhstepma, nstepma; /* Decreasing with age */
 5072:   double age, agelim, hf;
 5073:   double ***p3matp, ***p3matm, ***varhe;
 5074:   double **dnewm,**doldm;
 5075:   double *xp, *xm;
 5076:   double **gp, **gm;
 5077:   double ***gradg, ***trgradg;
 5078:   int theta;
 5079: 
 5080:   double eip, vip;
 5081: 
 5082:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
 5083:   xp=vector(1,npar);
 5084:   xm=vector(1,npar);
 5085:   dnewm=matrix(1,nlstate*nlstate,1,npar);
 5086:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
 5087:   
 5088:   pstamp(ficresstdeij);
 5089:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
 5090:   fprintf(ficresstdeij,"# Age");
 5091:   for(i=1; i<=nlstate;i++){
 5092:     for(j=1; j<=nlstate;j++)
 5093:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
 5094:     fprintf(ficresstdeij," e%1d. ",i);
 5095:   }
 5096:   fprintf(ficresstdeij,"\n");
 5097: 
 5098:   pstamp(ficrescveij);
 5099:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
 5100:   fprintf(ficrescveij,"# Age");
 5101:   for(i=1; i<=nlstate;i++)
 5102:     for(j=1; j<=nlstate;j++){
 5103:       cptj= (j-1)*nlstate+i;
 5104:       for(i2=1; i2<=nlstate;i2++)
 5105: 	for(j2=1; j2<=nlstate;j2++){
 5106: 	  cptj2= (j2-1)*nlstate+i2;
 5107: 	  if(cptj2 <= cptj)
 5108: 	    fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
 5109: 	}
 5110:     }
 5111:   fprintf(ficrescveij,"\n");
 5112:   
 5113:   if(estepm < stepm){
 5114:     printf ("Problem %d lower than %d\n",estepm, stepm);
 5115:   }
 5116:   else  hstepm=estepm;   
 5117:   /* We compute the life expectancy from trapezoids spaced every estepm months
 5118:    * This is mainly to measure the difference between two models: for example
 5119:    * if stepm=24 months pijx are given only every 2 years and by summing them
 5120:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 5121:    * progression in between and thus overestimating or underestimating according
 5122:    * to the curvature of the survival function. If, for the same date, we 
 5123:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 5124:    * to compare the new estimate of Life expectancy with the same linear 
 5125:    * hypothesis. A more precise result, taking into account a more precise
 5126:    * curvature will be obtained if estepm is as small as stepm. */
 5127: 
 5128:   /* For example we decided to compute the life expectancy with the smallest unit */
 5129:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 5130:      nhstepm is the number of hstepm from age to agelim 
 5131:      nstepm is the number of stepm from age to agelin. 
 5132:      Look at hpijx to understand the reason of that which relies in memory size
 5133:      and note for a fixed period like estepm months */
 5134:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 5135:      survival function given by stepm (the optimization length). Unfortunately it
 5136:      means that if the survival funtion is printed only each two years of age and if
 5137:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 5138:      results. So we changed our mind and took the option of the best precision.
 5139:   */
 5140:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 5141: 
 5142:   /* If stepm=6 months */
 5143:   /* nhstepm age range expressed in number of stepm */
 5144:   agelim=AGESUP;
 5145:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
 5146:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 5147:   /* if (stepm >= YEARM) hstepm=1;*/
 5148:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 5149:   
 5150:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5151:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5152:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
 5153:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
 5154:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
 5155:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
 5156: 
 5157:   for (age=bage; age<=fage; age ++){ 
 5158:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 5159:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 5160:     /* if (stepm >= YEARM) hstepm=1;*/
 5161:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 5162: 		
 5163:     /* If stepm=6 months */
 5164:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 5165:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 5166:     
 5167:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 5168: 		
 5169:     /* Computing  Variances of health expectancies */
 5170:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
 5171:        decrease memory allocation */
 5172:     for(theta=1; theta <=npar; theta++){
 5173:       for(i=1; i<=npar; i++){ 
 5174: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 5175: 	xm[i] = x[i] - (i==theta ?delti[theta]:0);
 5176:       }
 5177:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
 5178:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
 5179: 			
 5180:       for(j=1; j<= nlstate; j++){
 5181: 	for(i=1; i<=nlstate; i++){
 5182: 	  for(h=0; h<=nhstepm-1; h++){
 5183: 	    gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
 5184: 	    gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
 5185: 	  }
 5186: 	}
 5187:       }
 5188: 			
 5189:       for(ij=1; ij<= nlstate*nlstate; ij++)
 5190: 	for(h=0; h<=nhstepm-1; h++){
 5191: 	  gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
 5192: 	}
 5193:     }/* End theta */
 5194:     
 5195:     
 5196:     for(h=0; h<=nhstepm-1; h++)
 5197:       for(j=1; j<=nlstate*nlstate;j++)
 5198: 	for(theta=1; theta <=npar; theta++)
 5199: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 5200:     
 5201: 		
 5202:     for(ij=1;ij<=nlstate*nlstate;ij++)
 5203:       for(ji=1;ji<=nlstate*nlstate;ji++)
 5204: 	varhe[ij][ji][(int)age] =0.;
 5205: 		
 5206:     printf("%d|",(int)age);fflush(stdout);
 5207:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 5208:     for(h=0;h<=nhstepm-1;h++){
 5209:       for(k=0;k<=nhstepm-1;k++){
 5210: 	matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
 5211: 	matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
 5212: 	for(ij=1;ij<=nlstate*nlstate;ij++)
 5213: 	  for(ji=1;ji<=nlstate*nlstate;ji++)
 5214: 	    varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
 5215:       }
 5216:     }
 5217: 		
 5218:     /* Computing expectancies */
 5219:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
 5220:     for(i=1; i<=nlstate;i++)
 5221:       for(j=1; j<=nlstate;j++)
 5222: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 5223: 	  eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
 5224: 					
 5225: 	  /* 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]);*/
 5226: 					
 5227: 	}
 5228: 		
 5229:     fprintf(ficresstdeij,"%3.0f",age );
 5230:     for(i=1; i<=nlstate;i++){
 5231:       eip=0.;
 5232:       vip=0.;
 5233:       for(j=1; j<=nlstate;j++){
 5234: 	eip += eij[i][j][(int)age];
 5235: 	for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
 5236: 	  vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
 5237: 	fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
 5238:       }
 5239:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
 5240:     }
 5241:     fprintf(ficresstdeij,"\n");
 5242: 		
 5243:     fprintf(ficrescveij,"%3.0f",age );
 5244:     for(i=1; i<=nlstate;i++)
 5245:       for(j=1; j<=nlstate;j++){
 5246: 	cptj= (j-1)*nlstate+i;
 5247: 	for(i2=1; i2<=nlstate;i2++)
 5248: 	  for(j2=1; j2<=nlstate;j2++){
 5249: 	    cptj2= (j2-1)*nlstate+i2;
 5250: 	    if(cptj2 <= cptj)
 5251: 	      fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
 5252: 	  }
 5253:       }
 5254:     fprintf(ficrescveij,"\n");
 5255: 		
 5256:   }
 5257:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
 5258:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
 5259:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
 5260:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
 5261:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5262:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5263:   printf("\n");
 5264:   fprintf(ficlog,"\n");
 5265: 	
 5266:   free_vector(xm,1,npar);
 5267:   free_vector(xp,1,npar);
 5268:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
 5269:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
 5270:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
 5271: }
 5272:  
 5273: /************ Variance ******************/
 5274:  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[], int nres)
 5275:  {
 5276:    /* Variance of health expectancies */
 5277:    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
 5278:    /* double **newm;*/
 5279:    /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
 5280:   
 5281:    /* int movingaverage(); */
 5282:    double **dnewm,**doldm;
 5283:    double **dnewmp,**doldmp;
 5284:    int i, j, nhstepm, hstepm, h, nstepm ;
 5285:    int k;
 5286:    double *xp;
 5287:    double **gp, **gm;  /* for var eij */
 5288:    double ***gradg, ***trgradg; /*for var eij */
 5289:    double **gradgp, **trgradgp; /* for var p point j */
 5290:    double *gpp, *gmp; /* for var p point j */
 5291:    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
 5292:    double ***p3mat;
 5293:    double age,agelim, hf;
 5294:    /* double ***mobaverage; */
 5295:    int theta;
 5296:    char digit[4];
 5297:    char digitp[25];
 5298: 
 5299:    char fileresprobmorprev[FILENAMELENGTH];
 5300: 
 5301:    if(popbased==1){
 5302:      if(mobilav!=0)
 5303:        strcpy(digitp,"-POPULBASED-MOBILAV_");
 5304:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
 5305:    }
 5306:    else 
 5307:      strcpy(digitp,"-STABLBASED_");
 5308: 
 5309:    /* if (mobilav!=0) { */
 5310:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 5311:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
 5312:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
 5313:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
 5314:    /*   } */
 5315:    /* } */
 5316: 
 5317:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
 5318:    sprintf(digit,"%-d",ij);
 5319:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
 5320:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
 5321:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
 5322:    strcat(fileresprobmorprev,fileresu);
 5323:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
 5324:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
 5325:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
 5326:    }
 5327:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 5328:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 5329:    pstamp(ficresprobmorprev);
 5330:    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);
 5331:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
 5332:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
 5333:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
 5334:    }
 5335:    for(j=1;j<=cptcoveff;j++) 
 5336:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,j)]);
 5337:    fprintf(ficresprobmorprev,"\n");
 5338: 
 5339:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
 5340:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 5341:      fprintf(ficresprobmorprev," p.%-d SE",j);
 5342:      for(i=1; i<=nlstate;i++)
 5343:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 5344:    }  
 5345:    fprintf(ficresprobmorprev,"\n");
 5346:   
 5347:    fprintf(ficgp,"\n# Routine varevsij");
 5348:    fprintf(ficgp,"\nunset title \n");
 5349:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
 5350:    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");
 5351:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
 5352:    /*   } */
 5353:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 5354:    pstamp(ficresvij);
 5355:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
 5356:    if(popbased==1)
 5357:      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);
 5358:    else
 5359:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
 5360:    fprintf(ficresvij,"# Age");
 5361:    for(i=1; i<=nlstate;i++)
 5362:      for(j=1; j<=nlstate;j++)
 5363:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
 5364:    fprintf(ficresvij,"\n");
 5365: 
 5366:    xp=vector(1,npar);
 5367:    dnewm=matrix(1,nlstate,1,npar);
 5368:    doldm=matrix(1,nlstate,1,nlstate);
 5369:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
 5370:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 5371: 
 5372:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
 5373:    gpp=vector(nlstate+1,nlstate+ndeath);
 5374:    gmp=vector(nlstate+1,nlstate+ndeath);
 5375:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 5376:   
 5377:    if(estepm < stepm){
 5378:      printf ("Problem %d lower than %d\n",estepm, stepm);
 5379:    }
 5380:    else  hstepm=estepm;   
 5381:    /* For example we decided to compute the life expectancy with the smallest unit */
 5382:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 5383:       nhstepm is the number of hstepm from age to agelim 
 5384:       nstepm is the number of stepm from age to agelim. 
 5385:       Look at function hpijx to understand why because of memory size limitations, 
 5386:       we decided (b) to get a life expectancy respecting the most precise curvature of the
 5387:       survival function given by stepm (the optimization length). Unfortunately it
 5388:       means that if the survival funtion is printed every two years of age and if
 5389:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 5390:       results. So we changed our mind and took the option of the best precision.
 5391:    */
 5392:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 5393:    agelim = AGESUP;
 5394:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 5395:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 5396:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 5397:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5398:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
 5399:      gp=matrix(0,nhstepm,1,nlstate);
 5400:      gm=matrix(0,nhstepm,1,nlstate);
 5401: 		
 5402: 		
 5403:      for(theta=1; theta <=npar; theta++){
 5404:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
 5405: 	 xp[i] = x[i] + (i==theta ?delti[theta]:0);
 5406:        }
 5407: 			
 5408:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nresult);
 5409: 			
 5410:        if (popbased==1) {
 5411: 	 if(mobilav ==0){
 5412: 	   for(i=1; i<=nlstate;i++)
 5413: 	     prlim[i][i]=probs[(int)age][i][ij];
 5414: 	 }else{ /* mobilav */ 
 5415: 	   for(i=1; i<=nlstate;i++)
 5416: 	     prlim[i][i]=mobaverage[(int)age][i][ij];
 5417: 	 }
 5418:        }
 5419: 			
 5420:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
 5421:        for(j=1; j<= nlstate; j++){
 5422: 	 for(h=0; h<=nhstepm; h++){
 5423: 	   for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 5424: 	     gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 5425: 	 }
 5426:        }
 5427:        /* Next for computing probability of death (h=1 means
 5428: 	  computed over hstepm matrices product = hstepm*stepm months) 
 5429: 	  as a weighted average of prlim.
 5430:        */
 5431:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
 5432: 	 for(i=1,gpp[j]=0.; i<= nlstate; i++)
 5433: 	   gpp[j] += prlim[i][i]*p3mat[i][j][1];
 5434:        }    
 5435:        /* end probability of death */
 5436: 			
 5437:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
 5438: 	 xp[i] = x[i] - (i==theta ?delti[theta]:0);
 5439: 			
 5440:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nresult);
 5441: 			
 5442:        if (popbased==1) {
 5443: 	 if(mobilav ==0){
 5444: 	   for(i=1; i<=nlstate;i++)
 5445: 	     prlim[i][i]=probs[(int)age][i][ij];
 5446: 	 }else{ /* mobilav */ 
 5447: 	   for(i=1; i<=nlstate;i++)
 5448: 	     prlim[i][i]=mobaverage[(int)age][i][ij];
 5449: 	 }
 5450:        }
 5451: 			
 5452:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
 5453: 			
 5454:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
 5455: 	 for(h=0; h<=nhstepm; h++){
 5456: 	   for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 5457: 	     gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 5458: 	 }
 5459:        }
 5460:        /* This for computing probability of death (h=1 means
 5461: 	  computed over hstepm matrices product = hstepm*stepm months) 
 5462: 	  as a weighted average of prlim.
 5463:        */
 5464:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
 5465: 	 for(i=1,gmp[j]=0.; i<= nlstate; i++)
 5466: 	   gmp[j] += prlim[i][i]*p3mat[i][j][1];
 5467:        }    
 5468:        /* end probability of death */
 5469: 			
 5470:        for(j=1; j<= nlstate; j++) /* vareij */
 5471: 	 for(h=0; h<=nhstepm; h++){
 5472: 	   gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 5473: 	 }
 5474: 			
 5475:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
 5476: 	 gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
 5477:        }
 5478: 			
 5479:      } /* End theta */
 5480: 		
 5481:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
 5482: 		
 5483:      for(h=0; h<=nhstepm; h++) /* veij */
 5484:        for(j=1; j<=nlstate;j++)
 5485: 	 for(theta=1; theta <=npar; theta++)
 5486: 	   trgradg[h][j][theta]=gradg[h][theta][j];
 5487: 		
 5488:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
 5489:        for(theta=1; theta <=npar; theta++)
 5490: 	 trgradgp[j][theta]=gradgp[theta][j];
 5491: 		
 5492: 		
 5493:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 5494:      for(i=1;i<=nlstate;i++)
 5495:        for(j=1;j<=nlstate;j++)
 5496: 	 vareij[i][j][(int)age] =0.;
 5497: 		
 5498:      for(h=0;h<=nhstepm;h++){
 5499:        for(k=0;k<=nhstepm;k++){
 5500: 	 matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 5501: 	 matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
 5502: 	 for(i=1;i<=nlstate;i++)
 5503: 	   for(j=1;j<=nlstate;j++)
 5504: 	     vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
 5505:        }
 5506:      }
 5507: 		
 5508:      /* pptj */
 5509:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
 5510:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
 5511:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
 5512:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
 5513: 	 varppt[j][i]=doldmp[j][i];
 5514:      /* end ppptj */
 5515:      /*  x centered again */
 5516: 		
 5517:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nresult);
 5518: 		
 5519:      if (popbased==1) {
 5520:        if(mobilav ==0){
 5521: 	 for(i=1; i<=nlstate;i++)
 5522: 	   prlim[i][i]=probs[(int)age][i][ij];
 5523:        }else{ /* mobilav */ 
 5524: 	 for(i=1; i<=nlstate;i++)
 5525: 	   prlim[i][i]=mobaverage[(int)age][i][ij];
 5526:        }
 5527:      }
 5528: 		
 5529:      /* This for computing probability of death (h=1 means
 5530: 	computed over hstepm (estepm) matrices product = hstepm*stepm months) 
 5531: 	as a weighted average of prlim.
 5532:      */
 5533:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
 5534:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
 5535:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
 5536: 	 gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
 5537:      }    
 5538:      /* end probability of death */
 5539: 		
 5540:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
 5541:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 5542:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
 5543:        for(i=1; i<=nlstate;i++){
 5544: 	 fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 5545:        }
 5546:      } 
 5547:      fprintf(ficresprobmorprev,"\n");
 5548: 		
 5549:      fprintf(ficresvij,"%.0f ",age );
 5550:      for(i=1; i<=nlstate;i++)
 5551:        for(j=1; j<=nlstate;j++){
 5552: 	 fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
 5553:        }
 5554:      fprintf(ficresvij,"\n");
 5555:      free_matrix(gp,0,nhstepm,1,nlstate);
 5556:      free_matrix(gm,0,nhstepm,1,nlstate);
 5557:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 5558:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 5559:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5560:    } /* End age */
 5561:    free_vector(gpp,nlstate+1,nlstate+ndeath);
 5562:    free_vector(gmp,nlstate+1,nlstate+ndeath);
 5563:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
 5564:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 5565:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
 5566:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
 5567:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
 5568:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
 5569:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
 5570:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
 5571:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
 5572:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
 5573:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
 5574:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
 5575:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
 5576:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
 5577:    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);
 5578:    /*  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);
 5579:     */
 5580:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
 5581:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
 5582: 
 5583:    free_vector(xp,1,npar);
 5584:    free_matrix(doldm,1,nlstate,1,nlstate);
 5585:    free_matrix(dnewm,1,nlstate,1,npar);
 5586:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 5587:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
 5588:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 5589:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 5590:    fclose(ficresprobmorprev);
 5591:    fflush(ficgp);
 5592:    fflush(fichtm); 
 5593:  }  /* end varevsij */
 5594: 
 5595: /************ Variance of prevlim ******************/
 5596:  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[], int nres)
 5597: {
 5598:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
 5599:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 5600: 
 5601:   double **dnewm,**doldm;
 5602:   int i, j, nhstepm, hstepm;
 5603:   double *xp;
 5604:   double *gp, *gm;
 5605:   double **gradg, **trgradg;
 5606:   double **mgm, **mgp;
 5607:   double age,agelim;
 5608:   int theta;
 5609:   
 5610:   pstamp(ficresvpl);
 5611:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
 5612:   fprintf(ficresvpl,"# Age");
 5613:   for(i=1; i<=nlstate;i++)
 5614:       fprintf(ficresvpl," %1d-%1d",i,i);
 5615:   fprintf(ficresvpl,"\n");
 5616: 
 5617:   xp=vector(1,npar);
 5618:   dnewm=matrix(1,nlstate,1,npar);
 5619:   doldm=matrix(1,nlstate,1,nlstate);
 5620:   
 5621:   hstepm=1*YEARM; /* Every year of age */
 5622:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 5623:   agelim = AGESUP;
 5624:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 5625:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 5626:     if (stepm >= YEARM) hstepm=1;
 5627:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 5628:     gradg=matrix(1,npar,1,nlstate);
 5629:     mgp=matrix(1,npar,1,nlstate);
 5630:     mgm=matrix(1,npar,1,nlstate);
 5631:     gp=vector(1,nlstate);
 5632:     gm=vector(1,nlstate);
 5633: 
 5634:     for(theta=1; theta <=npar; theta++){
 5635:       for(i=1; i<=npar; i++){ /* Computes gradient */
 5636: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 5637:       }
 5638:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
 5639: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
 5640:       else
 5641: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
 5642:       for(i=1;i<=nlstate;i++){
 5643: 	gp[i] = prlim[i][i];
 5644: 	mgp[theta][i] = prlim[i][i];
 5645:       }
 5646:       for(i=1; i<=npar; i++) /* Computes gradient */
 5647: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 5648:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
 5649: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
 5650:       else
 5651: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
 5652:       for(i=1;i<=nlstate;i++){
 5653: 	gm[i] = prlim[i][i];
 5654: 	mgm[theta][i] = prlim[i][i];
 5655:       }
 5656:       for(i=1;i<=nlstate;i++)
 5657: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 5658:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
 5659:     } /* End theta */
 5660: 
 5661:     trgradg =matrix(1,nlstate,1,npar);
 5662: 
 5663:     for(j=1; j<=nlstate;j++)
 5664:       for(theta=1; theta <=npar; theta++)
 5665: 	trgradg[j][theta]=gradg[theta][j];
 5666:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
 5667:     /*   printf("\nmgm mgp %d ",(int)age); */
 5668:     /*   for(j=1; j<=nlstate;j++){ */
 5669:     /* 	printf(" %d ",j); */
 5670:     /* 	for(theta=1; theta <=npar; theta++) */
 5671:     /* 	  printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
 5672:     /* 	printf("\n "); */
 5673:     /*   } */
 5674:     /* } */
 5675:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
 5676:     /*   printf("\n gradg %d ",(int)age); */
 5677:     /*   for(j=1; j<=nlstate;j++){ */
 5678:     /* 	printf("%d ",j); */
 5679:     /* 	for(theta=1; theta <=npar; theta++) */
 5680:     /* 	  printf("%d %lf ",theta,gradg[theta][j]); */
 5681:     /* 	printf("\n "); */
 5682:     /*   } */
 5683:     /* } */
 5684: 
 5685:     for(i=1;i<=nlstate;i++)
 5686:       varpl[i][(int)age] =0.;
 5687:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
 5688:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 5689:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 5690:     }else{
 5691:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 5692:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 5693:     }
 5694:     for(i=1;i<=nlstate;i++)
 5695:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 5696: 
 5697:     fprintf(ficresvpl,"%.0f ",age );
 5698:     for(i=1; i<=nlstate;i++)
 5699:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
 5700:     fprintf(ficresvpl,"\n");
 5701:     free_vector(gp,1,nlstate);
 5702:     free_vector(gm,1,nlstate);
 5703:     free_matrix(mgm,1,npar,1,nlstate);
 5704:     free_matrix(mgp,1,npar,1,nlstate);
 5705:     free_matrix(gradg,1,npar,1,nlstate);
 5706:     free_matrix(trgradg,1,nlstate,1,npar);
 5707:   } /* End age */
 5708: 
 5709:   free_vector(xp,1,npar);
 5710:   free_matrix(doldm,1,nlstate,1,npar);
 5711:   free_matrix(dnewm,1,nlstate,1,nlstate);
 5712: 
 5713: }
 5714: 
 5715: /************ Variance of one-step probabilities  ******************/
 5716: 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[])
 5717:  {
 5718:    int i, j=0,  k1, l1, tj;
 5719:    int k2, l2, j1,  z1;
 5720:    int k=0, l;
 5721:    int first=1, first1, first2;
 5722:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
 5723:    double **dnewm,**doldm;
 5724:    double *xp;
 5725:    double *gp, *gm;
 5726:    double **gradg, **trgradg;
 5727:    double **mu;
 5728:    double age, cov[NCOVMAX+1];
 5729:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
 5730:    int theta;
 5731:    char fileresprob[FILENAMELENGTH];
 5732:    char fileresprobcov[FILENAMELENGTH];
 5733:    char fileresprobcor[FILENAMELENGTH];
 5734:    double ***varpij;
 5735: 
 5736:    strcpy(fileresprob,"PROB_"); 
 5737:    strcat(fileresprob,fileres);
 5738:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
 5739:      printf("Problem with resultfile: %s\n", fileresprob);
 5740:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
 5741:    }
 5742:    strcpy(fileresprobcov,"PROBCOV_"); 
 5743:    strcat(fileresprobcov,fileresu);
 5744:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
 5745:      printf("Problem with resultfile: %s\n", fileresprobcov);
 5746:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 5747:    }
 5748:    strcpy(fileresprobcor,"PROBCOR_"); 
 5749:    strcat(fileresprobcor,fileresu);
 5750:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 5751:      printf("Problem with resultfile: %s\n", fileresprobcor);
 5752:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 5753:    }
 5754:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 5755:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 5756:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 5757:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 5758:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 5759:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 5760:    pstamp(ficresprob);
 5761:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
 5762:    fprintf(ficresprob,"# Age");
 5763:    pstamp(ficresprobcov);
 5764:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
 5765:    fprintf(ficresprobcov,"# Age");
 5766:    pstamp(ficresprobcor);
 5767:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 5768:    fprintf(ficresprobcor,"# Age");
 5769: 
 5770: 
 5771:    for(i=1; i<=nlstate;i++)
 5772:      for(j=1; j<=(nlstate+ndeath);j++){
 5773:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
 5774:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
 5775:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
 5776:      }  
 5777:    /* fprintf(ficresprob,"\n");
 5778:       fprintf(ficresprobcov,"\n");
 5779:       fprintf(ficresprobcor,"\n");
 5780:    */
 5781:    xp=vector(1,npar);
 5782:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 5783:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 5784:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
 5785:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 5786:    first=1;
 5787:    fprintf(ficgp,"\n# Routine varprob");
 5788:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
 5789:    fprintf(fichtm,"\n");
 5790: 
 5791:    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);
 5792:    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);
 5793:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
 5794: and drawn. It helps understanding how is the covariance between two incidences.\
 5795:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
 5796:    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. \
 5797: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
 5798: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
 5799: standard deviations wide on each axis. <br>\
 5800:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
 5801:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 5802: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
 5803: 
 5804:    cov[1]=1;
 5805:    /* tj=cptcoveff; */
 5806:    tj = (int) pow(2,cptcoveff);
 5807:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
 5808:    j1=0;
 5809:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
 5810:      if  (cptcovn>0) {
 5811:        fprintf(ficresprob, "\n#********** Variable "); 
 5812:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5813:        fprintf(ficresprob, "**********\n#\n");
 5814:        fprintf(ficresprobcov, "\n#********** Variable "); 
 5815:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5816:        fprintf(ficresprobcov, "**********\n#\n");
 5817: 			
 5818:        fprintf(ficgp, "\n#********** Variable "); 
 5819:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5820:        fprintf(ficgp, "**********\n#\n");
 5821: 			
 5822: 			
 5823:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
 5824:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5825:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
 5826: 			
 5827:        fprintf(ficresprobcor, "\n#********** Variable ");    
 5828:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5829:        fprintf(ficresprobcor, "**********\n#");    
 5830:        if(invalidvarcomb[j1]){
 5831: 	 fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
 5832: 	 fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
 5833: 	 continue;
 5834:        }
 5835:      }
 5836:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
 5837:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 5838:      gp=vector(1,(nlstate)*(nlstate+ndeath));
 5839:      gm=vector(1,(nlstate)*(nlstate+ndeath));
 5840:      for (age=bage; age<=fage; age ++){ 
 5841:        cov[2]=age;
 5842:        if(nagesqr==1)
 5843: 	 cov[3]= age*age;
 5844:        for (k=1; k<=cptcovn;k++) {
 5845: 	 cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
 5846: 	 /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
 5847: 								    * 1  1 1 1 1
 5848: 								    * 2  2 1 1 1
 5849: 								    * 3  1 2 1 1
 5850: 								    */
 5851: 	 /* nbcode[1][1]=0 nbcode[1][2]=1;*/
 5852:        }
 5853:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 5854:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 5855:        for (k=1; k<=cptcovprod;k++)
 5856: 	 cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
 5857: 			
 5858: 			
 5859:        for(theta=1; theta <=npar; theta++){
 5860: 	 for(i=1; i<=npar; i++)
 5861: 	   xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
 5862: 				
 5863: 	 pmij(pmmij,cov,ncovmodel,xp,nlstate);
 5864: 				
 5865: 	 k=0;
 5866: 	 for(i=1; i<= (nlstate); i++){
 5867: 	   for(j=1; j<=(nlstate+ndeath);j++){
 5868: 	     k=k+1;
 5869: 	     gp[k]=pmmij[i][j];
 5870: 	   }
 5871: 	 }
 5872: 				
 5873: 	 for(i=1; i<=npar; i++)
 5874: 	   xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
 5875: 				
 5876: 	 pmij(pmmij,cov,ncovmodel,xp,nlstate);
 5877: 	 k=0;
 5878: 	 for(i=1; i<=(nlstate); i++){
 5879: 	   for(j=1; j<=(nlstate+ndeath);j++){
 5880: 	     k=k+1;
 5881: 	     gm[k]=pmmij[i][j];
 5882: 	   }
 5883: 	 }
 5884: 				
 5885: 	 for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
 5886: 	   gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
 5887:        }
 5888: 
 5889:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
 5890: 	 for(theta=1; theta <=npar; theta++)
 5891: 	   trgradg[j][theta]=gradg[theta][j];
 5892: 			
 5893:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
 5894:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
 5895: 			
 5896:        pmij(pmmij,cov,ncovmodel,x,nlstate);
 5897: 			
 5898:        k=0;
 5899:        for(i=1; i<=(nlstate); i++){
 5900: 	 for(j=1; j<=(nlstate+ndeath);j++){
 5901: 	   k=k+1;
 5902: 	   mu[k][(int) age]=pmmij[i][j];
 5903: 	 }
 5904:        }
 5905:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 5906: 	 for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 5907: 	   varpij[i][j][(int)age] = doldm[i][j];
 5908: 			
 5909:        /*printf("\n%d ",(int)age);
 5910: 	 for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 5911: 	 printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 5912: 	 fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 5913: 	 }*/
 5914: 			
 5915:        fprintf(ficresprob,"\n%d ",(int)age);
 5916:        fprintf(ficresprobcov,"\n%d ",(int)age);
 5917:        fprintf(ficresprobcor,"\n%d ",(int)age);
 5918: 			
 5919:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
 5920: 	 fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
 5921:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 5922: 	 fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
 5923: 	 fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
 5924:        }
 5925:        i=0;
 5926:        for (k=1; k<=(nlstate);k++){
 5927: 	 for (l=1; l<=(nlstate+ndeath);l++){ 
 5928: 	   i++;
 5929: 	   fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 5930: 	   fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
 5931: 	   for (j=1; j<=i;j++){
 5932: 	     /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
 5933: 	     fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
 5934: 	     fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
 5935: 	   }
 5936: 	 }
 5937:        }/* end of loop for state */
 5938:      } /* end of loop for age */
 5939:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
 5940:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 5941:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 5942:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 5943:     
 5944:      /* Confidence intervalle of pij  */
 5945:      /*
 5946:        fprintf(ficgp,"\nunset parametric;unset label");
 5947:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
 5948:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 5949:        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);
 5950:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
 5951:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
 5952:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
 5953:      */
 5954: 		
 5955:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
 5956:      first1=1;first2=2;
 5957:      for (k2=1; k2<=(nlstate);k2++){
 5958:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
 5959: 	 if(l2==k2) continue;
 5960: 	 j=(k2-1)*(nlstate+ndeath)+l2;
 5961: 	 for (k1=1; k1<=(nlstate);k1++){
 5962: 	   for (l1=1; l1<=(nlstate+ndeath);l1++){ 
 5963: 	     if(l1==k1) continue;
 5964: 	     i=(k1-1)*(nlstate+ndeath)+l1;
 5965: 	     if(i<=j) continue;
 5966: 	     for (age=bage; age<=fage; age ++){ 
 5967: 	       if ((int)age %5==0){
 5968: 		 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
 5969: 		 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
 5970: 		 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
 5971: 		 mu1=mu[i][(int) age]/stepm*YEARM ;
 5972: 		 mu2=mu[j][(int) age]/stepm*YEARM;
 5973: 		 c12=cv12/sqrt(v1*v2);
 5974: 		 /* Computing eigen value of matrix of covariance */
 5975: 		 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 5976: 		 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 5977: 		 if ((lc2 <0) || (lc1 <0) ){
 5978: 		   if(first2==1){
 5979: 		     first1=0;
 5980: 		     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);
 5981: 		   }
 5982: 		   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);
 5983: 		   /* lc1=fabs(lc1); */ /* If we want to have them positive */
 5984: 		   /* lc2=fabs(lc2); */
 5985: 		 }
 5986: 								
 5987: 		 /* Eigen vectors */
 5988: 		 v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
 5989: 		 /*v21=sqrt(1.-v11*v11); *//* error */
 5990: 		 v21=(lc1-v1)/cv12*v11;
 5991: 		 v12=-v21;
 5992: 		 v22=v11;
 5993: 		 tnalp=v21/v11;
 5994: 		 if(first1==1){
 5995: 		   first1=0;
 5996: 		   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);
 5997: 		 }
 5998: 		 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);
 5999: 		 /*printf(fignu*/
 6000: 		 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
 6001: 		 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
 6002: 		 if(first==1){
 6003: 		   first=0;
 6004: 		   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
 6005: 		   fprintf(ficgp,"\nset parametric;unset label");
 6006: 		   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);
 6007: 		   fprintf(ficgp,"\nset ter svg size 640, 480");
 6008: 		   fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
 6009:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">																		\
 6010: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
 6011: 			   subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,	\
 6012: 			   subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 6013: 		   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 6014: 		   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
 6015: 		   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 6016: 		   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 6017: 		   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 6018: 		   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",	\
 6019: 			   mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),										\
 6020: 			   mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 6021: 		 }else{
 6022: 		   first=0;
 6023: 		   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
 6024: 		   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 6025: 		   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 6026: 		   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", \
 6027: 			   mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),					\
 6028: 			   mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 6029: 		 }/* if first */
 6030: 	       } /* age mod 5 */
 6031: 	     } /* end loop age */
 6032: 	     fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 6033: 	     first=1;
 6034: 	   } /*l12 */
 6035: 	 } /* k12 */
 6036:        } /*l1 */
 6037:      }/* k1 */
 6038:    }  /* loop on combination of covariates j1 */
 6039:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 6040:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
 6041:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 6042:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
 6043:    free_vector(xp,1,npar);
 6044:    fclose(ficresprob);
 6045:    fclose(ficresprobcov);
 6046:    fclose(ficresprobcor);
 6047:    fflush(ficgp);
 6048:    fflush(fichtmcov);
 6049:  }
 6050: 
 6051: 
 6052: /******************* Printing html file ***********/
 6053: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
 6054: 		  int lastpass, int stepm, int weightopt, char model[],\
 6055: 		  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 6056: 		  int popforecast, int prevfcast, int backcast, int estepm , \
 6057: 		  double jprev1, double mprev1,double anprev1, double dateprev1, \
 6058: 		  double jprev2, double mprev2,double anprev2, double dateprev2){
 6059:   int jj1, k1, i1, cpt, k4, nres;
 6060: 
 6061:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
 6062:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
 6063: </ul>");
 6064:    fprintf(fichtm,"<ul><li> model=1+age+%s\n \
 6065: </ul>", model);
 6066:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
 6067:    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",
 6068: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
 6069:    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) ",
 6070: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
 6071:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
 6072:    fprintf(fichtm,"\
 6073:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 6074: 	   stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
 6075:    fprintf(fichtm,"\
 6076:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 6077: 	   stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
 6078:    fprintf(fichtm,"\
 6079:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 6080: 	   subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
 6081:    fprintf(fichtm,"\
 6082:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 6083: 	   subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
 6084:    fprintf(fichtm,"\
 6085:  - (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): \
 6086:    <a href=\"%s\">%s</a> <br>\n",
 6087: 	   estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
 6088:    if(prevfcast==1){
 6089:      fprintf(fichtm,"\
 6090:  - Prevalence projections by age and states:				\
 6091:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
 6092:    }
 6093: 
 6094:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
 6095: 
 6096:    m=pow(2,cptcoveff);
 6097:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 6098: 
 6099:    jj1=0;
 6100: 
 6101:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
 6102:    for(k1=1; k1<=m;k1++){
 6103:      if(TKresult[nres]!= k1)
 6104:        continue;
 6105: 
 6106:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
 6107:      jj1++;
 6108:      if (cptcovn > 0) {
 6109:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 6110:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
 6111: 	 fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
 6112: 	 printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
 6113: 	 /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
 6114: 	 /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
 6115:        }
 6116:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 6117: 	fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6118: 	printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
 6119:       }
 6120:        
 6121:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
 6122:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 6123:        if(invalidvarcomb[k1]){
 6124: 	 fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
 6125: 	 printf("\nCombination (%d) ignored because no cases \n",k1); 
 6126: 	 continue;
 6127:        }
 6128:      }
 6129:      /* aij, bij */
 6130:      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> \
 6131: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
 6132:      /* Pij */
 6133:      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> \
 6134: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
 6135:      /* Quasi-incidences */
 6136:      fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
 6137:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
 6138:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
 6139: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
 6140: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
 6141:      /* Survival functions (period) in state j */
 6142:      for(cpt=1; cpt<=nlstate;cpt++){
 6143:        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> \
 6144: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
 6145:      }
 6146:      /* State specific survival functions (period) */
 6147:      for(cpt=1; cpt<=nlstate;cpt++){
 6148:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
 6149:  Or probability to survive in various states (1 to %d) being in state %d at different ages.	\
 6150:  <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);
 6151:      }
 6152:      /* Period (stable) prevalence in each health state */
 6153:      for(cpt=1; cpt<=nlstate;cpt++){
 6154:        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> \
 6155: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
 6156:      }
 6157:      if(backcast==1){
 6158:        /* Period (stable) back prevalence in each health state */
 6159:        for(cpt=1; cpt<=nlstate;cpt++){
 6160: 	 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> \
 6161: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1);
 6162:        }
 6163:      }
 6164:      if(prevfcast==1){
 6165:        /* Projection of prevalence up to period (stable) prevalence in each health state */
 6166:        for(cpt=1; cpt<=nlstate;cpt++){
 6167: 	 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> \
 6168: <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);
 6169:        }
 6170:      }
 6171: 	 
 6172:      for(cpt=1; cpt<=nlstate;cpt++) {
 6173:        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> \
 6174: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
 6175:      }
 6176:      /* } /\* end i1 *\/ */
 6177:    }/* End k1 */
 6178:    fprintf(fichtm,"</ul>");
 6179: 
 6180:    fprintf(fichtm,"\
 6181: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
 6182:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
 6183:  - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
 6184: But because parameters are usually highly correlated (a higher incidence of disability \
 6185: and a higher incidence of recovery can give very close observed transition) it might \
 6186: be very useful to look not only at linear confidence intervals estimated from the \
 6187: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
 6188: (parameters) of the logistic regression, it might be more meaningful to visualize the \
 6189: covariance matrix of the one-step probabilities. \
 6190: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
 6191: 
 6192:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 6193: 	   subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
 6194:    fprintf(fichtm,"\
 6195:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 6196: 	   subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
 6197: 
 6198:    fprintf(fichtm,"\
 6199:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 6200: 	   subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
 6201:    fprintf(fichtm,"\
 6202:  - 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): \
 6203:    <a href=\"%s\">%s</a> <br>\n</li>",
 6204: 	   estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
 6205:    fprintf(fichtm,"\
 6206:  - (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): \
 6207:    <a href=\"%s\">%s</a> <br>\n</li>",
 6208: 	   estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
 6209:    fprintf(fichtm,"\
 6210:  - 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",
 6211: 	   estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
 6212:    fprintf(fichtm,"\
 6213:  - 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",
 6214: 	   estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
 6215:    fprintf(fichtm,"\
 6216:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
 6217: 	   subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
 6218: 
 6219: /*  if(popforecast==1) fprintf(fichtm,"\n */
 6220: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
 6221: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
 6222: /* 	<br>",fileres,fileres,fileres,fileres); */
 6223: /*  else  */
 6224: /*    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); */
 6225:    fflush(fichtm);
 6226:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
 6227: 
 6228:    m=pow(2,cptcoveff);
 6229:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 6230: 
 6231:    jj1=0;
 6232: 
 6233:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
 6234:    for(k1=1; k1<=m;k1++){
 6235:      if(TKresult[nres]!= k1)
 6236:        continue;
 6237:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
 6238:      jj1++;
 6239:      if (cptcovn > 0) {
 6240:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 6241:        for (cpt=1; cpt<=cptcoveff;cpt++)  /**< cptcoveff number of variables */
 6242: 	 fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
 6243: 	 /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
 6244:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 6245: 	fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6246:       }
 6247: 
 6248:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 6249: 
 6250:        if(invalidvarcomb[k1]){
 6251: 	 fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
 6252: 	 continue;
 6253:        }
 6254:      }
 6255:      for(cpt=1; cpt<=nlstate;cpt++) {
 6256:        fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
 6257: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d.svg\"> %s_%d-%d.svg</a>\n <br>\
 6258: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);  
 6259:      }
 6260:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
 6261: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
 6262: true period expectancies (those weighted with period prevalences are also\
 6263:  drawn in addition to the population based expectancies computed using\
 6264:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg</a>\n<br>\
 6265: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
 6266:      /* } /\* end i1 *\/ */
 6267:    }/* End k1 */
 6268:    fprintf(fichtm,"</ul>");
 6269:    fflush(fichtm);
 6270: }
 6271: 
 6272: /******************* Gnuplot file **************/
 6273: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
 6274: 
 6275:   char dirfileres[132],optfileres[132];
 6276:   char gplotcondition[132];
 6277:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,k4=0,ij=0, ijp=0, l=0;
 6278:   int lv=0, vlv=0, kl=0;
 6279:   int ng=0;
 6280:   int vpopbased;
 6281:   int ioffset; /* variable offset for columns */
 6282:   int nres=0; /* Index of resultline */
 6283: 
 6284: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
 6285: /*     printf("Problem with file %s",optionfilegnuplot); */
 6286: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
 6287: /*   } */
 6288: 
 6289:   /*#ifdef windows */
 6290:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 6291:   /*#endif */
 6292:   m=pow(2,cptcoveff);
 6293: 
 6294:   /* Contribution to likelihood */
 6295:   /* Plot the probability implied in the likelihood */
 6296:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
 6297:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
 6298:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
 6299:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
 6300: /* nice for mle=4 plot by number of matrix products.
 6301:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
 6302: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
 6303:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
 6304:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
 6305:   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));
 6306:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
 6307:   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));
 6308:   for (i=1; i<= nlstate ; i ++) {
 6309:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
 6310:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
 6311:     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);
 6312:     for (j=2; j<= nlstate+ndeath ; j ++) {
 6313:       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);
 6314:     }
 6315:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
 6316:   }
 6317:   /* 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 */		 
 6318:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
 6319:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
 6320:   fprintf(ficgp,"\nset out;unset log\n");
 6321:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
 6322: 
 6323:   strcpy(dirfileres,optionfilefiname);
 6324:   strcpy(optfileres,"vpl");
 6325:   /* 1eme*/
 6326:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
 6327:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
 6328:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 6329: 	/* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
 6330: 	if(TKresult[nres]!= k1)
 6331: 	  continue;
 6332: 	/* We are interested in selected combination by the resultline */
 6333: 	printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt);
 6334: 	fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
 6335: 	for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 6336: 	  lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
 6337: 	  /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6338: 	  /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6339: 	  /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6340: 	  vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
 6341: 	  /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
 6342: 	  printf(" V%d=%d ",Tvaraff[k],vlv);
 6343: 	  fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6344: 	}
 6345: 	for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 6346: 	  printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6347: 	  fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6348: 	}	
 6349: 	printf("\n#\n");
 6350: 	fprintf(ficgp,"\n#\n");
 6351: 	if(invalidvarcomb[k1]){
 6352: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6353: 	  continue;
 6354: 	}
 6355:       
 6356: 	fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
 6357: 	fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
 6358: 	fprintf(ficgp,"set xlabel \"Age\" \n\
 6359: set ylabel \"Probability\" \n		  \
 6360: set ter svg size 640, 480\n						\
 6361: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
 6362:       
 6363: 	for (i=1; i<= nlstate ; i ++) {
 6364: 	  if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 6365: 	  else        fprintf(ficgp," %%*lf (%%*lf)");
 6366: 	}
 6367: 	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);
 6368: 	for (i=1; i<= nlstate ; i ++) {
 6369: 	  if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 6370: 	  else fprintf(ficgp," %%*lf (%%*lf)");
 6371: 	} 
 6372: 	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); 
 6373: 	for (i=1; i<= nlstate ; i ++) {
 6374: 	  if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 6375: 	  else fprintf(ficgp," %%*lf (%%*lf)");
 6376: 	}  
 6377: 	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));
 6378: 	if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
 6379: 	  /* 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); */
 6380: 	  fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1 */
 6381: 	  if(cptcoveff ==0){
 6382: 	    fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line ",	 2+(cpt-1),  cpt );
 6383: 	  }else{
 6384: 	    kl=0;
 6385: 	    for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
 6386: 	      lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
 6387: 	      /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6388: 	      /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6389: 	      /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6390: 	      vlv= nbcode[Tvaraff[k]][lv];
 6391: 	      kl++;
 6392: 	      /* 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 *\/ */
 6393: 	      /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
 6394: 	      /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
 6395: 	      /* ''  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*/
 6396: 	      if(k==cptcoveff){
 6397: 		fprintf(ficgp,"$%d==%d && $%d==%d)? $%d : 1/0) t 'Backward prevalence in state %d' ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv], \
 6398: 			4+(cpt-1),  cpt );  /* 4 or 6 ?*/
 6399: 	      }else{
 6400: 		fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
 6401: 		kl++;
 6402: 	      }
 6403: 	    } /* end covariate */
 6404: 	  } /* end if no covariate */
 6405: 	} /* end if backcast */
 6406: 	fprintf(ficgp,"\nset out \n");
 6407:       } /* nres */
 6408:     } /* k1 */
 6409:   } /* cpt */
 6410: 
 6411:   
 6412:   /*2 eme*/
 6413:   for (k1=1; k1<= m ; k1 ++){  
 6414:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 6415:       if(TKresult[nres]!= k1)
 6416: 	continue;
 6417:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
 6418:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 6419: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 6420: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6421: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6422: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6423: 	vlv= nbcode[Tvaraff[k]][lv];
 6424: 	fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6425:       }
 6426:       /* for(k=1; k <= ncovds; k++){ */
 6427:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 6428: 	printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6429: 	fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6430:       }
 6431:       fprintf(ficgp,"\n#\n");
 6432:       if(invalidvarcomb[k1]){
 6433: 	fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6434: 	continue;
 6435:       }
 6436: 			
 6437:       fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
 6438:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 6439: 	if(vpopbased==0)
 6440: 	  fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
 6441: 	else
 6442: 	  fprintf(ficgp,"\nreplot ");
 6443: 	for (i=1; i<= nlstate+1 ; i ++) {
 6444: 	  k=2*i;
 6445: 	  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);
 6446: 	  for (j=1; j<= nlstate+1 ; j ++) {
 6447: 	    if (j==i) fprintf(ficgp," %%lf (%%lf)");
 6448: 	    else fprintf(ficgp," %%*lf (%%*lf)");
 6449: 	  }   
 6450: 	  if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
 6451: 	  else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
 6452: 	  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);
 6453: 	  for (j=1; j<= nlstate+1 ; j ++) {
 6454: 	    if (j==i) fprintf(ficgp," %%lf (%%lf)");
 6455: 	    else fprintf(ficgp," %%*lf (%%*lf)");
 6456: 	  }   
 6457: 	  fprintf(ficgp,"\" t\"\" w l lt 0,");
 6458: 	  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);
 6459: 	  for (j=1; j<= nlstate+1 ; j ++) {
 6460: 	    if (j==i) fprintf(ficgp," %%lf (%%lf)");
 6461: 	    else fprintf(ficgp," %%*lf (%%*lf)");
 6462: 	  }   
 6463: 	  if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
 6464: 	  else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
 6465: 	} /* state */
 6466:       } /* vpopbased */
 6467:       fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
 6468:     } /* end nres */
 6469:   } /* k1 end 2 eme*/
 6470: 	
 6471: 	
 6472:   /*3eme*/
 6473:   for (k1=1; k1<= m ; k1 ++){
 6474:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 6475:       if(TKresult[nres]!= k)
 6476: 	continue;
 6477: 
 6478:       for (cpt=1; cpt<= nlstate ; cpt ++) {
 6479: 	fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
 6480: 	for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 6481: 	  lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 6482: 	  /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6483: 	  /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6484: 	  /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6485: 	  vlv= nbcode[Tvaraff[k]][lv];
 6486: 	  fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6487: 	}
 6488: 	for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 6489: 	  fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6490: 	}	
 6491: 	fprintf(ficgp,"\n#\n");
 6492: 	if(invalidvarcomb[k1]){
 6493: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6494: 	  continue;
 6495: 	}
 6496: 			
 6497: 	/*       k=2+nlstate*(2*cpt-2); */
 6498: 	k=2+(nlstate+1)*(cpt-1);
 6499: 	fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
 6500: 	fprintf(ficgp,"set ter svg size 640, 480\n\
 6501: 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);
 6502: 	/*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 6503: 	  for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 6504: 	  fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 6505: 	  fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 6506: 	  for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 6507: 	  fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 6508: 				
 6509: 	*/
 6510: 	for (i=1; i< nlstate ; i ++) {
 6511: 	  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);
 6512: 	  /*	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);*/
 6513: 				
 6514: 	} 
 6515: 	fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
 6516:       }
 6517:     } /* end nres */
 6518:   } /* end kl 3eme */
 6519:   
 6520:   /* 4eme */
 6521:   /* Survival functions (period) from state i in state j by initial state i */
 6522:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
 6523:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 6524:       if(TKresult[nres]!= k1)
 6525: 	continue;
 6526:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
 6527: 	fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
 6528: 	for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 6529: 	  lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 6530: 	  /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6531: 	  /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6532: 	  /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6533: 	  vlv= nbcode[Tvaraff[k]][lv];
 6534: 	  fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6535: 	}
 6536: 	for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 6537: 	  fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6538: 	}	
 6539: 	fprintf(ficgp,"\n#\n");
 6540: 	if(invalidvarcomb[k1]){
 6541: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6542: 	  continue;
 6543: 	}
 6544:       
 6545: 	fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
 6546: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
 6547: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
 6548: 	k=3;
 6549: 	for (i=1; i<= nlstate ; i ++){
 6550: 	  if(i==1){
 6551: 	    fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 6552: 	  }else{
 6553: 	    fprintf(ficgp,", '' ");
 6554: 	  }
 6555: 	  l=(nlstate+ndeath)*(i-1)+1;
 6556: 	  fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 6557: 	  for (j=2; j<= nlstate+ndeath ; j ++)
 6558: 	    fprintf(ficgp,"+$%d",k+l+j-1);
 6559: 	  fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
 6560: 	} /* nlstate */
 6561: 	fprintf(ficgp,"\nset out\n");
 6562:       } /* end cpt state*/ 
 6563:     } /* end nres */
 6564:   } /* end covariate k1 */  
 6565: 
 6566: /* 5eme */
 6567:   /* Survival functions (period) from state i in state j by final state j */
 6568:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
 6569:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 6570:       if(TKresult[nres]!= k1)
 6571: 	continue;
 6572:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
 6573: 	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);
 6574: 	for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 6575: 	  lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 6576: 	  /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6577: 	  /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6578: 	  /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6579: 	  vlv= nbcode[Tvaraff[k]][lv];
 6580: 	  fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6581: 	}
 6582: 	for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 6583: 	  fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6584: 	}	
 6585: 	fprintf(ficgp,"\n#\n");
 6586: 	if(invalidvarcomb[k1]){
 6587: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6588: 	  continue;
 6589: 	}
 6590:       
 6591: 	fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
 6592: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
 6593: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
 6594: 	k=3;
 6595: 	for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
 6596: 	  if(j==1)
 6597: 	    fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 6598: 	  else
 6599: 	    fprintf(ficgp,", '' ");
 6600: 	  l=(nlstate+ndeath)*(cpt-1) +j;
 6601: 	  fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
 6602: 	  /* for (i=2; i<= nlstate+ndeath ; i ++) */
 6603: 	  /*   fprintf(ficgp,"+$%d",k+l+i-1); */
 6604: 	  fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
 6605: 	} /* nlstate */
 6606: 	fprintf(ficgp,", '' ");
 6607: 	fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
 6608: 	for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
 6609: 	  l=(nlstate+ndeath)*(cpt-1) +j;
 6610: 	  if(j < nlstate)
 6611: 	    fprintf(ficgp,"$%d +",k+l);
 6612: 	  else
 6613: 	    fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
 6614: 	}
 6615: 	fprintf(ficgp,"\nset out\n");
 6616:       } /* end cpt state*/ 
 6617:     } /* end covariate */  
 6618:   } /* end nres */
 6619:   
 6620: /* 6eme */
 6621:   /* CV preval stable (period) for each covariate */
 6622:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
 6623:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 6624:     if(TKresult[nres]!= k1)
 6625:       continue;
 6626:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 6627:       
 6628:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
 6629:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 6630: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 6631: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6632: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6633: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6634: 	vlv= nbcode[Tvaraff[k]][lv];
 6635: 	fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6636:       }
 6637:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 6638: 	fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6639:       }	
 6640:       fprintf(ficgp,"\n#\n");
 6641:       if(invalidvarcomb[k1]){
 6642: 	fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6643: 	continue;
 6644:       }
 6645:       
 6646:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
 6647:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 6648: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
 6649:       k=3; /* Offset */
 6650:       for (i=1; i<= nlstate ; i ++){
 6651: 	if(i==1)
 6652: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 6653: 	else
 6654: 	  fprintf(ficgp,", '' ");
 6655: 	l=(nlstate+ndeath)*(i-1)+1;
 6656: 	fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 6657: 	for (j=2; j<= nlstate ; j ++)
 6658: 	  fprintf(ficgp,"+$%d",k+l+j-1);
 6659: 	fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
 6660:       } /* nlstate */
 6661:       fprintf(ficgp,"\nset out\n");
 6662:     } /* end cpt state*/ 
 6663:   } /* end covariate */  
 6664:   
 6665:   
 6666: /* 7eme */
 6667:   if(backcast == 1){
 6668:     /* CV back preval stable (period) for each covariate */
 6669:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
 6670:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 6671:       if(TKresult[nres]!= k1)
 6672: 	continue;
 6673:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 6674: 	fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
 6675: 	for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 6676: 	  lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 6677: 	  /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6678: 	  /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6679: 	  /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6680: 	  vlv= nbcode[Tvaraff[k]][lv];
 6681: 	  fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6682: 	}
 6683: 	for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 6684: 	  fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6685: 	}	
 6686: 	fprintf(ficgp,"\n#\n");
 6687: 	if(invalidvarcomb[k1]){
 6688: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6689: 	  continue;
 6690: 	}
 6691: 	
 6692: 	fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1);
 6693: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 6694: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
 6695: 	k=3; /* Offset */
 6696: 	for (i=1; i<= nlstate ; i ++){
 6697: 	  if(i==1)
 6698: 	    fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
 6699: 	  else
 6700: 	    fprintf(ficgp,", '' ");
 6701: 	  /* l=(nlstate+ndeath)*(i-1)+1; */
 6702: 	  l=(nlstate+ndeath)*(cpt-1)+1;
 6703: 	  /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
 6704: 	  /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
 6705: 	  fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */
 6706: 	  /* for (j=2; j<= nlstate ; j ++) */
 6707: 	  /* 	fprintf(ficgp,"+$%d",k+l+j-1); */
 6708: 	  /* 	/\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
 6709: 	  fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
 6710: 	} /* nlstate */
 6711: 	fprintf(ficgp,"\nset out\n");
 6712:       } /* end cpt state*/ 
 6713:     } /* end covariate */  
 6714:   } /* End if backcast */
 6715:   
 6716:   /* 8eme */
 6717:   if(prevfcast==1){
 6718:     /* Projection from cross-sectional to stable (period) for each covariate */
 6719:     
 6720:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
 6721:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 6722:       if(TKresult[nres]!= k1)
 6723: 	continue;
 6724:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 6725: 	fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
 6726: 	for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
 6727: 	  lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
 6728: 	  /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6729: 	  /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6730: 	  /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6731: 	  vlv= nbcode[Tvaraff[k]][lv];
 6732: 	  fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6733: 	}
 6734: 	for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 6735: 	  fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6736: 	}	
 6737: 	fprintf(ficgp,"\n#\n");
 6738: 	if(invalidvarcomb[k1]){
 6739: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6740: 	  continue;
 6741: 	}
 6742: 	
 6743: 	fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
 6744: 	fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
 6745: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
 6746: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
 6747: 	for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
 6748: 	  /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 6749: 	  /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 6750: 	  /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 6751: 	  /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 6752: 	  if(i==1){
 6753: 	    fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
 6754: 	  }else{
 6755: 	    fprintf(ficgp,",\\\n '' ");
 6756: 	  }
 6757: 	  if(cptcoveff ==0){ /* No covariate */
 6758: 	    ioffset=2; /* Age is in 2 */
 6759: 	    /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
 6760: 	    /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
 6761: 	    /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
 6762: 	    /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
 6763: 	    fprintf(ficgp," u %d:(", ioffset); 
 6764: 	    if(i==nlstate+1)
 6765: 	      fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ",	\
 6766: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
 6767: 	    else
 6768: 	      fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",	\
 6769: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
 6770: 	  }else{ /* more than 2 covariates */
 6771: 	    if(cptcoveff ==1){
 6772: 	      ioffset=4; /* Age is in 4 */
 6773: 	    }else{
 6774: 	      ioffset=6; /* Age is in 6 */
 6775: 	      /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 6776: 	      /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
 6777: 	    }   
 6778: 	    fprintf(ficgp," u %d:(",ioffset); 
 6779: 	    kl=0;
 6780: 	    strcpy(gplotcondition,"(");
 6781: 	    for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
 6782: 	      lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
 6783: 	      /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6784: 	      /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6785: 	      /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6786: 	      vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
 6787: 	      kl++;
 6788: 	      sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
 6789: 	      kl++;
 6790: 	      if(k <cptcoveff && cptcoveff>1)
 6791: 		sprintf(gplotcondition+strlen(gplotcondition)," && ");
 6792: 	    }
 6793: 	    strcpy(gplotcondition+strlen(gplotcondition),")");
 6794: 	    /* 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 *\/ */
 6795: 	    /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
 6796: 	    /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
 6797: 	    /* ''  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*/
 6798: 	    if(i==nlstate+1){
 6799: 	      fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ", gplotcondition, \
 6800: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
 6801: 	    }else{
 6802: 	      fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
 6803: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
 6804: 	    }
 6805: 	  } /* end if covariate */
 6806: 	} /* nlstate */
 6807: 	fprintf(ficgp,"\nset out\n");
 6808:       } /* end cpt state*/
 6809:     } /* end covariate */
 6810:   } /* End if prevfcast */
 6811:   
 6812:   
 6813:   /* 9eme writing MLE parameters */
 6814:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
 6815:   for(i=1,jk=1; i <=nlstate; i++){
 6816:     fprintf(ficgp,"# initial state %d\n",i);
 6817:     for(k=1; k <=(nlstate+ndeath); k++){
 6818:       if (k != i) {
 6819: 	fprintf(ficgp,"#   current state %d\n",k);
 6820: 	for(j=1; j <=ncovmodel; j++){
 6821: 	  fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
 6822: 	  jk++; 
 6823: 	}
 6824: 	fprintf(ficgp,"\n");
 6825:       }
 6826:     }
 6827:   }
 6828:   fprintf(ficgp,"##############\n#\n");
 6829:   
 6830:   /*goto avoid;*/
 6831:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
 6832:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
 6833:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
 6834:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
 6835:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
 6836:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
 6837:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 6838:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 6839:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 6840:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 6841:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
 6842:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 6843:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
 6844:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
 6845:   fprintf(ficgp,"#\n");
 6846:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
 6847:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
 6848:     fprintf(ficgp,"#model=%s \n",model);
 6849:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
 6850:     fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
 6851:     for(jk=1; jk <=m; jk++)  /* For each combination of covariate */
 6852:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 6853:       if(TKresult[nres]!= jk)
 6854: 	continue;
 6855:       fprintf(ficgp,"# Combination of dummy  jk=%d and ",jk);
 6856:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 6857: 	fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6858:       }	
 6859:       fprintf(ficgp,"\n#\n");
 6860:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
 6861:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
 6862:       if (ng==1){
 6863: 	fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
 6864: 	fprintf(ficgp,"\nunset log y");
 6865:       }else if (ng==2){
 6866: 	fprintf(ficgp,"\nset ylabel \"Probability\"\n");
 6867: 	fprintf(ficgp,"\nset log y");
 6868:       }else if (ng==3){
 6869: 	fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
 6870: 	fprintf(ficgp,"\nset log y");
 6871:       }else
 6872: 	fprintf(ficgp,"\nunset title ");
 6873:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
 6874:       i=1;
 6875:       for(k2=1; k2<=nlstate; k2++) {
 6876: 	k3=i;
 6877: 	for(k=1; k<=(nlstate+ndeath); k++) {
 6878: 	  if (k != k2){
 6879: 	    switch( ng) {
 6880: 	    case 1:
 6881: 	      if(nagesqr==0)
 6882: 		fprintf(ficgp," p%d+p%d*x",i,i+1);
 6883: 	      else /* nagesqr =1 */
 6884: 		fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
 6885: 	      break;
 6886: 	    case 2: /* ng=2 */
 6887: 	      if(nagesqr==0)
 6888: 		fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
 6889: 	      else /* nagesqr =1 */
 6890: 		fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
 6891: 	      break;
 6892: 	    case 3:
 6893: 	      if(nagesqr==0)
 6894: 		fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
 6895: 	      else /* nagesqr =1 */
 6896: 		fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
 6897: 	      break;
 6898: 	    }
 6899: 	    ij=1;/* To be checked else nbcode[0][0] wrong */
 6900: 	    ijp=1; /* product no age */
 6901: 	    /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
 6902: 	    for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
 6903: 	      /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
 6904: 	      if(j==Tage[ij]) { /* Product by age */
 6905: 		if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
 6906: 		  if(DummyV[j]==0){
 6907: 		    fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
 6908: 		  }else{ /* quantitative */
 6909: 		    fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
 6910: 		    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
 6911: 		  }
 6912: 		  ij++;
 6913: 		}
 6914: 	      }else if(j==Tprod[ijp]) { /* */ 
 6915: 		/* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
 6916: 		if(ijp <=cptcovprod) { /* Product */
 6917: 		  if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
 6918: 		    if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
 6919: 		      /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(jk,j)],nbcode[Tvard[ijp][2]][codtabm(jk,j)]); */
 6920: 		      fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
 6921: 		    }else{ /* Vn is dummy and Vm is quanti */
 6922: 		      /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(jk,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
 6923: 		      fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
 6924: 		    }
 6925: 		  }else{ /* Vn*Vm Vn is quanti */
 6926: 		    if(DummyV[Tvard[ijp][2]]==0){
 6927: 		      fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
 6928: 		    }else{ /* Both quanti */
 6929: 		      fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
 6930: 		    }
 6931: 		  }
 6932: 		  ijp++;
 6933:   		}
 6934: 	      } else{  /* simple covariate */
 6935: 		/* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(jk,j)]); /\* Valgrind bug nbcode *\/ */
 6936: 		if(Dummy[j]==0){
 6937: 		  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
 6938: 		}else{ /* quantitative */
 6939: 		  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
 6940: 		  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
 6941: 		}
 6942: 	      } /* end simple */
 6943: 	    } /* end j */
 6944: 	  }else{
 6945: 	    i=i-ncovmodel;
 6946: 	    if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
 6947: 	      fprintf(ficgp," (1.");
 6948: 	  }
 6949: 	  
 6950: 	  if(ng != 1){
 6951: 	    fprintf(ficgp,")/(1");
 6952: 	    
 6953: 	    for(k1=1; k1 <=nlstate; k1++){ 
 6954: 	      if(nagesqr==0)
 6955: 		fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
 6956: 	      else /* nagesqr =1 */
 6957: 		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);
 6958: 	       
 6959: 	      ij=1;
 6960: 	      for(j=3; j <=ncovmodel-nagesqr; j++){
 6961: 		if((j-2)==Tage[ij]) { /* Bug valgrind */
 6962: 		  if(ij <=cptcovage) { /* Bug valgrind */
 6963: 		    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
 6964: 		    /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
 6965: 		    ij++;
 6966: 		  }
 6967: 		}
 6968: 		else
 6969: 		  fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);/* Valgrind bug nbcode */
 6970: 	      }
 6971: 	      fprintf(ficgp,")");
 6972: 	    }
 6973: 	    fprintf(ficgp,")");
 6974: 	    if(ng ==2)
 6975: 	      fprintf(ficgp," t \"p%d%d\" ", k2,k);
 6976: 	    else /* ng= 3 */
 6977: 	      fprintf(ficgp," t \"i%d%d\" ", k2,k);
 6978: 	  }else{ /* end ng <> 1 */
 6979: 	    if( k !=k2) /* logit p11 is hard to draw */
 6980: 	      fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
 6981: 	  }
 6982: 	  if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
 6983: 	    fprintf(ficgp,",");
 6984: 	  if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
 6985: 	    fprintf(ficgp,",");
 6986: 	  i=i+ncovmodel;
 6987: 	} /* end k */
 6988:       } /* end k2 */
 6989:       fprintf(ficgp,"\n set out\n");
 6990:     } /* end jk */
 6991:   } /* end ng */
 6992:   /* avoid: */
 6993:   fflush(ficgp); 
 6994: }  /* end gnuplot */
 6995: 
 6996: 
 6997: /*************** Moving average **************/
 6998: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
 6999:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
 7000:    
 7001:    int i, cpt, cptcod;
 7002:    int modcovmax =1;
 7003:    int mobilavrange, mob;
 7004:    int iage=0;
 7005: 
 7006:    double sum=0.;
 7007:    double age;
 7008:    double *sumnewp, *sumnewm;
 7009:    double *agemingood, *agemaxgood; /* Currently identical for all covariates */
 7010:   
 7011:   
 7012:    /* modcovmax=2*cptcoveff;/\* Max number of modalities. We suppose  */
 7013:    /* 		   a covariate has 2 modalities, should be equal to ncovcombmax  *\/ */
 7014: 
 7015:    sumnewp = vector(1,ncovcombmax);
 7016:    sumnewm = vector(1,ncovcombmax);
 7017:    agemingood = vector(1,ncovcombmax);	
 7018:    agemaxgood = vector(1,ncovcombmax);
 7019: 
 7020:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
 7021:      sumnewm[cptcod]=0.;
 7022:      sumnewp[cptcod]=0.;
 7023:      agemingood[cptcod]=0;
 7024:      agemaxgood[cptcod]=0;
 7025:    }
 7026:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
 7027:   
 7028:    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
 7029:      if(mobilav==1) mobilavrange=5; /* default */
 7030:      else mobilavrange=mobilav;
 7031:      for (age=bage; age<=fage; age++)
 7032:        for (i=1; i<=nlstate;i++)
 7033: 	 for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
 7034: 	   mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 7035:      /* We keep the original values on the extreme ages bage, fage and for 
 7036: 	fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
 7037: 	we use a 5 terms etc. until the borders are no more concerned. 
 7038:      */ 
 7039:      for (mob=3;mob <=mobilavrange;mob=mob+2){
 7040:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
 7041: 	 for (i=1; i<=nlstate;i++){
 7042: 	   for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
 7043: 	     mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
 7044: 	     for (cpt=1;cpt<=(mob-1)/2;cpt++){
 7045: 	       mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
 7046: 	       mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
 7047: 	     }
 7048: 	     mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
 7049: 	   }
 7050: 	 }
 7051:        }/* end age */
 7052:      }/* end mob */
 7053:    }else
 7054:      return -1;
 7055:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
 7056:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
 7057:      if(invalidvarcomb[cptcod]){
 7058:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
 7059:        continue;
 7060:      }
 7061: 
 7062:      agemingood[cptcod]=fage-(mob-1)/2;
 7063:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
 7064:        sumnewm[cptcod]=0.;
 7065:        for (i=1; i<=nlstate;i++){
 7066: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 7067:        }
 7068:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
 7069: 	 agemingood[cptcod]=age;
 7070:        }else{ /* bad */
 7071: 	 for (i=1; i<=nlstate;i++){
 7072: 	   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
 7073: 	 } /* i */
 7074:        } /* end bad */
 7075:      }/* age */
 7076:      sum=0.;
 7077:      for (i=1; i<=nlstate;i++){
 7078:        sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
 7079:      }
 7080:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
 7081:        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);
 7082:        /* for (i=1; i<=nlstate;i++){ */
 7083:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
 7084:        /* } /\* i *\/ */
 7085:      } /* end bad */
 7086:      /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
 7087:      /* From youngest, finding the oldest wrong */
 7088:      agemaxgood[cptcod]=bage+(mob-1)/2;
 7089:      for (age=bage+(mob-1)/2; age<=fage; age++){
 7090:        sumnewm[cptcod]=0.;
 7091:        for (i=1; i<=nlstate;i++){
 7092: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 7093:        }
 7094:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
 7095: 	 agemaxgood[cptcod]=age;
 7096:        }else{ /* bad */
 7097: 	 for (i=1; i<=nlstate;i++){
 7098: 	   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
 7099: 	 } /* i */
 7100:        } /* end bad */
 7101:      }/* age */
 7102:      sum=0.;
 7103:      for (i=1; i<=nlstate;i++){
 7104:        sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
 7105:      }
 7106:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
 7107:        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);
 7108:        /* for (i=1; i<=nlstate;i++){ */
 7109:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
 7110:        /* } /\* i *\/ */
 7111:      } /* end bad */
 7112: 		
 7113:      for (age=bage; age<=fage; age++){
 7114:        /* printf("%d %d ", cptcod, (int)age); */
 7115:        sumnewp[cptcod]=0.;
 7116:        sumnewm[cptcod]=0.;
 7117:        for (i=1; i<=nlstate;i++){
 7118: 	 sumnewp[cptcod]+=probs[(int)age][i][cptcod];
 7119: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 7120: 	 /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
 7121:        }
 7122:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
 7123:      }
 7124:      /* printf("\n"); */
 7125:      /* } */
 7126:      /* brutal averaging */
 7127:      for (i=1; i<=nlstate;i++){
 7128:        for (age=1; age<=bage; age++){
 7129: 	 mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
 7130: 	 /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
 7131:        }	
 7132:        for (age=fage; age<=AGESUP; age++){
 7133: 	 mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
 7134: 	 /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
 7135:        }
 7136:      } /* end i status */
 7137:      for (i=nlstate+1; i<=nlstate+ndeath;i++){
 7138:        for (age=1; age<=AGESUP; age++){
 7139: 	 /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
 7140: 	 mobaverage[(int)age][i][cptcod]=0.;
 7141:        }
 7142:      }
 7143:    }/* end cptcod */
 7144:    free_vector(sumnewm,1, ncovcombmax);
 7145:    free_vector(sumnewp,1, ncovcombmax);
 7146:    free_vector(agemaxgood,1, ncovcombmax);
 7147:    free_vector(agemingood,1, ncovcombmax);
 7148:    return 0;
 7149:  }/* End movingaverage */
 7150:  
 7151: 
 7152: /************** Forecasting ******************/
 7153:  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){
 7154:   /* proj1, year, month, day of starting projection 
 7155:      agemin, agemax range of age
 7156:      dateprev1 dateprev2 range of dates during which prevalence is computed
 7157:      anproj2 year of en of projection (same day and month as proj1).
 7158:   */
 7159:    int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
 7160:   double agec; /* generic age */
 7161:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
 7162:   double *popeffectif,*popcount;
 7163:   double ***p3mat;
 7164:   /* double ***mobaverage; */
 7165:   char fileresf[FILENAMELENGTH];
 7166: 
 7167:   agelim=AGESUP;
 7168:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 7169:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 7170:      We still use firstpass and lastpass as another selection.
 7171:   */
 7172:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
 7173:   /* 	      firstpass, lastpass,  stepm,  weightopt, model); */
 7174:  
 7175:   strcpy(fileresf,"F_"); 
 7176:   strcat(fileresf,fileresu);
 7177:   if((ficresf=fopen(fileresf,"w"))==NULL) {
 7178:     printf("Problem with forecast resultfile: %s\n", fileresf);
 7179:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
 7180:   }
 7181:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
 7182:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
 7183: 
 7184:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 7185: 
 7186: 
 7187:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 7188:   if (stepm<=12) stepsize=1;
 7189:   if(estepm < stepm){
 7190:     printf ("Problem %d lower than %d\n",estepm, stepm);
 7191:   }
 7192:   else  hstepm=estepm;   
 7193: 
 7194:   hstepm=hstepm/stepm; 
 7195:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
 7196:                                fractional in yp1 */
 7197:   anprojmean=yp;
 7198:   yp2=modf((yp1*12),&yp);
 7199:   mprojmean=yp;
 7200:   yp1=modf((yp2*30.5),&yp);
 7201:   jprojmean=yp;
 7202:   if(jprojmean==0) jprojmean=1;
 7203:   if(mprojmean==0) jprojmean=1;
 7204: 
 7205:   i1=pow(2,cptcoveff);
 7206:   if (cptcovn < 1){i1=1;}
 7207:   
 7208:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
 7209:   
 7210:   fprintf(ficresf,"#****** Routine prevforecast **\n");
 7211:   
 7212: /* 	      if (h==(int)(YEARM*yearp)){ */
 7213:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
 7214:   for(k=1; k<=i1;k++){
 7215:     if(TKresult[nres]!= k)
 7216:       continue;
 7217:     if(invalidvarcomb[k]){
 7218:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
 7219:       continue;
 7220:     }
 7221:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
 7222:     for(j=1;j<=cptcoveff;j++) {
 7223:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7224:     }
 7225:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 7226:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 7227:     }
 7228:     fprintf(ficresf," yearproj age");
 7229:     for(j=1; j<=nlstate+ndeath;j++){ 
 7230:       for(i=1; i<=nlstate;i++) 	      
 7231: 	fprintf(ficresf," p%d%d",i,j);
 7232:       fprintf(ficresf," wp.%d",j);
 7233:     }
 7234:     for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
 7235:       fprintf(ficresf,"\n");
 7236:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
 7237:       for (agec=fage; agec>=(ageminpar-1); agec--){ 
 7238: 	nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
 7239: 	nhstepm = nhstepm/hstepm; 
 7240: 	p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 7241: 	oldm=oldms;savm=savms;
 7242: 	hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
 7243: 	
 7244: 	for (h=0; h<=nhstepm; h++){
 7245: 	  if (h*hstepm/YEARM*stepm ==yearp) {
 7246: 	    fprintf(ficresf,"\n");
 7247: 	    for(j=1;j<=cptcoveff;j++) 
 7248: 	      fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7249: 	    fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
 7250: 	  } 
 7251: 	  for(j=1; j<=nlstate+ndeath;j++) {
 7252: 	    ppij=0.;
 7253: 	    for(i=1; i<=nlstate;i++) {
 7254: 	      if (mobilav==1) 
 7255: 		ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][k];
 7256: 	      else {
 7257: 		ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
 7258: 	      }
 7259: 	      if (h*hstepm/YEARM*stepm== yearp) {
 7260: 		fprintf(ficresf," %.3f", p3mat[i][j][h]);
 7261: 	      }
 7262: 	    } /* end i */
 7263: 	    if (h*hstepm/YEARM*stepm==yearp) {
 7264: 	      fprintf(ficresf," %.3f", ppij);
 7265: 	    }
 7266: 	  }/* end j */
 7267: 	} /* end h */
 7268: 	free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 7269:       } /* end agec */
 7270:     } /* end yearp */
 7271:   } /* end  k */
 7272: 	
 7273:   fclose(ficresf);
 7274:   printf("End of Computing forecasting \n");
 7275:   fprintf(ficlog,"End of Computing forecasting\n");
 7276: 
 7277: }
 7278: 
 7279: /* /\************** Back Forecasting ******************\/ */
 7280: /* 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){ */
 7281: /*   /\* back1, year, month, day of starting backection  */
 7282: /*      agemin, agemax range of age */
 7283: /*      dateprev1 dateprev2 range of dates during which prevalence is computed */
 7284: /*      anback2 year of en of backection (same day and month as back1). */
 7285: /*   *\/ */
 7286: /*   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
 7287: /*   double agec; /\* generic age *\/ */
 7288: /*   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
 7289: /*   double *popeffectif,*popcount; */
 7290: /*   double ***p3mat; */
 7291: /*   /\* double ***mobaverage; *\/ */
 7292: /*   char fileresfb[FILENAMELENGTH]; */
 7293: 	
 7294: /*   agelim=AGESUP; */
 7295: /*   /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
 7296: /*      in each health status at the date of interview (if between dateprev1 and dateprev2). */
 7297: /*      We still use firstpass and lastpass as another selection. */
 7298: /*   *\/ */
 7299: /*   /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
 7300: /*   /\* 	      firstpass, lastpass,  stepm,  weightopt, model); *\/ */
 7301: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
 7302: 	
 7303: /*   strcpy(fileresfb,"FB_");  */
 7304: /*   strcat(fileresfb,fileresu); */
 7305: /*   if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
 7306: /*     printf("Problem with back forecast resultfile: %s\n", fileresfb); */
 7307: /*     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
 7308: /*   } */
 7309: /*   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
 7310: /*   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
 7311: 	
 7312: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
 7313: 	
 7314: /*   /\* if (mobilav!=0) { *\/ */
 7315: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
 7316: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
 7317: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
 7318: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
 7319: /*   /\*   } *\/ */
 7320: /*   /\* } *\/ */
 7321: 	
 7322: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
 7323: /*   if (stepm<=12) stepsize=1; */
 7324: /*   if(estepm < stepm){ */
 7325: /*     printf ("Problem %d lower than %d\n",estepm, stepm); */
 7326: /*   } */
 7327: /*   else  hstepm=estepm;    */
 7328: 	
 7329: /*   hstepm=hstepm/stepm;  */
 7330: /*   yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
 7331: /*                                fractional in yp1 *\/ */
 7332: /*   anprojmean=yp; */
 7333: /*   yp2=modf((yp1*12),&yp); */
 7334: /*   mprojmean=yp; */
 7335: /*   yp1=modf((yp2*30.5),&yp); */
 7336: /*   jprojmean=yp; */
 7337: /*   if(jprojmean==0) jprojmean=1; */
 7338: /*   if(mprojmean==0) jprojmean=1; */
 7339: 	
 7340: /*   i1=cptcoveff; */
 7341: /*   if (cptcovn < 1){i1=1;} */
 7342:   
 7343: /*   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);  */
 7344:   
 7345: /*   fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
 7346: 	
 7347: /* 	/\* 	      if (h==(int)(YEARM*yearp)){ *\/ */
 7348: /*   for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
 7349: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
 7350: /*       k=k+1; */
 7351: /*       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
 7352: /*       for(j=1;j<=cptcoveff;j++) { */
 7353: /* 				fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
 7354: /*       } */
 7355: /*       fprintf(ficresfb," yearbproj age"); */
 7356: /*       for(j=1; j<=nlstate+ndeath;j++){  */
 7357: /* 				for(i=1; i<=nlstate;i++) 	       */
 7358: /*           fprintf(ficresfb," p%d%d",i,j); */
 7359: /* 				fprintf(ficresfb," p.%d",j); */
 7360: /*       } */
 7361: /*       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {  */
 7362: /* 				/\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  *\/ */
 7363: /* 				fprintf(ficresfb,"\n"); */
 7364: /* 				fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);    */
 7365: /* 				for (agec=fage; agec>=(ageminpar-1); agec--){  */
 7366: /* 					nhstepm=(int) rint((agelim-agec)*YEARM/stepm);  */
 7367: /* 					nhstepm = nhstepm/hstepm;  */
 7368: /* 					p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
 7369: /* 					oldm=oldms;savm=savms; */
 7370: /* 					hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k); 	 */
 7371: /* 					for (h=0; h<=nhstepm; h++){ */
 7372: /* 						if (h*hstepm/YEARM*stepm ==yearp) { */
 7373: /*               fprintf(ficresfb,"\n"); */
 7374: /*               for(j=1;j<=cptcoveff;j++)  */
 7375: /*                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
 7376: /* 							fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
 7377: /* 						}  */
 7378: /* 						for(j=1; j<=nlstate+ndeath;j++) { */
 7379: /* 							ppij=0.; */
 7380: /* 							for(i=1; i<=nlstate;i++) { */
 7381: /* 								if (mobilav==1)  */
 7382: /* 									ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
 7383: /* 								else { */
 7384: /* 									ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
 7385: /* 								} */
 7386: /* 								if (h*hstepm/YEARM*stepm== yearp) { */
 7387: /* 									fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
 7388: /* 								} */
 7389: /* 							} /\* end i *\/ */
 7390: /* 							if (h*hstepm/YEARM*stepm==yearp) { */
 7391: /* 								fprintf(ficresfb," %.3f", ppij); */
 7392: /* 							} */
 7393: /* 						}/\* end j *\/ */
 7394: /* 					} /\* end h *\/ */
 7395: /* 					free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
 7396: /* 				} /\* end agec *\/ */
 7397: /*       } /\* end yearp *\/ */
 7398: /*     } /\* end cptcod *\/ */
 7399: /*   } /\* end  cptcov *\/ */
 7400: 	
 7401: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
 7402: 	
 7403: /*   fclose(ficresfb); */
 7404: /*   printf("End of Computing Back forecasting \n"); */
 7405: /*   fprintf(ficlog,"End of Computing Back forecasting\n"); */
 7406: 	
 7407: /* } */
 7408: 
 7409: /************** Forecasting *****not tested NB*************/
 7410: /* void populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2s, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){ */
 7411:   
 7412: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
 7413: /*   int *popage; */
 7414: /*   double calagedatem, agelim, kk1, kk2; */
 7415: /*   double *popeffectif,*popcount; */
 7416: /*   double ***p3mat,***tabpop,***tabpopprev; */
 7417: /*   /\* double ***mobaverage; *\/ */
 7418: /*   char filerespop[FILENAMELENGTH]; */
 7419: 
 7420: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 7421: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 7422: /*   agelim=AGESUP; */
 7423: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
 7424:   
 7425: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
 7426:   
 7427:   
 7428: /*   strcpy(filerespop,"POP_");  */
 7429: /*   strcat(filerespop,fileresu); */
 7430: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
 7431: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
 7432: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
 7433: /*   } */
 7434: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
 7435: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
 7436: 
 7437: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
 7438: 
 7439: /*   /\* if (mobilav!=0) { *\/ */
 7440: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
 7441: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
 7442: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
 7443: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
 7444: /*   /\*   } *\/ */
 7445: /*   /\* } *\/ */
 7446: 
 7447: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
 7448: /*   if (stepm<=12) stepsize=1; */
 7449:   
 7450: /*   agelim=AGESUP; */
 7451:   
 7452: /*   hstepm=1; */
 7453: /*   hstepm=hstepm/stepm;  */
 7454: 	
 7455: /*   if (popforecast==1) { */
 7456: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
 7457: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
 7458: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
 7459: /*     }  */
 7460: /*     popage=ivector(0,AGESUP); */
 7461: /*     popeffectif=vector(0,AGESUP); */
 7462: /*     popcount=vector(0,AGESUP); */
 7463:     
 7464: /*     i=1;    */
 7465: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
 7466:     
 7467: /*     imx=i; */
 7468: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
 7469: /*   } */
 7470:   
 7471: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
 7472: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
 7473: /*       k=k+1; */
 7474: /*       fprintf(ficrespop,"\n#******"); */
 7475: /*       for(j=1;j<=cptcoveff;j++) { */
 7476: /* 	fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
 7477: /*       } */
 7478: /*       fprintf(ficrespop,"******\n"); */
 7479: /*       fprintf(ficrespop,"# Age"); */
 7480: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
 7481: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
 7482:       
 7483: /*       for (cpt=0; cpt<=0;cpt++) {  */
 7484: /* 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
 7485: 	
 7486: /* 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
 7487: /* 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
 7488: /* 	  nhstepm = nhstepm/hstepm;  */
 7489: 	  
 7490: /* 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
 7491: /* 	  oldm=oldms;savm=savms; */
 7492: /* 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
 7493: 	  
 7494: /* 	  for (h=0; h<=nhstepm; h++){ */
 7495: /* 	    if (h==(int) (calagedatem+YEARM*cpt)) { */
 7496: /* 	      fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
 7497: /* 	    }  */
 7498: /* 	    for(j=1; j<=nlstate+ndeath;j++) { */
 7499: /* 	      kk1=0.;kk2=0; */
 7500: /* 	      for(i=1; i<=nlstate;i++) {	       */
 7501: /* 		if (mobilav==1)  */
 7502: /* 		  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
 7503: /* 		else { */
 7504: /* 		  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
 7505: /* 		} */
 7506: /* 	      } */
 7507: /* 	      if (h==(int)(calagedatem+12*cpt)){ */
 7508: /* 		tabpop[(int)(agedeb)][j][cptcod]=kk1; */
 7509: /* 		/\*fprintf(ficrespop," %.3f", kk1); */
 7510: /* 		  if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
 7511: /* 	      } */
 7512: /* 	    } */
 7513: /* 	    for(i=1; i<=nlstate;i++){ */
 7514: /* 	      kk1=0.; */
 7515: /* 	      for(j=1; j<=nlstate;j++){ */
 7516: /* 		kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
 7517: /* 	      } */
 7518: /* 	      tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
 7519: /* 	    } */
 7520: 	    
 7521: /* 	    if (h==(int)(calagedatem+12*cpt)) */
 7522: /* 	      for(j=1; j<=nlstate;j++)  */
 7523: /* 		fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
 7524: /* 	  } */
 7525: /* 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
 7526: /* 	} */
 7527: /*       } */
 7528:       
 7529: /*       /\******\/ */
 7530:       
 7531: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
 7532: /* 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
 7533: /* 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
 7534: /* 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
 7535: /* 	  nhstepm = nhstepm/hstepm;  */
 7536: 	  
 7537: /* 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
 7538: /* 	  oldm=oldms;savm=savms; */
 7539: /* 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
 7540: /* 	  for (h=0; h<=nhstepm; h++){ */
 7541: /* 	    if (h==(int) (calagedatem+YEARM*cpt)) { */
 7542: /* 	      fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
 7543: /* 	    }  */
 7544: /* 	    for(j=1; j<=nlstate+ndeath;j++) { */
 7545: /* 	      kk1=0.;kk2=0; */
 7546: /* 	      for(i=1; i<=nlstate;i++) {	       */
 7547: /* 		kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];	 */
 7548: /* 	      } */
 7549: /* 	      if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);	 */
 7550: /* 	    } */
 7551: /* 	  } */
 7552: /* 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
 7553: /* 	} */
 7554: /*       } */
 7555: /*     }  */
 7556: /*   } */
 7557:   
 7558: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
 7559:   
 7560: /*   if (popforecast==1) { */
 7561: /*     free_ivector(popage,0,AGESUP); */
 7562: /*     free_vector(popeffectif,0,AGESUP); */
 7563: /*     free_vector(popcount,0,AGESUP); */
 7564: /*   } */
 7565: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 7566: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 7567: /*   fclose(ficrespop); */
 7568: /* } /\* End of popforecast *\/ */
 7569:  
 7570: int fileappend(FILE *fichier, char *optionfich)
 7571: {
 7572:   if((fichier=fopen(optionfich,"a"))==NULL) {
 7573:     printf("Problem with file: %s\n", optionfich);
 7574:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
 7575:     return (0);
 7576:   }
 7577:   fflush(fichier);
 7578:   return (1);
 7579: }
 7580: 
 7581: 
 7582: /**************** function prwizard **********************/
 7583: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
 7584: {
 7585: 
 7586:   /* Wizard to print covariance matrix template */
 7587: 
 7588:   char ca[32], cb[32];
 7589:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
 7590:   int numlinepar;
 7591: 
 7592:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 7593:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 7594:   for(i=1; i <=nlstate; i++){
 7595:     jj=0;
 7596:     for(j=1; j <=nlstate+ndeath; j++){
 7597:       if(j==i) continue;
 7598:       jj++;
 7599:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
 7600:       printf("%1d%1d",i,j);
 7601:       fprintf(ficparo,"%1d%1d",i,j);
 7602:       for(k=1; k<=ncovmodel;k++){
 7603: 	/* 	  printf(" %lf",param[i][j][k]); */
 7604: 	/* 	  fprintf(ficparo," %lf",param[i][j][k]); */
 7605: 	printf(" 0.");
 7606: 	fprintf(ficparo," 0.");
 7607:       }
 7608:       printf("\n");
 7609:       fprintf(ficparo,"\n");
 7610:     }
 7611:   }
 7612:   printf("# Scales (for hessian or gradient estimation)\n");
 7613:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
 7614:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
 7615:   for(i=1; i <=nlstate; i++){
 7616:     jj=0;
 7617:     for(j=1; j <=nlstate+ndeath; j++){
 7618:       if(j==i) continue;
 7619:       jj++;
 7620:       fprintf(ficparo,"%1d%1d",i,j);
 7621:       printf("%1d%1d",i,j);
 7622:       fflush(stdout);
 7623:       for(k=1; k<=ncovmodel;k++){
 7624: 	/* 	printf(" %le",delti3[i][j][k]); */
 7625: 	/* 	fprintf(ficparo," %le",delti3[i][j][k]); */
 7626: 	printf(" 0.");
 7627: 	fprintf(ficparo," 0.");
 7628:       }
 7629:       numlinepar++;
 7630:       printf("\n");
 7631:       fprintf(ficparo,"\n");
 7632:     }
 7633:   }
 7634:   printf("# Covariance matrix\n");
 7635: /* # 121 Var(a12)\n\ */
 7636: /* # 122 Cov(b12,a12) Var(b12)\n\ */
 7637: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 7638: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 7639: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 7640: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 7641: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 7642: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 7643:   fflush(stdout);
 7644:   fprintf(ficparo,"# Covariance matrix\n");
 7645:   /* # 121 Var(a12)\n\ */
 7646:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
 7647:   /* #   ...\n\ */
 7648:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
 7649:   
 7650:   for(itimes=1;itimes<=2;itimes++){
 7651:     jj=0;
 7652:     for(i=1; i <=nlstate; i++){
 7653:       for(j=1; j <=nlstate+ndeath; j++){
 7654: 	if(j==i) continue;
 7655: 	for(k=1; k<=ncovmodel;k++){
 7656: 	  jj++;
 7657: 	  ca[0]= k+'a'-1;ca[1]='\0';
 7658: 	  if(itimes==1){
 7659: 	    printf("#%1d%1d%d",i,j,k);
 7660: 	    fprintf(ficparo,"#%1d%1d%d",i,j,k);
 7661: 	  }else{
 7662: 	    printf("%1d%1d%d",i,j,k);
 7663: 	    fprintf(ficparo,"%1d%1d%d",i,j,k);
 7664: 	    /* 	printf(" %.5le",matcov[i][j]); */
 7665: 	  }
 7666: 	  ll=0;
 7667: 	  for(li=1;li <=nlstate; li++){
 7668: 	    for(lj=1;lj <=nlstate+ndeath; lj++){
 7669: 	      if(lj==li) continue;
 7670: 	      for(lk=1;lk<=ncovmodel;lk++){
 7671: 		ll++;
 7672: 		if(ll<=jj){
 7673: 		  cb[0]= lk +'a'-1;cb[1]='\0';
 7674: 		  if(ll<jj){
 7675: 		    if(itimes==1){
 7676: 		      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 7677: 		      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 7678: 		    }else{
 7679: 		      printf(" 0.");
 7680: 		      fprintf(ficparo," 0.");
 7681: 		    }
 7682: 		  }else{
 7683: 		    if(itimes==1){
 7684: 		      printf(" Var(%s%1d%1d)",ca,i,j);
 7685: 		      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
 7686: 		    }else{
 7687: 		      printf(" 0.");
 7688: 		      fprintf(ficparo," 0.");
 7689: 		    }
 7690: 		  }
 7691: 		}
 7692: 	      } /* end lk */
 7693: 	    } /* end lj */
 7694: 	  } /* end li */
 7695: 	  printf("\n");
 7696: 	  fprintf(ficparo,"\n");
 7697: 	  numlinepar++;
 7698: 	} /* end k*/
 7699:       } /*end j */
 7700:     } /* end i */
 7701:   } /* end itimes */
 7702: 
 7703: } /* end of prwizard */
 7704: /******************* Gompertz Likelihood ******************************/
 7705: double gompertz(double x[])
 7706: { 
 7707:   double A,B,L=0.0,sump=0.,num=0.;
 7708:   int i,n=0; /* n is the size of the sample */
 7709: 
 7710:   for (i=1;i<=imx ; i++) {
 7711:     sump=sump+weight[i];
 7712:     /*    sump=sump+1;*/
 7713:     num=num+1;
 7714:   }
 7715:  
 7716:  
 7717:   /* for (i=0; i<=imx; i++) 
 7718:      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]);*/
 7719: 
 7720:   for (i=1;i<=imx ; i++)
 7721:     {
 7722:       if (cens[i] == 1 && wav[i]>1)
 7723: 	A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
 7724:       
 7725:       if (cens[i] == 0 && wav[i]>1)
 7726: 	A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
 7727: 	     +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
 7728:       
 7729:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 7730:       if (wav[i] > 1 ) { /* ??? */
 7731: 	L=L+A*weight[i];
 7732: 	/* 	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]);*/
 7733:       }
 7734:     }
 7735: 
 7736:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 7737:  
 7738:   return -2*L*num/sump;
 7739: }
 7740: 
 7741: #ifdef GSL
 7742: /******************* Gompertz_f Likelihood ******************************/
 7743: double gompertz_f(const gsl_vector *v, void *params)
 7744: { 
 7745:   double A,B,LL=0.0,sump=0.,num=0.;
 7746:   double *x= (double *) v->data;
 7747:   int i,n=0; /* n is the size of the sample */
 7748: 
 7749:   for (i=0;i<=imx-1 ; i++) {
 7750:     sump=sump+weight[i];
 7751:     /*    sump=sump+1;*/
 7752:     num=num+1;
 7753:   }
 7754:  
 7755:  
 7756:   /* for (i=0; i<=imx; i++) 
 7757:      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]);*/
 7758:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
 7759:   for (i=1;i<=imx ; i++)
 7760:     {
 7761:       if (cens[i] == 1 && wav[i]>1)
 7762: 	A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
 7763:       
 7764:       if (cens[i] == 0 && wav[i]>1)
 7765: 	A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
 7766: 	     +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
 7767:       
 7768:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 7769:       if (wav[i] > 1 ) { /* ??? */
 7770: 	LL=LL+A*weight[i];
 7771: 	/* 	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]);*/
 7772:       }
 7773:     }
 7774: 
 7775:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 7776:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
 7777:  
 7778:   return -2*LL*num/sump;
 7779: }
 7780: #endif
 7781: 
 7782: /******************* Printing html file ***********/
 7783: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
 7784: 		  int lastpass, int stepm, int weightopt, char model[],\
 7785: 		  int imx,  double p[],double **matcov,double agemortsup){
 7786:   int i,k;
 7787: 
 7788:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
 7789:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
 7790:   for (i=1;i<=2;i++) 
 7791:     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]));
 7792:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
 7793:   fprintf(fichtm,"</ul>");
 7794: 
 7795: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
 7796: 
 7797:  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>");
 7798: 
 7799:  for (k=agegomp;k<(agemortsup-2);k++) 
 7800:    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]);
 7801: 
 7802:  
 7803:   fflush(fichtm);
 7804: }
 7805: 
 7806: /******************* Gnuplot file **************/
 7807: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 7808: 
 7809:   char dirfileres[132],optfileres[132];
 7810: 
 7811:   int ng;
 7812: 
 7813: 
 7814:   /*#ifdef windows */
 7815:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 7816:     /*#endif */
 7817: 
 7818: 
 7819:   strcpy(dirfileres,optionfilefiname);
 7820:   strcpy(optfileres,"vpl");
 7821:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
 7822:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
 7823:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
 7824:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
 7825:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
 7826: 
 7827: } 
 7828: 
 7829: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
 7830: {
 7831: 
 7832:   /*-------- data file ----------*/
 7833:   FILE *fic;
 7834:   char dummy[]="                         ";
 7835:   int i=0, j=0, n=0, iv=0;
 7836:   int lstra;
 7837:   int linei, month, year,iout;
 7838:   char line[MAXLINE], linetmp[MAXLINE];
 7839:   char stra[MAXLINE], strb[MAXLINE];
 7840:   char *stratrunc;
 7841: 
 7842: 
 7843: 
 7844:   if((fic=fopen(datafile,"r"))==NULL)    {
 7845:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
 7846:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
 7847:   }
 7848: 
 7849:   i=1;
 7850:   linei=0;
 7851:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
 7852:     linei=linei+1;
 7853:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
 7854:       if(line[j] == '\t')
 7855: 	line[j] = ' ';
 7856:     }
 7857:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
 7858:       ;
 7859:     };
 7860:     line[j+1]=0;  /* Trims blanks at end of line */
 7861:     if(line[0]=='#'){
 7862:       fprintf(ficlog,"Comment line\n%s\n",line);
 7863:       printf("Comment line\n%s\n",line);
 7864:       continue;
 7865:     }
 7866:     trimbb(linetmp,line); /* Trims multiple blanks in line */
 7867:     strcpy(line, linetmp);
 7868:     
 7869:     /* Loops on waves */
 7870:     for (j=maxwav;j>=1;j--){
 7871:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
 7872: 	cutv(stra, strb, line, ' '); 
 7873: 	if(strb[0]=='.') { /* Missing value */
 7874: 	  lval=-1;
 7875: 	  cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
 7876: 	  cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
 7877: 	  if(isalpha(strb[1])) { /* .m or .d Really Missing value */
 7878: 	    printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value out of %d measured at wave %d. If missing, you should remove this individual or impute a value.  Exiting.\n", strb, linei,i,line,iv, nqtv, j);
 7879: 	    fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value out of %d measured at wave %d. If missing, you should remove this individual or impute a value.  Exiting.\n", strb, linei,i,line,iv, nqtv, j);fflush(ficlog);
 7880: 	    return 1;
 7881: 	  }
 7882: 	}else{
 7883: 	  errno=0;
 7884: 	  /* what_kind_of_number(strb); */
 7885: 	  dval=strtod(strb,&endptr); 
 7886: 	  /* if( strb[0]=='\0' || (*endptr != '\0')){ */
 7887: 	  /* if(strb != endptr && *endptr == '\0') */
 7888: 	  /*    dval=dlval; */
 7889: 	  /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
 7890: 	  if( strb[0]=='\0' || (*endptr != '\0')){
 7891: 	    printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value out of %d measured at wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,iv, nqtv, j,maxwav);
 7892: 	    fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value out of %d measured at wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line, iv, nqtv, j,maxwav);fflush(ficlog);
 7893: 	    return 1;
 7894: 	  }
 7895: 	  cotqvar[j][iv][i]=dval; 
 7896: 	  cotvar[j][ntv+iv][i]=dval; 
 7897: 	}
 7898: 	strcpy(line,stra);
 7899:       }/* end loop ntqv */
 7900:       
 7901:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
 7902: 	cutv(stra, strb, line, ' '); 
 7903: 	if(strb[0]=='.') { /* Missing value */
 7904: 	  lval=-1;
 7905: 	}else{
 7906: 	  errno=0;
 7907: 	  lval=strtol(strb,&endptr,10); 
 7908: 	  /*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
 7909: 	  if( strb[0]=='\0' || (*endptr != '\0')){
 7910: 	    printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th dummy covariate out of %d measured at wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,iv, ntv, j,maxwav);
 7911: 	    fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d dummy covariate out of %d measured wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,iv, ntv,j,maxwav);fflush(ficlog);
 7912: 	    return 1;
 7913: 	  }
 7914: 	}
 7915: 	if(lval <-1 || lval >1){
 7916: 	  printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 7917:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 7918:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 7919:  For example, for multinomial values like 1, 2 and 3,\n			\
 7920:  build V1=0 V2=0 for the reference value (1),\n				\
 7921:         V1=1 V2=0 for (2) \n						\
 7922:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 7923:  output of IMaCh is often meaningless.\n				\
 7924:  Exiting.\n",lval,linei, i,line,j);
 7925: 	  fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 7926:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 7927:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 7928:  For example, for multinomial values like 1, 2 and 3,\n			\
 7929:  build V1=0 V2=0 for the reference value (1),\n				\
 7930:         V1=1 V2=0 for (2) \n						\
 7931:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 7932:  output of IMaCh is often meaningless.\n				\
 7933:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
 7934: 	  return 1;
 7935: 	}
 7936: 	cotvar[j][iv][i]=(double)(lval);
 7937: 	strcpy(line,stra);
 7938:       }/* end loop ntv */
 7939:       
 7940:       /* Statuses  at wave */
 7941:       cutv(stra, strb, line, ' '); 
 7942:       if(strb[0]=='.') { /* Missing value */
 7943: 	lval=-1;
 7944:       }else{
 7945: 	errno=0;
 7946: 	lval=strtol(strb,&endptr,10); 
 7947: 	/*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
 7948: 	if( strb[0]=='\0' || (*endptr != '\0')){
 7949: 	  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);
 7950: 	  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);
 7951: 	  return 1;
 7952: 	}
 7953:       }
 7954:       
 7955:       s[j][i]=lval;
 7956:       
 7957:       /* Date of Interview */
 7958:       strcpy(line,stra);
 7959:       cutv(stra, strb,line,' ');
 7960:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 7961:       }
 7962:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 7963: 	month=99;
 7964: 	year=9999;
 7965:       }else{
 7966: 	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);
 7967: 	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);
 7968: 	return 1;
 7969:       }
 7970:       anint[j][i]= (double) year; 
 7971:       mint[j][i]= (double)month; 
 7972:       strcpy(line,stra);
 7973:     } /* End loop on waves */
 7974:     
 7975:     /* Date of death */
 7976:     cutv(stra, strb,line,' '); 
 7977:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 7978:     }
 7979:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 7980:       month=99;
 7981:       year=9999;
 7982:     }else{
 7983:       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);
 7984:       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);
 7985:       return 1;
 7986:     }
 7987:     andc[i]=(double) year; 
 7988:     moisdc[i]=(double) month; 
 7989:     strcpy(line,stra);
 7990:     
 7991:     /* Date of birth */
 7992:     cutv(stra, strb,line,' '); 
 7993:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 7994:     }
 7995:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
 7996:       month=99;
 7997:       year=9999;
 7998:     }else{
 7999:       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);
 8000:       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);
 8001:       return 1;
 8002:     }
 8003:     if (year==9999) {
 8004:       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);
 8005:       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);
 8006:       return 1;
 8007:       
 8008:     }
 8009:     annais[i]=(double)(year);
 8010:     moisnais[i]=(double)(month); 
 8011:     strcpy(line,stra);
 8012:     
 8013:     /* Sample weight */
 8014:     cutv(stra, strb,line,' '); 
 8015:     errno=0;
 8016:     dval=strtod(strb,&endptr); 
 8017:     if( strb[0]=='\0' || (*endptr != '\0')){
 8018:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
 8019:       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);
 8020:       fflush(ficlog);
 8021:       return 1;
 8022:     }
 8023:     weight[i]=dval; 
 8024:     strcpy(line,stra);
 8025:     
 8026:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
 8027:       cutv(stra, strb, line, ' '); 
 8028:       if(strb[0]=='.') { /* Missing value */
 8029: 	lval=-1;
 8030:       }else{
 8031: 	errno=0;
 8032: 	/* what_kind_of_number(strb); */
 8033: 	dval=strtod(strb,&endptr);
 8034: 	/* if(strb != endptr && *endptr == '\0') */
 8035: 	/*   dval=dlval; */
 8036: 	/* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
 8037: 	if( strb[0]=='\0' || (*endptr != '\0')){
 8038: 	  printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value (out of %d) constant for all waves. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line, iv, nqv, maxwav);
 8039: 	  fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value (out of %d) constant for all waves. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line, iv, nqv, maxwav);fflush(ficlog);
 8040: 	  return 1;
 8041: 	}
 8042: 	coqvar[iv][i]=dval; 
 8043: 	covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
 8044:       }
 8045:       strcpy(line,stra);
 8046:     }/* end loop nqv */
 8047:     
 8048:     /* Covariate values */
 8049:     for (j=ncovcol;j>=1;j--){
 8050:       cutv(stra, strb,line,' '); 
 8051:       if(strb[0]=='.') { /* Missing covariate value */
 8052: 	lval=-1;
 8053:       }else{
 8054: 	errno=0;
 8055: 	lval=strtol(strb,&endptr,10); 
 8056: 	if( strb[0]=='\0' || (*endptr != '\0')){
 8057: 	  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);
 8058: 	  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);
 8059: 	  return 1;
 8060: 	}
 8061:       }
 8062:       if(lval <-1 || lval >1){
 8063: 	printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 8064:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 8065:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 8066:  For example, for multinomial values like 1, 2 and 3,\n			\
 8067:  build V1=0 V2=0 for the reference value (1),\n				\
 8068:         V1=1 V2=0 for (2) \n						\
 8069:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 8070:  output of IMaCh is often meaningless.\n				\
 8071:  Exiting.\n",lval,linei, i,line,j);
 8072: 	fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 8073:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 8074:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 8075:  For example, for multinomial values like 1, 2 and 3,\n			\
 8076:  build V1=0 V2=0 for the reference value (1),\n				\
 8077:         V1=1 V2=0 for (2) \n						\
 8078:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 8079:  output of IMaCh is often meaningless.\n				\
 8080:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
 8081: 	return 1;
 8082:       }
 8083:       covar[j][i]=(double)(lval);
 8084:       strcpy(line,stra);
 8085:     }  
 8086:     lstra=strlen(stra);
 8087:     
 8088:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
 8089:       stratrunc = &(stra[lstra-9]);
 8090:       num[i]=atol(stratrunc);
 8091:     }
 8092:     else
 8093:       num[i]=atol(stra);
 8094:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
 8095:       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;}*/
 8096:     
 8097:     i=i+1;
 8098:   } /* End loop reading  data */
 8099:   
 8100:   *imax=i-1; /* Number of individuals */
 8101:   fclose(fic);
 8102:   
 8103:   return (0);
 8104:   /* endread: */
 8105:   printf("Exiting readdata: ");
 8106:   fclose(fic);
 8107:   return (1);
 8108: }
 8109: 
 8110: void removefirstspace(char **stri){/*, char stro[]) {*/
 8111:   char *p1 = *stri, *p2 = *stri;
 8112:   while (*p2 == ' ')
 8113:     p2++; 
 8114:   /* while ((*p1++ = *p2++) !=0) */
 8115:   /*   ; */
 8116:   /* do */
 8117:   /*   while (*p2 == ' ') */
 8118:   /*     p2++; */
 8119:   /* while (*p1++ == *p2++); */
 8120:   *stri=p2; 
 8121: }
 8122: 
 8123: int decoderesult ( char resultline[], int nres)
 8124: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
 8125: {
 8126:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
 8127:   char resultsav[MAXLINE];
 8128:   int resultmodel[MAXLINE];
 8129:   int modelresult[MAXLINE];
 8130:   char stra[80], strb[80], strc[80], strd[80],stre[80];
 8131: 
 8132:   removefirstspace(&resultline);
 8133:   printf("decoderesult:%s\n",resultline);
 8134: 
 8135:   if (strstr(resultline,"v") !=0){
 8136:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
 8137:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
 8138:     return 1;
 8139:   }
 8140:   trimbb(resultsav, resultline);
 8141:   if (strlen(resultsav) >1){
 8142:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
 8143:   }
 8144:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
 8145:     printf("ERROR: the number of variable in the resultline, %d, differs from the number of variable used in the model line, %d.\n",j, cptcovs);
 8146:     fprintf(ficlog,"ERROR: the number of variable in the resultline, %d, differs from the number of variable used in the model line, %d.\n",j, cptcovs);
 8147:   }
 8148:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
 8149:     if(nbocc(resultsav,'=') >1){
 8150:        cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' 
 8151: 				      resultsav= V4=1 V5=25.1 V3=0 strb=V3=0 stra= V4=1 V5=25.1 */
 8152:        cutl(strc,strd,strb,'=');  /* strb:V4=1 strc=1 strd=V4 */
 8153:     }else
 8154:       cutl(strc,strd,resultsav,'=');
 8155:     Tvalsel[k]=atof(strc); /* 1 */
 8156:     
 8157:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
 8158:     Tvarsel[k]=atoi(strc);
 8159:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
 8160:     /* cptcovsel++;     */
 8161:     if (nbocc(stra,'=') >0)
 8162:       strcpy(resultsav,stra); /* and analyzes it */
 8163:   }
 8164:   /* Checking for missing or useless values in comparison of current model needs */
 8165:   for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 8166:     if(Typevar[k1]==0){ /* Single covariate in model */
 8167:       match=0;
 8168:       for(k2=1; k2 <=j;k2++){/* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
 8169: 	if(Tvar[k1]==Tvarsel[k2]) {/* Tvar[1]=5 == Tvarsel[2]=5   */
 8170: 	  modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
 8171: 	  match=1;
 8172: 	  break;
 8173: 	}
 8174:       }
 8175:       if(match == 0){
 8176: 	printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
 8177:       }
 8178:     }
 8179:   }
 8180:   /* Checking for missing or useless values in comparison of current model needs */
 8181:   for(k2=1; k2 <=j;k2++){ /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
 8182:     match=0;
 8183:     for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 8184:       if(Typevar[k1]==0){ /* Single */
 8185: 	if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
 8186: 	  resultmodel[k1]=k2;  /* resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
 8187: 	  ++match;
 8188: 	}
 8189:       }
 8190:     }
 8191:     if(match == 0){
 8192:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
 8193:     }else if(match > 1){
 8194:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
 8195:     }
 8196:   }
 8197:       
 8198:   /* We need to deduce which combination number is chosen and save quantitative values */
 8199:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 8200:   /* result line V4=1 V5=25.1 V3=0  V2=8 V1=1 */
 8201:   /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
 8202:   /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
 8203:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
 8204:   /*    1 0 0 0 */
 8205:   /*    2 1 0 0 */
 8206:   /*    3 0 1 0 */ 
 8207:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 */
 8208:   /*    5 0 0 1 */
 8209:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 */
 8210:   /*    7 0 1 1 */
 8211:   /*    8 1 1 1 */
 8212:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
 8213:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
 8214:   /* V5*age V5 known which value for nres?  */
 8215:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
 8216:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* model line */
 8217:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
 8218:       k3= resultmodel[k1]; /* resultmodel[2(V4)] = 1=k3 */
 8219:       k2=(int)Tvarsel[k3]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
 8220:       k+=Tvalsel[k3]*pow(2,k4);  /*  Tvalsel[1]=1  */
 8221:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres][1]=1(V4=1)  Tresult[nres][2]=0(V3=0) */
 8222:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
 8223:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
 8224:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
 8225:       k4++;;
 8226:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
 8227:       k3q= resultmodel[k1]; /* resultmodel[2] = 1=k3 */
 8228:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
 8229:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
 8230:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
 8231:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
 8232:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
 8233:       k4q++;;
 8234:     }
 8235:   }
 8236:   
 8237:   TKresult[nres]=++k; /* Combination for the nresult and the model */
 8238:   return (0);
 8239: }
 8240: 
 8241: int decodemodel( char model[], int lastobs)
 8242:  /**< This routine decodes the model and returns:
 8243: 	* Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
 8244: 	* - nagesqr = 1 if age*age in the model, otherwise 0.
 8245: 	* - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
 8246: 	* - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
 8247: 	* - cptcovage number of covariates with age*products =2
 8248: 	* - cptcovs number of simple covariates
 8249: 	* - 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
 8250: 	*     which is a new column after the 9 (ncovcol) variables. 
 8251: 	* - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
 8252: 	* - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
 8253: 	*    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
 8254: 	* - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
 8255: 	*/
 8256: {
 8257:   int i, j, k, ks, v;
 8258:   int  j1, k1, k2, k3, k4;
 8259:   char modelsav[80];
 8260:   char stra[80], strb[80], strc[80], strd[80],stre[80];
 8261:   char *strpt;
 8262: 
 8263:   /*removespace(model);*/
 8264:   if (strlen(model) >1){ /* If there is at least 1 covariate */
 8265:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
 8266:     if (strstr(model,"AGE") !=0){
 8267:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
 8268:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
 8269:       return 1;
 8270:     }
 8271:     if (strstr(model,"v") !=0){
 8272:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
 8273:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
 8274:       return 1;
 8275:     }
 8276:     strcpy(modelsav,model); 
 8277:     if ((strpt=strstr(model,"age*age")) !=0){
 8278:       printf(" strpt=%s, model=%s\n",strpt, model);
 8279:       if(strpt != model){
 8280: 	printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
 8281:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
 8282:  corresponding column of parameters.\n",model);
 8283: 	fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
 8284:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
 8285:  corresponding column of parameters.\n",model); fflush(ficlog);
 8286: 	return 1;
 8287:       }
 8288:       nagesqr=1;
 8289:       if (strstr(model,"+age*age") !=0)
 8290: 	substrchaine(modelsav, model, "+age*age");
 8291:       else if (strstr(model,"age*age+") !=0)
 8292: 	substrchaine(modelsav, model, "age*age+");
 8293:       else 
 8294: 	substrchaine(modelsav, model, "age*age");
 8295:     }else
 8296:       nagesqr=0;
 8297:     if (strlen(modelsav) >1){
 8298:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
 8299:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
 8300:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
 8301:       cptcovt= j+1; /* Number of total covariates in the model, not including
 8302: 		     * cst, age and age*age 
 8303: 		     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
 8304:       /* including age products which are counted in cptcovage.
 8305:        * but the covariates which are products must be treated 
 8306:        * separately: ncovn=4- 2=2 (V1+V3). */
 8307:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
 8308:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
 8309:       
 8310:       
 8311:       /*   Design
 8312:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
 8313:        *  <          ncovcol=8                >
 8314:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
 8315:        *   k=  1    2      3       4     5       6      7        8
 8316:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
 8317:        *  covar[k,i], value of kth covariate if not including age for individual i:
 8318:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
 8319:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
 8320:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
 8321:        *  Tage[++cptcovage]=k
 8322:        *       if products, new covar are created after ncovcol with k1
 8323:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
 8324:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
 8325:        *  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
 8326:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
 8327:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
 8328:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
 8329:        *  <          ncovcol=8                >
 8330:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
 8331:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
 8332:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
 8333:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 8334:        * p Tprod[1]@2={                         6, 5}
 8335:        *p Tvard[1][1]@4= {7, 8, 5, 6}
 8336:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
 8337:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 8338:        *How to reorganize?
 8339:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
 8340:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 8341:        *       {2,   1,     4,      8,    5,      6,     3,       7}
 8342:        * Struct []
 8343:        */
 8344:       
 8345:       /* This loop fills the array Tvar from the string 'model'.*/
 8346:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
 8347:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
 8348:       /* 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
 8349:       /* 	k=3 V4 Tvar[k=3]= 4 (from V4) */
 8350:       /* 	k=2 V1 Tvar[k=2]= 1 (from V1) */
 8351:       /* 	k=1 Tvar[1]=2 (from V2) */
 8352:       /* 	k=5 Tvar[5] */
 8353:       /* for (k=1; k<=cptcovn;k++) { */
 8354:       /* 	cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 8355:       /* 	} */
 8356:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
 8357:       /*
 8358:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
 8359:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
 8360:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
 8361:       }
 8362:       cptcovage=0;
 8363:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
 8364: 	cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
 8365: 					 modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
 8366: 	if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
 8367: 	/*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
 8368: 	/*scanf("%d",i);*/
 8369: 	if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
 8370: 	  cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
 8371: 	  if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
 8372: 	    /* covar is not filled and then is empty */
 8373: 	    cptcovprod--;
 8374: 	    cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
 8375: 	    Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
 8376: 	    Typevar[k]=1;  /* 1 for age product */
 8377: 	    cptcovage++; /* Sums the number of covariates which include age as a product */
 8378: 	    Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
 8379: 	    /*printf("stre=%s ", stre);*/
 8380: 	  } else if (strcmp(strd,"age")==0) { /* or age*Vn */
 8381: 	    cptcovprod--;
 8382: 	    cutl(stre,strb,strc,'V');
 8383: 	    Tvar[k]=atoi(stre);
 8384: 	    Typevar[k]=1;  /* 1 for age product */
 8385: 	    cptcovage++;
 8386: 	    Tage[cptcovage]=k;
 8387: 	  } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
 8388: 	    /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
 8389: 	    cptcovn++;
 8390: 	    cptcovprodnoage++;k1++;
 8391: 	    cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
 8392: 	    Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
 8393: 						because this model-covariate is a construction we invent a new column
 8394: 						which is after existing variables ncovcol+nqv+ntv+nqtv + k1
 8395: 						If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
 8396: 						Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
 8397: 	    Typevar[k]=2;  /* 2 for double fixed dummy covariates */
 8398: 	    cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
 8399: 	    Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
 8400: 	    Tposprod[k]=k1; /* Tpsprod[3]=1, Tposprod[2]=5 */
 8401: 	    Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
 8402: 	    Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
 8403: 	    k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
 8404: 	    /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
 8405: 	    /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
 8406:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
 8407: 	    /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
 8408: 	    for (i=1; i<=lastobs;i++){
 8409: 	      /* Computes the new covariate which is a product of
 8410: 		 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
 8411: 	      covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
 8412: 	    }
 8413: 	  } /* End age is not in the model */
 8414: 	} /* End if model includes a product */
 8415: 	else { /* no more sum */
 8416: 	  /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
 8417: 	  /*  scanf("%d",i);*/
 8418: 	  cutl(strd,strc,strb,'V');
 8419: 	  ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
 8420: 	  cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
 8421: 	  Tvar[k]=atoi(strd);
 8422: 	  Typevar[k]=0;  /* 0 for simple covariates */
 8423: 	}
 8424: 	strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
 8425: 				/*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
 8426: 				  scanf("%d",i);*/
 8427:       } /* end of loop + on total covariates */
 8428:     } /* end if strlen(modelsave == 0) age*age might exist */
 8429:   } /* end if strlen(model == 0) */
 8430:   
 8431:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
 8432:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
 8433:   
 8434:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
 8435:      printf("cptcovprod=%d ", cptcovprod);
 8436:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
 8437:      scanf("%d ",i);*/
 8438: 
 8439: 
 8440: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
 8441:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
 8442: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
 8443:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
 8444:    k =           1    2   3     4       5       6      7      8        9
 8445:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
 8446:    Typevar[k]=   0    0   0     2       1       0      2      1        1
 8447:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
 8448:    Dummy[k]      1    0   0     0       3       1      1      2        3
 8449: 	  Tmodelind[combination of covar]=k;
 8450: */  
 8451: /* Dispatching between quantitative and time varying covariates */
 8452:   /* If Tvar[k] >ncovcol it is a product */
 8453:   /* Tvar[k] is the value n of Vn with n varying for 1 to nvcol, or p  Vp=Vn*Vm for product */
 8454: 	/* Computing effective variables, ie used by the model, that is from the cptcovt variables */
 8455:   printf("Model=%s\n\
 8456: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
 8457: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
 8458: Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product\n",model);
 8459:   fprintf(ficlog,"Model=%s\n\
 8460: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
 8461: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
 8462: Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product\n",model);
 8463: 
 8464:   for(v=1; v <=ncovcol;v++){
 8465:     DummyV[v]=0;
 8466:     FixedV[v]=0;
 8467:   }
 8468:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
 8469:     DummyV[v]=1;
 8470:     FixedV[v]=0;
 8471:   }
 8472:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
 8473:     DummyV[v]=0;
 8474:     FixedV[v]=1;
 8475:   }
 8476:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
 8477:     DummyV[v]=1;
 8478:     FixedV[v]=1;
 8479:   }
 8480:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
 8481:     printf("Decodemodel: V%d, Dummy(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
 8482:     fprintf(ficlog,"Decodemodel: V%d, Dummy(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
 8483:   }
 8484:   for(k=1, ncovf=0, nsd=0, nsq=0, ncovv=0, ncova=0, ncoveff=0, nqfveff=0, ntveff=0, nqtveff=0;k<=cptcovt; k++){ /* or cptocvt */
 8485:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
 8486:       Fixed[k]= 0;
 8487:       Dummy[k]= 0;
 8488:       ncoveff++;
 8489:       ncovf++;
 8490:       nsd++;
 8491:       modell[k].maintype= FTYPE;
 8492:       TvarsD[nsd]=Tvar[k];
 8493:       TvarsDind[nsd]=k;
 8494:       TvarF[ncovf]=Tvar[k];
 8495:       TvarFind[ncovf]=k;
 8496:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 8497:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 8498:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
 8499:       Fixed[k]= 0;
 8500:       Dummy[k]= 0;
 8501:       ncoveff++;
 8502:       ncovf++;
 8503:       modell[k].maintype= FTYPE;
 8504:       TvarF[ncovf]=Tvar[k];
 8505:       TvarFind[ncovf]=k;
 8506:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 8507:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 8508:     }else if( Tvar[k] <=ncovcol+nqv && Typevar[k]==0){ /* Remind that product Vn*Vm are added in k*/ /* Only simple fixed quantitative variable */
 8509:       Fixed[k]= 0;
 8510:       Dummy[k]= 1;
 8511:       nqfveff++;
 8512:       modell[k].maintype= FTYPE;
 8513:       modell[k].subtype= FQ;
 8514:       nsq++;
 8515:       TvarsQ[nsq]=Tvar[k];
 8516:       TvarsQind[nsq]=k;
 8517:       ncovf++;
 8518:       TvarF[ncovf]=Tvar[k];
 8519:       TvarFind[ncovf]=k;
 8520:       TvarFQ[nqfveff]=Tvar[k]-ncovcol; /* TvarFQ[1]=V2-1=1st in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
 8521:       TvarFQind[nqfveff]=k; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
 8522:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying variables */
 8523:       Fixed[k]= 1;
 8524:       Dummy[k]= 0;
 8525:       ntveff++; /* Only simple time varying dummy variable */
 8526:       modell[k].maintype= VTYPE;
 8527:       modell[k].subtype= VD;
 8528:       nsd++;
 8529:       TvarsD[nsd]=Tvar[k];
 8530:       TvarsDind[nsd]=k;
 8531:       ncovv++; /* Only simple time varying variables */
 8532:       TvarV[ncovv]=Tvar[k];
 8533:       TvarVind[ncovv]=k;
 8534:       TvarVD[ntveff]=Tvar[k]; /* TvarVD[1]=V4  TvarVD[2]=V3 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying dummy variable */
 8535:       TvarVDind[ntveff]=k; /* TvarVDind[1]=2 TvarVDind[2]=3 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying dummy variable */
 8536:       printf("Quasi Tmodelind[%d]=%d,Tvar[Tmodelind[%d]]=V%d, ncovcol=%d, nqv=%d,Tvar[k]- ncovcol-nqv=%d\n",ntveff,k,ntveff,Tvar[k], ncovcol, nqv,Tvar[k]- ncovcol-nqv);
 8537:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
 8538:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
 8539:       Fixed[k]= 1;
 8540:       Dummy[k]= 1;
 8541:       nqtveff++;
 8542:       modell[k].maintype= VTYPE;
 8543:       modell[k].subtype= VQ;
 8544:       ncovv++; /* Only simple time varying variables */
 8545:       nsq++;
 8546:       TvarsQ[nsq]=Tvar[k];
 8547:       TvarsQind[nsq]=k;
 8548:       TvarV[ncovv]=Tvar[k];
 8549:       TvarVind[ncovv]=k;
 8550:       TvarVQ[nqtveff]=Tvar[k]; /* TvarVQ[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying quantitative variable */
 8551:       TvarVQind[nqtveff]=k; /* TvarVQind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying quantitative variable */
 8552:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
 8553:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
 8554:       printf("Quasi TmodelQind[%d]=%d,Tvar[TmodelQind[%d]]=V%d, ncovcol=%d, nqv=%d, ntv=%d,Tvar[k]- ncovcol-nqv-ntv=%d\n",nqtveff,k,nqtveff,Tvar[k], ncovcol, nqv, ntv, Tvar[k]- ncovcol-nqv-ntv);
 8555:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
 8556:     }else if (Typevar[k] == 1) {  /* product with age */
 8557:       ncova++;
 8558:       TvarA[ncova]=Tvar[k];
 8559:       TvarAind[ncova]=k;
 8560:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
 8561: 	Fixed[k]= 2;
 8562: 	Dummy[k]= 2;
 8563: 	modell[k].maintype= ATYPE;
 8564: 	modell[k].subtype= APFD;
 8565: 	/* ncoveff++; */
 8566:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
 8567: 	Fixed[k]= 2;
 8568: 	Dummy[k]= 3;
 8569: 	modell[k].maintype= ATYPE;
 8570: 	modell[k].subtype= APFQ;		/*	Product age * fixed quantitative */
 8571: 	/* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
 8572:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
 8573: 	Fixed[k]= 3;
 8574: 	Dummy[k]= 2;
 8575: 	modell[k].maintype= ATYPE;
 8576: 	modell[k].subtype= APVD;		/*	Product age * varying dummy */
 8577: 	/* ntveff++; /\* Only simple time varying dummy variable *\/ */
 8578:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
 8579: 	Fixed[k]= 3;
 8580: 	Dummy[k]= 3;
 8581: 	modell[k].maintype= ATYPE;
 8582: 	modell[k].subtype= APVQ;		/*	Product age * varying quantitative */
 8583: 	/* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
 8584:       }
 8585:     }else if (Typevar[k] == 2) {  /* product without age */
 8586:       k1=Tposprod[k];
 8587:       if(Tvard[k1][1] <=ncovcol){
 8588: 	if(Tvard[k1][2] <=ncovcol){
 8589: 	  Fixed[k]= 1;
 8590: 	  Dummy[k]= 0;
 8591: 	  modell[k].maintype= FTYPE;
 8592: 	  modell[k].subtype= FPDD;		/*	Product fixed dummy * fixed dummy */
 8593: 	  ncovf++; /* Fixed variables without age */
 8594: 	  TvarF[ncovf]=Tvar[k];
 8595: 	  TvarFind[ncovf]=k;
 8596: 	}else if(Tvard[k1][2] <=ncovcol+nqv){
 8597: 	  Fixed[k]= 0;  /* or 2 ?*/
 8598: 	  Dummy[k]= 1;
 8599: 	  modell[k].maintype= FTYPE;
 8600: 	  modell[k].subtype= FPDQ;		/*	Product fixed dummy * fixed quantitative */
 8601: 	  ncovf++; /* Varying variables without age */
 8602: 	  TvarF[ncovf]=Tvar[k];
 8603: 	  TvarFind[ncovf]=k;
 8604: 	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
 8605: 	  Fixed[k]= 1;
 8606: 	  Dummy[k]= 0;
 8607: 	  modell[k].maintype= VTYPE;
 8608: 	  modell[k].subtype= VPDD;		/*	Product fixed dummy * varying dummy */
 8609: 	  ncovv++; /* Varying variables without age */
 8610: 	  TvarV[ncovv]=Tvar[k];
 8611: 	  TvarVind[ncovv]=k;
 8612: 	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
 8613: 	  Fixed[k]= 1;
 8614: 	  Dummy[k]= 1;
 8615: 	  modell[k].maintype= VTYPE;
 8616: 	  modell[k].subtype= VPDQ;		/*	Product fixed dummy * varying quantitative */
 8617: 	  ncovv++; /* Varying variables without age */
 8618: 	  TvarV[ncovv]=Tvar[k];
 8619: 	  TvarVind[ncovv]=k;
 8620: 	} 
 8621:       }else if(Tvard[k1][1] <=ncovcol+nqv){
 8622: 	if(Tvard[k1][2] <=ncovcol){
 8623: 	  Fixed[k]= 0;  /* or 2 ?*/
 8624: 	  Dummy[k]= 1;
 8625: 	  modell[k].maintype= FTYPE;
 8626: 	  modell[k].subtype= FPDQ;		/*	Product fixed quantitative * fixed dummy */
 8627: 	  ncovf++; /* Fixed variables without age */
 8628: 	  TvarF[ncovf]=Tvar[k];
 8629: 	  TvarFind[ncovf]=k;
 8630: 	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
 8631: 	  Fixed[k]= 1;
 8632: 	  Dummy[k]= 1;
 8633: 	  modell[k].maintype= VTYPE;
 8634: 	  modell[k].subtype= VPDQ;		/*	Product fixed quantitative * varying dummy */
 8635: 	  ncovv++; /* Varying variables without age */
 8636: 	  TvarV[ncovv]=Tvar[k];
 8637: 	  TvarVind[ncovv]=k;
 8638: 	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
 8639: 	  Fixed[k]= 1;
 8640: 	  Dummy[k]= 1;
 8641: 	  modell[k].maintype= VTYPE;
 8642: 	  modell[k].subtype= VPQQ;		/*	Product fixed quantitative * varying quantitative */
 8643: 	  ncovv++; /* Varying variables without age */
 8644: 	  TvarV[ncovv]=Tvar[k];
 8645: 	  TvarVind[ncovv]=k;
 8646: 	  ncovv++; /* Varying variables without age */
 8647: 	  TvarV[ncovv]=Tvar[k];
 8648: 	  TvarVind[ncovv]=k;
 8649: 	} 
 8650:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
 8651: 	if(Tvard[k1][2] <=ncovcol){
 8652: 	  Fixed[k]= 1;
 8653: 	  Dummy[k]= 1;
 8654: 	  modell[k].maintype= VTYPE;
 8655: 	  modell[k].subtype= VPDD;		/*	Product time varying dummy * fixed dummy */
 8656: 	  ncovv++; /* Varying variables without age */
 8657: 	  TvarV[ncovv]=Tvar[k];
 8658: 	  TvarVind[ncovv]=k;
 8659: 	}else if(Tvard[k1][2] <=ncovcol+nqv){
 8660: 	  Fixed[k]= 1;
 8661: 	  Dummy[k]= 1;
 8662: 	  modell[k].maintype= VTYPE;
 8663: 	  modell[k].subtype= VPDQ;		/*	Product time varying dummy * fixed quantitative */
 8664: 	  ncovv++; /* Varying variables without age */
 8665: 	  TvarV[ncovv]=Tvar[k];
 8666: 	  TvarVind[ncovv]=k;
 8667: 	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
 8668: 	  Fixed[k]= 1;
 8669: 	  Dummy[k]= 0;
 8670: 	  modell[k].maintype= VTYPE;
 8671: 	  modell[k].subtype= VPDD;		/*	Product time varying dummy * time varying dummy */
 8672: 	  ncovv++; /* Varying variables without age */
 8673: 	  TvarV[ncovv]=Tvar[k];
 8674: 	  TvarVind[ncovv]=k;
 8675: 	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
 8676: 	  Fixed[k]= 1;
 8677: 	  Dummy[k]= 1;
 8678: 	  modell[k].maintype= VTYPE;
 8679: 	  modell[k].subtype= VPDQ;		/*	Product time varying dummy * time varying quantitative */
 8680: 	  ncovv++; /* Varying variables without age */
 8681: 	  TvarV[ncovv]=Tvar[k];
 8682: 	  TvarVind[ncovv]=k;
 8683: 	} 
 8684:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
 8685: 	if(Tvard[k1][2] <=ncovcol){
 8686: 	  Fixed[k]= 1;
 8687: 	  Dummy[k]= 1;
 8688: 	  modell[k].maintype= VTYPE;
 8689: 	  modell[k].subtype= VPDQ;		/*	Product time varying quantitative * fixed dummy */
 8690: 	  ncovv++; /* Varying variables without age */
 8691: 	  TvarV[ncovv]=Tvar[k];
 8692: 	  TvarVind[ncovv]=k;
 8693: 	}else if(Tvard[k1][2] <=ncovcol+nqv){
 8694: 	  Fixed[k]= 1;
 8695: 	  Dummy[k]= 1;
 8696: 	  modell[k].maintype= VTYPE;
 8697: 	  modell[k].subtype= VPQQ;		/*	Product time varying quantitative * fixed quantitative */
 8698: 	  ncovv++; /* Varying variables without age */
 8699: 	  TvarV[ncovv]=Tvar[k];
 8700: 	  TvarVind[ncovv]=k;
 8701: 	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
 8702: 	  Fixed[k]= 1;
 8703: 	  Dummy[k]= 1;
 8704: 	  modell[k].maintype= VTYPE;
 8705: 	  modell[k].subtype= VPDQ;		/*	Product time varying quantitative * time varying dummy */
 8706: 	  ncovv++; /* Varying variables without age */
 8707: 	  TvarV[ncovv]=Tvar[k];
 8708: 	  TvarVind[ncovv]=k;
 8709: 	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
 8710: 	  Fixed[k]= 1;
 8711: 	  Dummy[k]= 1;
 8712: 	  modell[k].maintype= VTYPE;
 8713: 	  modell[k].subtype= VPQQ;		/*	Product time varying quantitative * time varying quantitative */
 8714: 	  ncovv++; /* Varying variables without age */
 8715: 	  TvarV[ncovv]=Tvar[k];
 8716: 	  TvarVind[ncovv]=k;
 8717: 	} 
 8718:       }else{
 8719: 	printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
 8720: 	fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
 8721:       } /* end k1 */
 8722:     }else{
 8723:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
 8724:       fprintf(ficlog,"Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
 8725:     }
 8726:     printf("Decodemodel, k=%d, Tvar[%d]=V%d,Typevar=%d, Fixed=%d, Dummy=%d\n",k, k,Tvar[k],Typevar[k],Fixed[k],Dummy[k]);
 8727:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
 8728:     fprintf(ficlog,"Decodemodel, k=%d, Tvar[%d]=V%d,Typevar=%d, Fixed=%d, Dummy=%d\n",k, k,Tvar[k],Typevar[k],Fixed[k],Dummy[k]);
 8729:   }
 8730:   /* Searching for doublons in the model */
 8731:   for(k1=1; k1<= cptcovt;k1++){
 8732:     for(k2=1; k2 <k1;k2++){
 8733:       if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){
 8734: 	if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
 8735: 	  if(Tvar[k1]==Tvar[k2]){
 8736: 	    printf("Error duplication in the model=%s at positions (+) %d and %d, Tvar[%d]=V%d, Tvar[%d]=V%d, Typevar=%d, Fixed=%d, Dummy=%d\n", model, k1,k2, k1, Tvar[k1], k2, Tvar[k2],Typevar[k1],Fixed[Tvar[k1]],Dummy[Tvar[k1]]);
 8737: 	    fprintf(ficlog,"Error duplication in the model=%s at positions (+) %d and %d, Tvar[%d]=V%d, Tvar[%d]=V%d, Typevar=%d, Fixed=%d, Dummy=%d\n", model, k1,k2, k1, Tvar[k1], k2, Tvar[k2],Typevar[k1],Fixed[Tvar[k1]],Dummy[Tvar[k1]]); fflush(ficlog);
 8738: 	    return(1);
 8739: 	  }
 8740: 	}else if (Typevar[k1] ==2){
 8741: 	  k3=Tposprod[k1];
 8742: 	  k4=Tposprod[k2];
 8743: 	  if( ((Tvard[k3][1]== Tvard[k4][1])&&(Tvard[k3][2]== Tvard[k4][2])) || ((Tvard[k3][1]== Tvard[k4][2])&&(Tvard[k3][2]== Tvard[k4][1])) ){
 8744: 	    printf("Error duplication in the model=%s at positions (+) %d and %d, V%d*V%d, Typevar=%d, Fixed=%d, Dummy=%d\n",model, k1,k2, Tvard[k3][1], Tvard[k3][2],Typevar[k1],Fixed[Tvar[k1]],Dummy[Tvar[k1]]);
 8745: 	    fprintf(ficlog,"Error duplication in the model=%s at positions (+) %d and %d, V%d*V%d, Typevar=%d, Fixed=%d, Dummy=%d\n",model, k1,k2, Tvard[k3][1], Tvard[k3][2],Typevar[k1],Fixed[Tvar[k1]],Dummy[Tvar[k1]]); fflush(ficlog);
 8746: 	    return(1);
 8747: 	  }
 8748: 	}
 8749:       }
 8750:     }
 8751:   }
 8752:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
 8753:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
 8754:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
 8755:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
 8756:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
 8757:   /*endread:*/
 8758:   printf("Exiting decodemodel: ");
 8759:   return (1);
 8760: }
 8761: 
 8762: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
 8763: {
 8764:   int i, m;
 8765:   int firstone=0;
 8766:   
 8767:   for (i=1; i<=imx; i++) {
 8768:     for(m=2; (m<= maxwav); m++) {
 8769:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
 8770: 	anint[m][i]=9999;
 8771: 	if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
 8772: 	  s[m][i]=-1;
 8773:       }
 8774:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
 8775: 	*nberr = *nberr + 1;
 8776: 	if(firstone == 0){
 8777: 	  firstone=1;
 8778: 	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);
 8779: 	}
 8780: 	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);
 8781: 	s[m][i]=-1;
 8782:       }
 8783:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
 8784: 	(*nberr)++;
 8785: 	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]); 
 8786: 	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]); 
 8787: 	s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
 8788:       }
 8789:     }
 8790:   }
 8791: 
 8792:   for (i=1; i<=imx; i++)  {
 8793:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
 8794:     for(m=firstpass; (m<= lastpass); m++){
 8795:       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 */
 8796: 	if (s[m][i] >= nlstate+1) {
 8797: 	  if(agedc[i]>0){
 8798: 	    if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
 8799: 	      agev[m][i]=agedc[i];
 8800: 	      /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
 8801: 	    }else {
 8802: 	      if ((int)andc[i]!=9999){
 8803: 		nbwarn++;
 8804: 		printf("Warning negative age at death: %ld line:%d\n",num[i],i);
 8805: 		fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
 8806: 		agev[m][i]=-1;
 8807: 	      }
 8808: 	    }
 8809: 	  } /* agedc > 0 */
 8810: 	} /* end if */
 8811: 	else if(s[m][i] !=9){ /* Standard case, age in fractional
 8812: 				 years but with the precision of a month */
 8813: 	  agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
 8814: 	  if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
 8815: 	    agev[m][i]=1;
 8816: 	  else if(agev[m][i] < *agemin){ 
 8817: 	    *agemin=agev[m][i];
 8818: 	    printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
 8819: 	  }
 8820: 	  else if(agev[m][i] >*agemax){
 8821: 	    *agemax=agev[m][i];
 8822: 	    /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
 8823: 	  }
 8824: 	  /*agev[m][i]=anint[m][i]-annais[i];*/
 8825: 	  /*	 agev[m][i] = age[i]+2*m;*/
 8826: 	} /* en if 9*/
 8827: 	else { /* =9 */
 8828: 	  /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
 8829: 	  agev[m][i]=1;
 8830: 	  s[m][i]=-1;
 8831: 	}
 8832:       }
 8833:       else if(s[m][i]==0) /*= 0 Unknown */
 8834: 	agev[m][i]=1;
 8835:       else{
 8836: 	printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
 8837: 	fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
 8838: 	agev[m][i]=0;
 8839:       }
 8840:     } /* End for lastpass */
 8841:   }
 8842:     
 8843:   for (i=1; i<=imx; i++)  {
 8844:     for(m=firstpass; (m<=lastpass); m++){
 8845:       if (s[m][i] > (nlstate+ndeath)) {
 8846: 	(*nberr)++;
 8847: 	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);	
 8848: 	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);	
 8849: 	return 1;
 8850:       }
 8851:     }
 8852:   }
 8853: 
 8854:   /*for (i=1; i<=imx; i++){
 8855:   for (m=firstpass; (m<lastpass); m++){
 8856:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
 8857: }
 8858: 
 8859: }*/
 8860: 
 8861: 
 8862:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
 8863:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
 8864: 
 8865:   return (0);
 8866:  /* endread:*/
 8867:     printf("Exiting calandcheckages: ");
 8868:     return (1);
 8869: }
 8870: 
 8871: #if defined(_MSC_VER)
 8872: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 8873: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 8874: //#include "stdafx.h"
 8875: //#include <stdio.h>
 8876: //#include <tchar.h>
 8877: //#include <windows.h>
 8878: //#include <iostream>
 8879: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
 8880: 
 8881: LPFN_ISWOW64PROCESS fnIsWow64Process;
 8882: 
 8883: BOOL IsWow64()
 8884: {
 8885: 	BOOL bIsWow64 = FALSE;
 8886: 
 8887: 	//typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
 8888: 	//  (HANDLE, PBOOL);
 8889: 
 8890: 	//LPFN_ISWOW64PROCESS fnIsWow64Process;
 8891: 
 8892: 	HMODULE module = GetModuleHandle(_T("kernel32"));
 8893: 	const char funcName[] = "IsWow64Process";
 8894: 	fnIsWow64Process = (LPFN_ISWOW64PROCESS)
 8895: 		GetProcAddress(module, funcName);
 8896: 
 8897: 	if (NULL != fnIsWow64Process)
 8898: 	{
 8899: 		if (!fnIsWow64Process(GetCurrentProcess(),
 8900: 			&bIsWow64))
 8901: 			//throw std::exception("Unknown error");
 8902: 			printf("Unknown error\n");
 8903: 	}
 8904: 	return bIsWow64 != FALSE;
 8905: }
 8906: #endif
 8907: 
 8908: void syscompilerinfo(int logged)
 8909:  {
 8910:    /* #include "syscompilerinfo.h"*/
 8911:    /* command line Intel compiler 32bit windows, XP compatible:*/
 8912:    /* /GS /W3 /Gy
 8913:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
 8914:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
 8915:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
 8916:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
 8917:    */ 
 8918:    /* 64 bits */
 8919:    /*
 8920:      /GS /W3 /Gy
 8921:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
 8922:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
 8923:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
 8924:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
 8925:    /* Optimization are useless and O3 is slower than O2 */
 8926:    /*
 8927:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
 8928:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
 8929:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
 8930:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
 8931:    */
 8932:    /* Link is */ /* /OUT:"visual studio
 8933:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
 8934:       /PDB:"visual studio
 8935:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
 8936:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
 8937:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
 8938:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
 8939:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
 8940:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
 8941:       uiAccess='false'"
 8942:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
 8943:       /NOLOGO /TLBID:1
 8944:    */
 8945: #if defined __INTEL_COMPILER
 8946: #if defined(__GNUC__)
 8947: 	struct utsname sysInfo;  /* For Intel on Linux and OS/X */
 8948: #endif
 8949: #elif defined(__GNUC__) 
 8950: #ifndef  __APPLE__
 8951: #include <gnu/libc-version.h>  /* Only on gnu */
 8952: #endif
 8953:    struct utsname sysInfo;
 8954:    int cross = CROSS;
 8955:    if (cross){
 8956: 	   printf("Cross-");
 8957: 	   if(logged) fprintf(ficlog, "Cross-");
 8958:    }
 8959: #endif
 8960: 
 8961: #include <stdint.h>
 8962: 
 8963:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
 8964: #if defined(__clang__)
 8965:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");	/* Clang/LLVM. ---------------------------------------------- */
 8966: #endif
 8967: #if defined(__ICC) || defined(__INTEL_COMPILER)
 8968:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
 8969: #endif
 8970: #if defined(__GNUC__) || defined(__GNUG__)
 8971:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
 8972: #endif
 8973: #if defined(__HP_cc) || defined(__HP_aCC)
 8974:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
 8975: #endif
 8976: #if defined(__IBMC__) || defined(__IBMCPP__)
 8977:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
 8978: #endif
 8979: #if defined(_MSC_VER)
 8980:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
 8981: #endif
 8982: #if defined(__PGI)
 8983:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
 8984: #endif
 8985: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
 8986:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
 8987: #endif
 8988:    printf(" for "); if (logged) fprintf(ficlog, " for ");
 8989:    
 8990: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
 8991: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
 8992:     // Windows (x64 and x86)
 8993:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
 8994: #elif __unix__ // all unices, not all compilers
 8995:     // Unix
 8996:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
 8997: #elif __linux__
 8998:     // linux
 8999:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
 9000: #elif __APPLE__
 9001:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
 9002:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
 9003: #endif
 9004: 
 9005: /*  __MINGW32__	  */
 9006: /*  __CYGWIN__	 */
 9007: /* __MINGW64__  */
 9008: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
 9009: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
 9010: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
 9011: /* _WIN64  // Defined for applications for Win64. */
 9012: /* _M_X64 // Defined for compilations that target x64 processors. */
 9013: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
 9014: 
 9015: #if UINTPTR_MAX == 0xffffffff
 9016:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
 9017: #elif UINTPTR_MAX == 0xffffffffffffffff
 9018:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
 9019: #else
 9020:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
 9021: #endif
 9022: 
 9023: #if defined(__GNUC__)
 9024: # if defined(__GNUC_PATCHLEVEL__)
 9025: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 9026:                             + __GNUC_MINOR__ * 100 \
 9027:                             + __GNUC_PATCHLEVEL__)
 9028: # else
 9029: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 9030:                             + __GNUC_MINOR__ * 100)
 9031: # endif
 9032:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
 9033:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
 9034: 
 9035:    if (uname(&sysInfo) != -1) {
 9036:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 9037: 	 if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 9038:    }
 9039:    else
 9040:       perror("uname() error");
 9041:    //#ifndef __INTEL_COMPILER 
 9042: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
 9043:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
 9044:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
 9045: #endif
 9046: #endif
 9047: 
 9048:    //   void main()
 9049:    //   {
 9050: #if defined(_MSC_VER)
 9051:    if (IsWow64()){
 9052: 	   printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 9053: 	   if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 9054:    }
 9055:    else{
 9056: 	   printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 9057: 	   if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 9058:    }
 9059:    //	   printf("\nPress Enter to continue...");
 9060:    //	   getchar();
 9061:    //   }
 9062: 
 9063: #endif
 9064:    
 9065: 
 9066: }
 9067: 
 9068: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
 9069:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 9070:   int i, j, k, i1, k4=0, nres=0 ;
 9071:   /* double ftolpl = 1.e-10; */
 9072:   double age, agebase, agelim;
 9073:   double tot;
 9074: 
 9075:   strcpy(filerespl,"PL_");
 9076:   strcat(filerespl,fileresu);
 9077:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
 9078:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
 9079:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
 9080:   }
 9081:   printf("\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
 9082:   fprintf(ficlog,"\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
 9083:   pstamp(ficrespl);
 9084:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
 9085:   fprintf(ficrespl,"#Age ");
 9086:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
 9087:   fprintf(ficrespl,"\n");
 9088:   
 9089:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
 9090: 
 9091:   agebase=ageminpar;
 9092:   agelim=agemaxpar;
 9093: 
 9094:   /* i1=pow(2,ncoveff); */
 9095:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
 9096:   if (cptcovn < 1){i1=1;}
 9097: 
 9098:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
 9099:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 9100:       if(TKresult[nres]!= k)
 9101: 	continue;
 9102: 
 9103:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 9104:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
 9105:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 9106:       /* k=k+1; */
 9107:       /* to clean */
 9108:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
 9109:       fprintf(ficrespl,"#******");
 9110:       printf("#******");
 9111:       fprintf(ficlog,"#******");
 9112:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
 9113: 	fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
 9114: 	printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9115: 	fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9116:       }
 9117:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 9118: 	printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 9119: 	fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 9120: 	fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 9121:       }
 9122:       fprintf(ficrespl,"******\n");
 9123:       printf("******\n");
 9124:       fprintf(ficlog,"******\n");
 9125:       if(invalidvarcomb[k]){
 9126: 	printf("\nCombination (%d) ignored because no case \n",k); 
 9127: 	fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
 9128: 	fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
 9129: 	continue;
 9130:       }
 9131: 
 9132:       fprintf(ficrespl,"#Age ");
 9133:       for(j=1;j<=cptcoveff;j++) {
 9134: 	fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9135:       }
 9136:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
 9137:       fprintf(ficrespl,"Total Years_to_converge\n");
 9138:     
 9139:       for (age=agebase; age<=agelim; age++){
 9140: 	/* for (age=agebase; age<=agebase; age++){ */
 9141: 	prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
 9142: 	fprintf(ficrespl,"%.0f ",age );
 9143: 	for(j=1;j<=cptcoveff;j++)
 9144: 	  fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9145: 	tot=0.;
 9146: 	for(i=1; i<=nlstate;i++){
 9147: 	  tot +=  prlim[i][i];
 9148: 	  fprintf(ficrespl," %.5f", prlim[i][i]);
 9149: 	}
 9150: 	fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
 9151:       } /* Age */
 9152:       /* was end of cptcod */
 9153:     } /* cptcov */
 9154:   } /* nres */
 9155:   return 0;
 9156: }
 9157: 
 9158: 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){
 9159: 	/*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
 9160: 	
 9161: 	/* Computes the back prevalence limit  for any combination	of covariate values 
 9162:    * at any age between ageminpar and agemaxpar
 9163: 	 */
 9164:   int i, j, k, i1, nres=0 ;
 9165:   /* double ftolpl = 1.e-10; */
 9166:   double age, agebase, agelim;
 9167:   double tot;
 9168:   /* double ***mobaverage; */
 9169:   /* double	 **dnewm, **doldm, **dsavm;  /\* for use *\/ */
 9170: 
 9171:   strcpy(fileresplb,"PLB_");
 9172:   strcat(fileresplb,fileresu);
 9173:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
 9174:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
 9175:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
 9176:   }
 9177:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
 9178:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
 9179:   pstamp(ficresplb);
 9180:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
 9181:   fprintf(ficresplb,"#Age ");
 9182:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
 9183:   fprintf(ficresplb,"\n");
 9184:   
 9185:   
 9186:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
 9187:   
 9188:   agebase=ageminpar;
 9189:   agelim=agemaxpar;
 9190:   
 9191:   
 9192:   i1=pow(2,cptcoveff);
 9193:   if (cptcovn < 1){i1=1;}
 9194:   
 9195:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 9196:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
 9197:       if(TKresult[nres]!= k)
 9198: 	continue;
 9199:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
 9200:       fprintf(ficresplb,"#******");
 9201:       printf("#******");
 9202:       fprintf(ficlog,"#******");
 9203:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
 9204: 	fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9205: 	printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9206: 	fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9207:       }
 9208:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
 9209: 	printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
 9210: 	fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
 9211: 	fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
 9212:       }
 9213:       fprintf(ficresplb,"******\n");
 9214:       printf("******\n");
 9215:       fprintf(ficlog,"******\n");
 9216:       if(invalidvarcomb[k]){
 9217: 	printf("\nCombination (%d) ignored because no cases \n",k); 
 9218: 	fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
 9219: 	fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
 9220: 	continue;
 9221:       }
 9222:     
 9223:       fprintf(ficresplb,"#Age ");
 9224:       for(j=1;j<=cptcoveff;j++) {
 9225: 	fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9226:       }
 9227:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
 9228:       fprintf(ficresplb,"Total Years_to_converge\n");
 9229:     
 9230:     
 9231:       for (age=agebase; age<=agelim; age++){
 9232: 	/* for (age=agebase; age<=agebase; age++){ */
 9233: 	if(mobilavproj > 0){
 9234: 	  /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
 9235: 	  /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
 9236: 	  bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k);
 9237: 	}else if (mobilavproj == 0){
 9238: 	  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);
 9239: 	  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);
 9240: 	  exit(1);
 9241: 	}else{
 9242: 	  /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
 9243: 	  bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k);
 9244: 	}
 9245: 	fprintf(ficresplb,"%.0f ",age );
 9246: 	for(j=1;j<=cptcoveff;j++)
 9247: 	  fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9248: 	tot=0.;
 9249: 	for(i=1; i<=nlstate;i++){
 9250: 	  tot +=  bprlim[i][i];
 9251: 	  fprintf(ficresplb," %.5f", bprlim[i][i]);
 9252: 	}
 9253: 	fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
 9254:       } /* Age */
 9255:       /* was end of cptcod */
 9256:     } /* end of any combination */
 9257:   } /* end of nres */  
 9258:   /* hBijx(p, bage, fage); */
 9259:   /* fclose(ficrespijb); */
 9260:   
 9261:   return 0;
 9262: }
 9263:  
 9264: int hPijx(double *p, int bage, int fage){
 9265:     /*------------- h Pij x at various ages ------------*/
 9266: 
 9267:   int stepsize;
 9268:   int agelim;
 9269:   int hstepm;
 9270:   int nhstepm;
 9271:   int h, i, i1, j, k, k4, nres=0;
 9272: 
 9273:   double agedeb;
 9274:   double ***p3mat;
 9275: 
 9276:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
 9277:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
 9278:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
 9279:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
 9280:     }
 9281:     printf("Computing pij: result on file '%s' \n", filerespij);
 9282:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
 9283:   
 9284:     stepsize=(int) (stepm+YEARM-1)/YEARM;
 9285:     /*if (stepm<=24) stepsize=2;*/
 9286: 
 9287:     agelim=AGESUP;
 9288:     hstepm=stepsize*YEARM; /* Every year of age */
 9289:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
 9290: 		
 9291:     /* hstepm=1;   aff par mois*/
 9292:     pstamp(ficrespij);
 9293:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
 9294:     i1= pow(2,cptcoveff);
 9295: 		/* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 9296: 		/*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
 9297: 		/*  	k=k+1;  */
 9298:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
 9299:     for(k=1; k<=i1;k++){
 9300:       if(TKresult[nres]!= k)
 9301: 	continue;
 9302:       fprintf(ficrespij,"\n#****** ");
 9303:       for(j=1;j<=cptcoveff;j++) 
 9304: 	fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9305:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 9306: 	printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 9307: 	fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 9308:       }
 9309:       fprintf(ficrespij,"******\n");
 9310:       
 9311:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
 9312: 	nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 9313: 	nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 9314: 	
 9315: 	/*	  nhstepm=nhstepm*YEARM; aff par mois*/
 9316: 	
 9317: 	p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 9318: 	oldm=oldms;savm=savms;
 9319: 	hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
 9320: 	fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
 9321: 	for(i=1; i<=nlstate;i++)
 9322: 	  for(j=1; j<=nlstate+ndeath;j++)
 9323: 	    fprintf(ficrespij," %1d-%1d",i,j);
 9324: 	fprintf(ficrespij,"\n");
 9325: 	for (h=0; h<=nhstepm; h++){
 9326: 	  /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
 9327: 	  fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
 9328: 	  for(i=1; i<=nlstate;i++)
 9329: 	    for(j=1; j<=nlstate+ndeath;j++)
 9330: 	      fprintf(ficrespij," %.5f", p3mat[i][j][h]);
 9331: 	  fprintf(ficrespij,"\n");
 9332: 	}
 9333: 	free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 9334: 	fprintf(ficrespij,"\n");
 9335:       }
 9336:       /*}*/
 9337:     }
 9338:     return 0;
 9339: }
 9340:  
 9341:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
 9342:     /*------------- h Bij x at various ages ------------*/
 9343: 
 9344:   int stepsize;
 9345:   /* int agelim; */
 9346: 	int ageminl;
 9347:   int hstepm;
 9348:   int nhstepm;
 9349:   int h, i, i1, j, k, nres;
 9350: 	
 9351:   double agedeb;
 9352:   double ***p3mat;
 9353: 	
 9354:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
 9355:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
 9356:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
 9357:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
 9358:   }
 9359:   printf("Computing pij back: result on file '%s' \n", filerespijb);
 9360:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
 9361:   
 9362:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 9363:   /*if (stepm<=24) stepsize=2;*/
 9364:   
 9365:   /* agelim=AGESUP; */
 9366:   ageminl=30;
 9367:   hstepm=stepsize*YEARM; /* Every year of age */
 9368:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
 9369:   
 9370:   /* hstepm=1;   aff par mois*/
 9371:   pstamp(ficrespijb);
 9372:   fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
 9373:   i1= pow(2,cptcoveff);
 9374:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 9375:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
 9376:   /*  	k=k+1;  */
 9377:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 9378:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
 9379:       if(TKresult[nres]!= k)
 9380: 	continue;
 9381:       fprintf(ficrespijb,"\n#****** ");
 9382:       for(j=1;j<=cptcoveff;j++)
 9383: 	fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9384:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
 9385: 	fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
 9386:       }
 9387:       fprintf(ficrespijb,"******\n");
 9388:       if(invalidvarcomb[k]){
 9389: 	fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
 9390: 	continue;
 9391:       }
 9392:       
 9393:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
 9394:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
 9395: 	/* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
 9396: 	nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
 9397: 	nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
 9398: 	
 9399: 	/*	  nhstepm=nhstepm*YEARM; aff par mois*/
 9400: 	
 9401: 	p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 9402: 	/* oldm=oldms;savm=savms; */
 9403: 	/* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
 9404: 	hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
 9405: 	/* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
 9406: 	fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
 9407: 	for(i=1; i<=nlstate;i++)
 9408: 	  for(j=1; j<=nlstate+ndeath;j++)
 9409: 	    fprintf(ficrespijb," %1d-%1d",i,j);
 9410: 	fprintf(ficrespijb,"\n");
 9411: 	for (h=0; h<=nhstepm; h++){
 9412: 	  /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
 9413: 	  fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
 9414: 	  /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
 9415: 	  for(i=1; i<=nlstate;i++)
 9416: 	    for(j=1; j<=nlstate+ndeath;j++)
 9417: 	      fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
 9418: 	  fprintf(ficrespijb,"\n");
 9419: 	}
 9420: 	free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 9421: 	fprintf(ficrespijb,"\n");
 9422:       } /* end age deb */
 9423:     } /* end combination */
 9424:   } /* end nres */
 9425:   return 0;
 9426:  } /*  hBijx */
 9427: 
 9428: 
 9429: /***********************************************/
 9430: /**************** Main Program *****************/
 9431: /***********************************************/
 9432: 
 9433: int main(int argc, char *argv[])
 9434: {
 9435: #ifdef GSL
 9436:   const gsl_multimin_fminimizer_type *T;
 9437:   size_t iteri = 0, it;
 9438:   int rval = GSL_CONTINUE;
 9439:   int status = GSL_SUCCESS;
 9440:   double ssval;
 9441: #endif
 9442:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
 9443:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
 9444:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
 9445:   int jj, ll, li, lj, lk;
 9446:   int numlinepar=0; /* Current linenumber of parameter file */
 9447:   int num_filled;
 9448:   int itimes;
 9449:   int NDIM=2;
 9450:   int vpopbased=0;
 9451:   int nres=0;
 9452: 
 9453:   char ca[32], cb[32];
 9454:   /*  FILE *fichtm; *//* Html File */
 9455:   /* FILE *ficgp;*/ /*Gnuplot File */
 9456:   struct stat info;
 9457:   double agedeb=0.;
 9458: 
 9459:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
 9460:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
 9461: 
 9462:   double fret;
 9463:   double dum=0.; /* Dummy variable */
 9464:   double ***p3mat;
 9465:   /* double ***mobaverage; */
 9466: 
 9467:   char line[MAXLINE];
 9468:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
 9469: 
 9470:   char  modeltemp[MAXLINE];
 9471:   char resultline[MAXLINE];
 9472:   
 9473:   char pathr[MAXLINE], pathimach[MAXLINE]; 
 9474:   char *tok, *val; /* pathtot */
 9475:   int firstobs=1, lastobs=10;
 9476:   int c,  h , cpt, c2;
 9477:   int jl=0;
 9478:   int i1, j1, jk, stepsize=0;
 9479:   int count=0;
 9480: 
 9481:   int *tab; 
 9482:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
 9483:   int backcast=0;
 9484:   int mobilav=0,popforecast=0;
 9485:   int hstepm=0, nhstepm=0;
 9486:   int agemortsup;
 9487:   float  sumlpop=0.;
 9488:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
 9489:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
 9490: 
 9491:   double bage=0, fage=110., age, agelim=0., agebase=0.;
 9492:   double ftolpl=FTOL;
 9493:   double **prlim;
 9494:   double **bprlim;
 9495:   double ***param; /* Matrix of parameters */
 9496:   double  *p;
 9497:   double **matcov; /* Matrix of covariance */
 9498:   double **hess; /* Hessian matrix */
 9499:   double ***delti3; /* Scale */
 9500:   double *delti; /* Scale */
 9501:   double ***eij, ***vareij;
 9502:   double **varpl; /* Variances of prevalence limits by age */
 9503:   double *epj, vepp;
 9504: 
 9505:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
 9506:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
 9507: 
 9508:   double **ximort;
 9509:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
 9510:   int *dcwave;
 9511: 
 9512:   char z[1]="c";
 9513: 
 9514:   /*char  *strt;*/
 9515:   char strtend[80];
 9516: 
 9517: 
 9518: /*   setlocale (LC_ALL, ""); */
 9519: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
 9520: /*   textdomain (PACKAGE); */
 9521: /*   setlocale (LC_CTYPE, ""); */
 9522: /*   setlocale (LC_MESSAGES, ""); */
 9523: 
 9524:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
 9525:   rstart_time = time(NULL);  
 9526:   /*  (void) gettimeofday(&start_time,&tzp);*/
 9527:   start_time = *localtime(&rstart_time);
 9528:   curr_time=start_time;
 9529:   /*tml = *localtime(&start_time.tm_sec);*/
 9530:   /* strcpy(strstart,asctime(&tml)); */
 9531:   strcpy(strstart,asctime(&start_time));
 9532: 
 9533: /*  printf("Localtime (at start)=%s",strstart); */
 9534: /*  tp.tm_sec = tp.tm_sec +86400; */
 9535: /*  tm = *localtime(&start_time.tm_sec); */
 9536: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
 9537: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
 9538: /*   tmg.tm_hour=tmg.tm_hour + 1; */
 9539: /*   tp.tm_sec = mktime(&tmg); */
 9540: /*   strt=asctime(&tmg); */
 9541: /*   printf("Time(after) =%s",strstart);  */
 9542: /*  (void) time (&time_value);
 9543: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
 9544: *  tm = *localtime(&time_value);
 9545: *  strstart=asctime(&tm);
 9546: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
 9547: */
 9548: 
 9549:   nberr=0; /* Number of errors and warnings */
 9550:   nbwarn=0;
 9551: #ifdef WIN32
 9552:   _getcwd(pathcd, size);
 9553: #else
 9554:   getcwd(pathcd, size);
 9555: #endif
 9556:   syscompilerinfo(0);
 9557:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
 9558:   if(argc <=1){
 9559:     printf("\nEnter the parameter file name: ");
 9560:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
 9561:       printf("ERROR Empty parameter file name\n");
 9562:       goto end;
 9563:     }
 9564:     i=strlen(pathr);
 9565:     if(pathr[i-1]=='\n')
 9566:       pathr[i-1]='\0';
 9567:     i=strlen(pathr);
 9568:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
 9569:       pathr[i-1]='\0';
 9570:     }
 9571:     i=strlen(pathr);
 9572:     if( i==0 ){
 9573:       printf("ERROR Empty parameter file name\n");
 9574:       goto end;
 9575:     }
 9576:     for (tok = pathr; tok != NULL; ){
 9577:       printf("Pathr |%s|\n",pathr);
 9578:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
 9579:       printf("val= |%s| pathr=%s\n",val,pathr);
 9580:       strcpy (pathtot, val);
 9581:       if(pathr[0] == '\0') break; /* Dirty */
 9582:     }
 9583:   }
 9584:   else{
 9585:     strcpy(pathtot,argv[1]);
 9586:   }
 9587:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
 9588:   /*cygwin_split_path(pathtot,path,optionfile);
 9589:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
 9590:   /* cutv(path,optionfile,pathtot,'\\');*/
 9591: 
 9592:   /* Split argv[0], imach program to get pathimach */
 9593:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
 9594:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 9595:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 9596:  /*   strcpy(pathimach,argv[0]); */
 9597:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
 9598:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
 9599:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
 9600: #ifdef WIN32
 9601:   _chdir(path); /* Can be a relative path */
 9602:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
 9603: #else
 9604:   chdir(path); /* Can be a relative path */
 9605:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
 9606: #endif
 9607:   printf("Current directory %s!\n",pathcd);
 9608:   strcpy(command,"mkdir ");
 9609:   strcat(command,optionfilefiname);
 9610:   if((outcmd=system(command)) != 0){
 9611:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
 9612:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
 9613:     /* fclose(ficlog); */
 9614: /*     exit(1); */
 9615:   }
 9616: /*   if((imk=mkdir(optionfilefiname))<0){ */
 9617: /*     perror("mkdir"); */
 9618: /*   } */
 9619: 
 9620:   /*-------- arguments in the command line --------*/
 9621: 
 9622:   /* Main Log file */
 9623:   strcat(filelog, optionfilefiname);
 9624:   strcat(filelog,".log");    /* */
 9625:   if((ficlog=fopen(filelog,"w"))==NULL)    {
 9626:     printf("Problem with logfile %s\n",filelog);
 9627:     goto end;
 9628:   }
 9629:   fprintf(ficlog,"Log filename:%s\n",filelog);
 9630:   fprintf(ficlog,"Version %s %s",version,fullversion);
 9631:   fprintf(ficlog,"\nEnter the parameter file name: \n");
 9632:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
 9633:  path=%s \n\
 9634:  optionfile=%s\n\
 9635:  optionfilext=%s\n\
 9636:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
 9637: 
 9638:   syscompilerinfo(1);
 9639: 
 9640:   printf("Local time (at start):%s",strstart);
 9641:   fprintf(ficlog,"Local time (at start): %s",strstart);
 9642:   fflush(ficlog);
 9643: /*   (void) gettimeofday(&curr_time,&tzp); */
 9644: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
 9645: 
 9646:   /* */
 9647:   strcpy(fileres,"r");
 9648:   strcat(fileres, optionfilefiname);
 9649:   strcat(fileresu, optionfilefiname); /* Without r in front */
 9650:   strcat(fileres,".txt");    /* Other files have txt extension */
 9651:   strcat(fileresu,".txt");    /* Other files have txt extension */
 9652: 
 9653:   /* Main ---------arguments file --------*/
 9654: 
 9655:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
 9656:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 9657:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 9658:     fflush(ficlog);
 9659:     /* goto end; */
 9660:     exit(70); 
 9661:   }
 9662: 
 9663: 
 9664: 
 9665:   strcpy(filereso,"o");
 9666:   strcat(filereso,fileresu);
 9667:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
 9668:     printf("Problem with Output resultfile: %s\n", filereso);
 9669:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
 9670:     fflush(ficlog);
 9671:     goto end;
 9672:   }
 9673: 
 9674:   /* Reads comments: lines beginning with '#' */
 9675:   numlinepar=0;
 9676: 
 9677:     /* First parameter line */
 9678:   while(fgets(line, MAXLINE, ficpar)) {
 9679:     /* If line starts with a # it is a comment */
 9680:     if (line[0] == '#') {
 9681:       numlinepar++;
 9682:       fputs(line,stdout);
 9683:       fputs(line,ficparo);
 9684:       fputs(line,ficlog);
 9685:       continue;
 9686:     }else
 9687:       break;
 9688:   }
 9689:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
 9690: 			title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
 9691:     if (num_filled != 5) {
 9692:       printf("Should be 5 parameters\n");
 9693:     }
 9694:     numlinepar++;
 9695:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
 9696:   }
 9697:   /* Second parameter line */
 9698:   while(fgets(line, MAXLINE, ficpar)) {
 9699:     /* If line starts with a # it is a comment */
 9700:     if (line[0] == '#') {
 9701:       numlinepar++;
 9702:       fputs(line,stdout);
 9703:       fputs(line,ficparo);
 9704:       fputs(line,ficlog);
 9705:       continue;
 9706:     }else
 9707:       break;
 9708:   }
 9709:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
 9710: 			&ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
 9711:     if (num_filled != 11) {
 9712:       printf("Not 11 parameters, for example:ftol=1.e-8 stepm=12 ncovcol=2 nqv=1 ntv=2 nqtv=1  nlstate=2 ndeath=1 maxwav=3 mle=1 weight=1\n");
 9713:       printf("but line=%s\n",line);
 9714:     }
 9715:     printf("ftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n",ftol, stepm, ncovcol, nqv, ntv, nqtv, nlstate, ndeath, maxwav, mle, weightopt);
 9716:   }
 9717:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
 9718:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
 9719:   /* Third parameter line */
 9720:   while(fgets(line, MAXLINE, ficpar)) {
 9721:     /* If line starts with a # it is a comment */
 9722:     if (line[0] == '#') {
 9723:       numlinepar++;
 9724:       fputs(line,stdout);
 9725:       fputs(line,ficparo);
 9726:       fputs(line,ficlog);
 9727:       continue;
 9728:     }else
 9729:       break;
 9730:   }
 9731:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
 9732:     if (num_filled == 0)
 9733:             model[0]='\0';
 9734:     else if (num_filled != 1){
 9735:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
 9736:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
 9737:       model[0]='\0';
 9738:       goto end;
 9739:     }
 9740:     else{
 9741:       if (model[0]=='+'){
 9742: 	for(i=1; i<=strlen(model);i++)
 9743: 	  modeltemp[i-1]=model[i];
 9744: 	strcpy(model,modeltemp); 
 9745:       }
 9746:     }
 9747:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
 9748:     printf("model=1+age+%s\n",model);fflush(stdout);
 9749:   }
 9750:   /* 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); */
 9751:   /* numlinepar=numlinepar+3; /\* In general *\/ */
 9752:   /* 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); */
 9753:   fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol, nqv, ntv, nqtv, nlstate,ndeath,maxwav, mle, weightopt,model);
 9754:   fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol, nqv, ntv, nqtv, nlstate,ndeath,maxwav, mle, weightopt,model);
 9755:   fflush(ficlog);
 9756:   /* if(model[0]=='#'|| model[0]== '\0'){ */
 9757:   if(model[0]=='#'){
 9758:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
 9759:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
 9760:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");		\
 9761:     if(mle != -1){
 9762:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
 9763:       exit(1);
 9764:     }
 9765:   }
 9766:   while((c=getc(ficpar))=='#' && c!= EOF){
 9767:     ungetc(c,ficpar);
 9768:     fgets(line, MAXLINE, ficpar);
 9769:     numlinepar++;
 9770:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
 9771:       z[0]=line[1];
 9772:     }
 9773:     /* printf("****line [1] = %c \n",line[1]); */
 9774:     fputs(line, stdout);
 9775:     //puts(line);
 9776:     fputs(line,ficparo);
 9777:     fputs(line,ficlog);
 9778:   }
 9779:   ungetc(c,ficpar);
 9780: 
 9781:    
 9782:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
 9783:   coqvar=matrix(1,nqv,1,n);  /**< Fixed quantitative covariate */
 9784:   cotvar=ma3x(1,maxwav,1,ntv+nqtv,1,n);  /**< Time varying covariate (dummy and quantitative)*/
 9785:   cotqvar=ma3x(1,maxwav,1,nqtv,1,n);  /**< Time varying quantitative covariate */
 9786:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
 9787:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
 9788:      v1+v2*age+v2*v3 makes cptcovn = 3
 9789:   */
 9790:   if (strlen(model)>1) 
 9791:     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*/
 9792:   else
 9793:     ncovmodel=2; /* Constant and age */
 9794:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
 9795:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
 9796:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
 9797:     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);
 9798:     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);
 9799:     fflush(stdout);
 9800:     fclose (ficlog);
 9801:     goto end;
 9802:   }
 9803:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 9804:   delti=delti3[1][1];
 9805:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
 9806:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
 9807:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 9808:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 9809:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 9810:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 9811:     fclose (ficparo);
 9812:     fclose (ficlog);
 9813:     goto end;
 9814:     exit(0);
 9815:   }  else if(mle==-5) { /* Main Wizard */
 9816:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 9817:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 9818:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 9819:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 9820:     matcov=matrix(1,npar,1,npar);
 9821:     hess=matrix(1,npar,1,npar);
 9822:   }  else{ /* Begin of mle != -1 or -5 */
 9823:     /* Read guessed parameters */
 9824:     /* Reads comments: lines beginning with '#' */
 9825:     while((c=getc(ficpar))=='#' && c!= EOF){
 9826:       ungetc(c,ficpar);
 9827:       fgets(line, MAXLINE, ficpar);
 9828:       numlinepar++;
 9829:       fputs(line,stdout);
 9830:       fputs(line,ficparo);
 9831:       fputs(line,ficlog);
 9832:     }
 9833:     ungetc(c,ficpar);
 9834:     
 9835:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 9836:     for(i=1; i <=nlstate; i++){
 9837:       j=0;
 9838:       for(jj=1; jj <=nlstate+ndeath; jj++){
 9839: 	if(jj==i) continue;
 9840: 	j++;
 9841: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 9842: 	if ((i1 != i) || (j1 != jj)){
 9843: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
 9844: It might be a problem of design; if ncovcol and the model are correct\n \
 9845: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
 9846: 	  exit(1);
 9847: 	}
 9848: 	fprintf(ficparo,"%1d%1d",i1,j1);
 9849: 	if(mle==1)
 9850: 	  printf("%1d%1d",i,jj);
 9851: 	fprintf(ficlog,"%1d%1d",i,jj);
 9852: 	for(k=1; k<=ncovmodel;k++){
 9853: 	  fscanf(ficpar," %lf",&param[i][j][k]);
 9854: 	  if(mle==1){
 9855: 	    printf(" %lf",param[i][j][k]);
 9856: 	    fprintf(ficlog," %lf",param[i][j][k]);
 9857: 	  }
 9858: 	  else
 9859: 	    fprintf(ficlog," %lf",param[i][j][k]);
 9860: 	  fprintf(ficparo," %lf",param[i][j][k]);
 9861: 	}
 9862: 	fscanf(ficpar,"\n");
 9863: 	numlinepar++;
 9864: 	if(mle==1)
 9865: 	  printf("\n");
 9866: 	fprintf(ficlog,"\n");
 9867: 	fprintf(ficparo,"\n");
 9868:       }
 9869:     }  
 9870:     fflush(ficlog);
 9871:     
 9872:     /* Reads scales values */
 9873:     p=param[1][1];
 9874:     
 9875:     /* Reads comments: lines beginning with '#' */
 9876:     while((c=getc(ficpar))=='#' && c!= EOF){
 9877:       ungetc(c,ficpar);
 9878:       fgets(line, MAXLINE, ficpar);
 9879:       numlinepar++;
 9880:       fputs(line,stdout);
 9881:       fputs(line,ficparo);
 9882:       fputs(line,ficlog);
 9883:     }
 9884:     ungetc(c,ficpar);
 9885: 
 9886:     for(i=1; i <=nlstate; i++){
 9887:       for(j=1; j <=nlstate+ndeath-1; j++){
 9888: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 9889: 	if ( (i1-i) * (j1-j) != 0){
 9890: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
 9891: 	  exit(1);
 9892: 	}
 9893: 	printf("%1d%1d",i,j);
 9894: 	fprintf(ficparo,"%1d%1d",i1,j1);
 9895: 	fprintf(ficlog,"%1d%1d",i1,j1);
 9896: 	for(k=1; k<=ncovmodel;k++){
 9897: 	  fscanf(ficpar,"%le",&delti3[i][j][k]);
 9898: 	  printf(" %le",delti3[i][j][k]);
 9899: 	  fprintf(ficparo," %le",delti3[i][j][k]);
 9900: 	  fprintf(ficlog," %le",delti3[i][j][k]);
 9901: 	}
 9902: 	fscanf(ficpar,"\n");
 9903: 	numlinepar++;
 9904: 	printf("\n");
 9905: 	fprintf(ficparo,"\n");
 9906: 	fprintf(ficlog,"\n");
 9907:       }
 9908:     }
 9909:     fflush(ficlog);
 9910:     
 9911:     /* Reads covariance matrix */
 9912:     delti=delti3[1][1];
 9913: 		
 9914: 		
 9915:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
 9916: 		
 9917:     /* Reads comments: lines beginning with '#' */
 9918:     while((c=getc(ficpar))=='#' && c!= EOF){
 9919:       ungetc(c,ficpar);
 9920:       fgets(line, MAXLINE, ficpar);
 9921:       numlinepar++;
 9922:       fputs(line,stdout);
 9923:       fputs(line,ficparo);
 9924:       fputs(line,ficlog);
 9925:     }
 9926:     ungetc(c,ficpar);
 9927: 		
 9928:     matcov=matrix(1,npar,1,npar);
 9929:     hess=matrix(1,npar,1,npar);
 9930:     for(i=1; i <=npar; i++)
 9931:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
 9932: 		
 9933:     /* Scans npar lines */
 9934:     for(i=1; i <=npar; i++){
 9935:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
 9936:       if(count != 3){
 9937: 	printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
 9938: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
 9939: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
 9940: 	fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
 9941: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
 9942: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
 9943: 	exit(1);
 9944:       }else{
 9945: 	if(mle==1)
 9946: 	  printf("%1d%1d%d",i1,j1,jk);
 9947:       }
 9948:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
 9949:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
 9950:       for(j=1; j <=i; j++){
 9951: 	fscanf(ficpar," %le",&matcov[i][j]);
 9952: 	if(mle==1){
 9953: 	  printf(" %.5le",matcov[i][j]);
 9954: 	}
 9955: 	fprintf(ficlog," %.5le",matcov[i][j]);
 9956: 	fprintf(ficparo," %.5le",matcov[i][j]);
 9957:       }
 9958:       fscanf(ficpar,"\n");
 9959:       numlinepar++;
 9960:       if(mle==1)
 9961: 				printf("\n");
 9962:       fprintf(ficlog,"\n");
 9963:       fprintf(ficparo,"\n");
 9964:     }
 9965:     /* End of read covariance matrix npar lines */
 9966:     for(i=1; i <=npar; i++)
 9967:       for(j=i+1;j<=npar;j++)
 9968: 	matcov[i][j]=matcov[j][i];
 9969:     
 9970:     if(mle==1)
 9971:       printf("\n");
 9972:     fprintf(ficlog,"\n");
 9973:     
 9974:     fflush(ficlog);
 9975:     
 9976:     /*-------- Rewriting parameter file ----------*/
 9977:     strcpy(rfileres,"r");    /* "Rparameterfile */
 9978:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
 9979:     strcat(rfileres,".");    /* */
 9980:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
 9981:     if((ficres =fopen(rfileres,"w"))==NULL) {
 9982:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
 9983:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
 9984:     }
 9985:     fprintf(ficres,"#%s\n",version);
 9986:   }    /* End of mle != -3 */
 9987:   
 9988:   /*  Main data
 9989:    */
 9990:   n= lastobs;
 9991:   num=lvector(1,n);
 9992:   moisnais=vector(1,n);
 9993:   annais=vector(1,n);
 9994:   moisdc=vector(1,n);
 9995:   andc=vector(1,n);
 9996:   weight=vector(1,n);
 9997:   agedc=vector(1,n);
 9998:   cod=ivector(1,n);
 9999:   for(i=1;i<=n;i++){
10000:     num[i]=0;
10001:     moisnais[i]=0;
10002:     annais[i]=0;
10003:     moisdc[i]=0;
10004:     andc[i]=0;
10005:     agedc[i]=0;
10006:     cod[i]=0;
10007:     weight[i]=1.0; /* Equal weights, 1 by default */
10008:   }
10009:   mint=matrix(1,maxwav,1,n);
10010:   anint=matrix(1,maxwav,1,n);
10011:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
10012:   tab=ivector(1,NCOVMAX);
10013:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
10014:   ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
10015: 
10016:   /* Reads data from file datafile */
10017:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
10018:     goto end;
10019: 
10020:   /* Calculation of the number of parameters from char model */
10021:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
10022: 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
10023: 	k=3 V4 Tvar[k=3]= 4 (from V4)
10024: 	k=2 V1 Tvar[k=2]= 1 (from V1)
10025: 	k=1 Tvar[1]=2 (from V2)
10026:   */
10027:   
10028:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
10029:   TvarsDind=ivector(1,NCOVMAX); /*  */
10030:   TvarsD=ivector(1,NCOVMAX); /*  */
10031:   TvarsQind=ivector(1,NCOVMAX); /*  */
10032:   TvarsQ=ivector(1,NCOVMAX); /*  */
10033:   TvarF=ivector(1,NCOVMAX); /*  */
10034:   TvarFind=ivector(1,NCOVMAX); /*  */
10035:   TvarV=ivector(1,NCOVMAX); /*  */
10036:   TvarVind=ivector(1,NCOVMAX); /*  */
10037:   TvarA=ivector(1,NCOVMAX); /*  */
10038:   TvarAind=ivector(1,NCOVMAX); /*  */
10039:   TvarFD=ivector(1,NCOVMAX); /*  */
10040:   TvarFDind=ivector(1,NCOVMAX); /*  */
10041:   TvarFQ=ivector(1,NCOVMAX); /*  */
10042:   TvarFQind=ivector(1,NCOVMAX); /*  */
10043:   TvarVD=ivector(1,NCOVMAX); /*  */
10044:   TvarVDind=ivector(1,NCOVMAX); /*  */
10045:   TvarVQ=ivector(1,NCOVMAX); /*  */
10046:   TvarVQind=ivector(1,NCOVMAX); /*  */
10047: 
10048:   Tvalsel=vector(1,NCOVMAX); /*  */
10049:   Tvarsel=ivector(1,NCOVMAX); /*  */
10050:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
10051:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
10052:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
10053:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
10054:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
10055:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
10056:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
10057:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
10058:   */
10059:   /* For model-covariate k tells which data-covariate to use but
10060:     because this model-covariate is a construction we invent a new column
10061:     ncovcol + k1
10062:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
10063:     Tvar[3=V1*V4]=4+1 etc */
10064:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
10065:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
10066:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
10067:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
10068:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
10069:   */
10070:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
10071:   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
10072: 			    * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
10073: 			    * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
10074:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
10075: 			 4 covariates (3 plus signs)
10076: 			 Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
10077: 		      */  
10078:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
10079: 				* individual dummy, fixed or varying:
10080: 				* Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
10081: 				* 3, 1, 0, 0, 0, 0, 0, 0},
10082: 				* model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
10083: 				* V1 df, V2 qf, V3 & V4 dv, V5 qv
10084: 				* Tmodelind[1]@9={9,0,3,2,}*/
10085:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
10086:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
10087: 				* individual quantitative, fixed or varying:
10088: 				* Tmodelqind[1]=1,Tvaraff[1]@9={4,
10089: 				* 3, 1, 0, 0, 0, 0, 0, 0},
10090: 				* model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
10091: /* Main decodemodel */
10092: 
10093: 
10094:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
10095:     goto end;
10096: 
10097:   if((double)(lastobs-imx)/(double)imx > 1.10){
10098:     nbwarn++;
10099:     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); 
10100:     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); 
10101:   }
10102:     /*  if(mle==1){*/
10103:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
10104:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
10105:   }
10106: 
10107:     /*-calculation of age at interview from date of interview and age at death -*/
10108:   agev=matrix(1,maxwav,1,imx);
10109: 
10110:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
10111:     goto end;
10112: 
10113: 
10114:   agegomp=(int)agemin;
10115:   free_vector(moisnais,1,n);
10116:   free_vector(annais,1,n);
10117:   /* free_matrix(mint,1,maxwav,1,n);
10118:      free_matrix(anint,1,maxwav,1,n);*/
10119:   /* free_vector(moisdc,1,n); */
10120:   /* free_vector(andc,1,n); */
10121:   /* */
10122:   
10123:   wav=ivector(1,imx);
10124:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
10125:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
10126:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
10127:   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.*/
10128:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
10129:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
10130:    
10131:   /* Concatenates waves */
10132:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
10133:      Death is a valid wave (if date is known).
10134:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
10135:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
10136:      and mw[mi+1][i]. dh depends on stepm.
10137:   */
10138: 
10139:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
10140:   /* */
10141:  
10142:   free_vector(moisdc,1,n);
10143:   free_vector(andc,1,n);
10144: 
10145:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
10146:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
10147:   ncodemax[1]=1;
10148:   Ndum =ivector(-1,NCOVMAX);  
10149:   cptcoveff=0;
10150:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
10151:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
10152:   }
10153:   
10154:   ncovcombmax=pow(2,cptcoveff);
10155:   invalidvarcomb=ivector(1, ncovcombmax); 
10156:   for(i=1;i<ncovcombmax;i++)
10157:     invalidvarcomb[i]=0;
10158:   
10159:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
10160:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
10161:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
10162:   
10163:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
10164:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
10165:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
10166:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
10167:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
10168:    * (currently 0 or 1) in the data.
10169:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
10170:    * corresponding modality (h,j).
10171:    */
10172: 
10173:   h=0;
10174:   /*if (cptcovn > 0) */
10175:   m=pow(2,cptcoveff);
10176:  
10177: 	  /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
10178: 	   * For k=4 covariates, h goes from 1 to m=2**k
10179: 	   * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
10180:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
10181: 	   *     h\k   1     2     3     4
10182: 	   *______________________________  
10183: 	   *     1 i=1 1 i=1 1 i=1 1 i=1 1
10184: 	   *     2     2     1     1     1
10185: 	   *     3 i=2 1     2     1     1
10186: 	   *     4     2     2     1     1
10187: 	   *     5 i=3 1 i=2 1     2     1
10188: 	   *     6     2     1     2     1
10189: 	   *     7 i=4 1     2     2     1
10190: 	   *     8     2     2     2     1
10191: 	   *     9 i=5 1 i=3 1 i=2 1     2
10192: 	   *    10     2     1     1     2
10193: 	   *    11 i=6 1     2     1     2
10194: 	   *    12     2     2     1     2
10195: 	   *    13 i=7 1 i=4 1     2     2    
10196: 	   *    14     2     1     2     2
10197: 	   *    15 i=8 1     2     2     2
10198: 	   *    16     2     2     2     2
10199: 	   */
10200:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
10201:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
10202:      * and the value of each covariate?
10203:      * V1=1, V2=1, V3=2, V4=1 ?
10204:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
10205:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
10206:      * In order to get the real value in the data, we use nbcode
10207:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
10208:      * We are keeping this crazy system in order to be able (in the future?) 
10209:      * to have more than 2 values (0 or 1) for a covariate.
10210:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
10211:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
10212:      *              bbbbbbbb
10213:      *              76543210     
10214:      *   h-1        00000101 (6-1=5)
10215:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
10216:      *           &
10217:      *     1        00000001 (1)
10218:      *              00000000        = 1 & ((h-1) >> (k-1))
10219:      *          +1= 00000001 =1 
10220:      *
10221:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
10222:      *          h'      1101 =2^3+2^2+0x2^1+2^0
10223:      *    >>k'            11
10224:      *          &   00000001
10225:      *            = 00000001
10226:      *      +1    = 00000010=2    =  codtabm(14,3)   
10227:      * Reverse h=6 and m=16?
10228:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
10229:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
10230:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
10231:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
10232:      * V3=decodtabm(14,3,2**4)=2
10233:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
10234:      *(h-1) >> (j-1)    0011 =13 >> 2
10235:      *          &1 000000001
10236:      *           = 000000001
10237:      *         +1= 000000010 =2
10238:      *                  2211
10239:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
10240:      *                  V3=2
10241: 		 * codtabm and decodtabm are identical
10242:      */
10243: 
10244: 
10245:  free_ivector(Ndum,-1,NCOVMAX);
10246: 
10247: 
10248:     
10249:   /* Initialisation of ----------- gnuplot -------------*/
10250:   strcpy(optionfilegnuplot,optionfilefiname);
10251:   if(mle==-3)
10252:     strcat(optionfilegnuplot,"-MORT_");
10253:   strcat(optionfilegnuplot,".gp");
10254: 
10255:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
10256:     printf("Problem with file %s",optionfilegnuplot);
10257:   }
10258:   else{
10259:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
10260:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
10261:     //fprintf(ficgp,"set missing 'NaNq'\n");
10262:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
10263:   }
10264:   /*  fclose(ficgp);*/
10265: 
10266: 
10267:   /* Initialisation of --------- index.htm --------*/
10268: 
10269:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
10270:   if(mle==-3)
10271:     strcat(optionfilehtm,"-MORT_");
10272:   strcat(optionfilehtm,".htm");
10273:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
10274:     printf("Problem with %s \n",optionfilehtm);
10275:     exit(0);
10276:   }
10277: 
10278:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
10279:   strcat(optionfilehtmcov,"-cov.htm");
10280:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
10281:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
10282:   }
10283:   else{
10284:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
10285: <hr size=\"2\" color=\"#EC5E5E\"> \n\
10286: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
10287: 	  optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
10288:   }
10289: 
10290:   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>  \
10291: <hr size=\"2\" color=\"#EC5E5E\"> \n\
10292: <font size=\"2\">IMaCh-%s <br> %s</font> \
10293: <hr size=\"2\" color=\"#EC5E5E\"> \n\
10294: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
10295: \n\
10296: <hr  size=\"2\" color=\"#EC5E5E\">\
10297:  <ul><li><h4>Parameter files</h4>\n\
10298:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
10299:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
10300:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
10301:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
10302:  - Date and time at start: %s</ul>\n",\
10303: 	  optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
10304: 	  optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
10305: 	  fileres,fileres,\
10306: 	  filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
10307:   fflush(fichtm);
10308: 
10309:   strcpy(pathr,path);
10310:   strcat(pathr,optionfilefiname);
10311: #ifdef WIN32
10312:   _chdir(optionfilefiname); /* Move to directory named optionfile */
10313: #else
10314:   chdir(optionfilefiname); /* Move to directory named optionfile */
10315: #endif
10316: 	  
10317:   
10318:   /* Calculates basic frequencies. Computes observed prevalence at single age 
10319: 		 and for any valid combination of covariates
10320:      and prints on file fileres'p'. */
10321:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
10322: 	      firstpass, lastpass,  stepm,  weightopt, model);
10323: 
10324:   fprintf(fichtm,"\n");
10325:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
10326: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
10327: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
10328: 	  imx,agemin,agemax,jmin,jmax,jmean);
10329:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
10330: 	oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
10331: 	newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
10332: 	savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
10333: 	oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
10334: 
10335:   /* For Powell, parameters are in a vector p[] starting at p[1]
10336:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
10337:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
10338: 
10339:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
10340:   /* For mortality only */
10341:   if (mle==-3){
10342:     ximort=matrix(1,NDIM,1,NDIM); 
10343: 		for(i=1;i<=NDIM;i++)
10344: 			for(j=1;j<=NDIM;j++)
10345: 				ximort[i][j]=0.;
10346:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
10347:     cens=ivector(1,n);
10348:     ageexmed=vector(1,n);
10349:     agecens=vector(1,n);
10350:     dcwave=ivector(1,n);
10351: 		
10352:     for (i=1; i<=imx; i++){
10353:       dcwave[i]=-1;
10354:       for (m=firstpass; m<=lastpass; m++)
10355: 	if (s[m][i]>nlstate) {
10356: 	  dcwave[i]=m;
10357: 	  /*	printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
10358: 	  break;
10359: 	}
10360:     }
10361:     
10362:     for (i=1; i<=imx; i++) {
10363:       if (wav[i]>0){
10364: 	ageexmed[i]=agev[mw[1][i]][i];
10365: 	j=wav[i];
10366: 	agecens[i]=1.; 
10367: 	
10368: 	if (ageexmed[i]> 1 && wav[i] > 0){
10369: 	  agecens[i]=agev[mw[j][i]][i];
10370: 	  cens[i]= 1;
10371: 	}else if (ageexmed[i]< 1) 
10372: 	  cens[i]= -1;
10373: 	if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
10374: 	  cens[i]=0 ;
10375:       }
10376:       else cens[i]=-1;
10377:     }
10378:     
10379:     for (i=1;i<=NDIM;i++) {
10380:       for (j=1;j<=NDIM;j++)
10381: 	ximort[i][j]=(i == j ? 1.0 : 0.0);
10382:     }
10383:     
10384:     /*p[1]=0.0268; p[NDIM]=0.083;*/
10385:     /*printf("%lf %lf", p[1], p[2]);*/
10386:     
10387:     
10388: #ifdef GSL
10389:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
10390: #else
10391:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
10392: #endif
10393:     strcpy(filerespow,"POW-MORT_"); 
10394:     strcat(filerespow,fileresu);
10395:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
10396:       printf("Problem with resultfile: %s\n", filerespow);
10397:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
10398:     }
10399: #ifdef GSL
10400:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
10401: #else
10402:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
10403: #endif
10404:     /*  for (i=1;i<=nlstate;i++)
10405: 	for(j=1;j<=nlstate+ndeath;j++)
10406: 	if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
10407:     */
10408:     fprintf(ficrespow,"\n");
10409: #ifdef GSL
10410:     /* gsl starts here */ 
10411:     T = gsl_multimin_fminimizer_nmsimplex;
10412:     gsl_multimin_fminimizer *sfm = NULL;
10413:     gsl_vector *ss, *x;
10414:     gsl_multimin_function minex_func;
10415: 
10416:     /* Initial vertex size vector */
10417:     ss = gsl_vector_alloc (NDIM);
10418:     
10419:     if (ss == NULL){
10420:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
10421:     }
10422:     /* Set all step sizes to 1 */
10423:     gsl_vector_set_all (ss, 0.001);
10424: 
10425:     /* Starting point */
10426:     
10427:     x = gsl_vector_alloc (NDIM);
10428:     
10429:     if (x == NULL){
10430:       gsl_vector_free(ss);
10431:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
10432:     }
10433:   
10434:     /* Initialize method and iterate */
10435:     /*     p[1]=0.0268; p[NDIM]=0.083; */
10436:     /*     gsl_vector_set(x, 0, 0.0268); */
10437:     /*     gsl_vector_set(x, 1, 0.083); */
10438:     gsl_vector_set(x, 0, p[1]);
10439:     gsl_vector_set(x, 1, p[2]);
10440: 
10441:     minex_func.f = &gompertz_f;
10442:     minex_func.n = NDIM;
10443:     minex_func.params = (void *)&p; /* ??? */
10444:     
10445:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
10446:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
10447:     
10448:     printf("Iterations beginning .....\n\n");
10449:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
10450: 
10451:     iteri=0;
10452:     while (rval == GSL_CONTINUE){
10453:       iteri++;
10454:       status = gsl_multimin_fminimizer_iterate(sfm);
10455:       
10456:       if (status) printf("error: %s\n", gsl_strerror (status));
10457:       fflush(0);
10458:       
10459:       if (status) 
10460:         break;
10461:       
10462:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
10463:       ssval = gsl_multimin_fminimizer_size (sfm);
10464:       
10465:       if (rval == GSL_SUCCESS)
10466:         printf ("converged to a local maximum at\n");
10467:       
10468:       printf("%5d ", iteri);
10469:       for (it = 0; it < NDIM; it++){
10470: 	printf ("%10.5f ", gsl_vector_get (sfm->x, it));
10471:       }
10472:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
10473:     }
10474:     
10475:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
10476:     
10477:     gsl_vector_free(x); /* initial values */
10478:     gsl_vector_free(ss); /* inital step size */
10479:     for (it=0; it<NDIM; it++){
10480:       p[it+1]=gsl_vector_get(sfm->x,it);
10481:       fprintf(ficrespow," %.12lf", p[it]);
10482:     }
10483:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
10484: #endif
10485: #ifdef POWELL
10486:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
10487: #endif  
10488:     fclose(ficrespow);
10489:     
10490:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
10491: 
10492:     for(i=1; i <=NDIM; i++)
10493:       for(j=i+1;j<=NDIM;j++)
10494: 				matcov[i][j]=matcov[j][i];
10495:     
10496:     printf("\nCovariance matrix\n ");
10497:     fprintf(ficlog,"\nCovariance matrix\n ");
10498:     for(i=1; i <=NDIM; i++) {
10499:       for(j=1;j<=NDIM;j++){ 
10500: 				printf("%f ",matcov[i][j]);
10501: 				fprintf(ficlog,"%f ",matcov[i][j]);
10502:       }
10503:       printf("\n ");  fprintf(ficlog,"\n ");
10504:     }
10505:     
10506:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
10507:     for (i=1;i<=NDIM;i++) {
10508:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
10509:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
10510:     }
10511:     lsurv=vector(1,AGESUP);
10512:     lpop=vector(1,AGESUP);
10513:     tpop=vector(1,AGESUP);
10514:     lsurv[agegomp]=100000;
10515:     
10516:     for (k=agegomp;k<=AGESUP;k++) {
10517:       agemortsup=k;
10518:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
10519:     }
10520:     
10521:     for (k=agegomp;k<agemortsup;k++)
10522:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
10523:     
10524:     for (k=agegomp;k<agemortsup;k++){
10525:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
10526:       sumlpop=sumlpop+lpop[k];
10527:     }
10528:     
10529:     tpop[agegomp]=sumlpop;
10530:     for (k=agegomp;k<(agemortsup-3);k++){
10531:       /*  tpop[k+1]=2;*/
10532:       tpop[k+1]=tpop[k]-lpop[k];
10533:     }
10534:     
10535:     
10536:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
10537:     for (k=agegomp;k<(agemortsup-2);k++) 
10538:       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]);
10539:     
10540:     
10541:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
10542: 		ageminpar=50;
10543: 		agemaxpar=100;
10544:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
10545:       	printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
10546: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
10547: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
10548:       	fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
10549: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
10550: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
10551:     }else{
10552: 			printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
10553: 			fprintf(ficlog,"Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
10554:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
10555: 		}
10556:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
10557: 		     stepm, weightopt,\
10558: 		     model,imx,p,matcov,agemortsup);
10559:     
10560:     free_vector(lsurv,1,AGESUP);
10561:     free_vector(lpop,1,AGESUP);
10562:     free_vector(tpop,1,AGESUP);
10563:     free_matrix(ximort,1,NDIM,1,NDIM);
10564:     free_ivector(cens,1,n);
10565:     free_vector(agecens,1,n);
10566:     free_ivector(dcwave,1,n);
10567: #ifdef GSL
10568: #endif
10569:   } /* Endof if mle==-3 mortality only */
10570:   /* Standard  */
10571:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
10572:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
10573:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
10574:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
10575:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
10576:     for (k=1; k<=npar;k++)
10577:       printf(" %d %8.5f",k,p[k]);
10578:     printf("\n");
10579:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
10580:       /* mlikeli uses func not funcone */
10581:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
10582:     }
10583:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
10584:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
10585:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
10586:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
10587:     }
10588:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
10589:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
10590:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
10591:     for (k=1; k<=npar;k++)
10592:       printf(" %d %8.5f",k,p[k]);
10593:     printf("\n");
10594:     
10595:     /*--------- results files --------------*/
10596:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle= 0 weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nqv, ntv, nqtv, nlstate, ndeath, maxwav, weightopt,model);
10597:     
10598:     
10599:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
10600:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
10601:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
10602:     for(i=1,jk=1; i <=nlstate; i++){
10603:       for(k=1; k <=(nlstate+ndeath); k++){
10604: 	if (k != i) {
10605: 	  printf("%d%d ",i,k);
10606: 	  fprintf(ficlog,"%d%d ",i,k);
10607: 	  fprintf(ficres,"%1d%1d ",i,k);
10608: 	  for(j=1; j <=ncovmodel; j++){
10609: 	    printf("%12.7f ",p[jk]);
10610: 	    fprintf(ficlog,"%12.7f ",p[jk]);
10611: 	    fprintf(ficres,"%12.7f ",p[jk]);
10612: 	    jk++; 
10613: 	  }
10614: 	  printf("\n");
10615: 	  fprintf(ficlog,"\n");
10616: 	  fprintf(ficres,"\n");
10617: 	}
10618:       }
10619:     }
10620:     if(mle != 0){
10621:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
10622:       ftolhess=ftol; /* Usually correct */
10623:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
10624:       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");
10625:       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");
10626:       for(i=1,jk=1; i <=nlstate; i++){
10627: 	for(k=1; k <=(nlstate+ndeath); k++){
10628: 	  if (k != i) {
10629: 	    printf("%d%d ",i,k);
10630: 	    fprintf(ficlog,"%d%d ",i,k);
10631: 	    for(j=1; j <=ncovmodel; j++){
10632: 	      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]));
10633: 	      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]));
10634: 	      jk++; 
10635: 	    }
10636: 	    printf("\n");
10637: 	    fprintf(ficlog,"\n");
10638: 	  }
10639: 	}
10640:       }
10641:     } /* end of hesscov and Wald tests */
10642:     
10643:     /*  */
10644:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
10645:     printf("# Scales (for hessian or gradient estimation)\n");
10646:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
10647:     for(i=1,jk=1; i <=nlstate; i++){
10648:       for(j=1; j <=nlstate+ndeath; j++){
10649: 	if (j!=i) {
10650: 	  fprintf(ficres,"%1d%1d",i,j);
10651: 	  printf("%1d%1d",i,j);
10652: 	  fprintf(ficlog,"%1d%1d",i,j);
10653: 	  for(k=1; k<=ncovmodel;k++){
10654: 	    printf(" %.5e",delti[jk]);
10655: 	    fprintf(ficlog," %.5e",delti[jk]);
10656: 	    fprintf(ficres," %.5e",delti[jk]);
10657: 	    jk++;
10658: 	  }
10659: 	  printf("\n");
10660: 	  fprintf(ficlog,"\n");
10661: 	  fprintf(ficres,"\n");
10662: 	}
10663:       }
10664:     }
10665:     
10666:     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");
10667:     if(mle >= 1) /* To big for the screen */
10668:       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");
10669:     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");
10670:     /* # 121 Var(a12)\n\ */
10671:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
10672:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
10673:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
10674:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
10675:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
10676:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
10677:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
10678:     
10679:     
10680:     /* Just to have a covariance matrix which will be more understandable
10681:        even is we still don't want to manage dictionary of variables
10682:     */
10683:     for(itimes=1;itimes<=2;itimes++){
10684:       jj=0;
10685:       for(i=1; i <=nlstate; i++){
10686: 	for(j=1; j <=nlstate+ndeath; j++){
10687: 	  if(j==i) continue;
10688: 	  for(k=1; k<=ncovmodel;k++){
10689: 	    jj++;
10690: 	    ca[0]= k+'a'-1;ca[1]='\0';
10691: 	    if(itimes==1){
10692: 	      if(mle>=1)
10693: 		printf("#%1d%1d%d",i,j,k);
10694: 	      fprintf(ficlog,"#%1d%1d%d",i,j,k);
10695: 	      fprintf(ficres,"#%1d%1d%d",i,j,k);
10696: 	    }else{
10697: 	      if(mle>=1)
10698: 		printf("%1d%1d%d",i,j,k);
10699: 	      fprintf(ficlog,"%1d%1d%d",i,j,k);
10700: 	      fprintf(ficres,"%1d%1d%d",i,j,k);
10701: 	    }
10702: 	    ll=0;
10703: 	    for(li=1;li <=nlstate; li++){
10704: 	      for(lj=1;lj <=nlstate+ndeath; lj++){
10705: 		if(lj==li) continue;
10706: 		for(lk=1;lk<=ncovmodel;lk++){
10707: 		  ll++;
10708: 		  if(ll<=jj){
10709: 		    cb[0]= lk +'a'-1;cb[1]='\0';
10710: 		    if(ll<jj){
10711: 		      if(itimes==1){
10712: 			if(mle>=1)
10713: 			  printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
10714: 			fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
10715: 			fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
10716: 		      }else{
10717: 			if(mle>=1)
10718: 			  printf(" %.5e",matcov[jj][ll]); 
10719: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
10720: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
10721: 		      }
10722: 		    }else{
10723: 		      if(itimes==1){
10724: 			if(mle>=1)
10725: 			  printf(" Var(%s%1d%1d)",ca,i,j);
10726: 			fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
10727: 			fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
10728: 		      }else{
10729: 			if(mle>=1)
10730: 			  printf(" %.7e",matcov[jj][ll]); 
10731: 			fprintf(ficlog," %.7e",matcov[jj][ll]); 
10732: 			fprintf(ficres," %.7e",matcov[jj][ll]); 
10733: 		      }
10734: 		    }
10735: 		  }
10736: 		} /* end lk */
10737: 	      } /* end lj */
10738: 	    } /* end li */
10739: 	    if(mle>=1)
10740: 	      printf("\n");
10741: 	    fprintf(ficlog,"\n");
10742: 	    fprintf(ficres,"\n");
10743: 	    numlinepar++;
10744: 	  } /* end k*/
10745: 	} /*end j */
10746:       } /* end i */
10747:     } /* end itimes */
10748:     
10749:     fflush(ficlog);
10750:     fflush(ficres);
10751:     while(fgets(line, MAXLINE, ficpar)) {
10752:       /* If line starts with a # it is a comment */
10753:       if (line[0] == '#') {
10754: 	numlinepar++;
10755: 	fputs(line,stdout);
10756: 	fputs(line,ficparo);
10757: 	fputs(line,ficlog);
10758: 	continue;
10759:       }else
10760: 	break;
10761:     }
10762:     
10763:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
10764:     /*   ungetc(c,ficpar); */
10765:     /*   fgets(line, MAXLINE, ficpar); */
10766:     /*   fputs(line,stdout); */
10767:     /*   fputs(line,ficparo); */
10768:     /* } */
10769:     /* ungetc(c,ficpar); */
10770:     
10771:     estepm=0;
10772:     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){
10773:       
10774:       if (num_filled != 6) {
10775: 	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);
10776: 	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);
10777: 	goto end;
10778:       }
10779:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
10780:     }
10781:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
10782:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
10783:     
10784:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
10785:     if (estepm==0 || estepm < stepm) estepm=stepm;
10786:     if (fage <= 2) {
10787:       bage = ageminpar;
10788:       fage = agemaxpar;
10789:     }
10790:     
10791:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
10792:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
10793:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
10794: 		
10795:     /* Other stuffs, more or less useful */    
10796:     while((c=getc(ficpar))=='#' && c!= EOF){
10797:       ungetc(c,ficpar);
10798:       fgets(line, MAXLINE, ficpar);
10799:       fputs(line,stdout);
10800:       fputs(line,ficparo);
10801:     }
10802:     ungetc(c,ficpar);
10803:     
10804:     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);
10805:     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);
10806:     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);
10807:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
10808:     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);
10809:     
10810:     while((c=getc(ficpar))=='#' && c!= EOF){
10811:       ungetc(c,ficpar);
10812:       fgets(line, MAXLINE, ficpar);
10813:       fputs(line,stdout);
10814:       fputs(line,ficparo);
10815:     }
10816:     ungetc(c,ficpar);
10817:     
10818:     
10819:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
10820:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
10821:     
10822:     fscanf(ficpar,"pop_based=%d\n",&popbased);
10823:     fprintf(ficlog,"pop_based=%d\n",popbased);
10824:     fprintf(ficparo,"pop_based=%d\n",popbased);   
10825:     fprintf(ficres,"pop_based=%d\n",popbased);   
10826:     
10827:     while((c=getc(ficpar))=='#' && c!= EOF){
10828:       ungetc(c,ficpar);
10829:       fgets(line, MAXLINE, ficpar);
10830:       fputs(line,stdout);
10831:       fputs(line,ficres);
10832:       fputs(line,ficparo);
10833:     }
10834:     ungetc(c,ficpar);
10835:     
10836:     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);
10837:     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);
10838:     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);
10839:     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);
10840:     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);
10841:     /* day and month of proj2 are not used but only year anproj2.*/
10842:     
10843:     while((c=getc(ficpar))=='#' && c!= EOF){
10844:       ungetc(c,ficpar);
10845:       fgets(line, MAXLINE, ficpar);
10846:       fputs(line,stdout);
10847:       fputs(line,ficparo);
10848:       fputs(line,ficres);
10849:     }
10850:     ungetc(c,ficpar);
10851:     
10852:     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);
10853:     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);
10854:     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);
10855:     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);
10856:     /* day and month of proj2 are not used but only year anproj2.*/
10857:     
10858:     /* Results */
10859:     nresult=0;
10860:     while(fgets(line, MAXLINE, ficpar)) {
10861:       /* If line starts with a # it is a comment */
10862:       if (line[0] == '#') {
10863: 	numlinepar++;
10864: 	fputs(line,stdout);
10865: 	fputs(line,ficparo);
10866: 	fputs(line,ficlog);
10867: 	fputs(line,ficres);
10868: 	continue;
10869:       }else
10870: 	break;
10871:     }
10872:     while((num_filled=sscanf(line,"result:%[^\n]\n",resultline)) !=EOF){
10873:       if (num_filled == 0)
10874: 	resultline[0]='\0';
10875:       else if (num_filled != 1){
10876: 	printf("ERROR %d: result line should be at minimum 'result=' %s\n",num_filled, line);
10877:       }
10878:       nresult++; /* Sum of resultlines */
10879:       printf("Result %d: result=%s\n",nresult, resultline);
10880:       if(nresult > MAXRESULTLINES){
10881: 	printf("ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
10882: 	fprintf(ficlog,"ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
10883: 	goto end;
10884:       }
10885:       decoderesult(resultline, nresult); /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
10886:       fprintf(ficparo,"result: %s\n",resultline);
10887:       fprintf(ficres,"result: %s\n",resultline);
10888:       fprintf(ficlog,"result: %s\n",resultline);
10889:       while(fgets(line, MAXLINE, ficpar)) {
10890: 	/* If line starts with a # it is a comment */
10891: 	if (line[0] == '#') {
10892: 	  numlinepar++;
10893: 	  fputs(line,stdout);
10894: 	  fputs(line,ficparo);
10895: 	  fputs(line,ficres);
10896: 	  fputs(line,ficlog);
10897: 	  continue;
10898: 	}else
10899: 	  break;
10900:       }
10901:       if (feof(ficpar))
10902: 	break;
10903:       else{ /* Processess output results for this combination of covariate values */
10904:       }				   
10905:     }
10906: 
10907: 
10908:     
10909:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
10910:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
10911:     
10912:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
10913:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
10914:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
10915: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
10916: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
10917:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
10918: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
10919: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
10920:     }else{
10921:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
10922:     }
10923:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
10924: 		 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
10925: 		 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
10926: 		
10927:     /*------------ free_vector  -------------*/
10928:     /*  chdir(path); */
10929: 		
10930:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
10931:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
10932:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
10933:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
10934:     free_lvector(num,1,n);
10935:     free_vector(agedc,1,n);
10936:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
10937:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
10938:     fclose(ficparo);
10939:     fclose(ficres);
10940: 		
10941: 		
10942:     /* Other results (useful)*/
10943: 		
10944: 		
10945:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
10946:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
10947:     prlim=matrix(1,nlstate,1,nlstate);
10948:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
10949:     fclose(ficrespl);
10950: 
10951:     /*------------- h Pij x at various ages ------------*/
10952:     /*#include "hpijx.h"*/
10953:     hPijx(p, bage, fage);
10954:     fclose(ficrespij);
10955:     
10956:     /* ncovcombmax=  pow(2,cptcoveff); */
10957:     /*-------------- Variance of one-step probabilities---*/
10958:     k=1;
10959:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
10960:     
10961:     /* Prevalence for each covariates in probs[age][status][cov] */
10962:     probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
10963:     for(i=1;i<=AGESUP;i++)
10964:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
10965: 	for(k=1;k<=ncovcombmax;k++)
10966: 	  probs[i][j][k]=0.;
10967:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
10968:     if (mobilav!=0 ||mobilavproj !=0 ) {
10969:       mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
10970:       for(i=1;i<=AGESUP;i++)
10971: 	for(j=1;j<=nlstate;j++)
10972: 	  for(k=1;k<=ncovcombmax;k++)
10973: 	    mobaverages[i][j][k]=0.;
10974:       mobaverage=mobaverages;
10975:       if (mobilav!=0) {
10976: 	printf("Movingaveraging observed prevalence\n");
10977: 	if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
10978: 	  fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
10979: 	  printf(" Error in movingaverage mobilav=%d\n",mobilav);
10980: 	}
10981:       }
10982:       /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
10983:       /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
10984:       else if (mobilavproj !=0) {
10985: 	printf("Movingaveraging projected observed prevalence\n");
10986: 	if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
10987: 	  fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
10988: 	  printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
10989: 	}
10990:       }
10991:     }/* end if moving average */
10992:     
10993:     /*---------- Forecasting ------------------*/
10994:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
10995:     if(prevfcast==1){
10996:       /*    if(stepm ==1){*/
10997:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
10998:     }
10999:     if(backcast==1){
11000:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath); 	
11001:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath); 	
11002:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
11003: 
11004:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
11005: 
11006:       bprlim=matrix(1,nlstate,1,nlstate);
11007:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
11008:       fclose(ficresplb);
11009: 
11010:       hBijx(p, bage, fage, mobaverage);
11011:       fclose(ficrespijb);
11012:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
11013: 
11014:       /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
11015: 	 bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
11016:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
11017:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
11018:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
11019:     }
11020:     
11021:  
11022:     /* ------ Other prevalence ratios------------ */
11023: 
11024:     free_ivector(wav,1,imx);
11025:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
11026:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
11027:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
11028: 		
11029: 		
11030:     /*---------- Health expectancies, no variances ------------*/
11031: 		
11032:     strcpy(filerese,"E_");
11033:     strcat(filerese,fileresu);
11034:     if((ficreseij=fopen(filerese,"w"))==NULL) {
11035:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
11036:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
11037:     }
11038:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
11039:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
11040: 
11041:     pstamp(ficreseij);
11042:  		
11043:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
11044:     if (cptcovn < 1){i1=1;}
11045:     
11046:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
11047:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
11048:       if(TKresult[nres]!= k)
11049: 	continue;
11050:       fprintf(ficreseij,"\n#****** ");
11051:       printf("\n#****** ");
11052:       for(j=1;j<=cptcoveff;j++) {
11053: 	fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11054: 	printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11055:       }
11056:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
11057: 	printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11058: 	fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11059:       }
11060:       fprintf(ficreseij,"******\n");
11061:       printf("******\n");
11062:       
11063:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
11064:       oldm=oldms;savm=savms;
11065:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
11066:       
11067:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
11068:     }
11069:     fclose(ficreseij);
11070:     printf("done evsij\n");fflush(stdout);
11071:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
11072: 		
11073:     /*---------- State-specific expectancies and variances ------------*/
11074: 		
11075: 		
11076:     strcpy(filerest,"T_");
11077:     strcat(filerest,fileresu);
11078:     if((ficrest=fopen(filerest,"w"))==NULL) {
11079:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
11080:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
11081:     }
11082:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
11083:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
11084: 		
11085: 
11086:     strcpy(fileresstde,"STDE_");
11087:     strcat(fileresstde,fileresu);
11088:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
11089:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
11090:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
11091:     }
11092:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
11093:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
11094: 
11095:     strcpy(filerescve,"CVE_");
11096:     strcat(filerescve,fileresu);
11097:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
11098:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
11099:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
11100:     }
11101:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
11102:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
11103: 
11104:     strcpy(fileresv,"V_");
11105:     strcat(fileresv,fileresu);
11106:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
11107:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
11108:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
11109:     }
11110:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
11111:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
11112: 
11113:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
11114:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
11115:           
11116:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
11117:     if (cptcovn < 1){i1=1;}
11118:     
11119:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
11120:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
11121:       if(TKresult[nres]!= k)
11122: 	continue;
11123:       printf("\n#****** Selected:");
11124:       fprintf(ficrest,"\n#****** Selected:");
11125:       fprintf(ficlog,"\n#****** Selected:");
11126:       for(j=1;j<=cptcoveff;j++){ 
11127: 	printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11128: 	fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11129: 	fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11130:       }
11131:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
11132: 	printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11133: 	fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11134: 	fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11135:       }	
11136:       fprintf(ficrest,"******\n");
11137:       fprintf(ficlog,"******\n");
11138:       printf("******\n");
11139:       
11140:       fprintf(ficresstdeij,"\n#****** ");
11141:       fprintf(ficrescveij,"\n#****** ");
11142:       for(j=1;j<=cptcoveff;j++) {
11143: 	fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11144: 	fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11145:       }
11146:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
11147: 	fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11148: 	fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11149:       }	
11150:       fprintf(ficresstdeij,"******\n");
11151:       fprintf(ficrescveij,"******\n");
11152:       
11153:       fprintf(ficresvij,"\n#****** ");
11154:       /* pstamp(ficresvij); */
11155:       for(j=1;j<=cptcoveff;j++) 
11156: 	fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11157:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
11158: 	fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11159:       }	
11160:       fprintf(ficresvij,"******\n");
11161:       
11162:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
11163:       oldm=oldms;savm=savms;
11164:       printf(" cvevsij ");
11165:       fprintf(ficlog, " cvevsij ");
11166:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
11167:       printf(" end cvevsij \n ");
11168:       fprintf(ficlog, " end cvevsij \n ");
11169:       
11170:       /*
11171:        */
11172:       /* goto endfree; */
11173:       
11174:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
11175:       pstamp(ficrest);
11176:       
11177:       
11178:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
11179: 	oldm=oldms;savm=savms; /* ZZ Segmentation fault */
11180: 	cptcod= 0; /* To be deleted */
11181: 	printf("varevsij vpopbased=%d \n",vpopbased);
11182: 	fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
11183: 	varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart, nres); /* cptcod not initialized Intel */
11184: 	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 ");
11185: 	if(vpopbased==1)
11186: 	  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);
11187: 	else
11188: 	  fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
11189: 	fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
11190: 	for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
11191: 	fprintf(ficrest,"\n");
11192: 	/* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
11193: 	epj=vector(1,nlstate+1);
11194: 	printf("Computing age specific period (stable) prevalences in each health state \n");
11195: 	fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
11196: 	for(age=bage; age <=fage ;age++){
11197: 	  prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
11198: 	  if (vpopbased==1) {
11199: 	    if(mobilav ==0){
11200: 	      for(i=1; i<=nlstate;i++)
11201: 		prlim[i][i]=probs[(int)age][i][k];
11202: 	    }else{ /* mobilav */ 
11203: 	      for(i=1; i<=nlstate;i++)
11204: 		prlim[i][i]=mobaverage[(int)age][i][k];
11205: 	    }
11206: 	  }
11207: 	  
11208: 	  fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
11209: 	  /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
11210: 	  /* printf(" age %4.0f ",age); */
11211: 	  for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
11212: 	    for(i=1, epj[j]=0.;i <=nlstate;i++) {
11213: 	      epj[j] += prlim[i][i]*eij[i][j][(int)age];
11214: 	      /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
11215: 	      /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
11216: 	    }
11217: 	    epj[nlstate+1] +=epj[j];
11218: 	  }
11219: 	  /* printf(" age %4.0f \n",age); */
11220: 	  
11221: 	  for(i=1, vepp=0.;i <=nlstate;i++)
11222: 	    for(j=1;j <=nlstate;j++)
11223: 	      vepp += vareij[i][j][(int)age];
11224: 	  fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
11225: 	  for(j=1;j <=nlstate;j++){
11226: 	    fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
11227: 	  }
11228: 	  fprintf(ficrest,"\n");
11229: 	}
11230:       } /* End vpopbased */
11231:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
11232:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
11233:       free_vector(epj,1,nlstate+1);
11234:       printf("done selection\n");fflush(stdout);
11235:       fprintf(ficlog,"done selection\n");fflush(ficlog);
11236:       
11237:       /*}*/
11238:     } /* End k selection */
11239: 
11240:     printf("done State-specific expectancies\n");fflush(stdout);
11241:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
11242: 
11243:     /*------- Variance of period (stable) prevalence------*/   
11244:     
11245:     strcpy(fileresvpl,"VPL_");
11246:     strcat(fileresvpl,fileresu);
11247:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
11248:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
11249:       exit(0);
11250:     }
11251:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
11252:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
11253:     
11254:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
11255:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
11256:     
11257:     i1=pow(2,cptcoveff);
11258:     if (cptcovn < 1){i1=1;}
11259: 
11260:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
11261:     for(k=1; k<=i1;k++){
11262:       if(TKresult[nres]!= k)
11263: 	continue;
11264:       fprintf(ficresvpl,"\n#****** ");
11265:       printf("\n#****** ");
11266:       fprintf(ficlog,"\n#****** ");
11267:       for(j=1;j<=cptcoveff;j++) {
11268: 	fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11269: 	fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11270: 	printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11271:       }
11272:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
11273: 	printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11274: 	fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11275: 	fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11276:       }	
11277:       fprintf(ficresvpl,"******\n");
11278:       printf("******\n");
11279:       fprintf(ficlog,"******\n");
11280:       
11281:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
11282:       oldm=oldms;savm=savms;
11283:       varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart, nres);
11284:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
11285:       /*}*/
11286:     }
11287:     
11288:     fclose(ficresvpl);
11289:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
11290:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
11291:     
11292:     free_vector(weight,1,n);
11293:     free_imatrix(Tvard,1,NCOVMAX,1,2);
11294:     free_imatrix(s,1,maxwav+1,1,n);
11295:     free_matrix(anint,1,maxwav,1,n); 
11296:     free_matrix(mint,1,maxwav,1,n);
11297:     free_ivector(cod,1,n);
11298:     free_ivector(tab,1,NCOVMAX);
11299:     fclose(ficresstdeij);
11300:     fclose(ficrescveij);
11301:     fclose(ficresvij);
11302:     fclose(ficrest);
11303:     fclose(ficpar);
11304:     
11305:     
11306:     /*---------- End : free ----------------*/
11307:     if (mobilav!=0 ||mobilavproj !=0)
11308:       free_ma3x(mobaverages,1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
11309:     free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
11310:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
11311:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
11312:   }  /* mle==-3 arrives here for freeing */
11313:   /* endfree:*/
11314:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
11315:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
11316:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
11317:   free_ma3x(cotqvar,1,maxwav,1,nqtv,1,n);
11318:   free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,1,n);
11319:   free_matrix(coqvar,1,maxwav,1,n);
11320:   free_matrix(covar,0,NCOVMAX,1,n);
11321:   free_matrix(matcov,1,npar,1,npar);
11322:   free_matrix(hess,1,npar,1,npar);
11323:   /*free_vector(delti,1,npar);*/
11324:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
11325:   free_matrix(agev,1,maxwav,1,imx);
11326:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
11327:   
11328:   free_ivector(ncodemax,1,NCOVMAX);
11329:   free_ivector(ncodemaxwundef,1,NCOVMAX);
11330:   free_ivector(Dummy,-1,NCOVMAX);
11331:   free_ivector(Fixed,-1,NCOVMAX);
11332:   free_ivector(DummyV,1,NCOVMAX);
11333:   free_ivector(FixedV,1,NCOVMAX);
11334:   free_ivector(Typevar,-1,NCOVMAX);
11335:   free_ivector(Tvar,1,NCOVMAX);
11336:   free_ivector(TvarsQ,1,NCOVMAX);
11337:   free_ivector(TvarsQind,1,NCOVMAX);
11338:   free_ivector(TvarsD,1,NCOVMAX);
11339:   free_ivector(TvarsDind,1,NCOVMAX);
11340:   free_ivector(TvarFD,1,NCOVMAX);
11341:   free_ivector(TvarFDind,1,NCOVMAX);
11342:   free_ivector(TvarF,1,NCOVMAX);
11343:   free_ivector(TvarFind,1,NCOVMAX);
11344:   free_ivector(TvarV,1,NCOVMAX);
11345:   free_ivector(TvarVind,1,NCOVMAX);
11346:   free_ivector(TvarA,1,NCOVMAX);
11347:   free_ivector(TvarAind,1,NCOVMAX);
11348:   free_ivector(TvarFQ,1,NCOVMAX);
11349:   free_ivector(TvarFQind,1,NCOVMAX);
11350:   free_ivector(TvarVD,1,NCOVMAX);
11351:   free_ivector(TvarVDind,1,NCOVMAX);
11352:   free_ivector(TvarVQ,1,NCOVMAX);
11353:   free_ivector(TvarVQind,1,NCOVMAX);
11354:   free_ivector(Tvarsel,1,NCOVMAX);
11355:   free_vector(Tvalsel,1,NCOVMAX);
11356:   free_ivector(Tposprod,1,NCOVMAX);
11357:   free_ivector(Tprod,1,NCOVMAX);
11358:   free_ivector(Tvaraff,1,NCOVMAX);
11359:   free_ivector(invalidvarcomb,1,ncovcombmax);
11360:   free_ivector(Tage,1,NCOVMAX);
11361:   free_ivector(Tmodelind,1,NCOVMAX);
11362:   free_ivector(TmodelInvind,1,NCOVMAX);
11363:   free_ivector(TmodelInvQind,1,NCOVMAX);
11364:   
11365:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
11366:   /* free_imatrix(codtab,1,100,1,10); */
11367:   fflush(fichtm);
11368:   fflush(ficgp);
11369:   
11370:   
11371:   if((nberr >0) || (nbwarn>0)){
11372:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
11373:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d. Please look at the log file for details.\n",nberr,nbwarn);
11374:   }else{
11375:     printf("End of Imach\n");
11376:     fprintf(ficlog,"End of Imach\n");
11377:   }
11378:   printf("See log file on %s\n",filelog);
11379:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
11380:   /*(void) gettimeofday(&end_time,&tzp);*/
11381:   rend_time = time(NULL);  
11382:   end_time = *localtime(&rend_time);
11383:   /* tml = *localtime(&end_time.tm_sec); */
11384:   strcpy(strtend,asctime(&end_time));
11385:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
11386:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
11387:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
11388:   
11389:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
11390:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
11391:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
11392:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
11393: /*   if(fileappend(fichtm,optionfilehtm)){ */
11394:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
11395:   fclose(fichtm);
11396:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
11397:   fclose(fichtmcov);
11398:   fclose(ficgp);
11399:   fclose(ficlog);
11400:   /*------ End -----------*/
11401:   
11402:   
11403:   printf("Before Current directory %s!\n",pathcd);
11404: #ifdef WIN32
11405:   if (_chdir(pathcd) != 0)
11406:     printf("Can't move to directory %s!\n",path);
11407:   if(_getcwd(pathcd,MAXLINE) > 0)
11408: #else
11409:     if(chdir(pathcd) != 0)
11410:       printf("Can't move to directory %s!\n", path);
11411:   if (getcwd(pathcd, MAXLINE) > 0)
11412: #endif 
11413:     printf("Current directory %s!\n",pathcd);
11414:   /*strcat(plotcmd,CHARSEPARATOR);*/
11415:   sprintf(plotcmd,"gnuplot");
11416: #ifdef _WIN32
11417:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
11418: #endif
11419:   if(!stat(plotcmd,&info)){
11420:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
11421:     if(!stat(getenv("GNUPLOTBIN"),&info)){
11422:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
11423:     }else
11424:       strcpy(pplotcmd,plotcmd);
11425: #ifdef __unix
11426:     strcpy(plotcmd,GNUPLOTPROGRAM);
11427:     if(!stat(plotcmd,&info)){
11428:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
11429:     }else
11430:       strcpy(pplotcmd,plotcmd);
11431: #endif
11432:   }else
11433:     strcpy(pplotcmd,plotcmd);
11434:   
11435:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
11436:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
11437:   
11438:   if((outcmd=system(plotcmd)) != 0){
11439:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
11440:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
11441:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
11442:     if((outcmd=system(plotcmd)) != 0)
11443:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
11444:   }
11445:   printf(" Successful, please wait...");
11446:   while (z[0] != 'q') {
11447:     /* chdir(path); */
11448:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
11449:     scanf("%s",z);
11450: /*     if (z[0] == 'c') system("./imach"); */
11451:     if (z[0] == 'e') {
11452: #ifdef __APPLE__
11453:       sprintf(pplotcmd, "open %s", optionfilehtm);
11454: #elif __linux
11455:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
11456: #else
11457:       sprintf(pplotcmd, "%s", optionfilehtm);
11458: #endif
11459:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
11460:       system(pplotcmd);
11461:     }
11462:     else if (z[0] == 'g') system(plotcmd);
11463:     else if (z[0] == 'q') exit(0);
11464:   }
11465: end:
11466:   while (z[0] != 'q') {
11467:     printf("\nType  q for exiting: "); fflush(stdout);
11468:     scanf("%s",z);
11469:   }
11470: }

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