File:  [Local Repository] / imach / src / imach.c
Revision 1.224: download - view: text, annotated - select for diffs
Fri Jul 1 13:16:01 2016 UTC (7 years, 10 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
Summary: Fixes

    1: /* $Id: imach.c,v 1.224 2016/07/01 13:16:01 brouard Exp $
    2:   $State: Exp $
    3:   $Log: imach.c,v $
    4:   Revision 1.224  2016/07/01 13:16:01  brouard
    5:   Summary: Fixes
    6: 
    7:   Revision 1.223  2016/02/19 09:23:35  brouard
    8:   Summary: temporary
    9: 
   10:   Revision 1.222  2016/02/17 08:14:50  brouard
   11:   Summary: Probably last 0.98 stable version 0.98r6
   12: 
   13:   Revision 1.221  2016/02/15 23:35:36  brouard
   14:   Summary: minor bug
   15: 
   16:   Revision 1.219  2016/02/15 00:48:12  brouard
   17:   *** empty log message ***
   18: 
   19:   Revision 1.218  2016/02/12 11:29:23  brouard
   20:   Summary: 0.99 Back projections
   21: 
   22:   Revision 1.217  2015/12/23 17:18:31  brouard
   23:   Summary: Experimental backcast
   24: 
   25:   Revision 1.216  2015/12/18 17:32:11  brouard
   26:   Summary: 0.98r4 Warning and status=-2
   27: 
   28:   Version 0.98r4 is now:
   29:    - displaying an error when status is -1, date of interview unknown and date of death known;
   30:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
   31:   Older changes concerning s=-2, dating from 2005 have been supersed.
   32: 
   33:   Revision 1.215  2015/12/16 08:52:24  brouard
   34:   Summary: 0.98r4 working
   35: 
   36:   Revision 1.214  2015/12/16 06:57:54  brouard
   37:   Summary: temporary not working
   38: 
   39:   Revision 1.213  2015/12/11 18:22:17  brouard
   40:   Summary: 0.98r4
   41: 
   42:   Revision 1.212  2015/11/21 12:47:24  brouard
   43:   Summary: minor typo
   44: 
   45:   Revision 1.211  2015/11/21 12:41:11  brouard
   46:   Summary: 0.98r3 with some graph of projected cross-sectional
   47: 
   48:   Author: Nicolas Brouard
   49: 
   50:   Revision 1.210  2015/11/18 17:41:20  brouard
   51:   Summary: Start working on projected prevalences
   52: 
   53:   Revision 1.209  2015/11/17 22:12:03  brouard
   54:   Summary: Adding ftolpl parameter
   55:   Author: N Brouard
   56: 
   57:   We had difficulties to get smoothed confidence intervals. It was due
   58:   to the period prevalence which wasn't computed accurately. The inner
   59:   parameter ftolpl is now an outer parameter of the .imach parameter
   60:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
   61:   computation are long.
   62: 
   63:   Revision 1.208  2015/11/17 14:31:57  brouard
   64:   Summary: temporary
   65: 
   66:   Revision 1.207  2015/10/27 17:36:57  brouard
   67:   *** empty log message ***
   68: 
   69:   Revision 1.206  2015/10/24 07:14:11  brouard
   70:   *** empty log message ***
   71: 
   72:   Revision 1.205  2015/10/23 15:50:53  brouard
   73:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
   74: 
   75:   Revision 1.204  2015/10/01 16:20:26  brouard
   76:   Summary: Some new graphs of contribution to likelihood
   77: 
   78:   Revision 1.203  2015/09/30 17:45:14  brouard
   79:   Summary: looking at better estimation of the hessian
   80: 
   81:   Also a better criteria for convergence to the period prevalence And
   82:   therefore adding the number of years needed to converge. (The
   83:   prevalence in any alive state shold sum to one
   84: 
   85:   Revision 1.202  2015/09/22 19:45:16  brouard
   86:   Summary: Adding some overall graph on contribution to likelihood. Might change
   87: 
   88:   Revision 1.201  2015/09/15 17:34:58  brouard
   89:   Summary: 0.98r0
   90: 
   91:   - Some new graphs like suvival functions
   92:   - Some bugs fixed like model=1+age+V2.
   93: 
   94:   Revision 1.200  2015/09/09 16:53:55  brouard
   95:   Summary: Big bug thanks to Flavia
   96: 
   97:   Even model=1+age+V2. did not work anymore
   98: 
   99:   Revision 1.199  2015/09/07 14:09:23  brouard
  100:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
  101: 
  102:   Revision 1.198  2015/09/03 07:14:39  brouard
  103:   Summary: 0.98q5 Flavia
  104: 
  105:   Revision 1.197  2015/09/01 18:24:39  brouard
  106:   *** empty log message ***
  107: 
  108:   Revision 1.196  2015/08/18 23:17:52  brouard
  109:   Summary: 0.98q5
  110: 
  111:   Revision 1.195  2015/08/18 16:28:39  brouard
  112:   Summary: Adding a hack for testing purpose
  113: 
  114:   After reading the title, ftol and model lines, if the comment line has
  115:   a q, starting with #q, the answer at the end of the run is quit. It
  116:   permits to run test files in batch with ctest. The former workaround was
  117:   $ echo q | imach foo.imach
  118: 
  119:   Revision 1.194  2015/08/18 13:32:00  brouard
  120:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
  121: 
  122:   Revision 1.193  2015/08/04 07:17:42  brouard
  123:   Summary: 0.98q4
  124: 
  125:   Revision 1.192  2015/07/16 16:49:02  brouard
  126:   Summary: Fixing some outputs
  127: 
  128:   Revision 1.191  2015/07/14 10:00:33  brouard
  129:   Summary: Some fixes
  130: 
  131:   Revision 1.190  2015/05/05 08:51:13  brouard
  132:   Summary: Adding digits in output parameters (7 digits instead of 6)
  133: 
  134:   Fix 1+age+.
  135: 
  136:   Revision 1.189  2015/04/30 14:45:16  brouard
  137:   Summary: 0.98q2
  138: 
  139:   Revision 1.188  2015/04/30 08:27:53  brouard
  140:   *** empty log message ***
  141: 
  142:   Revision 1.187  2015/04/29 09:11:15  brouard
  143:   *** empty log message ***
  144: 
  145:   Revision 1.186  2015/04/23 12:01:52  brouard
  146:   Summary: V1*age is working now, version 0.98q1
  147: 
  148:   Some codes had been disabled in order to simplify and Vn*age was
  149:   working in the optimization phase, ie, giving correct MLE parameters,
  150:   but, as usual, outputs were not correct and program core dumped.
  151: 
  152:   Revision 1.185  2015/03/11 13:26:42  brouard
  153:   Summary: Inclusion of compile and links command line for Intel Compiler
  154: 
  155:   Revision 1.184  2015/03/11 11:52:39  brouard
  156:   Summary: Back from Windows 8. Intel Compiler
  157: 
  158:   Revision 1.183  2015/03/10 20:34:32  brouard
  159:   Summary: 0.98q0, trying with directest, mnbrak fixed
  160: 
  161:   We use directest instead of original Powell test; probably no
  162:   incidence on the results, but better justifications;
  163:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
  164:   wrong results.
  165: 
  166:   Revision 1.182  2015/02/12 08:19:57  brouard
  167:   Summary: Trying to keep directest which seems simpler and more general
  168:   Author: Nicolas Brouard
  169: 
  170:   Revision 1.181  2015/02/11 23:22:24  brouard
  171:   Summary: Comments on Powell added
  172: 
  173:   Author:
  174: 
  175:   Revision 1.180  2015/02/11 17:33:45  brouard
  176:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
  177: 
  178:   Revision 1.179  2015/01/04 09:57:06  brouard
  179:   Summary: back to OS/X
  180: 
  181:   Revision 1.178  2015/01/04 09:35:48  brouard
  182:   *** empty log message ***
  183: 
  184:   Revision 1.177  2015/01/03 18:40:56  brouard
  185:   Summary: Still testing ilc32 on OSX
  186: 
  187:   Revision 1.176  2015/01/03 16:45:04  brouard
  188:   *** empty log message ***
  189: 
  190:   Revision 1.175  2015/01/03 16:33:42  brouard
  191:   *** empty log message ***
  192: 
  193:   Revision 1.174  2015/01/03 16:15:49  brouard
  194:   Summary: Still in cross-compilation
  195: 
  196:   Revision 1.173  2015/01/03 12:06:26  brouard
  197:   Summary: trying to detect cross-compilation
  198: 
  199:   Revision 1.172  2014/12/27 12:07:47  brouard
  200:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
  201: 
  202:   Revision 1.171  2014/12/23 13:26:59  brouard
  203:   Summary: Back from Visual C
  204: 
  205:   Still problem with utsname.h on Windows
  206: 
  207:   Revision 1.170  2014/12/23 11:17:12  brouard
  208:   Summary: Cleaning some \%% back to %%
  209: 
  210:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
  211: 
  212:   Revision 1.169  2014/12/22 23:08:31  brouard
  213:   Summary: 0.98p
  214: 
  215:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
  216: 
  217:   Revision 1.168  2014/12/22 15:17:42  brouard
  218:   Summary: update
  219: 
  220:   Revision 1.167  2014/12/22 13:50:56  brouard
  221:   Summary: Testing uname and compiler version and if compiled 32 or 64
  222: 
  223:   Testing on Linux 64
  224: 
  225:   Revision 1.166  2014/12/22 11:40:47  brouard
  226:   *** empty log message ***
  227: 
  228:   Revision 1.165  2014/12/16 11:20:36  brouard
  229:   Summary: After compiling on Visual C
  230: 
  231:   * imach.c (Module): Merging 1.61 to 1.162
  232: 
  233:   Revision 1.164  2014/12/16 10:52:11  brouard
  234:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
  235: 
  236:   * imach.c (Module): Merging 1.61 to 1.162
  237: 
  238:   Revision 1.163  2014/12/16 10:30:11  brouard
  239:   * imach.c (Module): Merging 1.61 to 1.162
  240: 
  241:   Revision 1.162  2014/09/25 11:43:39  brouard
  242:   Summary: temporary backup 0.99!
  243: 
  244:   Revision 1.1  2014/09/16 11:06:58  brouard
  245:   Summary: With some code (wrong) for nlopt
  246: 
  247:   Author:
  248: 
  249:   Revision 1.161  2014/09/15 20:41:41  brouard
  250:   Summary: Problem with macro SQR on Intel compiler
  251: 
  252:   Revision 1.160  2014/09/02 09:24:05  brouard
  253:   *** empty log message ***
  254: 
  255:   Revision 1.159  2014/09/01 10:34:10  brouard
  256:   Summary: WIN32
  257:   Author: Brouard
  258: 
  259:   Revision 1.158  2014/08/27 17:11:51  brouard
  260:   *** empty log message ***
  261: 
  262:   Revision 1.157  2014/08/27 16:26:55  brouard
  263:   Summary: Preparing windows Visual studio version
  264:   Author: Brouard
  265: 
  266:   In order to compile on Visual studio, time.h is now correct and time_t
  267:   and tm struct should be used. difftime should be used but sometimes I
  268:   just make the differences in raw time format (time(&now).
  269:   Trying to suppress #ifdef LINUX
  270:   Add xdg-open for __linux in order to open default browser.
  271: 
  272:   Revision 1.156  2014/08/25 20:10:10  brouard
  273:   *** empty log message ***
  274: 
  275:   Revision 1.155  2014/08/25 18:32:34  brouard
  276:   Summary: New compile, minor changes
  277:   Author: Brouard
  278: 
  279:   Revision 1.154  2014/06/20 17:32:08  brouard
  280:   Summary: Outputs now all graphs of convergence to period prevalence
  281: 
  282:   Revision 1.153  2014/06/20 16:45:46  brouard
  283:   Summary: If 3 live state, convergence to period prevalence on same graph
  284:   Author: Brouard
  285: 
  286:   Revision 1.152  2014/06/18 17:54:09  brouard
  287:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
  288: 
  289:   Revision 1.151  2014/06/18 16:43:30  brouard
  290:   *** empty log message ***
  291: 
  292:   Revision 1.150  2014/06/18 16:42:35  brouard
  293:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
  294:   Author: brouard
  295: 
  296:   Revision 1.149  2014/06/18 15:51:14  brouard
  297:   Summary: Some fixes in parameter files errors
  298:   Author: Nicolas Brouard
  299: 
  300:   Revision 1.148  2014/06/17 17:38:48  brouard
  301:   Summary: Nothing new
  302:   Author: Brouard
  303: 
  304:   Just a new packaging for OS/X version 0.98nS
  305: 
  306:   Revision 1.147  2014/06/16 10:33:11  brouard
  307:   *** empty log message ***
  308: 
  309:   Revision 1.146  2014/06/16 10:20:28  brouard
  310:   Summary: Merge
  311:   Author: Brouard
  312: 
  313:   Merge, before building revised version.
  314: 
  315:   Revision 1.145  2014/06/10 21:23:15  brouard
  316:   Summary: Debugging with valgrind
  317:   Author: Nicolas Brouard
  318: 
  319:   Lot of changes in order to output the results with some covariates
  320:   After the Edimburgh REVES conference 2014, it seems mandatory to
  321:   improve the code.
  322:   No more memory valgrind error but a lot has to be done in order to
  323:   continue the work of splitting the code into subroutines.
  324:   Also, decodemodel has been improved. Tricode is still not
  325:   optimal. nbcode should be improved. Documentation has been added in
  326:   the source code.
  327: 
  328:   Revision 1.143  2014/01/26 09:45:38  brouard
  329:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
  330: 
  331:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  332:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
  333: 
  334:   Revision 1.142  2014/01/26 03:57:36  brouard
  335:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
  336: 
  337:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  338: 
  339:   Revision 1.141  2014/01/26 02:42:01  brouard
  340:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  341: 
  342:   Revision 1.140  2011/09/02 10:37:54  brouard
  343:   Summary: times.h is ok with mingw32 now.
  344: 
  345:   Revision 1.139  2010/06/14 07:50:17  brouard
  346:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
  347:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
  348: 
  349:   Revision 1.138  2010/04/30 18:19:40  brouard
  350:   *** empty log message ***
  351: 
  352:   Revision 1.137  2010/04/29 18:11:38  brouard
  353:   (Module): Checking covariates for more complex models
  354:   than V1+V2. A lot of change to be done. Unstable.
  355: 
  356:   Revision 1.136  2010/04/26 20:30:53  brouard
  357:   (Module): merging some libgsl code. Fixing computation
  358:   of likelione (using inter/intrapolation if mle = 0) in order to
  359:   get same likelihood as if mle=1.
  360:   Some cleaning of code and comments added.
  361: 
  362:   Revision 1.135  2009/10/29 15:33:14  brouard
  363:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  364: 
  365:   Revision 1.134  2009/10/29 13:18:53  brouard
  366:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  367: 
  368:   Revision 1.133  2009/07/06 10:21:25  brouard
  369:   just nforces
  370: 
  371:   Revision 1.132  2009/07/06 08:22:05  brouard
  372:   Many tings
  373: 
  374:   Revision 1.131  2009/06/20 16:22:47  brouard
  375:   Some dimensions resccaled
  376: 
  377:   Revision 1.130  2009/05/26 06:44:34  brouard
  378:   (Module): Max Covariate is now set to 20 instead of 8. A
  379:   lot of cleaning with variables initialized to 0. Trying to make
  380:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
  381: 
  382:   Revision 1.129  2007/08/31 13:49:27  lievre
  383:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
  384: 
  385:   Revision 1.128  2006/06/30 13:02:05  brouard
  386:   (Module): Clarifications on computing e.j
  387: 
  388:   Revision 1.127  2006/04/28 18:11:50  brouard
  389:   (Module): Yes the sum of survivors was wrong since
  390:   imach-114 because nhstepm was no more computed in the age
  391:   loop. Now we define nhstepma in the age loop.
  392:   (Module): In order to speed up (in case of numerous covariates) we
  393:   compute health expectancies (without variances) in a first step
  394:   and then all the health expectancies with variances or standard
  395:   deviation (needs data from the Hessian matrices) which slows the
  396:   computation.
  397:   In the future we should be able to stop the program is only health
  398:   expectancies and graph are needed without standard deviations.
  399: 
  400:   Revision 1.126  2006/04/28 17:23:28  brouard
  401:   (Module): Yes the sum of survivors was wrong since
  402:   imach-114 because nhstepm was no more computed in the age
  403:   loop. Now we define nhstepma in the age loop.
  404:   Version 0.98h
  405: 
  406:   Revision 1.125  2006/04/04 15:20:31  lievre
  407:   Errors in calculation of health expectancies. Age was not initialized.
  408:   Forecasting file added.
  409: 
  410:   Revision 1.124  2006/03/22 17:13:53  lievre
  411:   Parameters are printed with %lf instead of %f (more numbers after the comma).
  412:   The log-likelihood is printed in the log file
  413: 
  414:   Revision 1.123  2006/03/20 10:52:43  brouard
  415:   * imach.c (Module): <title> changed, corresponds to .htm file
  416:   name. <head> headers where missing.
  417: 
  418:   * imach.c (Module): Weights can have a decimal point as for
  419:   English (a comma might work with a correct LC_NUMERIC environment,
  420:   otherwise the weight is truncated).
  421:   Modification of warning when the covariates values are not 0 or
  422:   1.
  423:   Version 0.98g
  424: 
  425:   Revision 1.122  2006/03/20 09:45:41  brouard
  426:   (Module): Weights can have a decimal point as for
  427:   English (a comma might work with a correct LC_NUMERIC environment,
  428:   otherwise the weight is truncated).
  429:   Modification of warning when the covariates values are not 0 or
  430:   1.
  431:   Version 0.98g
  432: 
  433:   Revision 1.121  2006/03/16 17:45:01  lievre
  434:   * imach.c (Module): Comments concerning covariates added
  435: 
  436:   * imach.c (Module): refinements in the computation of lli if
  437:   status=-2 in order to have more reliable computation if stepm is
  438:   not 1 month. Version 0.98f
  439: 
  440:   Revision 1.120  2006/03/16 15:10:38  lievre
  441:   (Module): refinements in the computation of lli if
  442:   status=-2 in order to have more reliable computation if stepm is
  443:   not 1 month. Version 0.98f
  444: 
  445:   Revision 1.119  2006/03/15 17:42:26  brouard
  446:   (Module): Bug if status = -2, the loglikelihood was
  447:   computed as likelihood omitting the logarithm. Version O.98e
  448: 
  449:   Revision 1.118  2006/03/14 18:20:07  brouard
  450:   (Module): varevsij Comments added explaining the second
  451:   table of variances if popbased=1 .
  452:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  453:   (Module): Function pstamp added
  454:   (Module): Version 0.98d
  455: 
  456:   Revision 1.117  2006/03/14 17:16:22  brouard
  457:   (Module): varevsij Comments added explaining the second
  458:   table of variances if popbased=1 .
  459:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  460:   (Module): Function pstamp added
  461:   (Module): Version 0.98d
  462: 
  463:   Revision 1.116  2006/03/06 10:29:27  brouard
  464:   (Module): Variance-covariance wrong links and
  465:   varian-covariance of ej. is needed (Saito).
  466: 
  467:   Revision 1.115  2006/02/27 12:17:45  brouard
  468:   (Module): One freematrix added in mlikeli! 0.98c
  469: 
  470:   Revision 1.114  2006/02/26 12:57:58  brouard
  471:   (Module): Some improvements in processing parameter
  472:   filename with strsep.
  473: 
  474:   Revision 1.113  2006/02/24 14:20:24  brouard
  475:   (Module): Memory leaks checks with valgrind and:
  476:   datafile was not closed, some imatrix were not freed and on matrix
  477:   allocation too.
  478: 
  479:   Revision 1.112  2006/01/30 09:55:26  brouard
  480:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
  481: 
  482:   Revision 1.111  2006/01/25 20:38:18  brouard
  483:   (Module): Lots of cleaning and bugs added (Gompertz)
  484:   (Module): Comments can be added in data file. Missing date values
  485:   can be a simple dot '.'.
  486: 
  487:   Revision 1.110  2006/01/25 00:51:50  brouard
  488:   (Module): Lots of cleaning and bugs added (Gompertz)
  489: 
  490:   Revision 1.109  2006/01/24 19:37:15  brouard
  491:   (Module): Comments (lines starting with a #) are allowed in data.
  492: 
  493:   Revision 1.108  2006/01/19 18:05:42  lievre
  494:   Gnuplot problem appeared...
  495:   To be fixed
  496: 
  497:   Revision 1.107  2006/01/19 16:20:37  brouard
  498:   Test existence of gnuplot in imach path
  499: 
  500:   Revision 1.106  2006/01/19 13:24:36  brouard
  501:   Some cleaning and links added in html output
  502: 
  503:   Revision 1.105  2006/01/05 20:23:19  lievre
  504:   *** empty log message ***
  505: 
  506:   Revision 1.104  2005/09/30 16:11:43  lievre
  507:   (Module): sump fixed, loop imx fixed, and simplifications.
  508:   (Module): If the status is missing at the last wave but we know
  509:   that the person is alive, then we can code his/her status as -2
  510:   (instead of missing=-1 in earlier versions) and his/her
  511:   contributions to the likelihood is 1 - Prob of dying from last
  512:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
  513:   the healthy state at last known wave). Version is 0.98
  514: 
  515:   Revision 1.103  2005/09/30 15:54:49  lievre
  516:   (Module): sump fixed, loop imx fixed, and simplifications.
  517: 
  518:   Revision 1.102  2004/09/15 17:31:30  brouard
  519:   Add the possibility to read data file including tab characters.
  520: 
  521:   Revision 1.101  2004/09/15 10:38:38  brouard
  522:   Fix on curr_time
  523: 
  524:   Revision 1.100  2004/07/12 18:29:06  brouard
  525:   Add version for Mac OS X. Just define UNIX in Makefile
  526: 
  527:   Revision 1.99  2004/06/05 08:57:40  brouard
  528:   *** empty log message ***
  529: 
  530:   Revision 1.98  2004/05/16 15:05:56  brouard
  531:   New version 0.97 . First attempt to estimate force of mortality
  532:   directly from the data i.e. without the need of knowing the health
  533:   state at each age, but using a Gompertz model: log u =a + b*age .
  534:   This is the basic analysis of mortality and should be done before any
  535:   other analysis, in order to test if the mortality estimated from the
  536:   cross-longitudinal survey is different from the mortality estimated
  537:   from other sources like vital statistic data.
  538: 
  539:   The same imach parameter file can be used but the option for mle should be -3.
  540: 
  541:   Agnès, who wrote this part of the code, tried to keep most of the
  542:   former routines in order to include the new code within the former code.
  543: 
  544:   The output is very simple: only an estimate of the intercept and of
  545:   the slope with 95% confident intervals.
  546: 
  547:   Current limitations:
  548:   A) Even if you enter covariates, i.e. with the
  549:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
  550:   B) There is no computation of Life Expectancy nor Life Table.
  551: 
  552:   Revision 1.97  2004/02/20 13:25:42  lievre
  553:   Version 0.96d. Population forecasting command line is (temporarily)
  554:   suppressed.
  555: 
  556:   Revision 1.96  2003/07/15 15:38:55  brouard
  557:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
  558:   rewritten within the same printf. Workaround: many printfs.
  559: 
  560:   Revision 1.95  2003/07/08 07:54:34  brouard
  561:   * imach.c (Repository):
  562:   (Repository): Using imachwizard code to output a more meaningful covariance
  563:   matrix (cov(a12,c31) instead of numbers.
  564: 
  565:   Revision 1.94  2003/06/27 13:00:02  brouard
  566:   Just cleaning
  567: 
  568:   Revision 1.93  2003/06/25 16:33:55  brouard
  569:   (Module): On windows (cygwin) function asctime_r doesn't
  570:   exist so I changed back to asctime which exists.
  571:   (Module): Version 0.96b
  572: 
  573:   Revision 1.92  2003/06/25 16:30:45  brouard
  574:   (Module): On windows (cygwin) function asctime_r doesn't
  575:   exist so I changed back to asctime which exists.
  576: 
  577:   Revision 1.91  2003/06/25 15:30:29  brouard
  578:   * imach.c (Repository): Duplicated warning errors corrected.
  579:   (Repository): Elapsed time after each iteration is now output. It
  580:   helps to forecast when convergence will be reached. Elapsed time
  581:   is stamped in powell.  We created a new html file for the graphs
  582:   concerning matrix of covariance. It has extension -cov.htm.
  583: 
  584:   Revision 1.90  2003/06/24 12:34:15  brouard
  585:   (Module): Some bugs corrected for windows. Also, when
  586:   mle=-1 a template is output in file "or"mypar.txt with the design
  587:   of the covariance matrix to be input.
  588: 
  589:   Revision 1.89  2003/06/24 12:30:52  brouard
  590:   (Module): Some bugs corrected for windows. Also, when
  591:   mle=-1 a template is output in file "or"mypar.txt with the design
  592:   of the covariance matrix to be input.
  593: 
  594:   Revision 1.88  2003/06/23 17:54:56  brouard
  595:   * 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.
  596: 
  597:   Revision 1.87  2003/06/18 12:26:01  brouard
  598:   Version 0.96
  599: 
  600:   Revision 1.86  2003/06/17 20:04:08  brouard
  601:   (Module): Change position of html and gnuplot routines and added
  602:   routine fileappend.
  603: 
  604:   Revision 1.85  2003/06/17 13:12:43  brouard
  605:   * imach.c (Repository): Check when date of death was earlier that
  606:   current date of interview. It may happen when the death was just
  607:   prior to the death. In this case, dh was negative and likelihood
  608:   was wrong (infinity). We still send an "Error" but patch by
  609:   assuming that the date of death was just one stepm after the
  610:   interview.
  611:   (Repository): Because some people have very long ID (first column)
  612:   we changed int to long in num[] and we added a new lvector for
  613:   memory allocation. But we also truncated to 8 characters (left
  614:   truncation)
  615:   (Repository): No more line truncation errors.
  616: 
  617:   Revision 1.84  2003/06/13 21:44:43  brouard
  618:   * imach.c (Repository): Replace "freqsummary" at a correct
  619:   place. It differs from routine "prevalence" which may be called
  620:   many times. Probs is memory consuming and must be used with
  621:   parcimony.
  622:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
  623: 
  624:   Revision 1.83  2003/06/10 13:39:11  lievre
  625:   *** empty log message ***
  626: 
  627:   Revision 1.82  2003/06/05 15:57:20  brouard
  628:   Add log in  imach.c and  fullversion number is now printed.
  629: 
  630: */
  631: /*
  632:    Interpolated Markov Chain
  633: 
  634:   Short summary of the programme:
  635:   
  636:   This program computes Healthy Life Expectancies from
  637:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
  638:   first survey ("cross") where individuals from different ages are
  639:   interviewed on their health status or degree of disability (in the
  640:   case of a health survey which is our main interest) -2- at least a
  641:   second wave of interviews ("longitudinal") which measure each change
  642:   (if any) in individual health status.  Health expectancies are
  643:   computed from the time spent in each health state according to a
  644:   model. More health states you consider, more time is necessary to reach the
  645:   Maximum Likelihood of the parameters involved in the model.  The
  646:   simplest model is the multinomial logistic model where pij is the
  647:   probability to be observed in state j at the second wave
  648:   conditional to be observed in state i at the first wave. Therefore
  649:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
  650:   'age' is age and 'sex' is a covariate. If you want to have a more
  651:   complex model than "constant and age", you should modify the program
  652:   where the markup *Covariates have to be included here again* invites
  653:   you to do it.  More covariates you add, slower the
  654:   convergence.
  655: 
  656:   The advantage of this computer programme, compared to a simple
  657:   multinomial logistic model, is clear when the delay between waves is not
  658:   identical for each individual. Also, if a individual missed an
  659:   intermediate interview, the information is lost, but taken into
  660:   account using an interpolation or extrapolation.  
  661: 
  662:   hPijx is the probability to be observed in state i at age x+h
  663:   conditional to the observed state i at age x. The delay 'h' can be
  664:   split into an exact number (nh*stepm) of unobserved intermediate
  665:   states. This elementary transition (by month, quarter,
  666:   semester or year) is modelled as a multinomial logistic.  The hPx
  667:   matrix is simply the matrix product of nh*stepm elementary matrices
  668:   and the contribution of each individual to the likelihood is simply
  669:   hPijx.
  670: 
  671:   Also this programme outputs the covariance matrix of the parameters but also
  672:   of the life expectancies. It also computes the period (stable) prevalence.
  673: 
  674: Back prevalence and projections:
  675:  - 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)
  676:     Computes the back prevalence limit  for any combination	of covariate values k
  677:     at any age between ageminpar and agemaxpar and returns it in **bprlim. In the loops,
  678:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm, **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
  679:  - hBijx Back Probability to be in state i at age x-h being in j at x
  680:    Computes for any combination of covariates k and any age between bage and fage 
  681:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
  682:  			oldm=oldms;savm=savms;
  683: 	 - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
  684:      Computes the transition matrix starting at age 'age' over
  685:      'nhstepm*hstepm*stepm' months (i.e. until
  686:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
  687:      nhstepm*hstepm matrices. Returns p3mat[i][j][h] after calling 
  688:      p3mat[i][j][h]=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\
  689: 									 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
  690: 
  691:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
  692:            Institut national d'études démographiques, Paris.
  693:   This software have been partly granted by Euro-REVES, a concerted action
  694:   from the European Union.
  695:   It is copyrighted identically to a GNU software product, ie programme and
  696:   software can be distributed freely for non commercial use. Latest version
  697:   can be accessed at http://euroreves.ined.fr/imach .
  698: 
  699:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
  700:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
  701:   
  702:   **********************************************************************/
  703: /*
  704:   main
  705:   read parameterfile
  706:   read datafile
  707:   concatwav
  708:   freqsummary
  709:   if (mle >= 1)
  710:     mlikeli
  711:   print results files
  712:   if mle==1 
  713:      computes hessian
  714:   read end of parameter file: agemin, agemax, bage, fage, estepm
  715:       begin-prev-date,...
  716:   open gnuplot file
  717:   open html file
  718:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
  719:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
  720:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
  721:     freexexit2 possible for memory heap.
  722: 
  723:   h Pij x                         | pij_nom  ficrestpij
  724:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
  725:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
  726:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
  727: 
  728:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
  729:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
  730:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
  731:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
  732:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
  733: 
  734:   forecasting if prevfcast==1 prevforecast call prevalence()
  735:   health expectancies
  736:   Variance-covariance of DFLE
  737:   prevalence()
  738:    movingaverage()
  739:   varevsij() 
  740:   if popbased==1 varevsij(,popbased)
  741:   total life expectancies
  742:   Variance of period (stable) prevalence
  743:  end
  744: */
  745: 
  746: /* #define DEBUG */
  747: /* #define DEBUGBRENT */
  748: /* #define DEBUGLINMIN */
  749: /* #define DEBUGHESS */
  750: #define DEBUGHESSIJ
  751: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
  752: #define POWELL /* Instead of NLOPT */
  753: #define POWELLNOF3INFF1TEST /* Skip test */
  754: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
  755: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
  756: 
  757: #include <math.h>
  758: #include <stdio.h>
  759: #include <stdlib.h>
  760: #include <string.h>
  761: 
  762: #ifdef _WIN32
  763: #include <io.h>
  764: #include <windows.h>
  765: #include <tchar.h>
  766: #else
  767: #include <unistd.h>
  768: #endif
  769: 
  770: #include <limits.h>
  771: #include <sys/types.h>
  772: 
  773: #if defined(__GNUC__)
  774: #include <sys/utsname.h> /* Doesn't work on Windows */
  775: #endif
  776: 
  777: #include <sys/stat.h>
  778: #include <errno.h>
  779: /* extern int errno; */
  780: 
  781: /* #ifdef LINUX */
  782: /* #include <time.h> */
  783: /* #include "timeval.h" */
  784: /* #else */
  785: /* #include <sys/time.h> */
  786: /* #endif */
  787: 
  788: #include <time.h>
  789: 
  790: #ifdef GSL
  791: #include <gsl/gsl_errno.h>
  792: #include <gsl/gsl_multimin.h>
  793: #endif
  794: 
  795: 
  796: #ifdef NLOPT
  797: #include <nlopt.h>
  798: typedef struct {
  799:   double (* function)(double [] );
  800: } myfunc_data ;
  801: #endif
  802: 
  803: /* #include <libintl.h> */
  804: /* #define _(String) gettext (String) */
  805: 
  806: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
  807: 
  808: #define GNUPLOTPROGRAM "gnuplot"
  809: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
  810: #define FILENAMELENGTH 132
  811: 
  812: #define	GLOCK_ERROR_NOPATH		-1	/* empty path */
  813: #define	GLOCK_ERROR_GETCWD		-2	/* cannot get cwd */
  814: 
  815: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
  816: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
  817: 
  818: #define NINTERVMAX 8
  819: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
  820: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
  821: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
  822: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
  823: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
  824: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
  825: #define MAXN 20000
  826: #define YEARM 12. /**< Number of months per year */
  827: /* #define AGESUP 130 */
  828: #define AGESUP 150
  829: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
  830: #define AGEBASE 40
  831: #define AGEOVERFLOW 1.e20
  832: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
  833: #ifdef _WIN32
  834: #define DIRSEPARATOR '\\'
  835: #define CHARSEPARATOR "\\"
  836: #define ODIRSEPARATOR '/'
  837: #else
  838: #define DIRSEPARATOR '/'
  839: #define CHARSEPARATOR "/"
  840: #define ODIRSEPARATOR '\\'
  841: #endif
  842: 
  843: /* $Id: imach.c,v 1.224 2016/07/01 13:16:01 brouard Exp $ */
  844: /* $State: Exp $ */
  845: #include "version.h"
  846: char version[]=__IMACH_VERSION__;
  847: 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";
  848: char fullversion[]="$Revision: 1.224 $ $Date: 2016/07/01 13:16:01 $"; 
  849: char strstart[80];
  850: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
  851: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
  852: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
  853: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
  854: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
  855: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
  856: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
  857: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
  858: int cptcovprodnoage=0; /**< Number of covariate products without age */   
  859: int cptcoveff=0; /* Total number of covariates to vary for printing results */
  860: int ncoveff=0; /* Total number of effective covariates in the model */
  861: int nqveff=0; /**< nqveff number of effective quantitative variables */
  862: int ntveff=0; /**< ntveff number of effective time varying variables */
  863: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
  864: int cptcov=0; /* Working variable */
  865: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
  866: int npar=NPARMAX;
  867: int nlstate=2; /* Number of live states */
  868: int ndeath=1; /* Number of dead states */
  869: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
  870: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
  871: int popbased=0;
  872: 
  873: int *wav; /* Number of waves for this individuual 0 is possible */
  874: int maxwav=0; /* Maxim number of waves */
  875: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
  876: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
  877: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
  878: 		   to the likelihood and the sum of weights (done by funcone)*/
  879: int mle=1, weightopt=0;
  880: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
  881: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
  882: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
  883: 	   * wave mi and wave mi+1 is not an exact multiple of stepm. */
  884: int countcallfunc=0;  /* Count the number of calls to func */
  885: double jmean=1; /* Mean space between 2 waves */
  886: double **matprod2(); /* test */
  887: double **oldm, **newm, **savm; /* Working pointers to matrices */
  888: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
  889: double	 **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
  890: 
  891: /*FILE *fic ; */ /* Used in readdata only */
  892: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
  893: FILE *ficlog, *ficrespow;
  894: int globpr=0; /* Global variable for printing or not */
  895: double fretone; /* Only one call to likelihood */
  896: long ipmx=0; /* Number of contributions */
  897: double sw; /* Sum of weights */
  898: char filerespow[FILENAMELENGTH];
  899: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
  900: FILE *ficresilk;
  901: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
  902: FILE *ficresprobmorprev;
  903: FILE *fichtm, *fichtmcov; /* Html File */
  904: FILE *ficreseij;
  905: char filerese[FILENAMELENGTH];
  906: FILE *ficresstdeij;
  907: char fileresstde[FILENAMELENGTH];
  908: FILE *ficrescveij;
  909: char filerescve[FILENAMELENGTH];
  910: FILE  *ficresvij;
  911: char fileresv[FILENAMELENGTH];
  912: FILE  *ficresvpl;
  913: char fileresvpl[FILENAMELENGTH];
  914: char title[MAXLINE];
  915: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
  916: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
  917: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
  918: char command[FILENAMELENGTH];
  919: int  outcmd=0;
  920: 
  921: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
  922: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
  923: char filelog[FILENAMELENGTH]; /* Log file */
  924: char filerest[FILENAMELENGTH];
  925: char fileregp[FILENAMELENGTH];
  926: char popfile[FILENAMELENGTH];
  927: 
  928: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
  929: 
  930: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
  931: /* struct timezone tzp; */
  932: /* extern int gettimeofday(); */
  933: struct tm tml, *gmtime(), *localtime();
  934: 
  935: extern time_t time();
  936: 
  937: struct tm start_time, end_time, curr_time, last_time, forecast_time;
  938: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
  939: struct tm tm;
  940: 
  941: char strcurr[80], strfor[80];
  942: 
  943: char *endptr;
  944: long lval;
  945: double dval;
  946: 
  947: #define NR_END 1
  948: #define FREE_ARG char*
  949: #define FTOL 1.0e-10
  950: 
  951: #define NRANSI 
  952: #define ITMAX 200 
  953: 
  954: #define TOL 2.0e-4 
  955: 
  956: #define CGOLD 0.3819660 
  957: #define ZEPS 1.0e-10 
  958: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
  959: 
  960: #define GOLD 1.618034 
  961: #define GLIMIT 100.0 
  962: #define TINY 1.0e-20 
  963: 
  964: static double maxarg1,maxarg2;
  965: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
  966: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
  967:   
  968: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
  969: #define rint(a) floor(a+0.5)
  970: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
  971: #define mytinydouble 1.0e-16
  972: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
  973: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
  974: /* static double dsqrarg; */
  975: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
  976: static double sqrarg;
  977: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
  978: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
  979: int agegomp= AGEGOMP;
  980: 
  981: int imx; 
  982: int stepm=1;
  983: /* Stepm, step in month: minimum step interpolation*/
  984: 
  985: int estepm;
  986: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
  987: 
  988: int m,nb;
  989: long *num;
  990: int firstpass=0, lastpass=4,*cod, *cens;
  991: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
  992: 		   covariate for which somebody answered excluding 
  993: 		   undefined. Usually 2: 0 and 1. */
  994: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
  995: 			     covariate for which somebody answered including 
  996: 			     undefined. Usually 3: -1, 0 and 1. */
  997: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
  998: double **pmmij, ***probs; /* Global pointer */
  999: double ***mobaverage, ***mobaverages; /* New global variable */
 1000: double *ageexmed,*agecens;
 1001: double dateintmean=0;
 1002: 
 1003: double *weight;
 1004: int **s; /* Status */
 1005: double *agedc;
 1006: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
 1007: 		  * covar=matrix(0,NCOVMAX,1,n); 
 1008: 		  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
 1009: double **coqvar; /* Fixed quantitative covariate */
 1010: double ***cotvar; /* Time varying covariate */
 1011: double ***cotqvar; /* Time varying quantitative covariate */
 1012: double  idx; 
 1013: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
 1014: int *Tage;
 1015: int *Ndum; /** Freq of modality (tricode */
 1016: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
 1017: int **Tvard, *Tprod, cptcovprod, *Tvaraff, *invalidvarcomb;
 1018: double *lsurv, *lpop, *tpop;
 1019: 
 1020: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
 1021: double ftolhess; /**< Tolerance for computing hessian */
 1022: 
 1023: /**************** split *************************/
 1024: static	int split( char *path, char *dirc, char *name, char *ext, char *finame )
 1025: {
 1026:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
 1027:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
 1028:   */ 
 1029:   char	*ss;				/* pointer */
 1030:   int	l1=0, l2=0;				/* length counters */
 1031: 
 1032:   l1 = strlen(path );			/* length of path */
 1033:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
 1034:   ss= strrchr( path, DIRSEPARATOR );		/* find last / */
 1035:   if ( ss == NULL ) {			/* no directory, so determine current directory */
 1036:     strcpy( name, path );		/* we got the fullname name because no directory */
 1037:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
 1038:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
 1039:     /* get current working directory */
 1040:     /*    extern  char* getcwd ( char *buf , int len);*/
 1041: #ifdef WIN32
 1042:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
 1043: #else
 1044: 	if (getcwd(dirc, FILENAME_MAX) == NULL) {
 1045: #endif
 1046:       return( GLOCK_ERROR_GETCWD );
 1047:     }
 1048:     /* got dirc from getcwd*/
 1049:     printf(" DIRC = %s \n",dirc);
 1050:   } else {				/* strip directory from path */
 1051:     ss++;				/* after this, the filename */
 1052:     l2 = strlen( ss );			/* length of filename */
 1053:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
 1054:     strcpy( name, ss );		/* save file name */
 1055:     strncpy( dirc, path, l1 - l2 );	/* now the directory */
 1056:     dirc[l1-l2] = '\0';			/* add zero */
 1057:     printf(" DIRC2 = %s \n",dirc);
 1058:   }
 1059:   /* We add a separator at the end of dirc if not exists */
 1060:   l1 = strlen( dirc );			/* length of directory */
 1061:   if( dirc[l1-1] != DIRSEPARATOR ){
 1062:     dirc[l1] =  DIRSEPARATOR;
 1063:     dirc[l1+1] = 0; 
 1064:     printf(" DIRC3 = %s \n",dirc);
 1065:   }
 1066:   ss = strrchr( name, '.' );		/* find last / */
 1067:   if (ss >0){
 1068:     ss++;
 1069:     strcpy(ext,ss);			/* save extension */
 1070:     l1= strlen( name);
 1071:     l2= strlen(ss)+1;
 1072:     strncpy( finame, name, l1-l2);
 1073:     finame[l1-l2]= 0;
 1074:   }
 1075: 
 1076:   return( 0 );				/* we're done */
 1077: }
 1078: 
 1079: 
 1080: /******************************************/
 1081: 
 1082: void replace_back_to_slash(char *s, char*t)
 1083: {
 1084:   int i;
 1085:   int lg=0;
 1086:   i=0;
 1087:   lg=strlen(t);
 1088:   for(i=0; i<= lg; i++) {
 1089:     (s[i] = t[i]);
 1090:     if (t[i]== '\\') s[i]='/';
 1091:   }
 1092: }
 1093: 
 1094: char *trimbb(char *out, char *in)
 1095: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
 1096:   char *s;
 1097:   s=out;
 1098:   while (*in != '\0'){
 1099:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
 1100:       in++;
 1101:     }
 1102:     *out++ = *in++;
 1103:   }
 1104:   *out='\0';
 1105:   return s;
 1106: }
 1107: 
 1108: /* char *substrchaine(char *out, char *in, char *chain) */
 1109: /* { */
 1110: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
 1111: /*   char *s, *t; */
 1112: /*   t=in;s=out; */
 1113: /*   while ((*in != *chain) && (*in != '\0')){ */
 1114: /*     *out++ = *in++; */
 1115: /*   } */
 1116: 
 1117: /*   /\* *in matches *chain *\/ */
 1118: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
 1119: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1120: /*   } */
 1121: /*   in--; chain--; */
 1122: /*   while ( (*in != '\0')){ */
 1123: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1124: /*     *out++ = *in++; */
 1125: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1126: /*   } */
 1127: /*   *out='\0'; */
 1128: /*   out=s; */
 1129: /*   return out; */
 1130: /* } */
 1131: char *substrchaine(char *out, char *in, char *chain)
 1132: {
 1133:   /* Substract chain 'chain' from 'in', return and output 'out' */
 1134:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
 1135: 
 1136:   char *strloc;
 1137: 
 1138:   strcpy (out, in); 
 1139:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
 1140:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
 1141:   if(strloc != NULL){ 
 1142:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
 1143:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
 1144:     /* strcpy (strloc, strloc +strlen(chain));*/
 1145:   }
 1146:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
 1147:   return out;
 1148: }
 1149: 
 1150: 
 1151: char *cutl(char *blocc, char *alocc, char *in, char occ)
 1152: {
 1153:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
 1154:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
 1155:      gives blocc="abcdef" and alocc="ghi2j".
 1156:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
 1157:   */
 1158:   char *s, *t;
 1159:   t=in;s=in;
 1160:   while ((*in != occ) && (*in != '\0')){
 1161:     *alocc++ = *in++;
 1162:   }
 1163:   if( *in == occ){
 1164:     *(alocc)='\0';
 1165:     s=++in;
 1166:   }
 1167:  
 1168:   if (s == t) {/* occ not found */
 1169:     *(alocc-(in-s))='\0';
 1170:     in=s;
 1171:   }
 1172:   while ( *in != '\0'){
 1173:     *blocc++ = *in++;
 1174:   }
 1175: 
 1176:   *blocc='\0';
 1177:   return t;
 1178: }
 1179: char *cutv(char *blocc, char *alocc, char *in, char occ)
 1180: {
 1181:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
 1182:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
 1183:      gives blocc="abcdef2ghi" and alocc="j".
 1184:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
 1185:   */
 1186:   char *s, *t;
 1187:   t=in;s=in;
 1188:   while (*in != '\0'){
 1189:     while( *in == occ){
 1190:       *blocc++ = *in++;
 1191:       s=in;
 1192:     }
 1193:     *blocc++ = *in++;
 1194:   }
 1195:   if (s == t) /* occ not found */
 1196:     *(blocc-(in-s))='\0';
 1197:   else
 1198:     *(blocc-(in-s)-1)='\0';
 1199:   in=s;
 1200:   while ( *in != '\0'){
 1201:     *alocc++ = *in++;
 1202:   }
 1203: 
 1204:   *alocc='\0';
 1205:   return s;
 1206: }
 1207: 
 1208: int nbocc(char *s, char occ)
 1209: {
 1210:   int i,j=0;
 1211:   int lg=20;
 1212:   i=0;
 1213:   lg=strlen(s);
 1214:   for(i=0; i<= lg; i++) {
 1215:   if  (s[i] == occ ) j++;
 1216:   }
 1217:   return j;
 1218: }
 1219: 
 1220: /* void cutv(char *u,char *v, char*t, char occ) */
 1221: /* { */
 1222: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
 1223: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
 1224: /*      gives u="abcdef2ghi" and v="j" *\/ */
 1225: /*   int i,lg,j,p=0; */
 1226: /*   i=0; */
 1227: /*   lg=strlen(t); */
 1228: /*   for(j=0; j<=lg-1; j++) { */
 1229: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
 1230: /*   } */
 1231: 
 1232: /*   for(j=0; j<p; j++) { */
 1233: /*     (u[j] = t[j]); */
 1234: /*   } */
 1235: /*      u[p]='\0'; */
 1236: 
 1237: /*    for(j=0; j<= lg; j++) { */
 1238: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
 1239: /*   } */
 1240: /* } */
 1241: 
 1242: #ifdef _WIN32
 1243: char * strsep(char **pp, const char *delim)
 1244: {
 1245:   char *p, *q;
 1246:          
 1247:   if ((p = *pp) == NULL)
 1248:     return 0;
 1249:   if ((q = strpbrk (p, delim)) != NULL)
 1250:   {
 1251:     *pp = q + 1;
 1252:     *q = '\0';
 1253:   }
 1254:   else
 1255:     *pp = 0;
 1256:   return p;
 1257: }
 1258: #endif
 1259: 
 1260: /********************** nrerror ********************/
 1261: 
 1262: void nrerror(char error_text[])
 1263: {
 1264:   fprintf(stderr,"ERREUR ...\n");
 1265:   fprintf(stderr,"%s\n",error_text);
 1266:   exit(EXIT_FAILURE);
 1267: }
 1268: /*********************** vector *******************/
 1269: double *vector(int nl, int nh)
 1270: {
 1271:   double *v;
 1272:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
 1273:   if (!v) nrerror("allocation failure in vector");
 1274:   return v-nl+NR_END;
 1275: }
 1276: 
 1277: /************************ free vector ******************/
 1278: void free_vector(double*v, int nl, int nh)
 1279: {
 1280:   free((FREE_ARG)(v+nl-NR_END));
 1281: }
 1282: 
 1283: /************************ivector *******************************/
 1284: int *ivector(long nl,long nh)
 1285: {
 1286:   int *v;
 1287:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
 1288:   if (!v) nrerror("allocation failure in ivector");
 1289:   return v-nl+NR_END;
 1290: }
 1291: 
 1292: /******************free ivector **************************/
 1293: void free_ivector(int *v, long nl, long nh)
 1294: {
 1295:   free((FREE_ARG)(v+nl-NR_END));
 1296: }
 1297: 
 1298: /************************lvector *******************************/
 1299: long *lvector(long nl,long nh)
 1300: {
 1301:   long *v;
 1302:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
 1303:   if (!v) nrerror("allocation failure in ivector");
 1304:   return v-nl+NR_END;
 1305: }
 1306: 
 1307: /******************free lvector **************************/
 1308: void free_lvector(long *v, long nl, long nh)
 1309: {
 1310:   free((FREE_ARG)(v+nl-NR_END));
 1311: }
 1312: 
 1313: /******************* imatrix *******************************/
 1314: int **imatrix(long nrl, long nrh, long ncl, long nch) 
 1315:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
 1316: { 
 1317:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
 1318:   int **m; 
 1319:   
 1320:   /* allocate pointers to rows */ 
 1321:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
 1322:   if (!m) nrerror("allocation failure 1 in matrix()"); 
 1323:   m += NR_END; 
 1324:   m -= nrl; 
 1325:   
 1326:   
 1327:   /* allocate rows and set pointers to them */ 
 1328:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
 1329:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
 1330:   m[nrl] += NR_END; 
 1331:   m[nrl] -= ncl; 
 1332:   
 1333:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
 1334:   
 1335:   /* return pointer to array of pointers to rows */ 
 1336:   return m; 
 1337: } 
 1338: 
 1339: /****************** free_imatrix *************************/
 1340: void free_imatrix(m,nrl,nrh,ncl,nch)
 1341:       int **m;
 1342:       long nch,ncl,nrh,nrl; 
 1343:      /* free an int matrix allocated by imatrix() */ 
 1344: { 
 1345:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
 1346:   free((FREE_ARG) (m+nrl-NR_END)); 
 1347: } 
 1348: 
 1349: /******************* matrix *******************************/
 1350: double **matrix(long nrl, long nrh, long ncl, long nch)
 1351: {
 1352:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
 1353:   double **m;
 1354: 
 1355:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1356:   if (!m) nrerror("allocation failure 1 in matrix()");
 1357:   m += NR_END;
 1358:   m -= nrl;
 1359: 
 1360:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1361:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1362:   m[nrl] += NR_END;
 1363:   m[nrl] -= ncl;
 1364: 
 1365:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1366:   return m;
 1367:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
 1368: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
 1369: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
 1370:    */
 1371: }
 1372: 
 1373: /*************************free matrix ************************/
 1374: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
 1375: {
 1376:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1377:   free((FREE_ARG)(m+nrl-NR_END));
 1378: }
 1379: 
 1380: /******************* ma3x *******************************/
 1381: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
 1382: {
 1383:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
 1384:   double ***m;
 1385: 
 1386:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1387:   if (!m) nrerror("allocation failure 1 in matrix()");
 1388:   m += NR_END;
 1389:   m -= nrl;
 1390: 
 1391:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1392:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1393:   m[nrl] += NR_END;
 1394:   m[nrl] -= ncl;
 1395: 
 1396:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1397: 
 1398:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
 1399:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
 1400:   m[nrl][ncl] += NR_END;
 1401:   m[nrl][ncl] -= nll;
 1402:   for (j=ncl+1; j<=nch; j++) 
 1403:     m[nrl][j]=m[nrl][j-1]+nlay;
 1404:   
 1405:   for (i=nrl+1; i<=nrh; i++) {
 1406:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
 1407:     for (j=ncl+1; j<=nch; j++) 
 1408:       m[i][j]=m[i][j-1]+nlay;
 1409:   }
 1410:   return m; 
 1411:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
 1412:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
 1413:   */
 1414: }
 1415: 
 1416: /*************************free ma3x ************************/
 1417: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
 1418: {
 1419:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
 1420:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1421:   free((FREE_ARG)(m+nrl-NR_END));
 1422: }
 1423: 
 1424: /*************** function subdirf ***********/
 1425: char *subdirf(char fileres[])
 1426: {
 1427:   /* Caution optionfilefiname is hidden */
 1428:   strcpy(tmpout,optionfilefiname);
 1429:   strcat(tmpout,"/"); /* Add to the right */
 1430:   strcat(tmpout,fileres);
 1431:   return tmpout;
 1432: }
 1433: 
 1434: /*************** function subdirf2 ***********/
 1435: char *subdirf2(char fileres[], char *preop)
 1436: {
 1437:   
 1438:   /* Caution optionfilefiname is hidden */
 1439:   strcpy(tmpout,optionfilefiname);
 1440:   strcat(tmpout,"/");
 1441:   strcat(tmpout,preop);
 1442:   strcat(tmpout,fileres);
 1443:   return tmpout;
 1444: }
 1445: 
 1446: /*************** function subdirf3 ***********/
 1447: char *subdirf3(char fileres[], char *preop, char *preop2)
 1448: {
 1449:   
 1450:   /* Caution optionfilefiname is hidden */
 1451:   strcpy(tmpout,optionfilefiname);
 1452:   strcat(tmpout,"/");
 1453:   strcat(tmpout,preop);
 1454:   strcat(tmpout,preop2);
 1455:   strcat(tmpout,fileres);
 1456:   return tmpout;
 1457: }
 1458:  
 1459: /*************** function subdirfext ***********/
 1460: char *subdirfext(char fileres[], char *preop, char *postop)
 1461: {
 1462:   
 1463:   strcpy(tmpout,preop);
 1464:   strcat(tmpout,fileres);
 1465:   strcat(tmpout,postop);
 1466:   return tmpout;
 1467: }
 1468: 
 1469: /*************** function subdirfext3 ***********/
 1470: char *subdirfext3(char fileres[], char *preop, char *postop)
 1471: {
 1472:   
 1473:   /* Caution optionfilefiname is hidden */
 1474:   strcpy(tmpout,optionfilefiname);
 1475:   strcat(tmpout,"/");
 1476:   strcat(tmpout,preop);
 1477:   strcat(tmpout,fileres);
 1478:   strcat(tmpout,postop);
 1479:   return tmpout;
 1480: }
 1481:  
 1482: char *asc_diff_time(long time_sec, char ascdiff[])
 1483: {
 1484:   long sec_left, days, hours, minutes;
 1485:   days = (time_sec) / (60*60*24);
 1486:   sec_left = (time_sec) % (60*60*24);
 1487:   hours = (sec_left) / (60*60) ;
 1488:   sec_left = (sec_left) %(60*60);
 1489:   minutes = (sec_left) /60;
 1490:   sec_left = (sec_left) % (60);
 1491:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
 1492:   return ascdiff;
 1493: }
 1494: 
 1495: /***************** f1dim *************************/
 1496: extern int ncom; 
 1497: extern double *pcom,*xicom;
 1498: extern double (*nrfunc)(double []); 
 1499:  
 1500: double f1dim(double x) 
 1501: { 
 1502:   int j; 
 1503:   double f;
 1504:   double *xt; 
 1505:  
 1506:   xt=vector(1,ncom); 
 1507:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
 1508:   f=(*nrfunc)(xt); 
 1509:   free_vector(xt,1,ncom); 
 1510:   return f; 
 1511: } 
 1512: 
 1513: /*****************brent *************************/
 1514: double brent(double ax, double bx, double cx, double (*f)(double), double tol, 	double *xmin) 
 1515: {
 1516:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
 1517:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
 1518:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
 1519:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
 1520:    * returned function value. 
 1521:   */
 1522:   int iter; 
 1523:   double a,b,d,etemp;
 1524:   double fu=0,fv,fw,fx;
 1525:   double ftemp=0.;
 1526:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
 1527:   double e=0.0; 
 1528:  
 1529:   a=(ax < cx ? ax : cx); 
 1530:   b=(ax > cx ? ax : cx); 
 1531:   x=w=v=bx; 
 1532:   fw=fv=fx=(*f)(x); 
 1533:   for (iter=1;iter<=ITMAX;iter++) { 
 1534:     xm=0.5*(a+b); 
 1535:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
 1536:     /*		if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
 1537:     printf(".");fflush(stdout);
 1538:     fprintf(ficlog,".");fflush(ficlog);
 1539: #ifdef DEBUGBRENT
 1540:     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);
 1541:     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);
 1542:     /*		if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
 1543: #endif
 1544:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
 1545:       *xmin=x; 
 1546:       return fx; 
 1547:     } 
 1548:     ftemp=fu;
 1549:     if (fabs(e) > tol1) { 
 1550:       r=(x-w)*(fx-fv); 
 1551:       q=(x-v)*(fx-fw); 
 1552:       p=(x-v)*q-(x-w)*r; 
 1553:       q=2.0*(q-r); 
 1554:       if (q > 0.0) p = -p; 
 1555:       q=fabs(q); 
 1556:       etemp=e; 
 1557:       e=d; 
 1558:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
 1559: 				d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1560:       else { 
 1561: 				d=p/q; 
 1562: 				u=x+d; 
 1563: 				if (u-a < tol2 || b-u < tol2) 
 1564: 					d=SIGN(tol1,xm-x); 
 1565:       } 
 1566:     } else { 
 1567:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1568:     } 
 1569:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
 1570:     fu=(*f)(u); 
 1571:     if (fu <= fx) { 
 1572:       if (u >= x) a=x; else b=x; 
 1573:       SHFT(v,w,x,u) 
 1574:       SHFT(fv,fw,fx,fu) 
 1575:     } else { 
 1576:       if (u < x) a=u; else b=u; 
 1577:       if (fu <= fw || w == x) { 
 1578: 				v=w; 
 1579: 				w=u; 
 1580: 				fv=fw; 
 1581: 				fw=fu; 
 1582:       } else if (fu <= fv || v == x || v == w) { 
 1583: 				v=u; 
 1584: 				fv=fu; 
 1585:       } 
 1586:     } 
 1587:   } 
 1588:   nrerror("Too many iterations in brent"); 
 1589:   *xmin=x; 
 1590:   return fx; 
 1591: } 
 1592: 
 1593: /****************** mnbrak ***********************/
 1594: 
 1595: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
 1596: 	    double (*func)(double)) 
 1597: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
 1598: the downhill direction (defined by the function as evaluated at the initial points) and returns
 1599: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
 1600: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
 1601:    */
 1602:   double ulim,u,r,q, dum;
 1603:   double fu; 
 1604: 
 1605:   double scale=10.;
 1606:   int iterscale=0;
 1607: 
 1608:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
 1609:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
 1610: 
 1611: 
 1612:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
 1613:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
 1614:   /*   *bx = *ax - (*ax - *bx)/scale; */
 1615:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
 1616:   /* } */
 1617: 
 1618:   if (*fb > *fa) { 
 1619:     SHFT(dum,*ax,*bx,dum) 
 1620:     SHFT(dum,*fb,*fa,dum) 
 1621:   } 
 1622:   *cx=(*bx)+GOLD*(*bx-*ax); 
 1623:   *fc=(*func)(*cx); 
 1624: #ifdef DEBUG
 1625:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
 1626:   fprintf(ficlog,"mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
 1627: #endif
 1628:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc. If fc=inf it exits and if flat fb=fc it exits too.*/
 1629:     r=(*bx-*ax)*(*fb-*fc); 
 1630:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
 1631:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
 1632:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
 1633:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
 1634:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
 1635:       fu=(*func)(u); 
 1636: #ifdef DEBUG
 1637:       /* f(x)=A(x-u)**2+f(u) */
 1638:       double A, fparabu; 
 1639:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 1640:       fparabu= *fa - A*(*ax-u)*(*ax-u);
 1641:       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);
 1642:       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);
 1643:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
 1644:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
 1645:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
 1646:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
 1647: #endif 
 1648: #ifdef MNBRAKORIGINAL
 1649: #else
 1650: /*       if (fu > *fc) { */
 1651: /* #ifdef DEBUG */
 1652: /*       printf("mnbrak4  fu > fc \n"); */
 1653: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
 1654: /* #endif */
 1655: /* 	/\* 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 *\\/  *\/ */
 1656: /* 	/\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
 1657: /* 	dum=u; /\* Shifting c and u *\/ */
 1658: /* 	u = *cx; */
 1659: /* 	*cx = dum; */
 1660: /* 	dum = fu; */
 1661: /* 	fu = *fc; */
 1662: /* 	*fc =dum; */
 1663: /*       } else { /\* end *\/ */
 1664: /* #ifdef DEBUG */
 1665: /*       printf("mnbrak3  fu < fc \n"); */
 1666: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
 1667: /* #endif */
 1668: /* 	dum=u; /\* Shifting c and u *\/ */
 1669: /* 	u = *cx; */
 1670: /* 	*cx = dum; */
 1671: /* 	dum = fu; */
 1672: /* 	fu = *fc; */
 1673: /* 	*fc =dum; */
 1674: /*       } */
 1675: #ifdef DEBUGMNBRAK
 1676: 		 double A, fparabu; 
 1677:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 1678:      fparabu= *fa - A*(*ax-u)*(*ax-u);
 1679:      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);
 1680:      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);
 1681: #endif
 1682:       dum=u; /* Shifting c and u */
 1683:       u = *cx;
 1684:       *cx = dum;
 1685:       dum = fu;
 1686:       fu = *fc;
 1687:       *fc =dum;
 1688: #endif
 1689:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
 1690: #ifdef DEBUG
 1691:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
 1692:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
 1693: #endif
 1694:       fu=(*func)(u); 
 1695:       if (fu < *fc) { 
 1696: #ifdef DEBUG
 1697: 				printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
 1698: 			  fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
 1699: #endif
 1700: 			  SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
 1701: 				SHFT(*fb,*fc,fu,(*func)(u)) 
 1702: #ifdef DEBUG
 1703: 					printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
 1704: #endif
 1705:       } 
 1706:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
 1707: #ifdef DEBUG
 1708:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
 1709:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
 1710: #endif
 1711:       u=ulim; 
 1712:       fu=(*func)(u); 
 1713:     } else { /* u could be left to b (if r > q parabola has a maximum) */
 1714: #ifdef DEBUG
 1715:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
 1716:       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);
 1717: #endif
 1718:       u=(*cx)+GOLD*(*cx-*bx); 
 1719:       fu=(*func)(u); 
 1720: #ifdef DEBUG
 1721:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
 1722:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
 1723: #endif
 1724:     } /* end tests */
 1725:     SHFT(*ax,*bx,*cx,u) 
 1726:     SHFT(*fa,*fb,*fc,fu) 
 1727: #ifdef DEBUG
 1728:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
 1729:       fprintf(ficlog, "\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
 1730: #endif
 1731:   } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
 1732: } 
 1733: 
 1734: /*************** linmin ************************/
 1735: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
 1736: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
 1737: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
 1738: the value of func at the returned location p . This is actually all accomplished by calling the
 1739: routines mnbrak and brent .*/
 1740: int ncom; 
 1741: double *pcom,*xicom;
 1742: double (*nrfunc)(double []); 
 1743:  
 1744: #ifdef LINMINORIGINAL
 1745: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
 1746: #else
 1747: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
 1748: #endif
 1749: { 
 1750:   double brent(double ax, double bx, double cx, 
 1751: 	       double (*f)(double), double tol, double *xmin); 
 1752:   double f1dim(double x); 
 1753:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
 1754: 	      double *fc, double (*func)(double)); 
 1755:   int j; 
 1756:   double xx,xmin,bx,ax; 
 1757:   double fx,fb,fa;
 1758: 
 1759: #ifdef LINMINORIGINAL
 1760: #else
 1761:   double scale=10., axs, xxs; /* Scale added for infinity */
 1762: #endif
 1763:   
 1764:   ncom=n; 
 1765:   pcom=vector(1,n); 
 1766:   xicom=vector(1,n); 
 1767:   nrfunc=func; 
 1768:   for (j=1;j<=n;j++) { 
 1769:     pcom[j]=p[j]; 
 1770:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
 1771:   } 
 1772: 
 1773: #ifdef LINMINORIGINAL
 1774:   xx=1.;
 1775: #else
 1776:   axs=0.0;
 1777:   xxs=1.;
 1778:   do{
 1779:     xx= xxs;
 1780: #endif
 1781:     ax=0.;
 1782:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
 1783:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
 1784:     /* 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))   */
 1785:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
 1786:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
 1787:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
 1788:     /* 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]]*/
 1789: #ifdef LINMINORIGINAL
 1790: #else
 1791:     if (fx != fx){
 1792: 			xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
 1793: 			printf("|");
 1794: 			fprintf(ficlog,"|");
 1795: #ifdef DEBUGLINMIN
 1796: 			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);
 1797: #endif
 1798:     }
 1799:   }while(fx != fx && xxs > 1.e-5);
 1800: #endif
 1801:   
 1802: #ifdef DEBUGLINMIN
 1803:   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);
 1804:   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);
 1805: #endif
 1806: #ifdef LINMINORIGINAL
 1807: #else
 1808: 	if(fb == fx){ /* Flat function in the direction */
 1809: 		xmin=xx;
 1810:     *flat=1;
 1811: 	}else{
 1812:     *flat=0;
 1813: #endif
 1814: 		/*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
 1815:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
 1816:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
 1817:   /* fmin = f(p[j] + xmin * xi[j]) */
 1818:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
 1819:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
 1820: #ifdef DEBUG
 1821:   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);
 1822:   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);
 1823: #endif
 1824: #ifdef LINMINORIGINAL
 1825: #else
 1826: 			}
 1827: #endif
 1828: #ifdef DEBUGLINMIN
 1829:   printf("linmin end ");
 1830:   fprintf(ficlog,"linmin end ");
 1831: #endif
 1832:   for (j=1;j<=n;j++) { 
 1833: #ifdef LINMINORIGINAL
 1834:     xi[j] *= xmin; 
 1835: #else
 1836: #ifdef DEBUGLINMIN
 1837:     if(xxs <1.0)
 1838:       printf(" before xi[%d]=%12.8f", j,xi[j]);
 1839: #endif
 1840:     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) */
 1841: #ifdef DEBUGLINMIN
 1842:     if(xxs <1.0)
 1843:       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 );
 1844: #endif
 1845: #endif
 1846:     p[j] += xi[j]; /* Parameters values are updated accordingly */
 1847:   } 
 1848: #ifdef DEBUGLINMIN
 1849:   printf("\n");
 1850:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
 1851:   fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
 1852:   for (j=1;j<=n;j++) { 
 1853:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
 1854:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
 1855:     if(j % ncovmodel == 0){
 1856:       printf("\n");
 1857:       fprintf(ficlog,"\n");
 1858:     }
 1859:   }
 1860: #else
 1861: #endif
 1862:   free_vector(xicom,1,n); 
 1863:   free_vector(pcom,1,n); 
 1864: } 
 1865: 
 1866: 
 1867: /*************** powell ************************/
 1868: /*
 1869: Minimization of a function func of n variables. Input consists of an initial starting point
 1870: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
 1871: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
 1872: such that failure to decrease by more than this amount on one iteration signals doneness. On
 1873: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
 1874: function value at p , and iter is the number of iterations taken. The routine linmin is used.
 1875:  */
 1876: #ifdef LINMINORIGINAL
 1877: #else
 1878: 	int *flatdir; /* Function is vanishing in that direction */
 1879: 	int flat=0; /* Function is vanishing in that direction */
 1880: #endif
 1881: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
 1882: 	    double (*func)(double [])) 
 1883: { 
 1884: #ifdef LINMINORIGINAL
 1885:  void linmin(double p[], double xi[], int n, double *fret, 
 1886: 	      double (*func)(double [])); 
 1887: #else 
 1888:  void linmin(double p[], double xi[], int n, double *fret, 
 1889: 						 double (*func)(double []),int *flat); 
 1890: #endif
 1891:   int i,ibig,j; 
 1892:   double del,t,*pt,*ptt,*xit;
 1893:   double directest;
 1894:   double fp,fptt;
 1895:   double *xits;
 1896:   int niterf, itmp;
 1897: #ifdef LINMINORIGINAL
 1898: #else
 1899: 
 1900:   flatdir=ivector(1,n); 
 1901:   for (j=1;j<=n;j++) flatdir[j]=0; 
 1902: #endif
 1903: 
 1904:   pt=vector(1,n); 
 1905:   ptt=vector(1,n); 
 1906:   xit=vector(1,n); 
 1907:   xits=vector(1,n); 
 1908:   *fret=(*func)(p); 
 1909:   for (j=1;j<=n;j++) pt[j]=p[j]; 
 1910:   rcurr_time = time(NULL);  
 1911:   for (*iter=1;;++(*iter)) { 
 1912:     fp=(*fret); /* From former iteration or initial value */
 1913:     ibig=0; 
 1914:     del=0.0; 
 1915:     rlast_time=rcurr_time;
 1916:     /* (void) gettimeofday(&curr_time,&tzp); */
 1917:     rcurr_time = time(NULL);  
 1918:     curr_time = *localtime(&rcurr_time);
 1919:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
 1920:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
 1921: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
 1922:     for (i=1;i<=n;i++) {
 1923:       printf(" %d %.12f",i, p[i]);
 1924:       fprintf(ficlog," %d %.12lf",i, p[i]);
 1925:       fprintf(ficrespow," %.12lf", p[i]);
 1926:     }
 1927:     printf("\n");
 1928:     fprintf(ficlog,"\n");
 1929:     fprintf(ficrespow,"\n");fflush(ficrespow);
 1930:     if(*iter <=3){
 1931:       tml = *localtime(&rcurr_time);
 1932:       strcpy(strcurr,asctime(&tml));
 1933:       rforecast_time=rcurr_time; 
 1934:       itmp = strlen(strcurr);
 1935:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
 1936: 				strcurr[itmp-1]='\0';
 1937:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1938:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1939:       for(niterf=10;niterf<=30;niterf+=10){
 1940: 				rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
 1941: 				forecast_time = *localtime(&rforecast_time);
 1942: 				strcpy(strfor,asctime(&forecast_time));
 1943: 				itmp = strlen(strfor);
 1944: 				if(strfor[itmp-1]=='\n')
 1945: 					strfor[itmp-1]='\0';
 1946: 				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);
 1947: 				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);
 1948:       }
 1949:     }
 1950:     for (i=1;i<=n;i++) { /* For each direction i */
 1951:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
 1952:       fptt=(*fret); 
 1953: #ifdef DEBUG
 1954:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1955:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1956: #endif
 1957:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
 1958:       fprintf(ficlog,"%d",i);fflush(ficlog);
 1959: #ifdef LINMINORIGINAL
 1960:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
 1961: #else
 1962:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
 1963: 			flatdir[i]=flat; /* Function is vanishing in that direction i */
 1964: #endif
 1965: 			/* Outputs are fret(new point p) p is updated and xit rescaled */
 1966:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
 1967: 				/* because that direction will be replaced unless the gain del is small */
 1968: 				/* in comparison with the 'probable' gain, mu^2, with the last average direction. */
 1969: 				/* Unless the n directions are conjugate some gain in the determinant may be obtained */
 1970: 				/* with the new direction. */
 1971: 				del=fabs(fptt-(*fret)); 
 1972: 				ibig=i; 
 1973:       } 
 1974: #ifdef DEBUG
 1975:       printf("%d %.12e",i,(*fret));
 1976:       fprintf(ficlog,"%d %.12e",i,(*fret));
 1977:       for (j=1;j<=n;j++) {
 1978: 				xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
 1979: 				printf(" x(%d)=%.12e",j,xit[j]);
 1980: 				fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
 1981:       }
 1982:       for(j=1;j<=n;j++) {
 1983: 			printf(" p(%d)=%lf ",j,p[j]);
 1984: 			fprintf(ficlog," p(%d)=%lf ",j,p[j]);
 1985:       }
 1986:       printf("\n");
 1987:       fprintf(ficlog,"\n");
 1988: #endif
 1989:     } /* end loop on each direction i */
 1990:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
 1991:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
 1992:     /* New value of last point Pn is not computed, P(n-1) */
 1993:       for(j=1;j<=n;j++) {
 1994: 			  printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
 1995: 			  fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
 1996:       }
 1997:       printf("\n");
 1998:       fprintf(ficlog,"\n");
 1999: 
 2000:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
 2001:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
 2002:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
 2003:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
 2004:       /* decreased of more than 3.84  */
 2005:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
 2006:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
 2007:       /* By adding 10 parameters more the gain should be 18.31 */
 2008: 			
 2009:       /* Starting the program with initial values given by a former maximization will simply change */
 2010:       /* the scales of the directions and the directions, because the are reset to canonical directions */
 2011:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
 2012:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
 2013: #ifdef DEBUG
 2014:       int k[2],l;
 2015:       k[0]=1;
 2016:       k[1]=-1;
 2017:       printf("Max: %.12e",(*func)(p));
 2018:       fprintf(ficlog,"Max: %.12e",(*func)(p));
 2019:       for (j=1;j<=n;j++) {
 2020: 	printf(" %.12e",p[j]);
 2021: 	fprintf(ficlog," %.12e",p[j]);
 2022:       }
 2023:       printf("\n");
 2024:       fprintf(ficlog,"\n");
 2025:       for(l=0;l<=1;l++) {
 2026: 	for (j=1;j<=n;j++) {
 2027: 	  ptt[j]=p[j]+(p[j]-pt[j])*k[l];
 2028: 	  printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 2029: 	  fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 2030: 	}
 2031: 	printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 2032: 	fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 2033:       }
 2034: #endif
 2035: 
 2036: #ifdef LINMINORIGINAL
 2037: #else
 2038:       free_ivector(flatdir,1,n); 
 2039: #endif
 2040:       free_vector(xit,1,n); 
 2041:       free_vector(xits,1,n); 
 2042:       free_vector(ptt,1,n); 
 2043:       free_vector(pt,1,n); 
 2044:       return; 
 2045:     } /* enough precision */ 
 2046:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
 2047:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
 2048:       ptt[j]=2.0*p[j]-pt[j]; 
 2049:       xit[j]=p[j]-pt[j]; 
 2050:       pt[j]=p[j]; 
 2051:     } 
 2052:     fptt=(*func)(ptt); /* f_3 */
 2053: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
 2054: 		if (*iter <=4) {
 2055: #else			
 2056: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
 2057: #else
 2058:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
 2059: #endif
 2060:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
 2061:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
 2062:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
 2063:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
 2064:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
 2065:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
 2066:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
 2067:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
 2068:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
 2069:       /*  Even if f3 <f1, directest can be negative and t >0 */
 2070:       /* mu² and del² are equal when f3=f1 */
 2071: 			/* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
 2072: 			/* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
 2073: 			/* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
 2074: 			/* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
 2075: #ifdef NRCORIGINAL
 2076:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
 2077: #else
 2078:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
 2079:       t= t- del*SQR(fp-fptt);
 2080: #endif
 2081:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
 2082: #ifdef DEBUG
 2083:       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);
 2084:       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);
 2085:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 2086: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 2087:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 2088: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 2089:       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);
 2090:       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);
 2091: #endif
 2092: #ifdef POWELLORIGINAL
 2093:       if (t < 0.0) { /* Then we use it for new direction */
 2094: #else
 2095:       if (directest*t < 0.0) { /* Contradiction between both tests */
 2096: 				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);
 2097:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 2098:         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);
 2099:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 2100:       } 
 2101:       if (directest < 0.0) { /* Then we use it for new direction */
 2102: #endif
 2103: #ifdef DEBUGLINMIN
 2104: 				printf("Before linmin in direction P%d-P0\n",n);
 2105: 				for (j=1;j<=n;j++) {
 2106: 					printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2107: 					fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2108: 					if(j % ncovmodel == 0){
 2109: 						printf("\n");
 2110: 						fprintf(ficlog,"\n");
 2111: 					}
 2112: 				}
 2113: #endif
 2114: #ifdef LINMINORIGINAL
 2115:  				linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
 2116: #else
 2117: 				linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
 2118: 				flatdir[i]=flat; /* Function is vanishing in that direction i */
 2119: #endif
 2120: 
 2121: #ifdef DEBUGLINMIN
 2122: 				for (j=1;j<=n;j++) { 
 2123: 					printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2124: 					fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2125: 					if(j % ncovmodel == 0){
 2126: 						printf("\n");
 2127: 						fprintf(ficlog,"\n");
 2128: 					}
 2129: 				}
 2130: #endif
 2131: 				for (j=1;j<=n;j++) { 
 2132: 					xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
 2133: 					xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
 2134: 				}
 2135: #ifdef LINMINORIGINAL
 2136: #else
 2137: 				printf("Flat directions\n");
 2138: 				fprintf(ficlog,"Flat directions\n");
 2139: 				for (j=1;j<=n;j++) { 
 2140: 					printf("flatdir[%d]=%d ",j,flatdir[j]);
 2141: 					fprintf(ficlog,"flatdir[%d]=%d ",j,flatdir[j]);
 2142:         }
 2143: 				printf("\n");
 2144: 				fprintf(ficlog,"\n");
 2145: #endif
 2146: 				printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 2147: 				fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 2148: 				
 2149: #ifdef DEBUG
 2150: 				printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 2151: 				fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 2152: 				for(j=1;j<=n;j++){
 2153: 					printf(" %lf",xit[j]);
 2154: 					fprintf(ficlog," %lf",xit[j]);
 2155: 				}
 2156: 				printf("\n");
 2157: 				fprintf(ficlog,"\n");
 2158: #endif
 2159:       } /* end of t or directest negative */
 2160: #ifdef POWELLNOF3INFF1TEST
 2161: #else
 2162:     } /* end if (fptt < fp)  */
 2163: #endif
 2164: 		} /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
 2165: #endif
 2166:   } /* loop iteration */ 
 2167: } 
 2168: 
 2169: /**** Prevalence limit (stable or period prevalence)  ****************/
 2170: 
 2171: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
 2172: {
 2173:   /* Computes the prevalence limit in each live state at age x and for covariate ij by left multiplying the unit
 2174:      matrix by transitions matrix until convergence is reached with precision ftolpl */
 2175:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
 2176:   /* Wx is row vector: population in state 1, population in state 2, population dead */
 2177:   /* or prevalence in state 1, prevalence in state 2, 0 */
 2178:   /* newm is the matrix after multiplications, its rows are identical at a factor */
 2179:   /* Initial matrix pimij */
 2180:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
 2181:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
 2182:   /*  0,                   0                  , 1} */
 2183:   /*
 2184:    * and after some iteration: */
 2185:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
 2186:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
 2187:   /*  0,                   0                  , 1} */
 2188:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
 2189:   /* {0.51571254859325999, 0.4842874514067399, */
 2190:   /*  0.51326036147820708, 0.48673963852179264} */
 2191:   /* If we start from prlim again, prlim tends to a constant matrix */
 2192: 
 2193:   int i, ii,j,k;
 2194:   double *min, *max, *meandiff, maxmax,sumnew=0.;
 2195:   /* double **matprod2(); */ /* test */
 2196:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
 2197:   double **newm;
 2198:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
 2199:   int ncvloop=0;
 2200:   
 2201:   min=vector(1,nlstate);
 2202:   max=vector(1,nlstate);
 2203:   meandiff=vector(1,nlstate);
 2204: 
 2205: 	/* Starting with matrix unity */
 2206:   for (ii=1;ii<=nlstate+ndeath;ii++)
 2207:     for (j=1;j<=nlstate+ndeath;j++){
 2208:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2209:     }
 2210:   
 2211:   cov[1]=1.;
 2212:   
 2213:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2214:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
 2215:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
 2216:     ncvloop++;
 2217:     newm=savm;
 2218:     /* Covariates have to be included here again */
 2219:     cov[2]=agefin;
 2220:     if(nagesqr==1)
 2221:       cov[3]= agefin*agefin;;
 2222:     for (k=1; k<=cptcovn;k++) {
 2223:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 2224: 			/* Here comes the value of the covariate 'ij' */
 2225:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 2226:       /* 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])]); */
 2227:     }
 2228:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2229:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
 2230:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
 2231:     for (k=1; k<=cptcovprod;k++) /* Useless */
 2232:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 2233:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
 2234:     
 2235:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 2236:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 2237:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 2238:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2239:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 2240: 		/* age and covariate values of ij are in 'cov' */
 2241:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
 2242:     
 2243:     savm=oldm;
 2244:     oldm=newm;
 2245: 
 2246:     for(j=1; j<=nlstate; j++){
 2247:       max[j]=0.;
 2248:       min[j]=1.;
 2249:     }
 2250:     for(i=1;i<=nlstate;i++){
 2251:       sumnew=0;
 2252:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
 2253:       for(j=1; j<=nlstate; j++){ 
 2254: 	prlim[i][j]= newm[i][j]/(1-sumnew);
 2255: 	max[j]=FMAX(max[j],prlim[i][j]);
 2256: 	min[j]=FMIN(min[j],prlim[i][j]);
 2257:       }
 2258:     }
 2259: 
 2260:     maxmax=0.;
 2261:     for(j=1; j<=nlstate; j++){
 2262:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
 2263:       maxmax=FMAX(maxmax,meandiff[j]);
 2264:       /* 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); */
 2265:     } /* j loop */
 2266:     *ncvyear= (int)age- (int)agefin;
 2267:     /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
 2268:     if(maxmax < ftolpl){
 2269:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
 2270:       free_vector(min,1,nlstate);
 2271:       free_vector(max,1,nlstate);
 2272:       free_vector(meandiff,1,nlstate);
 2273:       return prlim;
 2274:     }
 2275:   } /* age loop */
 2276:     /* After some age loop it doesn't converge */
 2277:   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\
 2278: 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);
 2279:   /* 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); */
 2280:   free_vector(min,1,nlstate);
 2281:   free_vector(max,1,nlstate);
 2282:   free_vector(meandiff,1,nlstate);
 2283:   
 2284:   return prlim; /* should not reach here */
 2285: }
 2286: 
 2287: 
 2288:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
 2289: 
 2290:  /* 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) */
 2291:  /* 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) */
 2292:  double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij)
 2293: {
 2294:   /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
 2295:      matrix by transitions matrix until convergence is reached with precision ftolpl */
 2296:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
 2297:   /* Wx is row vector: population in state 1, population in state 2, population dead */
 2298:   /* or prevalence in state 1, prevalence in state 2, 0 */
 2299:   /* newm is the matrix after multiplications, its rows are identical at a factor */
 2300:   /* Initial matrix pimij */
 2301:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
 2302:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
 2303:   /*  0,                   0                  , 1} */
 2304:   /*
 2305:    * and after some iteration: */
 2306:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
 2307:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
 2308:   /*  0,                   0                  , 1} */
 2309:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
 2310:   /* {0.51571254859325999, 0.4842874514067399, */
 2311:   /*  0.51326036147820708, 0.48673963852179264} */
 2312:   /* If we start from prlim again, prlim tends to a constant matrix */
 2313: 
 2314:   int i, ii,j,k;
 2315:   double *min, *max, *meandiff, maxmax,sumnew=0.;
 2316:   /* double **matprod2(); */ /* test */
 2317:   double **out, cov[NCOVMAX+1], **bmij();
 2318:   double **newm;
 2319:   double	 **dnewm, **doldm, **dsavm;  /* for use */
 2320:   double	 **oldm, **savm;  /* for use */
 2321: 
 2322:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
 2323:   int ncvloop=0;
 2324:   
 2325:   min=vector(1,nlstate);
 2326:   max=vector(1,nlstate);
 2327:   meandiff=vector(1,nlstate);
 2328: 
 2329: 	dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
 2330: 	oldm=oldms; savm=savms;
 2331: 
 2332: 	/* Starting with matrix unity */
 2333: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2334: 		for (j=1;j<=nlstate+ndeath;j++){
 2335:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2336:     }
 2337:   
 2338:   cov[1]=1.;
 2339:   
 2340:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2341:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
 2342:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
 2343:   for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
 2344:     ncvloop++;
 2345:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
 2346: 		/* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
 2347:     /* Covariates have to be included here again */
 2348:     cov[2]=agefin;
 2349:     if(nagesqr==1)
 2350:       cov[3]= agefin*agefin;;
 2351:     for (k=1; k<=cptcovn;k++) {
 2352:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 2353:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 2354:       /* 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])]); */
 2355:     }
 2356:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2357:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
 2358:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
 2359:     for (k=1; k<=cptcovprod;k++) /* Useless */
 2360:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 2361:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
 2362:     
 2363:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 2364:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 2365:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 2366:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2367:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 2368: 		/* ij should be linked to the correct index of cov */
 2369: 		/* age and covariate values ij are in 'cov', but we need to pass
 2370: 		 * ij for the observed prevalence at age and status and covariate
 2371: 		 * number:  prevacurrent[(int)agefin][ii][ij]
 2372: 		 */
 2373:     /* 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 *\/ */
 2374:     /* 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 *\/ */
 2375:     out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij)); /* Bug Valgrind */
 2376:     savm=oldm;
 2377:     oldm=newm;
 2378:     for(j=1; j<=nlstate; j++){
 2379:       max[j]=0.;
 2380:       min[j]=1.;
 2381:     }
 2382:     for(j=1; j<=nlstate; j++){ 
 2383:       for(i=1;i<=nlstate;i++){
 2384: 				/* bprlim[i][j]= newm[i][j]/(1-sumnew); */
 2385: 				bprlim[i][j]= newm[i][j];
 2386: 				max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
 2387: 				min[i]=FMIN(min[i],bprlim[i][j]);
 2388:       }
 2389:     }
 2390: 		
 2391:     maxmax=0.;
 2392:     for(i=1; i<=nlstate; i++){
 2393:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
 2394:       maxmax=FMAX(maxmax,meandiff[i]);
 2395:       /* 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); */
 2396:     } /* j loop */
 2397:     *ncvyear= -( (int)age- (int)agefin);
 2398:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
 2399:     if(maxmax < ftolpl){
 2400:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
 2401:       free_vector(min,1,nlstate);
 2402:       free_vector(max,1,nlstate);
 2403:       free_vector(meandiff,1,nlstate);
 2404:       return bprlim;
 2405:     }
 2406:   } /* age loop */
 2407:     /* After some age loop it doesn't converge */
 2408:   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\
 2409: 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);
 2410:   /* 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); */
 2411:   free_vector(min,1,nlstate);
 2412:   free_vector(max,1,nlstate);
 2413:   free_vector(meandiff,1,nlstate);
 2414:   
 2415:   return bprlim; /* should not reach here */
 2416: }
 2417: 
 2418: /*************** transition probabilities ***************/ 
 2419: 
 2420: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 2421: {
 2422:   /* According to parameters values stored in x and the covariate's values stored in cov,
 2423:      computes the probability to be observed in state j being in state i by appying the
 2424:      model to the ncovmodel covariates (including constant and age).
 2425:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 2426:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 2427:      ncth covariate in the global vector x is given by the formula:
 2428:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 2429:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 2430:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 2431:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 2432:      Outputs ps[i][j] the probability to be observed in j being in j according to
 2433:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 2434:   */
 2435:   double s1, lnpijopii;
 2436:   /*double t34;*/
 2437:   int i,j, nc, ii, jj;
 2438: 
 2439:   for(i=1; i<= nlstate; i++){
 2440:     for(j=1; j<i;j++){
 2441:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2442: 	/*lnpijopii += param[i][j][nc]*cov[nc];*/
 2443: 	lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 2444: 	/* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2445:       }
 2446:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2447:       /* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2448:     }
 2449:     for(j=i+1; j<=nlstate+ndeath;j++){
 2450:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2451: 	/*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 2452: 	lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 2453: 	/* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 2454:       }
 2455:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2456:     }
 2457:   }
 2458:   
 2459:   for(i=1; i<= nlstate; i++){
 2460:     s1=0;
 2461:     for(j=1; j<i; j++){
 2462:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2463:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2464:     }
 2465:     for(j=i+1; j<=nlstate+ndeath; j++){
 2466:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2467:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2468:     }
 2469:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 2470:     ps[i][i]=1./(s1+1.);
 2471:     /* Computing other pijs */
 2472:     for(j=1; j<i; j++)
 2473:       ps[i][j]= exp(ps[i][j])*ps[i][i];
 2474:     for(j=i+1; j<=nlstate+ndeath; j++)
 2475:       ps[i][j]= exp(ps[i][j])*ps[i][i];
 2476:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 2477:   } /* end i */
 2478:   
 2479:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 2480:     for(jj=1; jj<= nlstate+ndeath; jj++){
 2481:       ps[ii][jj]=0;
 2482:       ps[ii][ii]=1;
 2483:     }
 2484:   }
 2485:   
 2486:   
 2487:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 2488:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 2489:   /* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 2490:   /*   } */
 2491:   /*   printf("\n "); */
 2492:   /* } */
 2493:   /* printf("\n ");printf("%lf ",cov[2]);*/
 2494:   /*
 2495:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
 2496: 		goto end;*/
 2497:   return ps;
 2498: }
 2499: 
 2500: /*************** backward transition probabilities ***************/ 
 2501: 
 2502:  /* 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 ) */
 2503: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
 2504:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
 2505: {
 2506:   /* Computes the backward probability at age agefin and covariate ij
 2507:    * and returns in **ps as well as **bmij.
 2508:    */
 2509:   int i, ii, j,k;
 2510:   
 2511:   double **out, **pmij();
 2512:   double sumnew=0.;
 2513:   double agefin;
 2514:   
 2515:   double **dnewm, **dsavm, **doldm;
 2516:   double **bbmij;
 2517:   
 2518:   doldm=ddoldms; /* global pointers */
 2519:   dnewm=ddnewms;
 2520:   dsavm=ddsavms;
 2521:   
 2522:   agefin=cov[2];
 2523:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
 2524:      the observed prevalence (with this covariate ij) */
 2525:   dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
 2526:   /* We do have the matrix Px in savm  and we need pij */
 2527:   for (j=1;j<=nlstate+ndeath;j++){
 2528:     sumnew=0.; /* w1 p11 + w2 p21 only on live states */
 2529:     for (ii=1;ii<=nlstate;ii++){
 2530:       sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
 2531:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
 2532:     for (ii=1;ii<=nlstate+ndeath;ii++){
 2533:       if(sumnew >= 1.e-10){
 2534: 	/* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
 2535: 	/* 	doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
 2536: 	/* }else if(agefin >= agemaxpar+stepm/YEARM){ */
 2537: 	/* 	doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
 2538: 	/* }else */
 2539: 	doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
 2540:       }else{
 2541: 	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);
 2542:       }
 2543:     } /*End ii */
 2544:   } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
 2545:   /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
 2546:   bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
 2547:   /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
 2548:   /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
 2549:   /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
 2550:   /* left Product of this matrix by diag matrix of prevalences (savm) */
 2551:   for (j=1;j<=nlstate+ndeath;j++){
 2552:     for (ii=1;ii<=nlstate+ndeath;ii++){
 2553:       dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
 2554:     }
 2555:   } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
 2556:   ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
 2557:   /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
 2558:   /* end bmij */
 2559:   return ps; 
 2560: }
 2561: /*************** transition probabilities ***************/ 
 2562: 
 2563: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 2564: {
 2565:   /* According to parameters values stored in x and the covariate's values stored in cov,
 2566:      computes the probability to be observed in state j being in state i by appying the
 2567:      model to the ncovmodel covariates (including constant and age).
 2568:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 2569:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 2570:      ncth covariate in the global vector x is given by the formula:
 2571:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 2572:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 2573:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 2574:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 2575:      Outputs ps[i][j] the probability to be observed in j being in j according to
 2576:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 2577:   */
 2578:   double s1, lnpijopii;
 2579:   /*double t34;*/
 2580:   int i,j, nc, ii, jj;
 2581: 
 2582: 	for(i=1; i<= nlstate; i++){
 2583: 		for(j=1; j<i;j++){
 2584: 			for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2585: 				/*lnpijopii += param[i][j][nc]*cov[nc];*/
 2586: 				lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 2587: 				/* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2588: 			}
 2589: 			ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2590: 			/* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2591: 		}
 2592: 		for(j=i+1; j<=nlstate+ndeath;j++){
 2593: 			for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2594: 				/*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 2595: 				lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 2596: 				/* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 2597: 			}
 2598: 			ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2599: 		}
 2600: 	}
 2601: 	
 2602: 	for(i=1; i<= nlstate; i++){
 2603: 		s1=0;
 2604: 		for(j=1; j<i; j++){
 2605: 			s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2606: 			/*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2607: 		}
 2608: 		for(j=i+1; j<=nlstate+ndeath; j++){
 2609: 			s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2610: 			/*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2611: 		}
 2612: 		/* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 2613: 		ps[i][i]=1./(s1+1.);
 2614: 		/* Computing other pijs */
 2615: 		for(j=1; j<i; j++)
 2616: 			ps[i][j]= exp(ps[i][j])*ps[i][i];
 2617: 		for(j=i+1; j<=nlstate+ndeath; j++)
 2618: 			ps[i][j]= exp(ps[i][j])*ps[i][i];
 2619: 		/* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 2620: 	} /* end i */
 2621: 	
 2622: 	for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 2623: 		for(jj=1; jj<= nlstate+ndeath; jj++){
 2624: 			ps[ii][jj]=0;
 2625: 			ps[ii][ii]=1;
 2626: 		}
 2627: 	}
 2628: 	/* Added for backcast */ /* Transposed matrix too */
 2629: 	for(jj=1; jj<= nlstate+ndeath; jj++){
 2630: 		s1=0.;
 2631: 		for(ii=1; ii<= nlstate+ndeath; ii++){
 2632: 			s1+=ps[ii][jj];
 2633: 		}
 2634: 		for(ii=1; ii<= nlstate; ii++){
 2635: 			ps[ii][jj]=ps[ii][jj]/s1;
 2636: 		}
 2637: 	}
 2638: 	/* Transposition */
 2639: 	for(jj=1; jj<= nlstate+ndeath; jj++){
 2640: 		for(ii=jj; ii<= nlstate+ndeath; ii++){
 2641: 			s1=ps[ii][jj];
 2642: 			ps[ii][jj]=ps[jj][ii];
 2643: 			ps[jj][ii]=s1;
 2644: 		}
 2645: 	}
 2646: 	/* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 2647: 	/*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 2648: 	/* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 2649: 	/*   } */
 2650: 	/*   printf("\n "); */
 2651: 	/* } */
 2652: 	/* printf("\n ");printf("%lf ",cov[2]);*/
 2653: 	/*
 2654: 		for(i=1; i<= npar; i++) printf("%f ",x[i]);
 2655: 		goto end;*/
 2656: 	return ps;
 2657: }
 2658: 
 2659: 
 2660: /**************** Product of 2 matrices ******************/
 2661: 
 2662: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
 2663: {
 2664:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
 2665:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
 2666:   /* in, b, out are matrice of pointers which should have been initialized 
 2667:      before: only the contents of out is modified. The function returns
 2668:      a pointer to pointers identical to out */
 2669:   int i, j, k;
 2670:   for(i=nrl; i<= nrh; i++)
 2671:     for(k=ncolol; k<=ncoloh; k++){
 2672:       out[i][k]=0.;
 2673:       for(j=ncl; j<=nch; j++)
 2674:   	out[i][k] +=in[i][j]*b[j][k];
 2675:     }
 2676:   return out;
 2677: }
 2678: 
 2679: 
 2680: /************* Higher Matrix Product ***************/
 2681: 
 2682: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
 2683: {
 2684:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
 2685:      'nhstepm*hstepm*stepm' months (i.e. until
 2686:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
 2687:      nhstepm*hstepm matrices. 
 2688:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
 2689:      (typically every 2 years instead of every month which is too big 
 2690:      for the memory).
 2691:      Model is determined by parameters x and covariates have to be 
 2692:      included manually here. 
 2693: 
 2694:      */
 2695: 
 2696:   int i, j, d, h, k;
 2697:   double **out, cov[NCOVMAX+1];
 2698:   double **newm;
 2699:   double agexact;
 2700:   double agebegin, ageend;
 2701: 
 2702:   /* Hstepm could be zero and should return the unit matrix */
 2703:   for (i=1;i<=nlstate+ndeath;i++)
 2704:     for (j=1;j<=nlstate+ndeath;j++){
 2705:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 2706:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 2707:     }
 2708:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2709:   for(h=1; h <=nhstepm; h++){
 2710:     for(d=1; d <=hstepm; d++){
 2711:       newm=savm;
 2712:       /* Covariates have to be included here again */
 2713:       cov[1]=1.;
 2714:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
 2715:       cov[2]=agexact;
 2716:       if(nagesqr==1)
 2717: 				cov[3]= agexact*agexact;
 2718:       for (k=1; k<=cptcovn;k++) 
 2719: 				cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 2720: 			/* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 2721:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
 2722: 				/* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2723: 				cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 2724: 			/* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
 2725:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
 2726: 				cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
 2727: 			/* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 2728: 
 2729: 
 2730:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 2731:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 2732: 			/* right multiplication of oldm by the current matrix */
 2733:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
 2734: 		   pmij(pmmij,cov,ncovmodel,x,nlstate));
 2735:       /* if((int)age == 70){ */
 2736:       /* 	printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
 2737:       /* 	for(i=1; i<=nlstate+ndeath; i++) { */
 2738:       /* 	  printf("%d pmmij ",i); */
 2739:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 2740:       /* 	    printf("%f ",pmmij[i][j]); */
 2741:       /* 	  } */
 2742:       /* 	  printf(" oldm "); */
 2743:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 2744:       /* 	    printf("%f ",oldm[i][j]); */
 2745:       /* 	  } */
 2746:       /* 	  printf("\n"); */
 2747:       /* 	} */
 2748:       /* } */
 2749:       savm=oldm;
 2750:       oldm=newm;
 2751:     }
 2752:     for(i=1; i<=nlstate+ndeath; i++)
 2753:       for(j=1;j<=nlstate+ndeath;j++) {
 2754: 				po[i][j][h]=newm[i][j];
 2755: 				/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 2756:       }
 2757:     /*printf("h=%d ",h);*/
 2758:   } /* end h */
 2759: 	/*     printf("\n H=%d \n",h); */
 2760:   return po;
 2761: }
 2762: 
 2763: /************* Higher Back Matrix Product ***************/
 2764: /* 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 ) */
 2765: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
 2766: {
 2767:   /* Computes the transition matrix starting at age 'age' over
 2768:      'nhstepm*hstepm*stepm' months (i.e. until
 2769:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
 2770:      nhstepm*hstepm matrices.
 2771:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
 2772:      (typically every 2 years instead of every month which is too big
 2773:      for the memory).
 2774:      Model is determined by parameters x and covariates have to be
 2775:      included manually here.
 2776: 
 2777:   */
 2778: 
 2779:   int i, j, d, h, k;
 2780:   double **out, cov[NCOVMAX+1];
 2781:   double **newm;
 2782:   double agexact;
 2783:   double agebegin, ageend;
 2784:   double **oldm, **savm;
 2785: 
 2786:   oldm=oldms;savm=savms;
 2787:   /* Hstepm could be zero and should return the unit matrix */
 2788:   for (i=1;i<=nlstate+ndeath;i++)
 2789:     for (j=1;j<=nlstate+ndeath;j++){
 2790:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 2791:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 2792:     }
 2793:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2794:   for(h=1; h <=nhstepm; h++){
 2795:     for(d=1; d <=hstepm; d++){
 2796:       newm=savm;
 2797:       /* Covariates have to be included here again */
 2798:       cov[1]=1.;
 2799:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
 2800:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
 2801:       cov[2]=agexact;
 2802:       if(nagesqr==1)
 2803: 	cov[3]= agexact*agexact;
 2804:       for (k=1; k<=cptcovn;k++)
 2805: 	cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 2806:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 2807:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
 2808: 	/* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2809: 	cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 2810:       /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
 2811:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
 2812: 	cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
 2813:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 2814: 			
 2815: 			
 2816:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 2817:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 2818:       /* Careful transposed matrix */
 2819:       /* age is in cov[2] */
 2820:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
 2821:       /* 						 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
 2822:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
 2823: 		   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
 2824:       /* if((int)age == 70){ */
 2825:       /* 	printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
 2826:       /* 	for(i=1; i<=nlstate+ndeath; i++) { */
 2827:       /* 	  printf("%d pmmij ",i); */
 2828:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 2829:       /* 	    printf("%f ",pmmij[i][j]); */
 2830:       /* 	  } */
 2831:       /* 	  printf(" oldm "); */
 2832:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 2833:       /* 	    printf("%f ",oldm[i][j]); */
 2834:       /* 	  } */
 2835:       /* 	  printf("\n"); */
 2836:       /* 	} */
 2837:       /* } */
 2838:       savm=oldm;
 2839:       oldm=newm;
 2840:     }
 2841:     for(i=1; i<=nlstate+ndeath; i++)
 2842:       for(j=1;j<=nlstate+ndeath;j++) {
 2843: 	po[i][j][h]=newm[i][j];
 2844: 	/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 2845:       }
 2846:     /*printf("h=%d ",h);*/
 2847:   } /* end h */
 2848:   /*     printf("\n H=%d \n",h); */
 2849:   return po;
 2850: }
 2851: 
 2852: 
 2853: #ifdef NLOPT
 2854:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
 2855:   double fret;
 2856:   double *xt;
 2857:   int j;
 2858:   myfunc_data *d2 = (myfunc_data *) pd;
 2859: /* xt = (p1-1); */
 2860:   xt=vector(1,n); 
 2861:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
 2862: 
 2863:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
 2864:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
 2865:   printf("Function = %.12lf ",fret);
 2866:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
 2867:   printf("\n");
 2868:  free_vector(xt,1,n);
 2869:   return fret;
 2870: }
 2871: #endif
 2872: 
 2873: /*************** log-likelihood *************/
 2874: double func( double *x)
 2875: {
 2876: 	int i, ii, j, k, mi, d, kk;
 2877: 	int ioffset=0;
 2878: 	double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 2879: 	double **out;
 2880: 	double sw; /* Sum of weights */
 2881: 	double lli; /* Individual log likelihood */
 2882: 	int s1, s2;
 2883: 	int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate */
 2884: 	double bbh, survp;
 2885: 	long ipmx;
 2886: 	double agexact;
 2887: 	/*extern weight */
 2888: 	/* We are differentiating ll according to initial status */
 2889: 	/*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 2890: 	/*for(i=1;i<imx;i++) 
 2891: 		printf(" %d\n",s[4][i]);
 2892: 	*/
 2893: 
 2894: 	++countcallfunc;
 2895: 
 2896: 	cov[1]=1.;
 2897: 
 2898: 	for(k=1; k<=nlstate; k++) ll[k]=0.;
 2899:   ioffset=0;
 2900: 	if(mle==1){
 2901: 		for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2902: 			/* Computes the values of the ncovmodel covariates of the model
 2903: 				 depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
 2904: 				 Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
 2905: 				 to be observed in j being in i according to the model.
 2906: 			*/
 2907: 			ioffset=2+nagesqr+cptcovage;
 2908: 			/* for (k=1; k<=cptcovn;k++){ /\* Simple and product covariates without age* products *\/ */
 2909: 			for (k=1; k<=ncoveff;k++){ /* Simple and product covariates without age* products */
 2910: 				cov[++ioffset]=covar[Tvar[k]][i];
 2911: 			}
 2912: 			for(iqv=1; iqv <= nqveff; iqv++){ /* Quantitatives covariates */
 2913: 				cov[++ioffset]=coqvar[iqv][i];
 2914: 			}
 2915: 
 2916: 			/* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
 2917: 				 is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
 2918: 				 has been calculated etc */
 2919: 			/* For an individual i, wav[i] gives the number of effective waves */
 2920: 			/* We compute the contribution to Likelihood of each effective transition
 2921: 				 mw[mi][i] is real wave of the mi th effectve wave */
 2922: 			/* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
 2923: 				 s2=s[mw[mi+1][i]][i];
 2924: 				 And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
 2925: 				 But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
 2926: 				 meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
 2927: 			*/
 2928: 			for(mi=1; mi<= wav[i]-1; mi++){
 2929: 				for(itv=1; itv <= ntveff; itv++){ /* Varying dummy covariates */
 2930: 					cov[ioffset+itv]=cotvar[mw[mi][i]][itv][i];
 2931: 				}
 2932: 				for(iqtv=1; iqtv <= nqtveff; iqtv++){ /* Varying quantitatives covariates */
 2933: 					cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][iqtv][i];
 2934: 				}
 2935: 				/* ioffset=2+nagesqr+cptcovn+nqv+ntv+nqtv; */
 2936: 				for (ii=1;ii<=nlstate+ndeath;ii++)
 2937: 					for (j=1;j<=nlstate+ndeath;j++){
 2938: 						oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2939: 						savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2940: 					}
 2941: 				for(d=0; d<dh[mi][i]; d++){
 2942: 					newm=savm;
 2943: 					agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2944: 					cov[2]=agexact;
 2945: 					if(nagesqr==1)
 2946: 						cov[3]= agexact*agexact;  /* Should be changed here */
 2947: 					for (kk=1; kk<=cptcovage;kk++) {
 2948: 						cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
 2949: 					}
 2950: 					out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2951: 											 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2952: 					savm=oldm;
 2953: 					oldm=newm;
 2954: 				} /* end mult */
 2955: 				
 2956: 					/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 2957: 				/* But now since version 0.9 we anticipate for bias at large stepm.
 2958: 				 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 2959: 				 * (in months) between two waves is not a multiple of stepm, we rounded to 
 2960: 				 * the nearest (and in case of equal distance, to the lowest) interval but now
 2961: 				 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 2962: 				 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
 2963: 				 * probability in order to take into account the bias as a fraction of the way
 2964: 				 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
 2965: 				 * -stepm/2 to stepm/2 .
 2966: 				 * For stepm=1 the results are the same as for previous versions of Imach.
 2967: 				 * For stepm > 1 the results are less biased than in previous versions. 
 2968: 				 */
 2969: 				s1=s[mw[mi][i]][i];
 2970: 				s2=s[mw[mi+1][i]][i];
 2971: 				bbh=(double)bh[mi][i]/(double)stepm; 
 2972: 				/* bias bh is positive if real duration
 2973: 				 * is higher than the multiple of stepm and negative otherwise.
 2974: 				 */
 2975: 				/* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
 2976: 				if( s2 > nlstate){ 
 2977: 					/* i.e. if s2 is a death state and if the date of death is known 
 2978: 						 then the contribution to the likelihood is the probability to 
 2979: 						 die between last step unit time and current  step unit time, 
 2980: 						 which is also equal to probability to die before dh 
 2981: 						 minus probability to die before dh-stepm . 
 2982: 						 In version up to 0.92 likelihood was computed
 2983: 						 as if date of death was unknown. Death was treated as any other
 2984: 						 health state: the date of the interview describes the actual state
 2985: 						 and not the date of a change in health state. The former idea was
 2986: 						 to consider that at each interview the state was recorded
 2987: 						 (healthy, disable or death) and IMaCh was corrected; but when we
 2988: 						 introduced the exact date of death then we should have modified
 2989: 						 the contribution of an exact death to the likelihood. This new
 2990: 						 contribution is smaller and very dependent of the step unit
 2991: 						 stepm. It is no more the probability to die between last interview
 2992: 						 and month of death but the probability to survive from last
 2993: 						 interview up to one month before death multiplied by the
 2994: 						 probability to die within a month. Thanks to Chris
 2995: 						 Jackson for correcting this bug.  Former versions increased
 2996: 						 mortality artificially. The bad side is that we add another loop
 2997: 						 which slows down the processing. The difference can be up to 10%
 2998: 						 lower mortality.
 2999: 					*/
 3000: 					/* If, at the beginning of the maximization mostly, the
 3001: 						 cumulative probability or probability to be dead is
 3002: 						 constant (ie = 1) over time d, the difference is equal to
 3003: 						 0.  out[s1][3] = savm[s1][3]: probability, being at state
 3004: 						 s1 at precedent wave, to be dead a month before current
 3005: 						 wave is equal to probability, being at state s1 at
 3006: 						 precedent wave, to be dead at mont of the current
 3007: 						 wave. Then the observed probability (that this person died)
 3008: 						 is null according to current estimated parameter. In fact,
 3009: 						 it should be very low but not zero otherwise the log go to
 3010: 						 infinity.
 3011: 					*/
 3012: /* #ifdef INFINITYORIGINAL */
 3013: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 3014: /* #else */
 3015: /* 	  if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
 3016: /* 	    lli=log(mytinydouble); */
 3017: /* 	  else */
 3018: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 3019: /* #endif */
 3020: 					lli=log(out[s1][s2] - savm[s1][s2]);
 3021: 	  
 3022: 				} else if  ( s2==-1 ) { /* alive */
 3023: 					for (j=1,survp=0. ; j<=nlstate; j++) 
 3024: 						survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 3025: 					/*survp += out[s1][j]; */
 3026: 					lli= log(survp);
 3027: 				}
 3028: 				else if  (s2==-4) { 
 3029: 					for (j=3,survp=0. ; j<=nlstate; j++)  
 3030: 						survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 3031: 					lli= log(survp); 
 3032: 				} 
 3033: 				else if  (s2==-5) { 
 3034: 					for (j=1,survp=0. ; j<=2; j++)  
 3035: 						survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 3036: 					lli= log(survp); 
 3037: 				} 
 3038: 				else{
 3039: 					lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 3040: 					/*  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 */
 3041: 				} 
 3042: 				/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 3043: 				/*if(lli ==000.0)*/
 3044: 				/*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); */
 3045: 				ipmx +=1;
 3046: 				sw += weight[i];
 3047: 				ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3048: 				/* if (lli < log(mytinydouble)){ */
 3049: 				/*   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); */
 3050: 				/*   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]); */
 3051: 				/* } */
 3052: 			} /* end of wave */
 3053: 		} /* end of individual */
 3054: 	}  else if(mle==2){
 3055: 		for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3056: 			for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 3057: 			for(mi=1; mi<= wav[i]-1; mi++){
 3058: 				for (ii=1;ii<=nlstate+ndeath;ii++)
 3059: 					for (j=1;j<=nlstate+ndeath;j++){
 3060: 						oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3061: 						savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3062: 					}
 3063: 				for(d=0; d<=dh[mi][i]; d++){
 3064: 					newm=savm;
 3065: 					agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3066: 					cov[2]=agexact;
 3067: 					if(nagesqr==1)
 3068: 						cov[3]= agexact*agexact;
 3069: 					for (kk=1; kk<=cptcovage;kk++) {
 3070: 						cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3071: 					}
 3072: 					out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3073: 											 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3074: 					savm=oldm;
 3075: 					oldm=newm;
 3076: 				} /* end mult */
 3077:       
 3078: 				s1=s[mw[mi][i]][i];
 3079: 				s2=s[mw[mi+1][i]][i];
 3080: 				bbh=(double)bh[mi][i]/(double)stepm; 
 3081: 				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 */
 3082: 				ipmx +=1;
 3083: 				sw += weight[i];
 3084: 				ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3085: 			} /* end of wave */
 3086: 		} /* end of individual */
 3087: 	}  else if(mle==3){  /* exponential inter-extrapolation */
 3088: 		for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3089: 			for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 3090: 			for(mi=1; mi<= wav[i]-1; mi++){
 3091: 				for (ii=1;ii<=nlstate+ndeath;ii++)
 3092: 					for (j=1;j<=nlstate+ndeath;j++){
 3093: 						oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3094: 						savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3095: 					}
 3096: 				for(d=0; d<dh[mi][i]; d++){
 3097: 					newm=savm;
 3098: 					agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3099: 					cov[2]=agexact;
 3100: 					if(nagesqr==1)
 3101: 						cov[3]= agexact*agexact;
 3102: 					for (kk=1; kk<=cptcovage;kk++) {
 3103: 						cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3104: 					}
 3105: 					out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3106: 											 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3107: 					savm=oldm;
 3108: 					oldm=newm;
 3109: 				} /* end mult */
 3110:       
 3111: 				s1=s[mw[mi][i]][i];
 3112: 				s2=s[mw[mi+1][i]][i];
 3113: 				bbh=(double)bh[mi][i]/(double)stepm; 
 3114: 				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 */
 3115: 				ipmx +=1;
 3116: 				sw += weight[i];
 3117: 				ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3118: 			} /* end of wave */
 3119: 		} /* end of individual */
 3120: 	}else if (mle==4){  /* ml=4 no inter-extrapolation */
 3121: 		for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3122: 			for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 3123: 			for(mi=1; mi<= wav[i]-1; mi++){
 3124: 				for (ii=1;ii<=nlstate+ndeath;ii++)
 3125: 					for (j=1;j<=nlstate+ndeath;j++){
 3126: 						oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3127: 						savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3128: 					}
 3129: 				for(d=0; d<dh[mi][i]; d++){
 3130: 					newm=savm;
 3131: 					agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3132: 					cov[2]=agexact;
 3133: 					if(nagesqr==1)
 3134: 						cov[3]= agexact*agexact;
 3135: 					for (kk=1; kk<=cptcovage;kk++) {
 3136: 						cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3137: 					}
 3138: 	
 3139: 					out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3140: 											 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3141: 					savm=oldm;
 3142: 					oldm=newm;
 3143: 				} /* end mult */
 3144:       
 3145: 				s1=s[mw[mi][i]][i];
 3146: 				s2=s[mw[mi+1][i]][i];
 3147: 				if( s2 > nlstate){ 
 3148: 					lli=log(out[s1][s2] - savm[s1][s2]);
 3149: 				} else if  ( s2==-1 ) { /* alive */
 3150: 					for (j=1,survp=0. ; j<=nlstate; j++) 
 3151: 						survp += out[s1][j];
 3152: 					lli= log(survp);
 3153: 				}else{
 3154: 					lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 3155: 				}
 3156: 				ipmx +=1;
 3157: 				sw += weight[i];
 3158: 				ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3159: /* 	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]); */
 3160: 			} /* end of wave */
 3161: 		} /* end of individual */
 3162: 	}else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
 3163: 		for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3164: 			for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 3165: 			for(mi=1; mi<= wav[i]-1; mi++){
 3166: 				for (ii=1;ii<=nlstate+ndeath;ii++)
 3167: 					for (j=1;j<=nlstate+ndeath;j++){
 3168: 						oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3169: 						savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3170: 					}
 3171: 				for(d=0; d<dh[mi][i]; d++){
 3172: 					newm=savm;
 3173: 					agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3174: 					cov[2]=agexact;
 3175: 					if(nagesqr==1)
 3176: 						cov[3]= agexact*agexact;
 3177: 					for (kk=1; kk<=cptcovage;kk++) {
 3178: 						cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3179: 					}
 3180: 	
 3181: 					out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3182: 											 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3183: 					savm=oldm;
 3184: 					oldm=newm;
 3185: 				} /* end mult */
 3186:       
 3187: 				s1=s[mw[mi][i]][i];
 3188: 				s2=s[mw[mi+1][i]][i];
 3189: 				lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 3190: 				ipmx +=1;
 3191: 				sw += weight[i];
 3192: 				ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3193: 				/*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]);*/
 3194: 			} /* end of wave */
 3195: 		} /* end of individual */
 3196: 	} /* End of if */
 3197: 	for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 3198: 	/* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 3199: 	l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 3200: 	return -l;
 3201: }
 3202: 
 3203: /*************** log-likelihood *************/
 3204: double funcone( double *x)
 3205: {
 3206:   /* Same as likeli but slower because of a lot of printf and if */
 3207:   int i, ii, j, k, mi, d, kk;
 3208: 	int ioffset=0;
 3209:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 3210:   double **out;
 3211:   double lli; /* Individual log likelihood */
 3212:   double llt;
 3213:   int s1, s2;
 3214: 	int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate */
 3215:   double bbh, survp;
 3216:   double agexact;
 3217:   double agebegin, ageend;
 3218:   /*extern weight */
 3219:   /* We are differentiating ll according to initial status */
 3220:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 3221:   /*for(i=1;i<imx;i++) 
 3222:     printf(" %d\n",s[4][i]);
 3223:   */
 3224:   cov[1]=1.;
 3225: 
 3226:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 3227:   ioffset=0;
 3228:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3229: 		ioffset=2+nagesqr+cptcovage;
 3230:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
 3231: 		for (k=1; k<=ncoveff;k++){ /* Simple and product covariates without age* products */
 3232: 			cov[++ioffset]=covar[Tvar[k]][i];
 3233: 		}
 3234: 		for(iqv=1; iqv <= nqveff; iqv++){ /* Quantitatives covariates */
 3235: 			cov[++ioffset]=coqvar[iqv][i];
 3236: 		}
 3237: 
 3238:     for(mi=1; mi<= wav[i]-1; mi++){
 3239: 			for(itv=1; itv <= ntveff; itv++){ /* Varying dummy covariates */
 3240: 				cov[ioffset+itv]=cotvar[mw[mi][i]][itv][i];
 3241: 			}
 3242: 			for(iqtv=1; iqtv <= nqtveff; iqtv++){ /* Varying quantitatives covariates */
 3243: 				cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][iqtv][i];
 3244: 			}
 3245:       for (ii=1;ii<=nlstate+ndeath;ii++)
 3246: 				for (j=1;j<=nlstate+ndeath;j++){
 3247: 					oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3248: 					savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3249: 				}
 3250:       
 3251:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
 3252:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
 3253:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
 3254: 				/*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 3255: 					and mw[mi+1][i]. dh depends on stepm.*/
 3256: 				newm=savm;
 3257: 				agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3258: 				cov[2]=agexact;
 3259: 				if(nagesqr==1)
 3260: 					cov[3]= agexact*agexact;
 3261: 				for (kk=1; kk<=cptcovage;kk++) {
 3262: 					cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3263: 				}
 3264: 				
 3265: 				/* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 3266: 				out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3267: 										 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3268: 				/* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
 3269: 				/* 	     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
 3270: 				savm=oldm;
 3271: 				oldm=newm;
 3272:       } /* end mult */
 3273:       
 3274:       s1=s[mw[mi][i]][i];
 3275:       s2=s[mw[mi+1][i]][i];
 3276:       /* if(s2==-1){ */
 3277:       /* 	printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
 3278:       /* 	/\* exit(1); *\/ */
 3279:       /* } */
 3280:       bbh=(double)bh[mi][i]/(double)stepm; 
 3281:       /* bias is positive if real duration
 3282:        * is higher than the multiple of stepm and negative otherwise.
 3283:        */
 3284:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
 3285: 				lli=log(out[s1][s2] - savm[s1][s2]);
 3286:       } else if  ( s2==-1 ) { /* alive */
 3287: 				for (j=1,survp=0. ; j<=nlstate; j++) 
 3288: 					survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 3289: 				lli= log(survp);
 3290:       }else if (mle==1){
 3291: 				lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 3292:       } else if(mle==2){
 3293: 				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 */
 3294:       } else if(mle==3){  /* exponential inter-extrapolation */
 3295: 				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 */
 3296:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
 3297: 				lli=log(out[s1][s2]); /* Original formula */
 3298:       } else{  /* mle=0 back to 1 */
 3299: 				lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 3300: 				/*lli=log(out[s1][s2]); */ /* Original formula */
 3301:       } /* End of if */
 3302:       ipmx +=1;
 3303:       sw += weight[i];
 3304:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3305:       /*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]); */
 3306:       if(globpr){
 3307: 				fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
 3308:  %11.6f %11.6f %11.6f ", \
 3309: 								num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
 3310: 								2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
 3311: 				for(k=1,llt=0.,l=0.; k<=nlstate; k++){
 3312: 					llt +=ll[k]*gipmx/gsw;
 3313: 					fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
 3314: 				}
 3315: 				fprintf(ficresilk," %10.6f\n", -llt);
 3316:       }
 3317:     } /* end of wave */
 3318:   } /* end of individual */
 3319:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 3320:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 3321:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 3322:   if(globpr==0){ /* First time we count the contributions and weights */
 3323:     gipmx=ipmx;
 3324:     gsw=sw;
 3325:   }
 3326:   return -l;
 3327: }
 3328: 
 3329: 
 3330: /*************** function likelione ***********/
 3331: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
 3332: {
 3333:   /* This routine should help understanding what is done with 
 3334:      the selection of individuals/waves and
 3335:      to check the exact contribution to the likelihood.
 3336:      Plotting could be done.
 3337:    */
 3338:   int k;
 3339: 
 3340:   if(*globpri !=0){ /* Just counts and sums, no printings */
 3341:     strcpy(fileresilk,"ILK_"); 
 3342:     strcat(fileresilk,fileresu);
 3343:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
 3344:       printf("Problem with resultfile: %s\n", fileresilk);
 3345:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
 3346:     }
 3347:     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");
 3348:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
 3349:     /* 	i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
 3350:     for(k=1; k<=nlstate; k++) 
 3351:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
 3352:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
 3353:   }
 3354: 
 3355:   *fretone=(*funcone)(p);
 3356:   if(*globpri !=0){
 3357:     fclose(ficresilk);
 3358:     if (mle ==0)
 3359:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
 3360:     else if(mle >=1)
 3361:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
 3362:     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));
 3363:     
 3364:       
 3365:     for (k=1; k<= nlstate ; k++) {
 3366:       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> \
 3367: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
 3368:     }
 3369:     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> \
 3370: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
 3371:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
 3372: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
 3373:     fflush(fichtm);
 3374:   }
 3375:   return;
 3376: }
 3377: 
 3378: 
 3379: /*********** Maximum Likelihood Estimation ***************/
 3380: 
 3381: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
 3382: {
 3383:   int i,j, iter=0;
 3384:   double **xi;
 3385:   double fret;
 3386:   double fretone; /* Only one call to likelihood */
 3387:   /*  char filerespow[FILENAMELENGTH];*/
 3388: 
 3389: #ifdef NLOPT
 3390:   int creturn;
 3391:   nlopt_opt opt;
 3392:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
 3393:   double *lb;
 3394:   double minf; /* the minimum objective value, upon return */
 3395:   double * p1; /* Shifted parameters from 0 instead of 1 */
 3396:   myfunc_data dinst, *d = &dinst;
 3397: #endif
 3398: 
 3399: 
 3400:   xi=matrix(1,npar,1,npar);
 3401:   for (i=1;i<=npar;i++)
 3402:     for (j=1;j<=npar;j++)
 3403:       xi[i][j]=(i==j ? 1.0 : 0.0);
 3404:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
 3405:   strcpy(filerespow,"POW_"); 
 3406:   strcat(filerespow,fileres);
 3407:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
 3408:     printf("Problem with resultfile: %s\n", filerespow);
 3409:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 3410:   }
 3411:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
 3412:   for (i=1;i<=nlstate;i++)
 3413:     for(j=1;j<=nlstate+ndeath;j++)
 3414:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 3415:   fprintf(ficrespow,"\n");
 3416: #ifdef POWELL
 3417:   powell(p,xi,npar,ftol,&iter,&fret,func);
 3418: #endif
 3419: 
 3420: #ifdef NLOPT
 3421: #ifdef NEWUOA
 3422:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
 3423: #else
 3424:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
 3425: #endif
 3426:   lb=vector(0,npar-1);
 3427:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
 3428:   nlopt_set_lower_bounds(opt, lb);
 3429:   nlopt_set_initial_step1(opt, 0.1);
 3430:   
 3431:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
 3432:   d->function = func;
 3433:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
 3434:   nlopt_set_min_objective(opt, myfunc, d);
 3435:   nlopt_set_xtol_rel(opt, ftol);
 3436:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
 3437:     printf("nlopt failed! %d\n",creturn); 
 3438:   }
 3439:   else {
 3440:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
 3441:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
 3442:     iter=1; /* not equal */
 3443:   }
 3444:   nlopt_destroy(opt);
 3445: #endif
 3446:   free_matrix(xi,1,npar,1,npar);
 3447:   fclose(ficrespow);
 3448:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 3449:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 3450:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 3451: 
 3452: }
 3453: 
 3454: /**** Computes Hessian and covariance matrix ***/
 3455: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
 3456: {
 3457:   double  **a,**y,*x,pd;
 3458:   /* double **hess; */
 3459:   int i, j;
 3460:   int *indx;
 3461: 
 3462:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
 3463:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
 3464:   void lubksb(double **a, int npar, int *indx, double b[]) ;
 3465:   void ludcmp(double **a, int npar, int *indx, double *d) ;
 3466:   double gompertz(double p[]);
 3467:   /* hess=matrix(1,npar,1,npar); */
 3468: 
 3469:   printf("\nCalculation of the hessian matrix. Wait...\n");
 3470:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
 3471:   for (i=1;i<=npar;i++){
 3472:     printf("%d-",i);fflush(stdout);
 3473:     fprintf(ficlog,"%d-",i);fflush(ficlog);
 3474:    
 3475:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
 3476:     
 3477:     /*  printf(" %f ",p[i]);
 3478: 	printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
 3479:   }
 3480:   
 3481:   for (i=1;i<=npar;i++) {
 3482:     for (j=1;j<=npar;j++)  {
 3483:       if (j>i) { 
 3484: 	printf(".%d-%d",i,j);fflush(stdout);
 3485: 	fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
 3486: 	hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
 3487: 	
 3488: 	hess[j][i]=hess[i][j];    
 3489: 	/*printf(" %lf ",hess[i][j]);*/
 3490:       }
 3491:     }
 3492:   }
 3493:   printf("\n");
 3494:   fprintf(ficlog,"\n");
 3495: 
 3496:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
 3497:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
 3498:   
 3499:   a=matrix(1,npar,1,npar);
 3500:   y=matrix(1,npar,1,npar);
 3501:   x=vector(1,npar);
 3502:   indx=ivector(1,npar);
 3503:   for (i=1;i<=npar;i++)
 3504:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
 3505:   ludcmp(a,npar,indx,&pd);
 3506: 
 3507:   for (j=1;j<=npar;j++) {
 3508:     for (i=1;i<=npar;i++) x[i]=0;
 3509:     x[j]=1;
 3510:     lubksb(a,npar,indx,x);
 3511:     for (i=1;i<=npar;i++){ 
 3512:       matcov[i][j]=x[i];
 3513:     }
 3514:   }
 3515: 
 3516:   printf("\n#Hessian matrix#\n");
 3517:   fprintf(ficlog,"\n#Hessian matrix#\n");
 3518:   for (i=1;i<=npar;i++) { 
 3519:     for (j=1;j<=npar;j++) { 
 3520:       printf("%.6e ",hess[i][j]);
 3521:       fprintf(ficlog,"%.6e ",hess[i][j]);
 3522:     }
 3523:     printf("\n");
 3524:     fprintf(ficlog,"\n");
 3525:   }
 3526: 
 3527:   /* printf("\n#Covariance matrix#\n"); */
 3528:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
 3529:   /* for (i=1;i<=npar;i++) {  */
 3530:   /*   for (j=1;j<=npar;j++) {  */
 3531:   /*     printf("%.6e ",matcov[i][j]); */
 3532:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
 3533:   /*   } */
 3534:   /*   printf("\n"); */
 3535:   /*   fprintf(ficlog,"\n"); */
 3536:   /* } */
 3537: 
 3538:   /* Recompute Inverse */
 3539:   /* for (i=1;i<=npar;i++) */
 3540:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
 3541:   /* ludcmp(a,npar,indx,&pd); */
 3542: 
 3543:   /*  printf("\n#Hessian matrix recomputed#\n"); */
 3544: 
 3545:   /* for (j=1;j<=npar;j++) { */
 3546:   /*   for (i=1;i<=npar;i++) x[i]=0; */
 3547:   /*   x[j]=1; */
 3548:   /*   lubksb(a,npar,indx,x); */
 3549:   /*   for (i=1;i<=npar;i++){  */
 3550:   /*     y[i][j]=x[i]; */
 3551:   /*     printf("%.3e ",y[i][j]); */
 3552:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
 3553:   /*   } */
 3554:   /*   printf("\n"); */
 3555:   /*   fprintf(ficlog,"\n"); */
 3556:   /* } */
 3557: 
 3558:   /* Verifying the inverse matrix */
 3559: #ifdef DEBUGHESS
 3560:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
 3561: 
 3562:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
 3563:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
 3564: 
 3565:   for (j=1;j<=npar;j++) {
 3566:     for (i=1;i<=npar;i++){ 
 3567:       printf("%.2f ",y[i][j]);
 3568:       fprintf(ficlog,"%.2f ",y[i][j]);
 3569:     }
 3570:     printf("\n");
 3571:     fprintf(ficlog,"\n");
 3572:   }
 3573: #endif
 3574: 
 3575:   free_matrix(a,1,npar,1,npar);
 3576:   free_matrix(y,1,npar,1,npar);
 3577:   free_vector(x,1,npar);
 3578:   free_ivector(indx,1,npar);
 3579:   /* free_matrix(hess,1,npar,1,npar); */
 3580: 
 3581: 
 3582: }
 3583: 
 3584: /*************** hessian matrix ****************/
 3585: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
 3586: { /* Around values of x, computes the function func and returns the scales delti and hessian */
 3587:   int i;
 3588:   int l=1, lmax=20;
 3589:   double k1,k2, res, fx;
 3590:   double p2[MAXPARM+1]; /* identical to x */
 3591:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 3592:   int k=0,kmax=10;
 3593:   double l1;
 3594: 
 3595:   fx=func(x);
 3596:   for (i=1;i<=npar;i++) p2[i]=x[i];
 3597:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
 3598:     l1=pow(10,l);
 3599:     delts=delt;
 3600:     for(k=1 ; k <kmax; k=k+1){
 3601:       delt = delta*(l1*k);
 3602:       p2[theta]=x[theta] +delt;
 3603:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
 3604:       p2[theta]=x[theta]-delt;
 3605:       k2=func(p2)-fx;
 3606:       /*res= (k1-2.0*fx+k2)/delt/delt; */
 3607:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
 3608:       
 3609: #ifdef DEBUGHESSII
 3610:       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);
 3611:       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);
 3612: #endif
 3613:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
 3614:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 3615: 	k=kmax;
 3616:       }
 3617:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
 3618: 	k=kmax; l=lmax*10;
 3619:       }
 3620:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
 3621: 	delts=delt;
 3622:       }
 3623:     } /* End loop k */
 3624:   }
 3625:   delti[theta]=delts;
 3626:   return res; 
 3627:   
 3628: }
 3629: 
 3630: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
 3631: {
 3632:   int i;
 3633:   int l=1, lmax=20;
 3634:   double k1,k2,k3,k4,res,fx;
 3635:   double p2[MAXPARM+1];
 3636:   int k, kmax=1;
 3637:   double v1, v2, cv12, lc1, lc2;
 3638: 
 3639:   int firstime=0;
 3640:   
 3641:   fx=func(x);
 3642:   for (k=1; k<=kmax; k=k+10) {
 3643:     for (i=1;i<=npar;i++) p2[i]=x[i];
 3644:     p2[thetai]=x[thetai]+delti[thetai]*k;
 3645:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
 3646:     k1=func(p2)-fx;
 3647:   
 3648:     p2[thetai]=x[thetai]+delti[thetai]*k;
 3649:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
 3650:     k2=func(p2)-fx;
 3651:   
 3652:     p2[thetai]=x[thetai]-delti[thetai]*k;
 3653:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
 3654:     k3=func(p2)-fx;
 3655:   
 3656:     p2[thetai]=x[thetai]-delti[thetai]*k;
 3657:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
 3658:     k4=func(p2)-fx;
 3659:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
 3660:     if(k1*k2*k3*k4 <0.){
 3661:       firstime=1;
 3662:       kmax=kmax+10;
 3663:     }
 3664:     if(kmax >=10 || firstime ==1){
 3665:       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);
 3666:       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);
 3667:       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);
 3668:       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);
 3669:     }
 3670: #ifdef DEBUGHESSIJ
 3671:     v1=hess[thetai][thetai];
 3672:     v2=hess[thetaj][thetaj];
 3673:     cv12=res;
 3674:     /* Computing eigen value of Hessian matrix */
 3675:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3676:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3677:     if ((lc2 <0) || (lc1 <0) ){
 3678:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
 3679:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
 3680:       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);
 3681:       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);
 3682:     }
 3683: #endif
 3684:   }
 3685:   return res;
 3686: }
 3687: 
 3688:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
 3689: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
 3690: /* { */
 3691: /*   int i; */
 3692: /*   int l=1, lmax=20; */
 3693: /*   double k1,k2,k3,k4,res,fx; */
 3694: /*   double p2[MAXPARM+1]; */
 3695: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
 3696: /*   int k=0,kmax=10; */
 3697: /*   double l1; */
 3698:   
 3699: /*   fx=func(x); */
 3700: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
 3701: /*     l1=pow(10,l); */
 3702: /*     delts=delt; */
 3703: /*     for(k=1 ; k <kmax; k=k+1){ */
 3704: /*       delt = delti*(l1*k); */
 3705: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
 3706: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
 3707: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
 3708: /*       k1=func(p2)-fx; */
 3709:       
 3710: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
 3711: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
 3712: /*       k2=func(p2)-fx; */
 3713:       
 3714: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
 3715: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
 3716: /*       k3=func(p2)-fx; */
 3717:       
 3718: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
 3719: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
 3720: /*       k4=func(p2)-fx; */
 3721: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
 3722: /* #ifdef DEBUGHESSIJ */
 3723: /*       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); */
 3724: /*       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); */
 3725: /* #endif */
 3726: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
 3727: /* 	k=kmax; */
 3728: /*       } */
 3729: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
 3730: /* 	k=kmax; l=lmax*10; */
 3731: /*       } */
 3732: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
 3733: /* 	delts=delt; */
 3734: /*       } */
 3735: /*     } /\* End loop k *\/ */
 3736: /*   } */
 3737: /*   delti[theta]=delts; */
 3738: /*   return res;  */
 3739: /* } */
 3740: 
 3741: 
 3742: /************** Inverse of matrix **************/
 3743: void ludcmp(double **a, int n, int *indx, double *d) 
 3744: { 
 3745:   int i,imax,j,k; 
 3746:   double big,dum,sum,temp; 
 3747:   double *vv; 
 3748:  
 3749:   vv=vector(1,n); 
 3750:   *d=1.0; 
 3751:   for (i=1;i<=n;i++) { 
 3752:     big=0.0; 
 3753:     for (j=1;j<=n;j++) 
 3754:       if ((temp=fabs(a[i][j])) > big) big=temp; 
 3755:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
 3756:     vv[i]=1.0/big; 
 3757:   } 
 3758:   for (j=1;j<=n;j++) { 
 3759:     for (i=1;i<j;i++) { 
 3760:       sum=a[i][j]; 
 3761:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
 3762:       a[i][j]=sum; 
 3763:     } 
 3764:     big=0.0; 
 3765:     for (i=j;i<=n;i++) { 
 3766:       sum=a[i][j]; 
 3767:       for (k=1;k<j;k++) 
 3768: 	sum -= a[i][k]*a[k][j]; 
 3769:       a[i][j]=sum; 
 3770:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
 3771: 	big=dum; 
 3772: 	imax=i; 
 3773:       } 
 3774:     } 
 3775:     if (j != imax) { 
 3776:       for (k=1;k<=n;k++) { 
 3777: 	dum=a[imax][k]; 
 3778: 	a[imax][k]=a[j][k]; 
 3779: 	a[j][k]=dum; 
 3780:       } 
 3781:       *d = -(*d); 
 3782:       vv[imax]=vv[j]; 
 3783:     } 
 3784:     indx[j]=imax; 
 3785:     if (a[j][j] == 0.0) a[j][j]=TINY; 
 3786:     if (j != n) { 
 3787:       dum=1.0/(a[j][j]); 
 3788:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
 3789:     } 
 3790:   } 
 3791:   free_vector(vv,1,n);  /* Doesn't work */
 3792: ;
 3793: } 
 3794: 
 3795: void lubksb(double **a, int n, int *indx, double b[]) 
 3796: { 
 3797:   int i,ii=0,ip,j; 
 3798:   double sum; 
 3799:  
 3800:   for (i=1;i<=n;i++) { 
 3801:     ip=indx[i]; 
 3802:     sum=b[ip]; 
 3803:     b[ip]=b[i]; 
 3804:     if (ii) 
 3805:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
 3806:     else if (sum) ii=i; 
 3807:     b[i]=sum; 
 3808:   } 
 3809:   for (i=n;i>=1;i--) { 
 3810:     sum=b[i]; 
 3811:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
 3812:     b[i]=sum/a[i][i]; 
 3813:   } 
 3814: } 
 3815: 
 3816: void pstamp(FILE *fichier)
 3817: {
 3818:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
 3819: }
 3820: 
 3821: /************ Frequencies ********************/
 3822:  void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
 3823: 									 int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[],	\
 3824: 									 int firstpass,  int lastpass, int stepm, int weightopt, char model[])
 3825:  {  /* Some frequencies */
 3826:   
 3827: 	 int i, m, jk, j1, bool, z1,j;
 3828: 	 int iind=0, iage=0;
 3829: 	 int mi; /* Effective wave */
 3830: 	 int first;
 3831: 	 double ***freq; /* Frequencies */
 3832: 	 double *meanq;
 3833: 	 double **meanqt;
 3834: 	 double *pp, **prop, *posprop, *pospropt;
 3835: 	 double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
 3836: 	 char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
 3837: 	 double agebegin, ageend;
 3838:     
 3839: 	 pp=vector(1,nlstate);
 3840: 	 prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
 3841: 	 posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
 3842: 	 pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
 3843: 	 /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
 3844: 	 meanq=vector(1,nqveff);
 3845: 	 meanqt=matrix(1,lastpass,1,nqtveff);
 3846: 	 strcpy(fileresp,"P_");
 3847: 	 strcat(fileresp,fileresu);
 3848: 	 /*strcat(fileresphtm,fileresu);*/
 3849: 	 if((ficresp=fopen(fileresp,"w"))==NULL) {
 3850: 		 printf("Problem with prevalence resultfile: %s\n", fileresp);
 3851: 		 fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
 3852: 		 exit(0);
 3853: 	 }
 3854: 
 3855: 	 strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
 3856: 	 if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
 3857: 		 printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
 3858: 		 fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
 3859: 		 fflush(ficlog);
 3860: 		 exit(70); 
 3861: 	 }
 3862: 	 else{
 3863: 		 fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 3864: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 3865: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
 3866: 						 fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 3867: 	 }
 3868: 	 fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies and prevalence by age at begin of transition</h4>\n",fileresphtm, fileresphtm);
 3869:     
 3870: 	 strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
 3871: 	 if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
 3872: 		 printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
 3873: 		 fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
 3874: 		 fflush(ficlog);
 3875: 		 exit(70); 
 3876: 	 }
 3877: 	 else{
 3878: 		 fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 3879: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 3880: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
 3881: 						 fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 3882: 	 }
 3883: 	 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);
 3884: 
 3885: 	 freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
 3886: 	 j1=0;
 3887:   
 3888: 	 j=ncoveff;
 3889: 	 if (cptcovn<1) {j=1;ncodemax[1]=1;}
 3890: 
 3891: 	 first=1;
 3892: 
 3893: 	 /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
 3894: 			reference=low_education V1=0,V2=0
 3895: 			med_educ                V1=1 V2=0, 
 3896: 			high_educ               V1=0 V2=1
 3897: 			Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
 3898: 	 */
 3899: 
 3900: 	 for (j1 = 1; j1 <= (int) pow(2,j); j1++){ /* Loop on covariates combination excluding varying and quantitatives */
 3901: 		 posproptt=0.;
 3902: 		 /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
 3903: 			 scanf("%d", i);*/
 3904: 		 for (i=-5; i<=nlstate+ndeath; i++)  
 3905: 			 for (jk=-5; jk<=nlstate+ndeath; jk++)  
 3906: 				 for(m=iagemin; m <= iagemax+3; m++)
 3907: 					 freq[i][jk][m]=0;
 3908:       
 3909: 		 for (i=1; i<=nlstate; i++)  {
 3910: 			 for(m=iagemin; m <= iagemax+3; m++)
 3911: 				 prop[i][m]=0;
 3912: 			 posprop[i]=0;
 3913: 			 pospropt[i]=0;
 3914: 		 }
 3915: 		 for (z1=1; z1<= nqveff; z1++) {  
 3916: 			 meanq[z1]+=0.;
 3917: 			 for(m=1;m<=lastpass;m++){
 3918: 				 meanqt[m][z1]=0.;
 3919: 			 }
 3920: 		 }
 3921:       
 3922: 		 dateintsum=0;
 3923: 		 k2cpt=0;
 3924:      /* For that comination of covariate j1, we count and print the frequencies */
 3925: 		 for (iind=1; iind<=imx; iind++) { /* For each individual iind */
 3926: 			 bool=1;
 3927: 			 if (nqveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
 3928: 				 for (z1=1; z1<= nqveff; z1++) {  
 3929: 					 meanq[z1]+=coqvar[Tvar[z1]][iind];
 3930: 				 }
 3931: 				 for (z1=1; z1<=ncoveff; z1++) {  
 3932: 					 /* if(Tvaraff[z1] ==-20){ */
 3933: 					 /* 	 /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
 3934: 					 /* }else  if(Tvaraff[z1] ==-10){ */
 3935: 					 /* 	 /\* sumnew+=coqvar[z1][iind]; *\/ */
 3936: 					 /* }else  */
 3937: 					 if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
 3938: 						 /* Tests if this individual i responded to j1 (V4=1 V3=0) */
 3939: 						 bool=0;
 3940: 						 /* 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", 
 3941:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
 3942:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
 3943: 						 /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
 3944: 					 } 
 3945: 				 } /* end z1 */
 3946: 			 } /* cptcovn > 0 */
 3947: 
 3948: 			 if (bool==1){ /* We selected an individual iin satisfying combination j1 */
 3949: 				 /* for(m=firstpass; m<=lastpass; m++){ */
 3950: 				 for(mi=1; mi<wav[iind];mi++){
 3951: 					 m=mw[mi][iind];
 3952: 					 /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
 3953: 							and mw[mi+1][iind]. dh depends on stepm. */
 3954: 					 agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
 3955: 					 ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
 3956: 					 if(m >=firstpass && m <=lastpass){
 3957: 						 k2=anint[m][iind]+(mint[m][iind]/12.);
 3958: 						 /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
 3959: 						 if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
 3960: 						 if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
 3961: 						 if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
 3962: 							 prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
 3963: 						 if (m<lastpass) {
 3964: 							 /* if(s[m][iind]==4 && s[m+1][iind]==4) */
 3965: 							 /*   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]); */
 3966: 							 if(s[m][iind]==-1)
 3967: 								 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.));
 3968: 							 freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
 3969: 							 /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
 3970: 							 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 */
 3971: 						 }
 3972: 					 }  
 3973: 					 if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99)) {
 3974: 						 dateintsum=dateintsum+k2;
 3975: 						 k2cpt++;
 3976: 						 /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
 3977: 					 }
 3978: 					 /*}*/
 3979: 				 } /* end m */
 3980: 			 } /* end bool */
 3981: 		 } /* end iind = 1 to imx */
 3982:        /* prop[s][age] is feeded for any initial and valid live state as well as
 3983: 					freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
 3984: 
 3985: 
 3986: 		 /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 3987: 		 pstamp(ficresp);
 3988: 		 if  (ncoveff>0) {
 3989: 			 fprintf(ficresp, "\n#********** Variable "); 
 3990: 			 fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
 3991: 			 fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
 3992: 			 for (z1=1; z1<=ncoveff; z1++){
 3993: 				 fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 3994: 				 fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 3995: 				 fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 3996: 			 }
 3997: 			 fprintf(ficresp, "**********\n#");
 3998: 			 fprintf(ficresphtm, "**********</h3>\n");
 3999: 			 fprintf(ficresphtmfr, "**********</h3>\n");
 4000: 			 fprintf(ficlog, "\n#********** Variable "); 
 4001: 			 for (z1=1; z1<=ncoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 4002: 			 fprintf(ficlog, "**********\n");
 4003: 		 }
 4004: 		 fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
 4005: 		 for(i=1; i<=nlstate;i++) {
 4006: 			 fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
 4007: 			 fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
 4008: 		 }
 4009: 		 fprintf(ficresp, "\n");
 4010: 		 fprintf(ficresphtm, "\n");
 4011:       
 4012: 		 /* Header of frequency table by age */
 4013: 		 fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
 4014: 		 fprintf(ficresphtmfr,"<th>Age</th> ");
 4015: 		 for(jk=-1; jk <=nlstate+ndeath; jk++){
 4016: 			 for(m=-1; m <=nlstate+ndeath; m++){
 4017: 				 if(jk!=0 && m!=0)
 4018: 					 fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
 4019: 			 }
 4020: 		 }
 4021: 		 fprintf(ficresphtmfr, "\n");
 4022:       
 4023: 		 /* For each age */
 4024: 		 for(iage=iagemin; iage <= iagemax+3; iage++){
 4025: 			 fprintf(ficresphtm,"<tr>");
 4026: 			 if(iage==iagemax+1){
 4027: 				 fprintf(ficlog,"1");
 4028: 				 fprintf(ficresphtmfr,"<tr><th>0</th> ");
 4029: 			 }else if(iage==iagemax+2){
 4030: 				 fprintf(ficlog,"0");
 4031: 				 fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
 4032: 			 }else if(iage==iagemax+3){
 4033: 				 fprintf(ficlog,"Total");
 4034: 				 fprintf(ficresphtmfr,"<tr><th>Total</th> ");
 4035: 			 }else{
 4036: 				 if(first==1){
 4037: 					 first=0;
 4038: 					 printf("See log file for details...\n");
 4039: 				 }
 4040: 				 fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
 4041: 				 fprintf(ficlog,"Age %d", iage);
 4042: 			 }
 4043: 			 for(jk=1; jk <=nlstate ; jk++){
 4044: 				 for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
 4045: 					 pp[jk] += freq[jk][m][iage]; 
 4046: 			 }
 4047: 			 for(jk=1; jk <=nlstate ; jk++){
 4048: 				 for(m=-1, pos=0; m <=0 ; m++)
 4049: 					 pos += freq[jk][m][iage];
 4050: 				 if(pp[jk]>=1.e-10){
 4051: 					 if(first==1){
 4052: 						 printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 4053: 					 }
 4054: 					 fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 4055: 				 }else{
 4056: 					 if(first==1)
 4057: 						 printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 4058: 					 fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 4059: 				 }
 4060: 			 }
 4061: 
 4062: 			 for(jk=1; jk <=nlstate ; jk++){ 
 4063: 				 /* posprop[jk]=0; */
 4064: 				 for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
 4065: 					 pp[jk] += freq[jk][m][iage];
 4066: 			 }	/* pp[jk] is the total number of transitions starting from state jk and any ending status until this age */
 4067: 
 4068: 			 for(jk=1,pos=0, pospropta=0.; jk <=nlstate ; jk++){
 4069: 				 pos += pp[jk]; /* pos is the total number of transitions until this age */
 4070: 				 posprop[jk] += prop[jk][iage]; /* prop is the number of transitions from a live state
 4071: 																					 from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
 4072: 				 pospropta += prop[jk][iage]; /* prop is the number of transitions from a live state
 4073: 																					 from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
 4074: 			 }
 4075: 			 for(jk=1; jk <=nlstate ; jk++){
 4076: 				 if(pos>=1.e-5){
 4077: 					 if(first==1)
 4078: 						 printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 4079: 					 fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 4080: 				 }else{
 4081: 					 if(first==1)
 4082: 						 printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 4083: 					 fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 4084: 				 }
 4085: 				 if( iage <= iagemax){
 4086: 					 if(pos>=1.e-5){
 4087: 						 fprintf(ficresp," %d %.5f %.0f %.0f",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
 4088: 						 fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
 4089: 						 /*probs[iage][jk][j1]= pp[jk]/pos;*/
 4090: 						 /*printf("\niage=%d jk=%d j1=%d %.5f %.0f %.0f %f",iage,jk,j1,pp[jk]/pos, pp[jk],pos,probs[iage][jk][j1]);*/
 4091: 					 }
 4092: 					 else{
 4093: 						 fprintf(ficresp," %d NaNq %.0f %.0f",iage,prop[jk][iage],pospropta);
 4094: 						 fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[jk][iage],pospropta);
 4095: 					 }
 4096: 				 }
 4097: 				 pospropt[jk] +=posprop[jk];
 4098: 			 } /* end loop jk */
 4099: 			 /* pospropt=0.; */
 4100: 			 for(jk=-1; jk <=nlstate+ndeath; jk++){
 4101: 				 for(m=-1; m <=nlstate+ndeath; m++){
 4102: 					 if(freq[jk][m][iage] !=0 ) { /* minimizing output */
 4103: 						 if(first==1){
 4104: 							 printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]);
 4105: 						 }
 4106: 						 fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iage]);
 4107: 					 }
 4108: 					 if(jk!=0 && m!=0)
 4109: 						 fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][iage]);
 4110: 				 }
 4111: 			 } /* end loop jk */
 4112: 			 posproptt=0.; 
 4113: 			 for(jk=1; jk <=nlstate; jk++){
 4114: 				 posproptt += pospropt[jk];
 4115: 			 }
 4116: 			 fprintf(ficresphtmfr,"</tr>\n ");
 4117: 			 if(iage <= iagemax){
 4118: 				 fprintf(ficresp,"\n");
 4119: 				 fprintf(ficresphtm,"</tr>\n");
 4120: 			 }
 4121: 			 if(first==1)
 4122: 				 printf("Others in log...\n");
 4123: 			 fprintf(ficlog,"\n");
 4124: 		 } /* end loop age iage */
 4125: 		 fprintf(ficresphtm,"<tr><th>Tot</th>");
 4126: 		 for(jk=1; jk <=nlstate ; jk++){
 4127: 			 if(posproptt < 1.e-5){
 4128: 				 fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[jk],posproptt);	
 4129: 			 }else{
 4130: 				 fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[jk]/posproptt,pospropt[jk],posproptt);	
 4131: 			 }
 4132: 		 }
 4133: 		 fprintf(ficresphtm,"</tr>\n");
 4134: 		 fprintf(ficresphtm,"</table>\n");
 4135: 		 fprintf(ficresphtmfr,"</table>\n");
 4136: 		 if(posproptt < 1.e-5){
 4137: 			 fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
 4138: 			 fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
 4139: 			 fprintf(ficres,"\n  This combination (%d) is not valid and no result will be produced\n\n",j1);
 4140: 			 invalidvarcomb[j1]=1;
 4141: 		 }else{
 4142: 			 fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
 4143: 			 invalidvarcomb[j1]=0;
 4144: 		 }
 4145: 		 fprintf(ficresphtmfr,"</table>\n");
 4146: 	 } /* end selected combination of covariate j1 */
 4147: 	 dateintmean=dateintsum/k2cpt; 
 4148: 		 
 4149: 	 fclose(ficresp);
 4150: 	 fclose(ficresphtm);
 4151: 	 fclose(ficresphtmfr);
 4152: 	 free_vector(meanq,1,nqveff);
 4153: 	 free_matrix(meanqt,1,lastpass,1,nqtveff);
 4154: 	 free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);
 4155: 	 free_vector(pospropt,1,nlstate);
 4156: 	 free_vector(posprop,1,nlstate);
 4157: 	 free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);
 4158: 	 free_vector(pp,1,nlstate);
 4159: 	 /* End of freqsummary */
 4160:  }
 4161: 
 4162: /************ Prevalence ********************/
 4163:  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)
 4164:  {  
 4165:    /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 4166:       in each health status at the date of interview (if between dateprev1 and dateprev2).
 4167:       We still use firstpass and lastpass as another selection.
 4168:    */
 4169:  
 4170:    int i, m, jk, j1, bool, z1,j;
 4171:    int mi; /* Effective wave */
 4172:    int iage;
 4173:    double agebegin, ageend;
 4174: 
 4175:    double **prop;
 4176:    double posprop; 
 4177:    double  y2; /* in fractional years */
 4178:    int iagemin, iagemax;
 4179:    int first; /** to stop verbosity which is redirected to log file */
 4180: 
 4181:    iagemin= (int) agemin;
 4182:    iagemax= (int) agemax;
 4183:    /*pp=vector(1,nlstate);*/
 4184:    prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
 4185:    /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
 4186:    j1=0;
 4187:   
 4188:    /*j=cptcoveff;*/
 4189:    if (cptcovn<1) {j=1;ncodemax[1]=1;}
 4190:   
 4191:    first=1;
 4192:    for(j1=1; j1<= (int) pow(2,nqveff);j1++){ /* For each combination of covariate */
 4193:      for (i=1; i<=nlstate; i++)  
 4194:        for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)
 4195: 	 prop[i][iage]=0.0;
 4196:     
 4197:      for (i=1; i<=imx; i++) { /* Each individual */
 4198:        bool=1;
 4199:        if  (cptcovn>0) {  /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
 4200: 	 for (z1=1; z1<=nqveff; z1++) /* For each covariate, look at the value for individual i and checks if it is equal to the corresponding value of this covariate according to current combination j1*/
 4201: 	   if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
 4202: 	     bool=0;
 4203:        } 
 4204:        if (bool==1) { /* For this combination of covariates values, this individual fits */
 4205: 	 /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
 4206: 	 for(mi=1; mi<wav[i];mi++){
 4207: 	   m=mw[mi][i];
 4208: 	   agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
 4209: 	   /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
 4210: 	   if(m >=firstpass && m <=lastpass){
 4211: 	     y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
 4212: 	     if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
 4213: 	       if(agev[m][i]==0) agev[m][i]=iagemax+1;
 4214: 	       if(agev[m][i]==1) agev[m][i]=iagemax+2;
 4215: 	       if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){
 4216: 		 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); 
 4217: 		 exit(1);
 4218: 	       }
 4219: 	       if (s[m][i]>0 && s[m][i]<=nlstate) { 
 4220: 		 /*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]]);*/
 4221: 		 prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
 4222: 		 prop[s[m][i]][iagemax+3] += weight[i]; 
 4223: 	       } /* end valid statuses */ 
 4224: 	     } /* end selection of dates */
 4225: 	   } /* end selection of waves */
 4226: 	 } /* end effective waves */
 4227:        } /* end bool */
 4228:      }
 4229:      for(i=iagemin; i <= iagemax+3; i++){  
 4230:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
 4231: 	 posprop += prop[jk][i]; 
 4232:        } 
 4233:       
 4234:        for(jk=1; jk <=nlstate ; jk++){	    
 4235: 	 if( i <=  iagemax){ 
 4236: 	   if(posprop>=1.e-5){ 
 4237: 	     probs[i][jk][j1]= prop[jk][i]/posprop;
 4238: 	   } else{
 4239: 	     if(first==1){
 4240: 	       first=0;
 4241: 	       printf("Warning Observed prevalence probs[%d][%d][%d]=%lf because of lack of cases\nSee others on log file...\n",jk,i,j1,probs[i][jk][j1]);
 4242: 	     }
 4243: 	   }
 4244: 	 } 
 4245:        }/* end jk */ 
 4246:      }/* end i */ 
 4247:      /*} *//* end i1 */
 4248:    } /* end j1 */
 4249:   
 4250:    /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
 4251:    /*free_vector(pp,1,nlstate);*/
 4252:    free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);
 4253:  }  /* End of prevalence */
 4254: 
 4255: /************* Waves Concatenation ***************/
 4256: 
 4257: 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)
 4258: {
 4259:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 4260:      Death is a valid wave (if date is known).
 4261:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
 4262:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 4263:      and mw[mi+1][i]. dh depends on stepm.
 4264:      */
 4265: 
 4266:   int i=0, mi=0, m=0, mli=0;
 4267:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
 4268:      double sum=0., jmean=0.;*/
 4269:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
 4270:   int j, k=0,jk, ju, jl;
 4271:   double sum=0.;
 4272:   first=0;
 4273:   firstwo=0;
 4274:   firsthree=0;
 4275:   firstfour=0;
 4276:   jmin=100000;
 4277:   jmax=-1;
 4278:   jmean=0.;
 4279: 
 4280: /* Treating live states */
 4281:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
 4282:     mi=0;  /* First valid wave */
 4283: 		mli=0; /* Last valid wave */
 4284:     m=firstpass;
 4285:     while(s[m][i] <= nlstate){  /* a live state */
 4286: 			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 */
 4287: 				mli=m-1;/* mw[++mi][i]=m-1; */
 4288: 			}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 */
 4289: 				mw[++mi][i]=m;
 4290: 				mli=m;
 4291:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
 4292:       if(m < lastpass){ /* m < lastpass, standard case */
 4293: 				m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
 4294:       }
 4295: 			else{ /* m >= lastpass, eventual special issue with warning */
 4296: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
 4297: 				break;
 4298: #else
 4299: 				if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
 4300: 					if(firsthree == 0){
 4301: 						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);
 4302: 						firsthree=1;
 4303: 					}
 4304: 					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);
 4305: 					mw[++mi][i]=m;
 4306: 					mli=m;
 4307: 				}
 4308: 				if(s[m][i]==-2){ /* Vital status is really unknown */
 4309: 					nbwarn++;
 4310: 					if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
 4311: 						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);
 4312: 						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);
 4313: 					}
 4314: 					break;
 4315: 				}
 4316: 				break;
 4317: #endif
 4318: 			}/* End m >= lastpass */
 4319:     }/* end while */
 4320: 
 4321:   	/* mi is the last effective wave, m is lastpass, mw[j][i] gives the # of j-th effective wave for individual i */
 4322:     /* After last pass */
 4323: /* Treating death states */
 4324:     if (s[m][i] > nlstate){  /* In a death state */
 4325: 			/* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
 4326: 			/* } */
 4327:       mi++;	/* Death is another wave */
 4328:       /* if(mi==0)  never been interviewed correctly before death */
 4329: 			/* Only death is a correct wave */
 4330:       mw[mi][i]=m;
 4331:     }
 4332: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
 4333: 		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 */
 4334:       /* m++; */
 4335:       /* mi++; */
 4336:       /* s[m][i]=nlstate+1;  /\* We are setting the status to the last of non live state *\/ */
 4337:       /* mw[mi][i]=m; */
 4338:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
 4339: 				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 */
 4340: 					nbwarn++;
 4341: 					if(firstfiv==0){
 4342: 						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 );
 4343: 						firstfiv=1;
 4344: 					}else{
 4345: 						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 );
 4346: 					}
 4347: 				}else{ /* Death occured afer last wave potential bias */
 4348: 					nberr++;
 4349: 					if(firstwo==0){
 4350: 						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 );
 4351: 						firstwo=1;
 4352: 					}
 4353: 					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 );
 4354: 				}
 4355:       }else{ /* end date of interview is known */
 4356: 				/* death is known but not confirmed by death status at any wave */
 4357: 				if(firstfour==0){
 4358: 					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 );
 4359: 					firstfour=1;
 4360: 				}
 4361: 				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 );
 4362:       }
 4363:     } /* end if date of death is known */
 4364: #endif
 4365:     wav[i]=mi; /* mi should be the last effective wave (or mli) */
 4366:     /* wav[i]=mw[mi][i]; */
 4367:     if(mi==0){
 4368:       nbwarn++;
 4369:       if(first==0){
 4370: 				printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
 4371: 				first=1;
 4372:       }
 4373:       if(first==1){
 4374: 				fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
 4375:       }
 4376:     } /* end mi==0 */
 4377:   } /* End individuals */
 4378:   /* wav and mw are no more changed */
 4379: 	
 4380:   
 4381:   for(i=1; i<=imx; i++){
 4382:     for(mi=1; mi<wav[i];mi++){
 4383:       if (stepm <=0)
 4384: 				dh[mi][i]=1;
 4385:       else{
 4386: 				if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
 4387: 					if (agedc[i] < 2*AGESUP) {
 4388: 						j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
 4389: 						if(j==0) j=1;  /* Survives at least one month after exam */
 4390: 						else if(j<0){
 4391: 							nberr++;
 4392: 							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]);
 4393: 							j=1; /* Temporary Dangerous patch */
 4394: 							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);
 4395: 							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]);
 4396: 							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);
 4397: 						}
 4398: 						k=k+1;
 4399: 						if (j >= jmax){
 4400: 							jmax=j;
 4401: 							ijmax=i;
 4402: 						}
 4403: 						if (j <= jmin){
 4404: 							jmin=j;
 4405: 							ijmin=i;
 4406: 						}
 4407: 						sum=sum+j;
 4408: 						/*if (j<0) printf("j=%d num=%d \n",j,i);*/
 4409: 						/*	  printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
 4410: 					}
 4411: 				}
 4412: 				else{
 4413: 					j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 4414: /* 	  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]); */
 4415: 					
 4416: 					k=k+1;
 4417: 					if (j >= jmax) {
 4418: 						jmax=j;
 4419: 						ijmax=i;
 4420: 					}
 4421: 					else if (j <= jmin){
 4422: 						jmin=j;
 4423: 						ijmin=i;
 4424: 					}
 4425: 					/*	    if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
 4426: 					/*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]);*/
 4427: 					if(j<0){
 4428: 						nberr++;
 4429: 						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]);
 4430: 						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]);
 4431: 					}
 4432: 					sum=sum+j;
 4433: 				}
 4434: 				jk= j/stepm;
 4435: 				jl= j -jk*stepm;
 4436: 				ju= j -(jk+1)*stepm;
 4437: 				if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
 4438: 					if(jl==0){
 4439: 						dh[mi][i]=jk;
 4440: 						bh[mi][i]=0;
 4441: 					}else{ /* We want a negative bias in order to only have interpolation ie
 4442: 									* to avoid the price of an extra matrix product in likelihood */
 4443: 						dh[mi][i]=jk+1;
 4444: 						bh[mi][i]=ju;
 4445: 					}
 4446: 				}else{
 4447: 					if(jl <= -ju){
 4448: 						dh[mi][i]=jk;
 4449: 						bh[mi][i]=jl;	/* bias is positive if real duration
 4450: 													 * is higher than the multiple of stepm and negative otherwise.
 4451: 													 */
 4452: 					}
 4453: 					else{
 4454: 						dh[mi][i]=jk+1;
 4455: 						bh[mi][i]=ju;
 4456: 					}
 4457: 					if(dh[mi][i]==0){
 4458: 						dh[mi][i]=1; /* At least one step */
 4459: 						bh[mi][i]=ju; /* At least one step */
 4460: 						/*  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);*/
 4461: 					}
 4462: 				} /* end if mle */
 4463:       }
 4464:     } /* end wave */
 4465:   }
 4466:   jmean=sum/k;
 4467:   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);
 4468:   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);
 4469:  }
 4470: 
 4471: /*********** Tricode ****************************/
 4472:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
 4473: {
 4474:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
 4475:   /*	  Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
 4476:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
 4477:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
 4478:    * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
 4479:   */
 4480: 
 4481:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
 4482:   int modmaxcovj=0; /* Modality max of covariates j */
 4483:   int cptcode=0; /* Modality max of covariates j */
 4484:   int modmincovj=0; /* Modality min of covariates j */
 4485: 
 4486: 
 4487:   /* cptcoveff=0;  */
 4488: 	/* *cptcov=0; */
 4489:  
 4490:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
 4491: 
 4492:   /* Loop on covariates without age and products and no quantitative variable */
 4493:   /* for (j=1; j<=(cptcovs); j++) { /\* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only *\/ */
 4494:   for (j=1; j<=(*cptcov); j++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
 4495:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
 4496:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
 4497: 																modality of this covariate Vj*/
 4498: 			if(Tvar[j]  >=1 && Tvar[j]  <= *cptcov){ /* A real fixed covariate */
 4499: 				ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
 4500: 																			* If product of Vn*Vm, still boolean *:
 4501: 																			* If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
 4502: 																			* 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
 4503: 				/* Finds for covariate j, n=Tvar[j] of Vn . ij is the
 4504: 					 modality of the nth covariate of individual i. */
 4505: 				if (ij > modmaxcovj)
 4506: 					modmaxcovj=ij; 
 4507: 				else if (ij < modmincovj) 
 4508: 					modmincovj=ij; 
 4509: 				if ((ij < -1) && (ij > NCOVMAX)){
 4510: 					printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
 4511: 					exit(1);
 4512: 				}else
 4513: 					Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
 4514:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
 4515:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
 4516:       /* getting the maximum value of the modality of the covariate
 4517: 				 (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
 4518: 				 female ies 1, then modmaxcovj=1.*/
 4519: 			}
 4520: 		} /* end for loop on individuals i */
 4521:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
 4522:     fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
 4523:     cptcode=modmaxcovj;
 4524:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
 4525: 		/*for (i=0; i<=cptcode; i++) {*/
 4526:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
 4527:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
 4528:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
 4529:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
 4530: 				if( k != -1){
 4531: 					ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
 4532: 														 covariate for which somebody answered excluding 
 4533: 														 undefined. Usually 2: 0 and 1. */
 4534: 				}
 4535: 				ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
 4536: 																covariate for which somebody answered including 
 4537: 																undefined. Usually 3: -1, 0 and 1. */
 4538:       }
 4539:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
 4540: 			 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
 4541:     } /* Ndum[-1] number of undefined modalities */
 4542: 		
 4543:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
 4544:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
 4545:        If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
 4546:        modmincovj=3; modmaxcovj = 7;
 4547:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
 4548:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
 4549:        defining two dummy variables: variables V1_1 and V1_2.
 4550:        nbcode[Tvar[j]][ij]=k;
 4551:        nbcode[Tvar[j]][1]=0;
 4552:        nbcode[Tvar[j]][2]=1;
 4553:        nbcode[Tvar[j]][3]=2;
 4554:        To be continued (not working yet).
 4555:     */
 4556:     ij=0; /* ij is similar to i but can jump over null modalities */
 4557:     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*/
 4558:     	if (Ndum[i] == 0) { /* If nobody responded to this modality k */
 4559: 				break;
 4560: 			}
 4561: 			ij++;
 4562: 			nbcode[Tvar[j]][ij]=i;  /* stores the original value of modality i in an array nbcode, ij modality from 1 to last non-nul modality.*/
 4563: 			cptcode = ij; /* New max modality for covar j */
 4564:     } /* end of loop on modality i=-1 to 1 or more */
 4565: 		
 4566:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
 4567:     /* 	/\*recode from 0 *\/ */
 4568:     /* 				     k is a modality. If we have model=V1+V1*sex  */
 4569:     /* 				     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
 4570:     /* 				  But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
 4571:     /* 	} */
 4572:     /* 	/\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
 4573:     /* 	if (ij > ncodemax[j]) { */
 4574:     /* 	  printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
 4575:     /* 	  fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
 4576:     /* 	  break; */
 4577:     /* 	} */
 4578:     /*   }  /\* end of loop on modality k *\/ */
 4579:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
 4580:   
 4581: 	for (k=-1; k< maxncov; k++) Ndum[k]=0; 
 4582:   
 4583:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
 4584: 		/* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
 4585: 		ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
 4586: 		Ndum[ij]++; /* Might be supersed V1 + V1*age */
 4587: 	} /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
 4588: 	
 4589: 	ij=0;
 4590: 	for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
 4591: 		/*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
 4592: 		if((Ndum[i]!=0) && (i<=ncovcol)){
 4593: 			/*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
 4594: 			Tvaraff[++ij]=i; /*For printing (unclear) */
 4595: 		}else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){
 4596: 			Tvaraff[++ij]=-10; /* Dont'n know how to treat quantitative variables yet */
 4597: 		}else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){
 4598: 			Tvaraff[++ij]=i; /*For printing (unclear) */
 4599: 		}else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){
 4600: 		 Tvaraff[++ij]=-20; /* Dont'n know how to treat quantitative variables yet */
 4601: 		}
 4602: 	} /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
 4603: 	/* ij--; */
 4604: 	/* cptcoveff=ij; /\*Number of total covariates*\/ */
 4605: 	*cptcov=ij; /*Number of total real effective covariates: effective
 4606: 							 * because they can be excluded from the model and real
 4607: 							 * if in the model but excluded because missing values*/
 4608: }
 4609: 
 4610: 
 4611: /*********** Health Expectancies ****************/
 4612: 
 4613: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
 4614: 
 4615: {
 4616:   /* Health expectancies, no variances */
 4617:   int i, j, nhstepm, hstepm, h, nstepm;
 4618:   int nhstepma, nstepma; /* Decreasing with age */
 4619:   double age, agelim, hf;
 4620:   double ***p3mat;
 4621:   double eip;
 4622: 
 4623:   pstamp(ficreseij);
 4624:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
 4625:   fprintf(ficreseij,"# Age");
 4626:   for(i=1; i<=nlstate;i++){
 4627:     for(j=1; j<=nlstate;j++){
 4628:       fprintf(ficreseij," e%1d%1d ",i,j);
 4629:     }
 4630:     fprintf(ficreseij," e%1d. ",i);
 4631:   }
 4632:   fprintf(ficreseij,"\n");
 4633: 
 4634:   
 4635:   if(estepm < stepm){
 4636:     printf ("Problem %d lower than %d\n",estepm, stepm);
 4637:   }
 4638:   else  hstepm=estepm;   
 4639:   /* We compute the life expectancy from trapezoids spaced every estepm months
 4640:    * This is mainly to measure the difference between two models: for example
 4641:    * if stepm=24 months pijx are given only every 2 years and by summing them
 4642:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 4643:    * progression in between and thus overestimating or underestimating according
 4644:    * to the curvature of the survival function. If, for the same date, we 
 4645:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 4646:    * to compare the new estimate of Life expectancy with the same linear 
 4647:    * hypothesis. A more precise result, taking into account a more precise
 4648:    * curvature will be obtained if estepm is as small as stepm. */
 4649: 
 4650:   /* For example we decided to compute the life expectancy with the smallest unit */
 4651:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 4652:      nhstepm is the number of hstepm from age to agelim 
 4653:      nstepm is the number of stepm from age to agelin. 
 4654:      Look at hpijx to understand the reason of that which relies in memory size
 4655:      and note for a fixed period like estepm months */
 4656:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 4657:      survival function given by stepm (the optimization length). Unfortunately it
 4658:      means that if the survival funtion is printed only each two years of age and if
 4659:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 4660:      results. So we changed our mind and took the option of the best precision.
 4661:   */
 4662:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 4663: 
 4664:   agelim=AGESUP;
 4665:   /* If stepm=6 months */
 4666:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
 4667:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 4668:     
 4669: /* nhstepm age range expressed in number of stepm */
 4670:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 4671:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 4672:   /* if (stepm >= YEARM) hstepm=1;*/
 4673:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 4674:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4675: 
 4676:   for (age=bage; age<=fage; age ++){ 
 4677:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 4678:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 4679:     /* if (stepm >= YEARM) hstepm=1;*/
 4680:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 4681: 
 4682:     /* If stepm=6 months */
 4683:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 4684:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 4685:     
 4686:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 4687:     
 4688:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 4689:     
 4690:     printf("%d|",(int)age);fflush(stdout);
 4691:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 4692:     
 4693:     /* Computing expectancies */
 4694:     for(i=1; i<=nlstate;i++)
 4695:       for(j=1; j<=nlstate;j++)
 4696: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 4697: 	  eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
 4698: 	  
 4699: 	  /* 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]);*/
 4700: 
 4701: 	}
 4702: 
 4703:     fprintf(ficreseij,"%3.0f",age );
 4704:     for(i=1; i<=nlstate;i++){
 4705:       eip=0;
 4706:       for(j=1; j<=nlstate;j++){
 4707: 	eip +=eij[i][j][(int)age];
 4708: 	fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
 4709:       }
 4710:       fprintf(ficreseij,"%9.4f", eip );
 4711:     }
 4712:     fprintf(ficreseij,"\n");
 4713:     
 4714:   }
 4715:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4716:   printf("\n");
 4717:   fprintf(ficlog,"\n");
 4718:   
 4719: }
 4720: 
 4721: 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[] )
 4722: 
 4723: {
 4724:   /* Covariances of health expectancies eij and of total life expectancies according
 4725:      to initial status i, ei. .
 4726:   */
 4727:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
 4728:   int nhstepma, nstepma; /* Decreasing with age */
 4729:   double age, agelim, hf;
 4730:   double ***p3matp, ***p3matm, ***varhe;
 4731:   double **dnewm,**doldm;
 4732:   double *xp, *xm;
 4733:   double **gp, **gm;
 4734:   double ***gradg, ***trgradg;
 4735:   int theta;
 4736: 
 4737:   double eip, vip;
 4738: 
 4739:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
 4740:   xp=vector(1,npar);
 4741:   xm=vector(1,npar);
 4742:   dnewm=matrix(1,nlstate*nlstate,1,npar);
 4743:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
 4744:   
 4745:   pstamp(ficresstdeij);
 4746:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
 4747:   fprintf(ficresstdeij,"# Age");
 4748:   for(i=1; i<=nlstate;i++){
 4749:     for(j=1; j<=nlstate;j++)
 4750:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
 4751:     fprintf(ficresstdeij," e%1d. ",i);
 4752:   }
 4753:   fprintf(ficresstdeij,"\n");
 4754: 
 4755:   pstamp(ficrescveij);
 4756:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
 4757:   fprintf(ficrescveij,"# Age");
 4758:   for(i=1; i<=nlstate;i++)
 4759:     for(j=1; j<=nlstate;j++){
 4760:       cptj= (j-1)*nlstate+i;
 4761:       for(i2=1; i2<=nlstate;i2++)
 4762: 	for(j2=1; j2<=nlstate;j2++){
 4763: 	  cptj2= (j2-1)*nlstate+i2;
 4764: 	  if(cptj2 <= cptj)
 4765: 	    fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
 4766: 	}
 4767:     }
 4768:   fprintf(ficrescveij,"\n");
 4769:   
 4770:   if(estepm < stepm){
 4771:     printf ("Problem %d lower than %d\n",estepm, stepm);
 4772:   }
 4773:   else  hstepm=estepm;   
 4774:   /* We compute the life expectancy from trapezoids spaced every estepm months
 4775:    * This is mainly to measure the difference between two models: for example
 4776:    * if stepm=24 months pijx are given only every 2 years and by summing them
 4777:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 4778:    * progression in between and thus overestimating or underestimating according
 4779:    * to the curvature of the survival function. If, for the same date, we 
 4780:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 4781:    * to compare the new estimate of Life expectancy with the same linear 
 4782:    * hypothesis. A more precise result, taking into account a more precise
 4783:    * curvature will be obtained if estepm is as small as stepm. */
 4784: 
 4785:   /* For example we decided to compute the life expectancy with the smallest unit */
 4786:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 4787:      nhstepm is the number of hstepm from age to agelim 
 4788:      nstepm is the number of stepm from age to agelin. 
 4789:      Look at hpijx to understand the reason of that which relies in memory size
 4790:      and note for a fixed period like estepm months */
 4791:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 4792:      survival function given by stepm (the optimization length). Unfortunately it
 4793:      means that if the survival funtion is printed only each two years of age and if
 4794:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 4795:      results. So we changed our mind and took the option of the best precision.
 4796:   */
 4797:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 4798: 
 4799:   /* If stepm=6 months */
 4800:   /* nhstepm age range expressed in number of stepm */
 4801:   agelim=AGESUP;
 4802:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
 4803:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 4804:   /* if (stepm >= YEARM) hstepm=1;*/
 4805:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 4806:   
 4807:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4808:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4809:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
 4810:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
 4811:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
 4812:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
 4813: 
 4814:   for (age=bage; age<=fage; age ++){ 
 4815:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 4816:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 4817:     /* if (stepm >= YEARM) hstepm=1;*/
 4818:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 4819: 		
 4820:     /* If stepm=6 months */
 4821:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 4822:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 4823:     
 4824:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 4825: 		
 4826:     /* Computing  Variances of health expectancies */
 4827:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
 4828:        decrease memory allocation */
 4829:     for(theta=1; theta <=npar; theta++){
 4830:       for(i=1; i<=npar; i++){ 
 4831: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 4832: 	xm[i] = x[i] - (i==theta ?delti[theta]:0);
 4833:       }
 4834:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
 4835:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
 4836: 			
 4837:       for(j=1; j<= nlstate; j++){
 4838: 	for(i=1; i<=nlstate; i++){
 4839: 	  for(h=0; h<=nhstepm-1; h++){
 4840: 	    gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
 4841: 	    gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
 4842: 	  }
 4843: 	}
 4844:       }
 4845: 			
 4846:       for(ij=1; ij<= nlstate*nlstate; ij++)
 4847: 	for(h=0; h<=nhstepm-1; h++){
 4848: 	  gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
 4849: 	}
 4850:     }/* End theta */
 4851:     
 4852:     
 4853:     for(h=0; h<=nhstepm-1; h++)
 4854:       for(j=1; j<=nlstate*nlstate;j++)
 4855: 	for(theta=1; theta <=npar; theta++)
 4856: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 4857:     
 4858: 		
 4859:     for(ij=1;ij<=nlstate*nlstate;ij++)
 4860:       for(ji=1;ji<=nlstate*nlstate;ji++)
 4861: 	varhe[ij][ji][(int)age] =0.;
 4862: 		
 4863:     printf("%d|",(int)age);fflush(stdout);
 4864:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 4865:     for(h=0;h<=nhstepm-1;h++){
 4866:       for(k=0;k<=nhstepm-1;k++){
 4867: 	matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
 4868: 	matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
 4869: 	for(ij=1;ij<=nlstate*nlstate;ij++)
 4870: 	  for(ji=1;ji<=nlstate*nlstate;ji++)
 4871: 	    varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
 4872:       }
 4873:     }
 4874: 		
 4875:     /* Computing expectancies */
 4876:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 4877:     for(i=1; i<=nlstate;i++)
 4878:       for(j=1; j<=nlstate;j++)
 4879: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 4880: 	  eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
 4881: 					
 4882: 	  /* 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]);*/
 4883: 					
 4884: 	}
 4885: 		
 4886:     fprintf(ficresstdeij,"%3.0f",age );
 4887:     for(i=1; i<=nlstate;i++){
 4888:       eip=0.;
 4889:       vip=0.;
 4890:       for(j=1; j<=nlstate;j++){
 4891: 	eip += eij[i][j][(int)age];
 4892: 	for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
 4893: 	  vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
 4894: 	fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
 4895:       }
 4896:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
 4897:     }
 4898:     fprintf(ficresstdeij,"\n");
 4899: 		
 4900:     fprintf(ficrescveij,"%3.0f",age );
 4901:     for(i=1; i<=nlstate;i++)
 4902:       for(j=1; j<=nlstate;j++){
 4903: 	cptj= (j-1)*nlstate+i;
 4904: 	for(i2=1; i2<=nlstate;i2++)
 4905: 	  for(j2=1; j2<=nlstate;j2++){
 4906: 	    cptj2= (j2-1)*nlstate+i2;
 4907: 	    if(cptj2 <= cptj)
 4908: 	      fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
 4909: 	  }
 4910:       }
 4911:     fprintf(ficrescveij,"\n");
 4912: 		
 4913:   }
 4914:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
 4915:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
 4916:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
 4917:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
 4918:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4919:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4920:   printf("\n");
 4921:   fprintf(ficlog,"\n");
 4922: 	
 4923:   free_vector(xm,1,npar);
 4924:   free_vector(xp,1,npar);
 4925:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
 4926:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
 4927:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
 4928: }
 4929:  
 4930: /************ Variance ******************/
 4931:  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[])
 4932:  {
 4933:    /* Variance of health expectancies */
 4934:    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
 4935:    /* double **newm;*/
 4936:    /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
 4937:   
 4938:    /* int movingaverage(); */
 4939:    double **dnewm,**doldm;
 4940:    double **dnewmp,**doldmp;
 4941:    int i, j, nhstepm, hstepm, h, nstepm ;
 4942:    int k;
 4943:    double *xp;
 4944:    double **gp, **gm;  /* for var eij */
 4945:    double ***gradg, ***trgradg; /*for var eij */
 4946:    double **gradgp, **trgradgp; /* for var p point j */
 4947:    double *gpp, *gmp; /* for var p point j */
 4948:    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
 4949:    double ***p3mat;
 4950:    double age,agelim, hf;
 4951:    /* double ***mobaverage; */
 4952:    int theta;
 4953:    char digit[4];
 4954:    char digitp[25];
 4955: 
 4956:    char fileresprobmorprev[FILENAMELENGTH];
 4957: 
 4958:    if(popbased==1){
 4959:      if(mobilav!=0)
 4960:        strcpy(digitp,"-POPULBASED-MOBILAV_");
 4961:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
 4962:    }
 4963:    else 
 4964:      strcpy(digitp,"-STABLBASED_");
 4965: 
 4966:    /* if (mobilav!=0) { */
 4967:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 4968:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
 4969:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
 4970:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
 4971:    /*   } */
 4972:    /* } */
 4973: 
 4974:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
 4975:    sprintf(digit,"%-d",ij);
 4976:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
 4977:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
 4978:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
 4979:    strcat(fileresprobmorprev,fileresu);
 4980:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
 4981:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
 4982:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
 4983:    }
 4984:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 4985:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 4986:    pstamp(ficresprobmorprev);
 4987:    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);
 4988:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
 4989:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 4990:      fprintf(ficresprobmorprev," p.%-d SE",j);
 4991:      for(i=1; i<=nlstate;i++)
 4992:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 4993:    }  
 4994:    fprintf(ficresprobmorprev,"\n");
 4995:   
 4996:    fprintf(ficgp,"\n# Routine varevsij");
 4997:    fprintf(ficgp,"\nunset title \n");
 4998:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
 4999:    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");
 5000:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
 5001:    /*   } */
 5002:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 5003:    pstamp(ficresvij);
 5004:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
 5005:    if(popbased==1)
 5006:      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);
 5007:    else
 5008:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
 5009:    fprintf(ficresvij,"# Age");
 5010:    for(i=1; i<=nlstate;i++)
 5011:      for(j=1; j<=nlstate;j++)
 5012:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
 5013:    fprintf(ficresvij,"\n");
 5014: 
 5015:    xp=vector(1,npar);
 5016:    dnewm=matrix(1,nlstate,1,npar);
 5017:    doldm=matrix(1,nlstate,1,nlstate);
 5018:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
 5019:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 5020: 
 5021:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
 5022:    gpp=vector(nlstate+1,nlstate+ndeath);
 5023:    gmp=vector(nlstate+1,nlstate+ndeath);
 5024:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 5025:   
 5026:    if(estepm < stepm){
 5027:      printf ("Problem %d lower than %d\n",estepm, stepm);
 5028:    }
 5029:    else  hstepm=estepm;   
 5030:    /* For example we decided to compute the life expectancy with the smallest unit */
 5031:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 5032:       nhstepm is the number of hstepm from age to agelim 
 5033:       nstepm is the number of stepm from age to agelim. 
 5034:       Look at function hpijx to understand why because of memory size limitations, 
 5035:       we decided (b) to get a life expectancy respecting the most precise curvature of the
 5036:       survival function given by stepm (the optimization length). Unfortunately it
 5037:       means that if the survival funtion is printed every two years of age and if
 5038:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 5039:       results. So we changed our mind and took the option of the best precision.
 5040:    */
 5041:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 5042:    agelim = AGESUP;
 5043:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 5044:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 5045:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 5046:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5047:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
 5048:      gp=matrix(0,nhstepm,1,nlstate);
 5049:      gm=matrix(0,nhstepm,1,nlstate);
 5050: 		
 5051: 		
 5052:      for(theta=1; theta <=npar; theta++){
 5053:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
 5054: 	 xp[i] = x[i] + (i==theta ?delti[theta]:0);
 5055:        }
 5056: 			
 5057:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 5058: 			
 5059:        if (popbased==1) {
 5060: 	 if(mobilav ==0){
 5061: 	   for(i=1; i<=nlstate;i++)
 5062: 	     prlim[i][i]=probs[(int)age][i][ij];
 5063: 	 }else{ /* mobilav */ 
 5064: 	   for(i=1; i<=nlstate;i++)
 5065: 	     prlim[i][i]=mobaverage[(int)age][i][ij];
 5066: 	 }
 5067:        }
 5068: 			
 5069:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
 5070:        for(j=1; j<= nlstate; j++){
 5071: 	 for(h=0; h<=nhstepm; h++){
 5072: 	   for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 5073: 	     gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 5074: 	 }
 5075:        }
 5076:        /* Next for computing probability of death (h=1 means
 5077: 	  computed over hstepm matrices product = hstepm*stepm months) 
 5078: 	  as a weighted average of prlim.
 5079:        */
 5080:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
 5081: 	 for(i=1,gpp[j]=0.; i<= nlstate; i++)
 5082: 	   gpp[j] += prlim[i][i]*p3mat[i][j][1];
 5083:        }    
 5084:        /* end probability of death */
 5085: 			
 5086:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
 5087: 	 xp[i] = x[i] - (i==theta ?delti[theta]:0);
 5088: 			
 5089:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
 5090: 			
 5091:        if (popbased==1) {
 5092: 	 if(mobilav ==0){
 5093: 	   for(i=1; i<=nlstate;i++)
 5094: 	     prlim[i][i]=probs[(int)age][i][ij];
 5095: 	 }else{ /* mobilav */ 
 5096: 	   for(i=1; i<=nlstate;i++)
 5097: 	     prlim[i][i]=mobaverage[(int)age][i][ij];
 5098: 	 }
 5099:        }
 5100: 			
 5101:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 5102: 			
 5103:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
 5104: 	 for(h=0; h<=nhstepm; h++){
 5105: 	   for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 5106: 	     gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 5107: 	 }
 5108:        }
 5109:        /* This for computing probability of death (h=1 means
 5110: 	  computed over hstepm matrices product = hstepm*stepm months) 
 5111: 	  as a weighted average of prlim.
 5112:        */
 5113:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
 5114: 	 for(i=1,gmp[j]=0.; i<= nlstate; i++)
 5115: 	   gmp[j] += prlim[i][i]*p3mat[i][j][1];
 5116:        }    
 5117:        /* end probability of death */
 5118: 			
 5119:        for(j=1; j<= nlstate; j++) /* vareij */
 5120: 	 for(h=0; h<=nhstepm; h++){
 5121: 	   gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 5122: 	 }
 5123: 			
 5124:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
 5125: 	 gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
 5126:        }
 5127: 			
 5128:      } /* End theta */
 5129: 		
 5130:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
 5131: 		
 5132:      for(h=0; h<=nhstepm; h++) /* veij */
 5133:        for(j=1; j<=nlstate;j++)
 5134: 	 for(theta=1; theta <=npar; theta++)
 5135: 	   trgradg[h][j][theta]=gradg[h][theta][j];
 5136: 		
 5137:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
 5138:        for(theta=1; theta <=npar; theta++)
 5139: 	 trgradgp[j][theta]=gradgp[theta][j];
 5140: 		
 5141: 		
 5142:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 5143:      for(i=1;i<=nlstate;i++)
 5144:        for(j=1;j<=nlstate;j++)
 5145: 	 vareij[i][j][(int)age] =0.;
 5146: 		
 5147:      for(h=0;h<=nhstepm;h++){
 5148:        for(k=0;k<=nhstepm;k++){
 5149: 	 matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 5150: 	 matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
 5151: 	 for(i=1;i<=nlstate;i++)
 5152: 	   for(j=1;j<=nlstate;j++)
 5153: 	     vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
 5154:        }
 5155:      }
 5156: 		
 5157:      /* pptj */
 5158:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
 5159:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
 5160:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
 5161:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
 5162: 	 varppt[j][i]=doldmp[j][i];
 5163:      /* end ppptj */
 5164:      /*  x centered again */
 5165: 		
 5166:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
 5167: 		
 5168:      if (popbased==1) {
 5169:        if(mobilav ==0){
 5170: 	 for(i=1; i<=nlstate;i++)
 5171: 	   prlim[i][i]=probs[(int)age][i][ij];
 5172:        }else{ /* mobilav */ 
 5173: 	 for(i=1; i<=nlstate;i++)
 5174: 	   prlim[i][i]=mobaverage[(int)age][i][ij];
 5175:        }
 5176:      }
 5177: 		
 5178:      /* This for computing probability of death (h=1 means
 5179: 	computed over hstepm (estepm) matrices product = hstepm*stepm months) 
 5180: 	as a weighted average of prlim.
 5181:      */
 5182:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
 5183:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
 5184:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
 5185: 	 gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
 5186:      }    
 5187:      /* end probability of death */
 5188: 		
 5189:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
 5190:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 5191:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
 5192:        for(i=1; i<=nlstate;i++){
 5193: 	 fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 5194:        }
 5195:      } 
 5196:      fprintf(ficresprobmorprev,"\n");
 5197: 		
 5198:      fprintf(ficresvij,"%.0f ",age );
 5199:      for(i=1; i<=nlstate;i++)
 5200:        for(j=1; j<=nlstate;j++){
 5201: 	 fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
 5202:        }
 5203:      fprintf(ficresvij,"\n");
 5204:      free_matrix(gp,0,nhstepm,1,nlstate);
 5205:      free_matrix(gm,0,nhstepm,1,nlstate);
 5206:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 5207:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 5208:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5209:    } /* End age */
 5210:    free_vector(gpp,nlstate+1,nlstate+ndeath);
 5211:    free_vector(gmp,nlstate+1,nlstate+ndeath);
 5212:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
 5213:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 5214:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
 5215:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
 5216:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
 5217:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
 5218:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
 5219:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
 5220:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
 5221:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
 5222:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
 5223:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
 5224:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
 5225:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
 5226:    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);
 5227:    /*  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);
 5228:     */
 5229:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
 5230:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
 5231: 
 5232:    free_vector(xp,1,npar);
 5233:    free_matrix(doldm,1,nlstate,1,nlstate);
 5234:    free_matrix(dnewm,1,nlstate,1,npar);
 5235:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 5236:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
 5237:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 5238:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 5239:    fclose(ficresprobmorprev);
 5240:    fflush(ficgp);
 5241:    fflush(fichtm); 
 5242:  }  /* end varevsij */
 5243: 
 5244: /************ Variance of prevlim ******************/
 5245:  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[])
 5246: {
 5247:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
 5248:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 5249: 
 5250:   double **dnewm,**doldm;
 5251:   int i, j, nhstepm, hstepm;
 5252:   double *xp;
 5253:   double *gp, *gm;
 5254:   double **gradg, **trgradg;
 5255:   double **mgm, **mgp;
 5256:   double age,agelim;
 5257:   int theta;
 5258:   
 5259:   pstamp(ficresvpl);
 5260:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
 5261:   fprintf(ficresvpl,"# Age");
 5262:   for(i=1; i<=nlstate;i++)
 5263:       fprintf(ficresvpl," %1d-%1d",i,i);
 5264:   fprintf(ficresvpl,"\n");
 5265: 
 5266:   xp=vector(1,npar);
 5267:   dnewm=matrix(1,nlstate,1,npar);
 5268:   doldm=matrix(1,nlstate,1,nlstate);
 5269:   
 5270:   hstepm=1*YEARM; /* Every year of age */
 5271:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 5272:   agelim = AGESUP;
 5273:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 5274:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 5275:     if (stepm >= YEARM) hstepm=1;
 5276:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 5277:     gradg=matrix(1,npar,1,nlstate);
 5278:     mgp=matrix(1,npar,1,nlstate);
 5279:     mgm=matrix(1,npar,1,nlstate);
 5280:     gp=vector(1,nlstate);
 5281:     gm=vector(1,nlstate);
 5282: 
 5283:     for(theta=1; theta <=npar; theta++){
 5284:       for(i=1; i<=npar; i++){ /* Computes gradient */
 5285: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 5286:       }
 5287:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
 5288: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 5289:       else
 5290: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 5291:       for(i=1;i<=nlstate;i++){
 5292: 	gp[i] = prlim[i][i];
 5293: 	mgp[theta][i] = prlim[i][i];
 5294:       }
 5295:       for(i=1; i<=npar; i++) /* Computes gradient */
 5296: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 5297:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
 5298: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 5299:       else
 5300: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 5301:       for(i=1;i<=nlstate;i++){
 5302: 	gm[i] = prlim[i][i];
 5303: 	mgm[theta][i] = prlim[i][i];
 5304:       }
 5305:       for(i=1;i<=nlstate;i++)
 5306: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 5307:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
 5308:     } /* End theta */
 5309: 
 5310:     trgradg =matrix(1,nlstate,1,npar);
 5311: 
 5312:     for(j=1; j<=nlstate;j++)
 5313:       for(theta=1; theta <=npar; theta++)
 5314: 	trgradg[j][theta]=gradg[theta][j];
 5315:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
 5316:     /*   printf("\nmgm mgp %d ",(int)age); */
 5317:     /*   for(j=1; j<=nlstate;j++){ */
 5318:     /* 	printf(" %d ",j); */
 5319:     /* 	for(theta=1; theta <=npar; theta++) */
 5320:     /* 	  printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
 5321:     /* 	printf("\n "); */
 5322:     /*   } */
 5323:     /* } */
 5324:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
 5325:     /*   printf("\n gradg %d ",(int)age); */
 5326:     /*   for(j=1; j<=nlstate;j++){ */
 5327:     /* 	printf("%d ",j); */
 5328:     /* 	for(theta=1; theta <=npar; theta++) */
 5329:     /* 	  printf("%d %lf ",theta,gradg[theta][j]); */
 5330:     /* 	printf("\n "); */
 5331:     /*   } */
 5332:     /* } */
 5333: 
 5334:     for(i=1;i<=nlstate;i++)
 5335:       varpl[i][(int)age] =0.;
 5336:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
 5337:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 5338:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 5339:     }else{
 5340:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 5341:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 5342:     }
 5343:     for(i=1;i<=nlstate;i++)
 5344:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 5345: 
 5346:     fprintf(ficresvpl,"%.0f ",age );
 5347:     for(i=1; i<=nlstate;i++)
 5348:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
 5349:     fprintf(ficresvpl,"\n");
 5350:     free_vector(gp,1,nlstate);
 5351:     free_vector(gm,1,nlstate);
 5352:     free_matrix(mgm,1,npar,1,nlstate);
 5353:     free_matrix(mgp,1,npar,1,nlstate);
 5354:     free_matrix(gradg,1,npar,1,nlstate);
 5355:     free_matrix(trgradg,1,nlstate,1,npar);
 5356:   } /* End age */
 5357: 
 5358:   free_vector(xp,1,npar);
 5359:   free_matrix(doldm,1,nlstate,1,npar);
 5360:   free_matrix(dnewm,1,nlstate,1,nlstate);
 5361: 
 5362: }
 5363: 
 5364: /************ Variance of one-step probabilities  ******************/
 5365: 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[])
 5366:  {
 5367:    int i, j=0,  k1, l1, tj;
 5368:    int k2, l2, j1,  z1;
 5369:    int k=0, l;
 5370:    int first=1, first1, first2;
 5371:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
 5372:    double **dnewm,**doldm;
 5373:    double *xp;
 5374:    double *gp, *gm;
 5375:    double **gradg, **trgradg;
 5376:    double **mu;
 5377:    double age, cov[NCOVMAX+1];
 5378:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
 5379:    int theta;
 5380:    char fileresprob[FILENAMELENGTH];
 5381:    char fileresprobcov[FILENAMELENGTH];
 5382:    char fileresprobcor[FILENAMELENGTH];
 5383:    double ***varpij;
 5384: 
 5385:    strcpy(fileresprob,"PROB_"); 
 5386:    strcat(fileresprob,fileres);
 5387:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
 5388:      printf("Problem with resultfile: %s\n", fileresprob);
 5389:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
 5390:    }
 5391:    strcpy(fileresprobcov,"PROBCOV_"); 
 5392:    strcat(fileresprobcov,fileresu);
 5393:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
 5394:      printf("Problem with resultfile: %s\n", fileresprobcov);
 5395:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 5396:    }
 5397:    strcpy(fileresprobcor,"PROBCOR_"); 
 5398:    strcat(fileresprobcor,fileresu);
 5399:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 5400:      printf("Problem with resultfile: %s\n", fileresprobcor);
 5401:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 5402:    }
 5403:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 5404:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 5405:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 5406:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 5407:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 5408:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 5409:    pstamp(ficresprob);
 5410:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
 5411:    fprintf(ficresprob,"# Age");
 5412:    pstamp(ficresprobcov);
 5413:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
 5414:    fprintf(ficresprobcov,"# Age");
 5415:    pstamp(ficresprobcor);
 5416:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 5417:    fprintf(ficresprobcor,"# Age");
 5418: 
 5419: 
 5420:    for(i=1; i<=nlstate;i++)
 5421:      for(j=1; j<=(nlstate+ndeath);j++){
 5422:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
 5423:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
 5424:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
 5425:      }  
 5426:    /* fprintf(ficresprob,"\n");
 5427:       fprintf(ficresprobcov,"\n");
 5428:       fprintf(ficresprobcor,"\n");
 5429:    */
 5430:    xp=vector(1,npar);
 5431:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 5432:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 5433:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
 5434:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 5435:    first=1;
 5436:    fprintf(ficgp,"\n# Routine varprob");
 5437:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
 5438:    fprintf(fichtm,"\n");
 5439: 
 5440:    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);
 5441:    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);
 5442:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
 5443: and drawn. It helps understanding how is the covariance between two incidences.\
 5444:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
 5445:    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. \
 5446: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
 5447: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
 5448: standard deviations wide on each axis. <br>\
 5449:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
 5450:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 5451: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
 5452: 
 5453:    cov[1]=1;
 5454:    /* tj=cptcoveff; */
 5455:    tj = (int) pow(2,nqveff);
 5456:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
 5457:    j1=0;
 5458:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
 5459:      if  (cptcovn>0) {
 5460:        fprintf(ficresprob, "\n#********** Variable "); 
 5461:        for (z1=1; z1<=nqveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5462:        fprintf(ficresprob, "**********\n#\n");
 5463:        fprintf(ficresprobcov, "\n#********** Variable "); 
 5464:        for (z1=1; z1<=nqveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5465:        fprintf(ficresprobcov, "**********\n#\n");
 5466: 			
 5467:        fprintf(ficgp, "\n#********** Variable "); 
 5468:        for (z1=1; z1<=nqveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5469:        fprintf(ficgp, "**********\n#\n");
 5470: 			
 5471: 			
 5472:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
 5473:        for (z1=1; z1<=nqveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5474:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
 5475: 			
 5476:        fprintf(ficresprobcor, "\n#********** Variable ");    
 5477:        for (z1=1; z1<=nqveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5478:        fprintf(ficresprobcor, "**********\n#");    
 5479:        if(invalidvarcomb[j1]){
 5480: 	 fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
 5481: 	 fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
 5482: 	 continue;
 5483:        }
 5484:      }
 5485:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
 5486:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 5487:      gp=vector(1,(nlstate)*(nlstate+ndeath));
 5488:      gm=vector(1,(nlstate)*(nlstate+ndeath));
 5489:      for (age=bage; age<=fage; age ++){ 
 5490:        cov[2]=age;
 5491:        if(nagesqr==1)
 5492: 	 cov[3]= age*age;
 5493:        for (k=1; k<=cptcovn;k++) {
 5494: 	 cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
 5495: 	 /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
 5496: 								    * 1  1 1 1 1
 5497: 								    * 2  2 1 1 1
 5498: 								    * 3  1 2 1 1
 5499: 								    */
 5500: 	 /* nbcode[1][1]=0 nbcode[1][2]=1;*/
 5501:        }
 5502:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 5503:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 5504:        for (k=1; k<=cptcovprod;k++)
 5505: 	 cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
 5506: 			
 5507: 			
 5508:        for(theta=1; theta <=npar; theta++){
 5509: 	 for(i=1; i<=npar; i++)
 5510: 	   xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
 5511: 				
 5512: 	 pmij(pmmij,cov,ncovmodel,xp,nlstate);
 5513: 				
 5514: 	 k=0;
 5515: 	 for(i=1; i<= (nlstate); i++){
 5516: 	   for(j=1; j<=(nlstate+ndeath);j++){
 5517: 	     k=k+1;
 5518: 	     gp[k]=pmmij[i][j];
 5519: 	   }
 5520: 	 }
 5521: 				
 5522: 	 for(i=1; i<=npar; i++)
 5523: 	   xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
 5524: 				
 5525: 	 pmij(pmmij,cov,ncovmodel,xp,nlstate);
 5526: 	 k=0;
 5527: 	 for(i=1; i<=(nlstate); i++){
 5528: 	   for(j=1; j<=(nlstate+ndeath);j++){
 5529: 	     k=k+1;
 5530: 	     gm[k]=pmmij[i][j];
 5531: 	   }
 5532: 	 }
 5533: 				
 5534: 	 for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
 5535: 	   gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
 5536:        }
 5537: 
 5538:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
 5539: 	 for(theta=1; theta <=npar; theta++)
 5540: 	   trgradg[j][theta]=gradg[theta][j];
 5541: 			
 5542:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
 5543:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
 5544: 			
 5545:        pmij(pmmij,cov,ncovmodel,x,nlstate);
 5546: 			
 5547:        k=0;
 5548:        for(i=1; i<=(nlstate); i++){
 5549: 	 for(j=1; j<=(nlstate+ndeath);j++){
 5550: 	   k=k+1;
 5551: 	   mu[k][(int) age]=pmmij[i][j];
 5552: 	 }
 5553:        }
 5554:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 5555: 	 for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 5556: 	   varpij[i][j][(int)age] = doldm[i][j];
 5557: 			
 5558:        /*printf("\n%d ",(int)age);
 5559: 	 for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 5560: 	 printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 5561: 	 fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 5562: 	 }*/
 5563: 			
 5564:        fprintf(ficresprob,"\n%d ",(int)age);
 5565:        fprintf(ficresprobcov,"\n%d ",(int)age);
 5566:        fprintf(ficresprobcor,"\n%d ",(int)age);
 5567: 			
 5568:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
 5569: 	 fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
 5570:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 5571: 	 fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
 5572: 	 fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
 5573:        }
 5574:        i=0;
 5575:        for (k=1; k<=(nlstate);k++){
 5576: 	 for (l=1; l<=(nlstate+ndeath);l++){ 
 5577: 	   i++;
 5578: 	   fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 5579: 	   fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
 5580: 	   for (j=1; j<=i;j++){
 5581: 	     /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
 5582: 	     fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
 5583: 	     fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
 5584: 	   }
 5585: 	 }
 5586:        }/* end of loop for state */
 5587:      } /* end of loop for age */
 5588:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
 5589:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 5590:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 5591:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 5592:     
 5593:      /* Confidence intervalle of pij  */
 5594:      /*
 5595:        fprintf(ficgp,"\nunset parametric;unset label");
 5596:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
 5597:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 5598:        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);
 5599:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
 5600:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
 5601:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
 5602:      */
 5603: 		
 5604:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
 5605:      first1=1;first2=2;
 5606:      for (k2=1; k2<=(nlstate);k2++){
 5607:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
 5608: 	 if(l2==k2) continue;
 5609: 	 j=(k2-1)*(nlstate+ndeath)+l2;
 5610: 	 for (k1=1; k1<=(nlstate);k1++){
 5611: 	   for (l1=1; l1<=(nlstate+ndeath);l1++){ 
 5612: 	     if(l1==k1) continue;
 5613: 	     i=(k1-1)*(nlstate+ndeath)+l1;
 5614: 	     if(i<=j) continue;
 5615: 	     for (age=bage; age<=fage; age ++){ 
 5616: 	       if ((int)age %5==0){
 5617: 		 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
 5618: 		 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
 5619: 		 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
 5620: 		 mu1=mu[i][(int) age]/stepm*YEARM ;
 5621: 		 mu2=mu[j][(int) age]/stepm*YEARM;
 5622: 		 c12=cv12/sqrt(v1*v2);
 5623: 		 /* Computing eigen value of matrix of covariance */
 5624: 		 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 5625: 		 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 5626: 		 if ((lc2 <0) || (lc1 <0) ){
 5627: 		   if(first2==1){
 5628: 		     first1=0;
 5629: 		     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);
 5630: 		   }
 5631: 		   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);
 5632: 		   /* lc1=fabs(lc1); */ /* If we want to have them positive */
 5633: 		   /* lc2=fabs(lc2); */
 5634: 		 }
 5635: 								
 5636: 		 /* Eigen vectors */
 5637: 		 v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
 5638: 		 /*v21=sqrt(1.-v11*v11); *//* error */
 5639: 		 v21=(lc1-v1)/cv12*v11;
 5640: 		 v12=-v21;
 5641: 		 v22=v11;
 5642: 		 tnalp=v21/v11;
 5643: 		 if(first1==1){
 5644: 		   first1=0;
 5645: 		   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);
 5646: 		 }
 5647: 		 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);
 5648: 		 /*printf(fignu*/
 5649: 		 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
 5650: 		 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
 5651: 		 if(first==1){
 5652: 		   first=0;
 5653: 		   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
 5654: 		   fprintf(ficgp,"\nset parametric;unset label");
 5655: 		   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);
 5656: 		   fprintf(ficgp,"\nset ter svg size 640, 480");
 5657: 		   fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
 5658:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">																		\
 5659: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
 5660: 			   subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,	\
 5661: 			   subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 5662: 		   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 5663: 		   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
 5664: 		   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 5665: 		   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 5666: 		   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 5667: 		   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",	\
 5668: 			   mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),										\
 5669: 			   mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 5670: 		 }else{
 5671: 		   first=0;
 5672: 		   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
 5673: 		   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 5674: 		   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 5675: 		   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", \
 5676: 			   mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),					\
 5677: 			   mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 5678: 		 }/* if first */
 5679: 	       } /* age mod 5 */
 5680: 	     } /* end loop age */
 5681: 	     fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 5682: 	     first=1;
 5683: 	   } /*l12 */
 5684: 	 } /* k12 */
 5685:        } /*l1 */
 5686:      }/* k1 */
 5687:    }  /* loop on combination of covariates j1 */
 5688:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 5689:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
 5690:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 5691:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
 5692:    free_vector(xp,1,npar);
 5693:    fclose(ficresprob);
 5694:    fclose(ficresprobcov);
 5695:    fclose(ficresprobcor);
 5696:    fflush(ficgp);
 5697:    fflush(fichtmcov);
 5698:  }
 5699: 
 5700: 
 5701: /******************* Printing html file ***********/
 5702: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
 5703: 		  int lastpass, int stepm, int weightopt, char model[],\
 5704: 		  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 5705: 		  int popforecast, int prevfcast, int backcast, int estepm , \
 5706: 		  double jprev1, double mprev1,double anprev1, double dateprev1, \
 5707: 		  double jprev2, double mprev2,double anprev2, double dateprev2){
 5708:   int jj1, k1, i1, cpt;
 5709: 
 5710:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
 5711:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
 5712: </ul>");
 5713:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
 5714:    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",
 5715: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
 5716:    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) ",
 5717: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
 5718:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
 5719:    fprintf(fichtm,"\
 5720:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 5721: 	   stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
 5722:    fprintf(fichtm,"\
 5723:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 5724: 	   stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
 5725:    fprintf(fichtm,"\
 5726:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 5727: 	   subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
 5728:    fprintf(fichtm,"\
 5729:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 5730: 	   subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
 5731:    fprintf(fichtm,"\
 5732:  - (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): \
 5733:    <a href=\"%s\">%s</a> <br>\n",
 5734: 	   estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
 5735:    if(prevfcast==1){
 5736:      fprintf(fichtm,"\
 5737:  - Prevalence projections by age and states:				\
 5738:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
 5739:    }
 5740: 
 5741:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
 5742: 
 5743:    m=pow(2,nqveff);
 5744:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 5745: 
 5746:    jj1=0;
 5747:    for(k1=1; k1<=m;k1++){
 5748: 
 5749:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
 5750:      jj1++;
 5751:      if (cptcovn > 0) {
 5752:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 5753:        for (cpt=1; cpt<=nqveff;cpt++){ 
 5754: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
 5755: 	 printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
 5756:        }
 5757:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 5758:        if(invalidvarcomb[k1]){
 5759: 	 fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
 5760: 	 printf("\nCombination (%d) ignored because no cases \n",k1); 
 5761: 	 continue;
 5762:        }
 5763:      }
 5764:      /* aij, bij */
 5765:      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> \
 5766: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
 5767:      /* Pij */
 5768:      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> \
 5769: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
 5770:      /* Quasi-incidences */
 5771:      fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
 5772:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
 5773:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
 5774: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
 5775: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
 5776:      /* Survival functions (period) in state j */
 5777:      for(cpt=1; cpt<=nlstate;cpt++){
 5778:        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> \
 5779: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
 5780:      }
 5781:      /* State specific survival functions (period) */
 5782:      for(cpt=1; cpt<=nlstate;cpt++){
 5783:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
 5784:  Or probability to survive in various states (1 to %d) being in state %d at different ages.	\
 5785:  <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);
 5786:      }
 5787:      /* Period (stable) prevalence in each health state */
 5788:      for(cpt=1; cpt<=nlstate;cpt++){
 5789:        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> \
 5790: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
 5791:      }
 5792:      if(backcast==1){
 5793:        /* Period (stable) back prevalence in each health state */
 5794:        for(cpt=1; cpt<=nlstate;cpt++){
 5795: 	 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> \
 5796: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1);
 5797:        }
 5798:      }
 5799:      if(prevfcast==1){
 5800:        /* Projection of prevalence up to period (stable) prevalence in each health state */
 5801:        for(cpt=1; cpt<=nlstate;cpt++){
 5802: 	 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> \
 5803: <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);
 5804:        }
 5805:      }
 5806: 	 
 5807:      for(cpt=1; cpt<=nlstate;cpt++) {
 5808:        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> \
 5809: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
 5810:      }
 5811:      /* } /\* end i1 *\/ */
 5812:    }/* End k1 */
 5813:    fprintf(fichtm,"</ul>");
 5814: 
 5815:    fprintf(fichtm,"\
 5816: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
 5817:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
 5818:  - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
 5819: But because parameters are usually highly correlated (a higher incidence of disability \
 5820: and a higher incidence of recovery can give very close observed transition) it might \
 5821: be very useful to look not only at linear confidence intervals estimated from the \
 5822: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
 5823: (parameters) of the logistic regression, it might be more meaningful to visualize the \
 5824: covariance matrix of the one-step probabilities. \
 5825: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
 5826: 
 5827:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 5828: 	   subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
 5829:    fprintf(fichtm,"\
 5830:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 5831: 	   subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
 5832: 
 5833:    fprintf(fichtm,"\
 5834:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 5835: 	   subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
 5836:    fprintf(fichtm,"\
 5837:  - 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): \
 5838:    <a href=\"%s\">%s</a> <br>\n</li>",
 5839: 	   estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
 5840:    fprintf(fichtm,"\
 5841:  - (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): \
 5842:    <a href=\"%s\">%s</a> <br>\n</li>",
 5843: 	   estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
 5844:    fprintf(fichtm,"\
 5845:  - 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",
 5846: 	   estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
 5847:    fprintf(fichtm,"\
 5848:  - 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",
 5849: 	   estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
 5850:    fprintf(fichtm,"\
 5851:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
 5852: 	   subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
 5853: 
 5854: /*  if(popforecast==1) fprintf(fichtm,"\n */
 5855: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
 5856: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
 5857: /* 	<br>",fileres,fileres,fileres,fileres); */
 5858: /*  else  */
 5859: /*    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); */
 5860:    fflush(fichtm);
 5861:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
 5862: 
 5863:    m=pow(2,nqveff);
 5864:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 5865: 
 5866:    jj1=0;
 5867:    for(k1=1; k1<=m;k1++){
 5868:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
 5869:      jj1++;
 5870:      if (cptcovn > 0) {
 5871:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 5872:        for (cpt=1; cpt<=nqveff;cpt++) 
 5873: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
 5874:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 5875: 
 5876:        if(invalidvarcomb[k1]){
 5877: 	 fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
 5878: 	 continue;
 5879:        }
 5880:      }
 5881:      for(cpt=1; cpt<=nlstate;cpt++) {
 5882:        fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
 5883: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d.svg\"> %s_%d-%d.svg</a>\n <br>\
 5884: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);  
 5885:      }
 5886:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
 5887: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
 5888: true period expectancies (those weighted with period prevalences are also\
 5889:  drawn in addition to the population based expectancies computed using\
 5890:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg</a>\n<br>\
 5891: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
 5892:      /* } /\* end i1 *\/ */
 5893:    }/* End k1 */
 5894:    fprintf(fichtm,"</ul>");
 5895:    fflush(fichtm);
 5896: }
 5897: 
 5898: /******************* Gnuplot file **************/
 5899: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
 5900: 
 5901:   char dirfileres[132],optfileres[132];
 5902:   char gplotcondition[132];
 5903:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
 5904:   int lv=0, vlv=0, kl=0;
 5905:   int ng=0;
 5906:   int vpopbased;
 5907:   int ioffset; /* variable offset for columns */
 5908: 
 5909: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
 5910: /*     printf("Problem with file %s",optionfilegnuplot); */
 5911: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
 5912: /*   } */
 5913: 
 5914:   /*#ifdef windows */
 5915:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 5916:   /*#endif */
 5917:   m=pow(2,nqveff);
 5918: 
 5919:   /* Contribution to likelihood */
 5920:   /* Plot the probability implied in the likelihood */
 5921:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
 5922:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
 5923:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
 5924:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
 5925: /* nice for mle=4 plot by number of matrix products.
 5926:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
 5927: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
 5928:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
 5929:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
 5930:   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));
 5931:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
 5932:   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));
 5933:   for (i=1; i<= nlstate ; i ++) {
 5934:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
 5935:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
 5936:     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);
 5937:     for (j=2; j<= nlstate+ndeath ; j ++) {
 5938:       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);
 5939:     }
 5940:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
 5941:   }
 5942:   /* 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 */		 
 5943:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
 5944:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
 5945:   fprintf(ficgp,"\nset out;unset log\n");
 5946:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
 5947: 
 5948:   strcpy(dirfileres,optionfilefiname);
 5949:   strcpy(optfileres,"vpl");
 5950:   /* 1eme*/
 5951:   for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
 5952:     for (k1=1; k1<= m ; k1 ++) { /* For each valid combination of covariate */
 5953:       /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
 5954:       fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
 5955:       for (k=1; k<=nqveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 5956: 	lv= decodtabm(k1,k,nqveff); /* Should be the value of the covariate corresponding to k1 combination */
 5957: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 5958: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 5959: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 5960: 	vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
 5961: 	/* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
 5962: 	fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 5963:       }
 5964:       fprintf(ficgp,"\n#\n");
 5965:       if(invalidvarcomb[k1]){
 5966: 	fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 5967: 	continue;
 5968:       }
 5969: 
 5970:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
 5971:       fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
 5972:       fprintf(ficgp,"set xlabel \"Age\" \n\
 5973: set ylabel \"Probability\" \n	\
 5974: set ter svg size 640, 480\n	\
 5975: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
 5976: 			
 5977:       for (i=1; i<= nlstate ; i ++) {
 5978: 	if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 5979: 	else        fprintf(ficgp," %%*lf (%%*lf)");
 5980:       }
 5981:       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);
 5982:       for (i=1; i<= nlstate ; i ++) {
 5983: 	if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 5984: 	else fprintf(ficgp," %%*lf (%%*lf)");
 5985:       } 
 5986:       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); 
 5987:       for (i=1; i<= nlstate ; i ++) {
 5988: 	if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 5989: 	else fprintf(ficgp," %%*lf (%%*lf)");
 5990:       }  
 5991:       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));
 5992:       if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
 5993: 	/* 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); */
 5994: 	fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1 */
 5995: 	if(nqveff ==0){
 5996: 	  fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line ",	 2+(cpt-1),  cpt );
 5997: 	}else{
 5998: 	  kl=0;
 5999: 	  for (k=1; k<=nqveff; k++){    /* For each combination of covariate  */
 6000: 	    lv= decodtabm(k1,k,nqveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
 6001: 	    /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6002: 	    /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6003: 	    /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6004: 	    vlv= nbcode[Tvaraff[k]][lv];
 6005: 	    kl++;
 6006: 	    /* 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 *\/ */
 6007: 	    /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
 6008: 	    /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
 6009: 	    /* ''  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*/
 6010: 	    if(k==nqveff){
 6011: 	      fprintf(ficgp,"$%d==%d && $%d==%d)? $%d : 1/0) t 'Backward prevalence in state %d' with line ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv], \
 6012: 		      6+(cpt-1),  cpt );
 6013: 	    }else{
 6014: 	      fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
 6015: 	      kl++;
 6016: 	    }
 6017: 	  } /* end covariate */
 6018: 	} /* end if no covariate */
 6019:       } /* end if backcast */
 6020:       fprintf(ficgp,"\nset out \n");
 6021:     } /* k1 */
 6022:   } /* cpt */
 6023:   /*2 eme*/
 6024:   for (k1=1; k1<= m ; k1 ++) { 
 6025: 
 6026:     fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
 6027:     for (k=1; k<=nqveff; k++){    /* For each covariate and each value */
 6028:       lv= decodtabm(k1,k,nqveff); /* Should be the covariate number corresponding to k1 combination */
 6029:       /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6030:       /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6031:       /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6032:       vlv= nbcode[Tvaraff[k]][lv];
 6033:       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6034:     }
 6035:     fprintf(ficgp,"\n#\n");
 6036:     if(invalidvarcomb[k1]){
 6037:       fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6038:       continue;
 6039:     }
 6040: 			
 6041:     fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
 6042:     for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 6043:       if(vpopbased==0)
 6044: 	fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
 6045:       else
 6046: 	fprintf(ficgp,"\nreplot ");
 6047:       for (i=1; i<= nlstate+1 ; i ++) {
 6048: 	k=2*i;
 6049: 	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);
 6050: 	for (j=1; j<= nlstate+1 ; j ++) {
 6051: 	  if (j==i) fprintf(ficgp," %%lf (%%lf)");
 6052: 	  else fprintf(ficgp," %%*lf (%%*lf)");
 6053: 	}   
 6054: 	if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
 6055: 	else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
 6056: 	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);
 6057: 	for (j=1; j<= nlstate+1 ; j ++) {
 6058: 	  if (j==i) fprintf(ficgp," %%lf (%%lf)");
 6059: 	  else fprintf(ficgp," %%*lf (%%*lf)");
 6060: 	}   
 6061: 	fprintf(ficgp,"\" t\"\" w l lt 0,");
 6062: 	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);
 6063: 	for (j=1; j<= nlstate+1 ; j ++) {
 6064: 	  if (j==i) fprintf(ficgp," %%lf (%%lf)");
 6065: 	  else fprintf(ficgp," %%*lf (%%*lf)");
 6066: 	}   
 6067: 	if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
 6068: 	else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
 6069:       } /* state */
 6070:     } /* vpopbased */
 6071:     fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
 6072:   } /* k1 */
 6073: 	
 6074: 	
 6075:   /*3eme*/
 6076:   for (k1=1; k1<= m ; k1 ++) { 
 6077: 
 6078:     for (cpt=1; cpt<= nlstate ; cpt ++) {
 6079:       fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  cov=%d state=%d",k1, cpt);
 6080:       for (k=1; k<=nqveff; k++){    /* For each covariate and each value */
 6081: 	lv= decodtabm(k1,k,nqveff); /* Should be the covariate number corresponding to k1 combination */
 6082: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6083: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6084: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6085: 	vlv= nbcode[Tvaraff[k]][lv];
 6086: 	fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6087:       }
 6088:       fprintf(ficgp,"\n#\n");
 6089:       if(invalidvarcomb[k1]){
 6090: 	fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6091: 	continue;
 6092:       }
 6093: 			
 6094:       /*       k=2+nlstate*(2*cpt-2); */
 6095:       k=2+(nlstate+1)*(cpt-1);
 6096:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
 6097:       fprintf(ficgp,"set ter svg size 640, 480\n\
 6098: 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);
 6099:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 6100: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 6101: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 6102: 	fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 6103: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 6104: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 6105: 				
 6106:       */
 6107:       for (i=1; i< nlstate ; i ++) {
 6108: 	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);
 6109: 	/*	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);*/
 6110: 				
 6111:       } 
 6112:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
 6113:     }
 6114:   }
 6115:   
 6116:   /* 4eme */
 6117:   /* Survival functions (period) from state i in state j by initial state i */
 6118:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
 6119: 
 6120:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 6121:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
 6122:       for (k=1; k<=nqveff; k++){    /* For each covariate and each value */
 6123: 	lv= decodtabm(k1,k,nqveff); /* Should be the covariate number corresponding to k1 combination */
 6124: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6125: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6126: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6127: 	vlv= nbcode[Tvaraff[k]][lv];
 6128: 	fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6129:       }
 6130:       fprintf(ficgp,"\n#\n");
 6131:       if(invalidvarcomb[k1]){
 6132: 	fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6133: 	continue;
 6134:       }
 6135: 			
 6136:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
 6137:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
 6138: set ter svg size 640, 480\n																							\
 6139: unset log y\n																														\
 6140: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 6141:       k=3;
 6142:       for (i=1; i<= nlstate ; i ++){
 6143: 	if(i==1){
 6144: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 6145: 	}else{
 6146: 	  fprintf(ficgp,", '' ");
 6147: 	}
 6148: 	l=(nlstate+ndeath)*(i-1)+1;
 6149: 	fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 6150: 	for (j=2; j<= nlstate+ndeath ; j ++)
 6151: 	  fprintf(ficgp,"+$%d",k+l+j-1);
 6152: 	fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
 6153:       } /* nlstate */
 6154:       fprintf(ficgp,"\nset out\n");
 6155:     } /* end cpt state*/ 
 6156:   } /* end covariate */  
 6157: 	
 6158: /* 5eme */
 6159:   /* Survival functions (period) from state i in state j by final state j */
 6160:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
 6161:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
 6162: 			
 6163:       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);
 6164:       for (k=1; k<=nqveff; k++){    /* For each covariate and each value */
 6165: 				lv= decodtabm(k1,k,nqveff); /* Should be the covariate number corresponding to k1 combination */
 6166: 				/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6167: 				/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6168: 				/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6169: 				vlv= nbcode[Tvaraff[k]][lv];
 6170: 				fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6171:       }
 6172:       fprintf(ficgp,"\n#\n");
 6173:       if(invalidvarcomb[k1]){
 6174: 				fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6175: 				continue;
 6176:       }
 6177: 			
 6178:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
 6179:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
 6180: set ter svg size 640, 480\n																							\
 6181: unset log y\n																														\
 6182: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 6183:       k=3;
 6184:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
 6185: 				if(j==1)
 6186: 					fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 6187: 				else
 6188: 					fprintf(ficgp,", '' ");
 6189: 				l=(nlstate+ndeath)*(cpt-1) +j;
 6190: 				fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
 6191: 				/* for (i=2; i<= nlstate+ndeath ; i ++) */
 6192: 				/*   fprintf(ficgp,"+$%d",k+l+i-1); */
 6193: 				fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
 6194:       } /* nlstate */
 6195:       fprintf(ficgp,", '' ");
 6196:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
 6197:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
 6198: 				l=(nlstate+ndeath)*(cpt-1) +j;
 6199: 				if(j < nlstate)
 6200: 					fprintf(ficgp,"$%d +",k+l);
 6201: 				else
 6202: 					fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
 6203:       }
 6204:       fprintf(ficgp,"\nset out\n");
 6205:     } /* end cpt state*/ 
 6206:   } /* end covariate */  
 6207: 	
 6208: /* 6eme */
 6209:   /* CV preval stable (period) for each covariate */
 6210:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
 6211:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 6212: 			
 6213:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
 6214:       for (k=1; k<=nqveff; k++){    /* For each covariate and each value */
 6215: 				lv= decodtabm(k1,k,nqveff); /* Should be the covariate number corresponding to k1 combination */
 6216: 				/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6217: 				/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6218: 				/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6219: 				vlv= nbcode[Tvaraff[k]][lv];
 6220: 				fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6221:       }
 6222:       fprintf(ficgp,"\n#\n");
 6223:       if(invalidvarcomb[k1]){
 6224: 				fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6225: 				continue;
 6226:       }
 6227: 			
 6228:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
 6229:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 6230: set ter svg size 640, 480\n																						 \
 6231: unset log y\n																													 \
 6232: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 6233:       k=3; /* Offset */
 6234:       for (i=1; i<= nlstate ; i ++){
 6235: 				if(i==1)
 6236: 					fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 6237: 				else
 6238: 					fprintf(ficgp,", '' ");
 6239: 				l=(nlstate+ndeath)*(i-1)+1;
 6240: 				fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 6241: 				for (j=2; j<= nlstate ; j ++)
 6242: 					fprintf(ficgp,"+$%d",k+l+j-1);
 6243: 				fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
 6244:       } /* nlstate */
 6245:       fprintf(ficgp,"\nset out\n");
 6246:     } /* end cpt state*/ 
 6247:   } /* end covariate */  
 6248: 	
 6249: 	
 6250: /* 7eme */
 6251:   if(backcast == 1){
 6252:     /* CV back preval stable (period) for each covariate */
 6253:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
 6254:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 6255: 				fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
 6256: 				for (k=1; k<=nqveff; k++){    /* For each covariate and each value */
 6257: 					lv= decodtabm(k1,k,nqveff); /* Should be the covariate number corresponding to k1 combination */
 6258: 					/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6259: 					/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6260: 	  /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6261: 					vlv= nbcode[Tvaraff[k]][lv];
 6262: 					fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6263: 				}
 6264: 				fprintf(ficgp,"\n#\n");
 6265: 				if(invalidvarcomb[k1]){
 6266: 					fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6267: 					continue;
 6268: 				}
 6269: 				
 6270: 				fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1);
 6271: 				fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 6272: set ter svg size 640, 480\n																							\
 6273: unset log y\n																														\
 6274: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 6275: 				k=3; /* Offset */
 6276: 				for (i=1; i<= nlstate ; i ++){
 6277: 					if(i==1)
 6278: 						fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
 6279: 					else
 6280: 						fprintf(ficgp,", '' ");
 6281: 					/* l=(nlstate+ndeath)*(i-1)+1; */
 6282: 					l=(nlstate+ndeath)*(cpt-1)+1;
 6283: 					/* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
 6284: 					/* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
 6285: 					fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */
 6286: 					/* for (j=2; j<= nlstate ; j ++) */
 6287: 					/* 	fprintf(ficgp,"+$%d",k+l+j-1); */
 6288: 					/* 	/\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
 6289: 					fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
 6290: 				} /* nlstate */
 6291: 				fprintf(ficgp,"\nset out\n");
 6292:       } /* end cpt state*/ 
 6293:     } /* end covariate */  
 6294:   } /* End if backcast */
 6295:   
 6296:   /* 8eme */
 6297:   if(prevfcast==1){
 6298:     /* Projection from cross-sectional to stable (period) for each covariate */
 6299:     
 6300:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
 6301:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 6302: 				fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
 6303: 				for (k=1; k<=nqveff; k++){    /* For each correspondig covariate value  */
 6304: 					lv= decodtabm(k1,k,nqveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
 6305: 					/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6306: 					/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6307: 					/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6308: 					vlv= nbcode[Tvaraff[k]][lv];
 6309: 					fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6310: 				}
 6311: 				fprintf(ficgp,"\n#\n");
 6312: 				if(invalidvarcomb[k1]){
 6313: 					fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6314: 					continue;
 6315: 				}
 6316: 				
 6317: 				fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
 6318: 				fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
 6319: 				fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
 6320: set ter svg size 640, 480\n																							\
 6321: unset log y\n																														\
 6322: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 6323: 				for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
 6324: 					/*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 6325: 					/*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 6326: 					/*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 6327: 					/*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 6328: 					if(i==1){
 6329: 						fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
 6330: 					}else{
 6331: 						fprintf(ficgp,",\\\n '' ");
 6332: 					}
 6333: 					if(nqveff ==0){ /* No covariate */
 6334: 						ioffset=2; /* Age is in 2 */
 6335: 						/*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
 6336: 						/*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
 6337: 						/*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
 6338: 						/*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
 6339: 						fprintf(ficgp," u %d:(", ioffset); 
 6340: 						if(i==nlstate+1)
 6341: 							fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ",			\
 6342: 											ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
 6343: 						else
 6344: 							fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",			\
 6345: 											ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
 6346: 					}else{ /* more than 2 covariates */
 6347: 						if(nqveff ==1){
 6348: 							ioffset=4; /* Age is in 4 */
 6349: 						}else{
 6350: 							ioffset=6; /* Age is in 6 */
 6351: 							/*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 6352: 							/*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
 6353: 						}   
 6354: 						fprintf(ficgp," u %d:(",ioffset); 
 6355: 						kl=0;
 6356: 						strcpy(gplotcondition,"(");
 6357: 						for (k=1; k<=nqveff; k++){    /* For each covariate writing the chain of conditions */
 6358: 							lv= decodtabm(k1,k,nqveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
 6359: 							/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6360: 							/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6361: 							/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6362: 							vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
 6363: 							kl++;
 6364: 							sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
 6365: 							kl++;
 6366: 							if(k <nqveff && nqveff>1)
 6367: 								sprintf(gplotcondition+strlen(gplotcondition)," && ");
 6368: 						}
 6369: 						strcpy(gplotcondition+strlen(gplotcondition),")");
 6370: 						/* 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 *\/ */
 6371: 						/*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
 6372: 						/*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
 6373: 						/* ''  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*/
 6374: 						if(i==nlstate+1){
 6375: 							fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ", gplotcondition, \
 6376: 											ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
 6377: 						}else{
 6378: 							fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
 6379: 											ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
 6380: 						}
 6381: 					} /* end if covariate */
 6382: 				} /* nlstate */
 6383: 				fprintf(ficgp,"\nset out\n");
 6384:       } /* end cpt state*/
 6385:     } /* end covariate */
 6386:   } /* End if prevfcast */
 6387: 	
 6388: 	
 6389:   /* proba elementaires */
 6390:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
 6391:   for(i=1,jk=1; i <=nlstate; i++){
 6392:     fprintf(ficgp,"# initial state %d\n",i);
 6393:     for(k=1; k <=(nlstate+ndeath); k++){
 6394:       if (k != i) {
 6395: 				fprintf(ficgp,"#   current state %d\n",k);
 6396: 				for(j=1; j <=ncovmodel; j++){
 6397: 					fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
 6398: 					jk++; 
 6399: 				}
 6400: 				fprintf(ficgp,"\n");
 6401:       }
 6402:     }
 6403:   }
 6404:   fprintf(ficgp,"##############\n#\n");
 6405: 	
 6406:   /*goto avoid;*/
 6407:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
 6408:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
 6409:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
 6410:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
 6411:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
 6412:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 6413:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 6414:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 6415:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 6416:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
 6417:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 6418:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
 6419:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
 6420:   fprintf(ficgp,"#\n");
 6421:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
 6422:     fprintf(ficgp,"# ng=%d\n",ng);
 6423:     fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",nqveff,m);
 6424:     for(jk=1; jk <=m; jk++) {
 6425:       fprintf(ficgp,"#    jk=%d\n",jk);
 6426:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
 6427:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
 6428:       if (ng==1){
 6429: 	fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
 6430: 	fprintf(ficgp,"\nunset log y");
 6431:       }else if (ng==2){
 6432: 	fprintf(ficgp,"\nset ylabel \"Probability\"\n");
 6433: 	fprintf(ficgp,"\nset log y");
 6434:       }else if (ng==3){
 6435: 	fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
 6436: 	fprintf(ficgp,"\nset log y");
 6437:       }else
 6438: 	fprintf(ficgp,"\nunset title ");
 6439:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
 6440:       i=1;
 6441:       for(k2=1; k2<=nlstate; k2++) {
 6442: 	k3=i;
 6443: 	for(k=1; k<=(nlstate+ndeath); k++) {
 6444: 	  if (k != k2){
 6445: 	    switch( ng) {
 6446: 	    case 1:
 6447: 	      if(nagesqr==0)
 6448: 		fprintf(ficgp," p%d+p%d*x",i,i+1);
 6449: 	      else /* nagesqr =1 */
 6450: 		fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
 6451: 	      break;
 6452: 	    case 2: /* ng=2 */
 6453: 	      if(nagesqr==0)
 6454: 		fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
 6455: 	      else /* nagesqr =1 */
 6456: 		fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
 6457: 	      break;
 6458: 	    case 3:
 6459: 	      if(nagesqr==0)
 6460: 		fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
 6461: 	      else /* nagesqr =1 */
 6462: 		fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
 6463: 	      break;
 6464: 	    }
 6465: 	    ij=1;/* To be checked else nbcode[0][0] wrong */
 6466: 	    for(j=3; j <=ncovmodel-nagesqr; j++) {
 6467: 	      /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
 6468: 	      if(ij <=cptcovage) { /* Bug valgrind */
 6469: 		if((j-2)==Tage[ij]) { /* Bug valgrind */
 6470: 		  fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
 6471: 		  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
 6472: 		  ij++;
 6473: 		}
 6474: 	      }
 6475: 	      else
 6476: 		fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
 6477: 	    }
 6478: 	  }else{
 6479: 	    i=i-ncovmodel;
 6480: 	    if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
 6481: 	      fprintf(ficgp," (1.");
 6482: 	  }
 6483: 	   
 6484: 	  if(ng != 1){
 6485: 	    fprintf(ficgp,")/(1");
 6486: 	     
 6487: 	    for(k1=1; k1 <=nlstate; k1++){ 
 6488: 	      if(nagesqr==0)
 6489: 		fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
 6490: 	      else /* nagesqr =1 */
 6491: 		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);
 6492: 	       
 6493: 	      ij=1;
 6494: 	      for(j=3; j <=ncovmodel-nagesqr; j++){
 6495: 		if(ij <=cptcovage) { /* Bug valgrind */
 6496: 		  if((j-2)==Tage[ij]) { /* Bug valgrind */
 6497: 		    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
 6498: 		    /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
 6499: 		    ij++;
 6500: 		  }
 6501: 		}
 6502: 		else
 6503: 		  fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
 6504: 	      }
 6505: 	      fprintf(ficgp,")");
 6506: 	    }
 6507: 	    fprintf(ficgp,")");
 6508: 	    if(ng ==2)
 6509: 	      fprintf(ficgp," t \"p%d%d\" ", k2,k);
 6510: 	    else /* ng= 3 */
 6511: 	      fprintf(ficgp," t \"i%d%d\" ", k2,k);
 6512: 	  }else{ /* end ng <> 1 */
 6513: 	    if( k !=k2) /* logit p11 is hard to draw */
 6514: 	      fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
 6515: 	  }
 6516: 	  if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
 6517: 	    fprintf(ficgp,",");
 6518: 	  if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
 6519: 	    fprintf(ficgp,",");
 6520: 	  i=i+ncovmodel;
 6521: 	} /* end k */
 6522:       } /* end k2 */
 6523:       fprintf(ficgp,"\n set out\n");
 6524:     } /* end jk */
 6525:   } /* end ng */
 6526:   /* avoid: */
 6527:   fflush(ficgp); 
 6528: }  /* end gnuplot */
 6529: 
 6530: 
 6531: /*************** Moving average **************/
 6532: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
 6533:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
 6534:    
 6535:    int i, cpt, cptcod;
 6536:    int modcovmax =1;
 6537:    int mobilavrange, mob;
 6538:    int iage=0;
 6539: 
 6540:    double sum=0.;
 6541:    double age;
 6542:    double *sumnewp, *sumnewm;
 6543:    double *agemingood, *agemaxgood; /* Currently identical for all covariates */
 6544:   
 6545:   
 6546:    /* modcovmax=2*nqveff;/\* Max number of modalities. We suppose  */
 6547:    /* 		   a covariate has 2 modalities, should be equal to ncovcombmax  *\/ */
 6548: 
 6549:    sumnewp = vector(1,ncovcombmax);
 6550:    sumnewm = vector(1,ncovcombmax);
 6551:    agemingood = vector(1,ncovcombmax);	
 6552:    agemaxgood = vector(1,ncovcombmax);
 6553: 
 6554:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
 6555:      sumnewm[cptcod]=0.;
 6556:      sumnewp[cptcod]=0.;
 6557:      agemingood[cptcod]=0;
 6558:      agemaxgood[cptcod]=0;
 6559:    }
 6560:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
 6561:   
 6562:    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
 6563:      if(mobilav==1) mobilavrange=5; /* default */
 6564:      else mobilavrange=mobilav;
 6565:      for (age=bage; age<=fage; age++)
 6566:        for (i=1; i<=nlstate;i++)
 6567: 	 for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
 6568: 	   mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 6569:      /* We keep the original values on the extreme ages bage, fage and for 
 6570: 	fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
 6571: 	we use a 5 terms etc. until the borders are no more concerned. 
 6572:      */ 
 6573:      for (mob=3;mob <=mobilavrange;mob=mob+2){
 6574:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
 6575: 	 for (i=1; i<=nlstate;i++){
 6576: 	   for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
 6577: 	     mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
 6578: 	     for (cpt=1;cpt<=(mob-1)/2;cpt++){
 6579: 	       mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
 6580: 	       mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
 6581: 	     }
 6582: 	     mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
 6583: 	   }
 6584: 	 }
 6585:        }/* end age */
 6586:      }/* end mob */
 6587:    }else
 6588:      return -1;
 6589:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
 6590:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
 6591:      if(invalidvarcomb[cptcod]){
 6592:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
 6593:        continue;
 6594:      }
 6595: 
 6596:      agemingood[cptcod]=fage-(mob-1)/2;
 6597:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
 6598:        sumnewm[cptcod]=0.;
 6599:        for (i=1; i<=nlstate;i++){
 6600: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 6601:        }
 6602:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
 6603: 	 agemingood[cptcod]=age;
 6604:        }else{ /* bad */
 6605: 	 for (i=1; i<=nlstate;i++){
 6606: 	   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
 6607: 	 } /* i */
 6608:        } /* end bad */
 6609:      }/* age */
 6610:      sum=0.;
 6611:      for (i=1; i<=nlstate;i++){
 6612:        sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
 6613:      }
 6614:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
 6615:        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);
 6616:        /* for (i=1; i<=nlstate;i++){ */
 6617:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
 6618:        /* } /\* i *\/ */
 6619:      } /* end bad */
 6620:      /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
 6621:      /* From youngest, finding the oldest wrong */
 6622:      agemaxgood[cptcod]=bage+(mob-1)/2;
 6623:      for (age=bage+(mob-1)/2; age<=fage; age++){
 6624:        sumnewm[cptcod]=0.;
 6625:        for (i=1; i<=nlstate;i++){
 6626: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 6627:        }
 6628:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
 6629: 	 agemaxgood[cptcod]=age;
 6630:        }else{ /* bad */
 6631: 	 for (i=1; i<=nlstate;i++){
 6632: 	   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
 6633: 	 } /* i */
 6634:        } /* end bad */
 6635:      }/* age */
 6636:      sum=0.;
 6637:      for (i=1; i<=nlstate;i++){
 6638:        sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
 6639:      }
 6640:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
 6641:        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);
 6642:        /* for (i=1; i<=nlstate;i++){ */
 6643:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
 6644:        /* } /\* i *\/ */
 6645:      } /* end bad */
 6646: 		
 6647:      for (age=bage; age<=fage; age++){
 6648:        printf("%d %d ", cptcod, (int)age);
 6649:        sumnewp[cptcod]=0.;
 6650:        sumnewm[cptcod]=0.;
 6651:        for (i=1; i<=nlstate;i++){
 6652: 	 sumnewp[cptcod]+=probs[(int)age][i][cptcod];
 6653: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 6654: 	 /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
 6655:        }
 6656:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
 6657:      }
 6658:      /* printf("\n"); */
 6659:      /* } */
 6660:      /* brutal averaging */
 6661:      for (i=1; i<=nlstate;i++){
 6662:        for (age=1; age<=bage; age++){
 6663: 	 mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
 6664: 	 /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
 6665:        }	
 6666:        for (age=fage; age<=AGESUP; age++){
 6667: 	 mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
 6668: 	 /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
 6669:        }
 6670:      } /* end i status */
 6671:      for (i=nlstate+1; i<=nlstate+ndeath;i++){
 6672:        for (age=1; age<=AGESUP; age++){
 6673: 	 /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
 6674: 	 mobaverage[(int)age][i][cptcod]=0.;
 6675:        }
 6676:      }
 6677:    }/* end cptcod */
 6678:    free_vector(sumnewm,1, ncovcombmax);
 6679:    free_vector(sumnewp,1, ncovcombmax);
 6680:    free_vector(agemaxgood,1, ncovcombmax);
 6681:    free_vector(agemingood,1, ncovcombmax);
 6682:    return 0;
 6683:  }/* End movingaverage */
 6684:  
 6685: 
 6686: /************** Forecasting ******************/
 6687: 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 nqveff){
 6688:   /* proj1, year, month, day of starting projection 
 6689:      agemin, agemax range of age
 6690:      dateprev1 dateprev2 range of dates during which prevalence is computed
 6691:      anproj2 year of en of projection (same day and month as proj1).
 6692:   */
 6693:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
 6694:   double agec; /* generic age */
 6695:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
 6696:   double *popeffectif,*popcount;
 6697:   double ***p3mat;
 6698:   /* double ***mobaverage; */
 6699:   char fileresf[FILENAMELENGTH];
 6700: 
 6701:   agelim=AGESUP;
 6702:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 6703:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 6704:      We still use firstpass and lastpass as another selection.
 6705:   */
 6706:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
 6707:   /* 	      firstpass, lastpass,  stepm,  weightopt, model); */
 6708:  
 6709:   strcpy(fileresf,"F_"); 
 6710:   strcat(fileresf,fileresu);
 6711:   if((ficresf=fopen(fileresf,"w"))==NULL) {
 6712:     printf("Problem with forecast resultfile: %s\n", fileresf);
 6713:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
 6714:   }
 6715:   printf("Computing forecasting: result on file '%s', please wait... \n", fileresf);
 6716:   fprintf(ficlog,"Computing forecasting: result on file '%s', please wait... \n", fileresf);
 6717: 
 6718:   if (nqveff==0) ncodemax[nqveff]=1;
 6719: 
 6720: 
 6721:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 6722:   if (stepm<=12) stepsize=1;
 6723:   if(estepm < stepm){
 6724:     printf ("Problem %d lower than %d\n",estepm, stepm);
 6725:   }
 6726:   else  hstepm=estepm;   
 6727: 
 6728:   hstepm=hstepm/stepm; 
 6729:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
 6730:                                fractional in yp1 */
 6731:   anprojmean=yp;
 6732:   yp2=modf((yp1*12),&yp);
 6733:   mprojmean=yp;
 6734:   yp1=modf((yp2*30.5),&yp);
 6735:   jprojmean=yp;
 6736:   if(jprojmean==0) jprojmean=1;
 6737:   if(mprojmean==0) jprojmean=1;
 6738: 
 6739:   i1=nqveff;
 6740:   if (cptcovn < 1){i1=1;}
 6741:   
 6742:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
 6743:   
 6744:   fprintf(ficresf,"#****** Routine prevforecast **\n");
 6745: 
 6746: /* 	      if (h==(int)(YEARM*yearp)){ */
 6747:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
 6748:     for(cptcod=1;cptcod<=ncodemax[nqveff];cptcod++){
 6749:       k=k+1;
 6750:       fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
 6751:       for(j=1;j<=nqveff;j++) {
 6752: 				fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 6753:       }
 6754:       fprintf(ficresf," yearproj age");
 6755:       for(j=1; j<=nlstate+ndeath;j++){ 
 6756: 				for(i=1; i<=nlstate;i++) 	      
 6757:           fprintf(ficresf," p%d%d",i,j);
 6758: 				fprintf(ficresf," wp.%d",j);
 6759:       }
 6760:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
 6761: 				fprintf(ficresf,"\n");
 6762: 				fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
 6763: 				for (agec=fage; agec>=(ageminpar-1); agec--){ 
 6764: 					nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
 6765: 					nhstepm = nhstepm/hstepm; 
 6766: 					p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6767: 					oldm=oldms;savm=savms;
 6768: 					hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
 6769: 					
 6770: 					for (h=0; h<=nhstepm; h++){
 6771: 						if (h*hstepm/YEARM*stepm ==yearp) {
 6772:               fprintf(ficresf,"\n");
 6773:               for(j=1;j<=nqveff;j++) 
 6774:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 6775: 							fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
 6776: 						} 
 6777: 						for(j=1; j<=nlstate+ndeath;j++) {
 6778: 							ppij=0.;
 6779: 							for(i=1; i<=nlstate;i++) {
 6780: 								if (mobilav==1) 
 6781: 									ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
 6782: 								else {
 6783: 									ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
 6784: 								}
 6785: 								if (h*hstepm/YEARM*stepm== yearp) {
 6786: 									fprintf(ficresf," %.3f", p3mat[i][j][h]);
 6787: 								}
 6788: 							} /* end i */
 6789: 							if (h*hstepm/YEARM*stepm==yearp) {
 6790: 								fprintf(ficresf," %.3f", ppij);
 6791: 							}
 6792: 						}/* end j */
 6793: 					} /* end h */
 6794: 					free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6795: 				} /* end agec */
 6796:       } /* end yearp */
 6797:     } /* end cptcod */
 6798:   } /* end  cptcov */
 6799: 	
 6800:   fclose(ficresf);
 6801:   printf("End of Computing forecasting \n");
 6802:   fprintf(ficlog,"End of Computing forecasting\n");
 6803: 
 6804: }
 6805: 
 6806: /* /\************** Back Forecasting ******************\/ */
 6807: /* 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 nqveff){ */
 6808: /*   /\* back1, year, month, day of starting backection  */
 6809: /*      agemin, agemax range of age */
 6810: /*      dateprev1 dateprev2 range of dates during which prevalence is computed */
 6811: /*      anback2 year of en of backection (same day and month as back1). */
 6812: /*   *\/ */
 6813: /*   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
 6814: /*   double agec; /\* generic age *\/ */
 6815: /*   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
 6816: /*   double *popeffectif,*popcount; */
 6817: /*   double ***p3mat; */
 6818: /*   /\* double ***mobaverage; *\/ */
 6819: /*   char fileresfb[FILENAMELENGTH]; */
 6820: 	
 6821: /*   agelim=AGESUP; */
 6822: /*   /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
 6823: /*      in each health status at the date of interview (if between dateprev1 and dateprev2). */
 6824: /*      We still use firstpass and lastpass as another selection. */
 6825: /*   *\/ */
 6826: /*   /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
 6827: /*   /\* 	      firstpass, lastpass,  stepm,  weightopt, model); *\/ */
 6828: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
 6829: 	
 6830: /*   strcpy(fileresfb,"FB_");  */
 6831: /*   strcat(fileresfb,fileresu); */
 6832: /*   if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
 6833: /*     printf("Problem with back forecast resultfile: %s\n", fileresfb); */
 6834: /*     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
 6835: /*   } */
 6836: /*   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
 6837: /*   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
 6838: 	
 6839: /*   if (nqveff==0) ncodemax[nqveff]=1; */
 6840: 	
 6841: /*   /\* if (mobilav!=0) { *\/ */
 6842: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
 6843: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
 6844: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
 6845: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
 6846: /*   /\*   } *\/ */
 6847: /*   /\* } *\/ */
 6848: 	
 6849: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
 6850: /*   if (stepm<=12) stepsize=1; */
 6851: /*   if(estepm < stepm){ */
 6852: /*     printf ("Problem %d lower than %d\n",estepm, stepm); */
 6853: /*   } */
 6854: /*   else  hstepm=estepm;    */
 6855: 	
 6856: /*   hstepm=hstepm/stepm;  */
 6857: /*   yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
 6858: /*                                fractional in yp1 *\/ */
 6859: /*   anprojmean=yp; */
 6860: /*   yp2=modf((yp1*12),&yp); */
 6861: /*   mprojmean=yp; */
 6862: /*   yp1=modf((yp2*30.5),&yp); */
 6863: /*   jprojmean=yp; */
 6864: /*   if(jprojmean==0) jprojmean=1; */
 6865: /*   if(mprojmean==0) jprojmean=1; */
 6866: 	
 6867: /*   i1=nqveff; */
 6868: /*   if (cptcovn < 1){i1=1;} */
 6869:   
 6870: /*   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);  */
 6871:   
 6872: /*   fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
 6873: 	
 6874: /* 	/\* 	      if (h==(int)(YEARM*yearp)){ *\/ */
 6875: /*   for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
 6876: /*     for(cptcod=1;cptcod<=ncodemax[nqveff];cptcod++){ */
 6877: /*       k=k+1; */
 6878: /*       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
 6879: /*       for(j=1;j<=nqveff;j++) { */
 6880: /* 				fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
 6881: /*       } */
 6882: /*       fprintf(ficresfb," yearbproj age"); */
 6883: /*       for(j=1; j<=nlstate+ndeath;j++){  */
 6884: /* 				for(i=1; i<=nlstate;i++) 	       */
 6885: /*           fprintf(ficresfb," p%d%d",i,j); */
 6886: /* 				fprintf(ficresfb," p.%d",j); */
 6887: /*       } */
 6888: /*       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {  */
 6889: /* 				/\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  *\/ */
 6890: /* 				fprintf(ficresfb,"\n"); */
 6891: /* 				fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);    */
 6892: /* 				for (agec=fage; agec>=(ageminpar-1); agec--){  */
 6893: /* 					nhstepm=(int) rint((agelim-agec)*YEARM/stepm);  */
 6894: /* 					nhstepm = nhstepm/hstepm;  */
 6895: /* 					p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
 6896: /* 					oldm=oldms;savm=savms; */
 6897: /* 					hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k); 	 */
 6898: /* 					for (h=0; h<=nhstepm; h++){ */
 6899: /* 						if (h*hstepm/YEARM*stepm ==yearp) { */
 6900: /*               fprintf(ficresfb,"\n"); */
 6901: /*               for(j=1;j<=nqveff;j++)  */
 6902: /*                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
 6903: /* 							fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
 6904: /* 						}  */
 6905: /* 						for(j=1; j<=nlstate+ndeath;j++) { */
 6906: /* 							ppij=0.; */
 6907: /* 							for(i=1; i<=nlstate;i++) { */
 6908: /* 								if (mobilav==1)  */
 6909: /* 									ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
 6910: /* 								else { */
 6911: /* 									ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
 6912: /* 								} */
 6913: /* 								if (h*hstepm/YEARM*stepm== yearp) { */
 6914: /* 									fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
 6915: /* 								} */
 6916: /* 							} /\* end i *\/ */
 6917: /* 							if (h*hstepm/YEARM*stepm==yearp) { */
 6918: /* 								fprintf(ficresfb," %.3f", ppij); */
 6919: /* 							} */
 6920: /* 						}/\* end j *\/ */
 6921: /* 					} /\* end h *\/ */
 6922: /* 					free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
 6923: /* 				} /\* end agec *\/ */
 6924: /*       } /\* end yearp *\/ */
 6925: /*     } /\* end cptcod *\/ */
 6926: /*   } /\* end  cptcov *\/ */
 6927: 	
 6928: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
 6929: 	
 6930: /*   fclose(ficresfb); */
 6931: /*   printf("End of Computing Back forecasting \n"); */
 6932: /*   fprintf(ficlog,"End of Computing Back forecasting\n"); */
 6933: 	
 6934: /* } */
 6935: 
 6936: /************** Forecasting *****not tested NB*************/
 6937: void populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){
 6938:   
 6939:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
 6940:   int *popage;
 6941:   double calagedatem, agelim, kk1, kk2;
 6942:   double *popeffectif,*popcount;
 6943:   double ***p3mat,***tabpop,***tabpopprev;
 6944:   /* double ***mobaverage; */
 6945:   char filerespop[FILENAMELENGTH];
 6946: 
 6947:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6948:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6949:   agelim=AGESUP;
 6950:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
 6951:   
 6952:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 6953:   
 6954:   
 6955:   strcpy(filerespop,"POP_"); 
 6956:   strcat(filerespop,fileresu);
 6957:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
 6958:     printf("Problem with forecast resultfile: %s\n", filerespop);
 6959:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
 6960:   }
 6961:   printf("Computing forecasting: result on file '%s' \n", filerespop);
 6962:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
 6963: 
 6964:   if (nqveff==0) ncodemax[nqveff]=1;
 6965: 
 6966:   /* if (mobilav!=0) { */
 6967:   /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 6968:   /*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ */
 6969:   /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
 6970:   /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
 6971:   /*   } */
 6972:   /* } */
 6973: 
 6974:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 6975:   if (stepm<=12) stepsize=1;
 6976:   
 6977:   agelim=AGESUP;
 6978:   
 6979:   hstepm=1;
 6980:   hstepm=hstepm/stepm; 
 6981: 	
 6982:   if (popforecast==1) {
 6983:     if((ficpop=fopen(popfile,"r"))==NULL) {
 6984:       printf("Problem with population file : %s\n",popfile);exit(0);
 6985:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
 6986:     } 
 6987:     popage=ivector(0,AGESUP);
 6988:     popeffectif=vector(0,AGESUP);
 6989:     popcount=vector(0,AGESUP);
 6990:     
 6991:     i=1;   
 6992:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
 6993:     
 6994:     imx=i;
 6995:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
 6996:   }
 6997:   
 6998:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
 6999:     for(cptcod=1;cptcod<=ncodemax[nqveff];cptcod++){
 7000:       k=k+1;
 7001:       fprintf(ficrespop,"\n#******");
 7002:       for(j=1;j<=nqveff;j++) {
 7003: 	fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7004:       }
 7005:       fprintf(ficrespop,"******\n");
 7006:       fprintf(ficrespop,"# Age");
 7007:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
 7008:       if (popforecast==1)  fprintf(ficrespop," [Population]");
 7009:       
 7010:       for (cpt=0; cpt<=0;cpt++) { 
 7011: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 7012: 	
 7013: 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 7014: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 7015: 	  nhstepm = nhstepm/hstepm; 
 7016: 	  
 7017: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 7018: 	  oldm=oldms;savm=savms;
 7019: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 7020: 	  
 7021: 	  for (h=0; h<=nhstepm; h++){
 7022: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 7023: 	      fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 7024: 	    } 
 7025: 	    for(j=1; j<=nlstate+ndeath;j++) {
 7026: 	      kk1=0.;kk2=0;
 7027: 	      for(i=1; i<=nlstate;i++) {	      
 7028: 		if (mobilav==1) 
 7029: 		  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
 7030: 		else {
 7031: 		  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
 7032: 		}
 7033: 	      }
 7034: 	      if (h==(int)(calagedatem+12*cpt)){
 7035: 		tabpop[(int)(agedeb)][j][cptcod]=kk1;
 7036: 		/*fprintf(ficrespop," %.3f", kk1);
 7037: 		  if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
 7038: 	      }
 7039: 	    }
 7040: 	    for(i=1; i<=nlstate;i++){
 7041: 	      kk1=0.;
 7042: 	      for(j=1; j<=nlstate;j++){
 7043: 		kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
 7044: 	      }
 7045: 	      tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
 7046: 	    }
 7047: 	    
 7048: 	    if (h==(int)(calagedatem+12*cpt))
 7049: 	      for(j=1; j<=nlstate;j++) 
 7050: 		fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
 7051: 	  }
 7052: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 7053: 	}
 7054:       }
 7055:       
 7056:       /******/
 7057:       
 7058:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
 7059: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 7060: 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 7061: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 7062: 	  nhstepm = nhstepm/hstepm; 
 7063: 	  
 7064: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 7065: 	  oldm=oldms;savm=savms;
 7066: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 7067: 	  for (h=0; h<=nhstepm; h++){
 7068: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 7069: 	      fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 7070: 	    } 
 7071: 	    for(j=1; j<=nlstate+ndeath;j++) {
 7072: 	      kk1=0.;kk2=0;
 7073: 	      for(i=1; i<=nlstate;i++) {	      
 7074: 		kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];	
 7075: 	      }
 7076: 	      if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);	
 7077: 	    }
 7078: 	  }
 7079: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 7080: 	}
 7081:       }
 7082:     } 
 7083:   }
 7084:   
 7085:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 7086:   
 7087:   if (popforecast==1) {
 7088:     free_ivector(popage,0,AGESUP);
 7089:     free_vector(popeffectif,0,AGESUP);
 7090:     free_vector(popcount,0,AGESUP);
 7091:   }
 7092:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 7093:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 7094:   fclose(ficrespop);
 7095: } /* End of popforecast */
 7096:  
 7097: int fileappend(FILE *fichier, char *optionfich)
 7098: {
 7099:   if((fichier=fopen(optionfich,"a"))==NULL) {
 7100:     printf("Problem with file: %s\n", optionfich);
 7101:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
 7102:     return (0);
 7103:   }
 7104:   fflush(fichier);
 7105:   return (1);
 7106: }
 7107: 
 7108: 
 7109: /**************** function prwizard **********************/
 7110: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
 7111: {
 7112: 
 7113:   /* Wizard to print covariance matrix template */
 7114: 
 7115:   char ca[32], cb[32];
 7116:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
 7117:   int numlinepar;
 7118: 
 7119:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 7120:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 7121:   for(i=1; i <=nlstate; i++){
 7122:     jj=0;
 7123:     for(j=1; j <=nlstate+ndeath; j++){
 7124:       if(j==i) continue;
 7125:       jj++;
 7126:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
 7127:       printf("%1d%1d",i,j);
 7128:       fprintf(ficparo,"%1d%1d",i,j);
 7129:       for(k=1; k<=ncovmodel;k++){
 7130: 	/* 	  printf(" %lf",param[i][j][k]); */
 7131: 	/* 	  fprintf(ficparo," %lf",param[i][j][k]); */
 7132: 	printf(" 0.");
 7133: 	fprintf(ficparo," 0.");
 7134:       }
 7135:       printf("\n");
 7136:       fprintf(ficparo,"\n");
 7137:     }
 7138:   }
 7139:   printf("# Scales (for hessian or gradient estimation)\n");
 7140:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
 7141:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
 7142:   for(i=1; i <=nlstate; i++){
 7143:     jj=0;
 7144:     for(j=1; j <=nlstate+ndeath; j++){
 7145:       if(j==i) continue;
 7146:       jj++;
 7147:       fprintf(ficparo,"%1d%1d",i,j);
 7148:       printf("%1d%1d",i,j);
 7149:       fflush(stdout);
 7150:       for(k=1; k<=ncovmodel;k++){
 7151: 	/* 	printf(" %le",delti3[i][j][k]); */
 7152: 	/* 	fprintf(ficparo," %le",delti3[i][j][k]); */
 7153: 	printf(" 0.");
 7154: 	fprintf(ficparo," 0.");
 7155:       }
 7156:       numlinepar++;
 7157:       printf("\n");
 7158:       fprintf(ficparo,"\n");
 7159:     }
 7160:   }
 7161:   printf("# Covariance matrix\n");
 7162: /* # 121 Var(a12)\n\ */
 7163: /* # 122 Cov(b12,a12) Var(b12)\n\ */
 7164: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 7165: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 7166: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 7167: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 7168: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 7169: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 7170:   fflush(stdout);
 7171:   fprintf(ficparo,"# Covariance matrix\n");
 7172:   /* # 121 Var(a12)\n\ */
 7173:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
 7174:   /* #   ...\n\ */
 7175:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
 7176:   
 7177:   for(itimes=1;itimes<=2;itimes++){
 7178:     jj=0;
 7179:     for(i=1; i <=nlstate; i++){
 7180:       for(j=1; j <=nlstate+ndeath; j++){
 7181: 	if(j==i) continue;
 7182: 	for(k=1; k<=ncovmodel;k++){
 7183: 	  jj++;
 7184: 	  ca[0]= k+'a'-1;ca[1]='\0';
 7185: 	  if(itimes==1){
 7186: 	    printf("#%1d%1d%d",i,j,k);
 7187: 	    fprintf(ficparo,"#%1d%1d%d",i,j,k);
 7188: 	  }else{
 7189: 	    printf("%1d%1d%d",i,j,k);
 7190: 	    fprintf(ficparo,"%1d%1d%d",i,j,k);
 7191: 	    /* 	printf(" %.5le",matcov[i][j]); */
 7192: 	  }
 7193: 	  ll=0;
 7194: 	  for(li=1;li <=nlstate; li++){
 7195: 	    for(lj=1;lj <=nlstate+ndeath; lj++){
 7196: 	      if(lj==li) continue;
 7197: 	      for(lk=1;lk<=ncovmodel;lk++){
 7198: 		ll++;
 7199: 		if(ll<=jj){
 7200: 		  cb[0]= lk +'a'-1;cb[1]='\0';
 7201: 		  if(ll<jj){
 7202: 		    if(itimes==1){
 7203: 		      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 7204: 		      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 7205: 		    }else{
 7206: 		      printf(" 0.");
 7207: 		      fprintf(ficparo," 0.");
 7208: 		    }
 7209: 		  }else{
 7210: 		    if(itimes==1){
 7211: 		      printf(" Var(%s%1d%1d)",ca,i,j);
 7212: 		      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
 7213: 		    }else{
 7214: 		      printf(" 0.");
 7215: 		      fprintf(ficparo," 0.");
 7216: 		    }
 7217: 		  }
 7218: 		}
 7219: 	      } /* end lk */
 7220: 	    } /* end lj */
 7221: 	  } /* end li */
 7222: 	  printf("\n");
 7223: 	  fprintf(ficparo,"\n");
 7224: 	  numlinepar++;
 7225: 	} /* end k*/
 7226:       } /*end j */
 7227:     } /* end i */
 7228:   } /* end itimes */
 7229: 
 7230: } /* end of prwizard */
 7231: /******************* Gompertz Likelihood ******************************/
 7232: double gompertz(double x[])
 7233: { 
 7234:   double A,B,L=0.0,sump=0.,num=0.;
 7235:   int i,n=0; /* n is the size of the sample */
 7236: 
 7237:   for (i=1;i<=imx ; i++) {
 7238:     sump=sump+weight[i];
 7239:     /*    sump=sump+1;*/
 7240:     num=num+1;
 7241:   }
 7242:  
 7243:  
 7244:   /* for (i=0; i<=imx; i++) 
 7245:      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]);*/
 7246: 
 7247:   for (i=1;i<=imx ; i++)
 7248:     {
 7249:       if (cens[i] == 1 && wav[i]>1)
 7250: 	A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
 7251:       
 7252:       if (cens[i] == 0 && wav[i]>1)
 7253: 	A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
 7254: 	     +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
 7255:       
 7256:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 7257:       if (wav[i] > 1 ) { /* ??? */
 7258: 	L=L+A*weight[i];
 7259: 	/* 	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]);*/
 7260:       }
 7261:     }
 7262: 
 7263:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 7264:  
 7265:   return -2*L*num/sump;
 7266: }
 7267: 
 7268: #ifdef GSL
 7269: /******************* Gompertz_f Likelihood ******************************/
 7270: double gompertz_f(const gsl_vector *v, void *params)
 7271: { 
 7272:   double A,B,LL=0.0,sump=0.,num=0.;
 7273:   double *x= (double *) v->data;
 7274:   int i,n=0; /* n is the size of the sample */
 7275: 
 7276:   for (i=0;i<=imx-1 ; i++) {
 7277:     sump=sump+weight[i];
 7278:     /*    sump=sump+1;*/
 7279:     num=num+1;
 7280:   }
 7281:  
 7282:  
 7283:   /* for (i=0; i<=imx; i++) 
 7284:      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]);*/
 7285:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
 7286:   for (i=1;i<=imx ; i++)
 7287:     {
 7288:       if (cens[i] == 1 && wav[i]>1)
 7289: 	A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
 7290:       
 7291:       if (cens[i] == 0 && wav[i]>1)
 7292: 	A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
 7293: 	     +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
 7294:       
 7295:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 7296:       if (wav[i] > 1 ) { /* ??? */
 7297: 	LL=LL+A*weight[i];
 7298: 	/* 	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]);*/
 7299:       }
 7300:     }
 7301: 
 7302:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 7303:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
 7304:  
 7305:   return -2*LL*num/sump;
 7306: }
 7307: #endif
 7308: 
 7309: /******************* Printing html file ***********/
 7310: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
 7311: 		  int lastpass, int stepm, int weightopt, char model[],\
 7312: 		  int imx,  double p[],double **matcov,double agemortsup){
 7313:   int i,k;
 7314: 
 7315:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
 7316:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
 7317:   for (i=1;i<=2;i++) 
 7318:     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]));
 7319:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
 7320:   fprintf(fichtm,"</ul>");
 7321: 
 7322: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
 7323: 
 7324:  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>");
 7325: 
 7326:  for (k=agegomp;k<(agemortsup-2);k++) 
 7327:    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]);
 7328: 
 7329:  
 7330:   fflush(fichtm);
 7331: }
 7332: 
 7333: /******************* Gnuplot file **************/
 7334: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 7335: 
 7336:   char dirfileres[132],optfileres[132];
 7337: 
 7338:   int ng;
 7339: 
 7340: 
 7341:   /*#ifdef windows */
 7342:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 7343:     /*#endif */
 7344: 
 7345: 
 7346:   strcpy(dirfileres,optionfilefiname);
 7347:   strcpy(optfileres,"vpl");
 7348:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
 7349:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
 7350:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
 7351:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
 7352:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
 7353: 
 7354: } 
 7355: 
 7356: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
 7357: {
 7358: 
 7359:   /*-------- data file ----------*/
 7360:   FILE *fic;
 7361:   char dummy[]="                         ";
 7362:   int i=0, j=0, n=0, iv=0;
 7363:   int lstra;
 7364:   int linei, month, year,iout;
 7365:   char line[MAXLINE], linetmp[MAXLINE];
 7366:   char stra[MAXLINE], strb[MAXLINE];
 7367:   char *stratrunc;
 7368: 
 7369: 
 7370: 
 7371:   if((fic=fopen(datafile,"r"))==NULL)    {
 7372:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
 7373:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
 7374:   }
 7375: 
 7376:   i=1;
 7377:   linei=0;
 7378:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
 7379:     linei=linei+1;
 7380:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
 7381:       if(line[j] == '\t')
 7382: 	line[j] = ' ';
 7383:     }
 7384:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
 7385:       ;
 7386:     };
 7387:     line[j+1]=0;  /* Trims blanks at end of line */
 7388:     if(line[0]=='#'){
 7389:       fprintf(ficlog,"Comment line\n%s\n",line);
 7390:       printf("Comment line\n%s\n",line);
 7391:       continue;
 7392:     }
 7393:     trimbb(linetmp,line); /* Trims multiple blanks in line */
 7394:     strcpy(line, linetmp);
 7395:     
 7396:     /* Loops on waves */
 7397:     for (j=maxwav;j>=1;j--){
 7398:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
 7399: 				cutv(stra, strb, line, ' '); 
 7400: 				if(strb[0]=='.') { /* Missing value */
 7401: 					lval=-1;
 7402: 				}else{
 7403: 					errno=0;
 7404: 					/* what_kind_of_number(strb); */
 7405: 					dval=strtod(strb,&endptr); 
 7406: 					/* if( strb[0]=='\0' || (*endptr != '\0')){ */
 7407: 					/* if(strb != endptr && *endptr == '\0') */
 7408: 					/*    dval=dlval; */
 7409: 					/* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
 7410: 					if( strb[0]=='\0' || (*endptr != '\0')){
 7411: 						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);
 7412: 						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);
 7413: 						return 1;
 7414: 					}
 7415: 					cotqvar[j][iv][i]=dval; 
 7416: 				}
 7417: 				strcpy(line,stra);
 7418:       }/* end loop ntqv */
 7419: 			
 7420:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
 7421: 				cutv(stra, strb, line, ' '); 
 7422: 				if(strb[0]=='.') { /* Missing value */
 7423: 					lval=-1;
 7424: 				}else{
 7425: 					errno=0;
 7426: 					lval=strtol(strb,&endptr,10); 
 7427: 					/*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
 7428: 					if( strb[0]=='\0' || (*endptr != '\0')){
 7429: 						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);
 7430: 						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);
 7431: 						return 1;
 7432: 					}
 7433: 				}
 7434: 				if(lval <-1 || lval >1){
 7435: 					printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 7436:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 7437:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 7438:  For example, for multinomial values like 1, 2 and 3,\n									\
 7439:  build V1=0 V2=0 for the reference value (1),\n													\
 7440:         V1=1 V2=0 for (2) \n																						\
 7441:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 7442:  output of IMaCh is often meaningless.\n																\
 7443:  Exiting.\n",lval,linei, i,line,j);
 7444: 					fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 7445:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 7446:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 7447:  For example, for multinomial values like 1, 2 and 3,\n									\
 7448:  build V1=0 V2=0 for the reference value (1),\n													\
 7449:         V1=1 V2=0 for (2) \n																						\
 7450:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 7451:  output of IMaCh is often meaningless.\n				\
 7452:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
 7453: 					return 1;
 7454: 				}
 7455: 				cotvar[j][iv][i]=(double)(lval);
 7456: 				strcpy(line,stra);
 7457:       }/* end loop ntv */
 7458: 
 7459:       /* Statuses  at wave */
 7460:       cutv(stra, strb, line, ' '); 
 7461:       if(strb[0]=='.') { /* Missing value */
 7462: 				lval=-1;
 7463:       }else{
 7464: 				errno=0;
 7465: 				lval=strtol(strb,&endptr,10); 
 7466: 				/*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
 7467: 				if( strb[0]=='\0' || (*endptr != '\0')){
 7468: 					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);
 7469: 					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);
 7470: 					return 1;
 7471: 				}
 7472:       }
 7473:      
 7474:       s[j][i]=lval;
 7475: 
 7476:       /* Date of Interview */
 7477:       strcpy(line,stra);
 7478:       cutv(stra, strb,line,' ');
 7479:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 7480:       }
 7481:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 7482: 				month=99;
 7483: 				year=9999;
 7484:       }else{
 7485: 				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);
 7486: 				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);
 7487: 				return 1;
 7488:       }
 7489:       anint[j][i]= (double) year; 
 7490:       mint[j][i]= (double)month; 
 7491:       strcpy(line,stra);
 7492:     } /* End loop on waves */
 7493: 
 7494:     /* Date of death */
 7495:     cutv(stra, strb,line,' '); 
 7496:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 7497:     }
 7498:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 7499:       month=99;
 7500:       year=9999;
 7501:     }else{
 7502:       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);
 7503: 			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);
 7504: 			return 1;
 7505:     }
 7506:     andc[i]=(double) year; 
 7507:     moisdc[i]=(double) month; 
 7508:     strcpy(line,stra);
 7509:     
 7510:     /* Date of birth */
 7511:     cutv(stra, strb,line,' '); 
 7512:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 7513:     }
 7514:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
 7515:       month=99;
 7516:       year=9999;
 7517:     }else{
 7518:       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);
 7519:       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);
 7520: 			return 1;
 7521:     }
 7522:     if (year==9999) {
 7523:       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);
 7524:       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);
 7525: 			return 1;
 7526: 
 7527:     }
 7528:     annais[i]=(double)(year);
 7529:     moisnais[i]=(double)(month); 
 7530:     strcpy(line,stra);
 7531: 
 7532:     /* Sample weight */
 7533:     cutv(stra, strb,line,' '); 
 7534:     errno=0;
 7535:     dval=strtod(strb,&endptr); 
 7536:     if( strb[0]=='\0' || (*endptr != '\0')){
 7537:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
 7538:       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);
 7539:       fflush(ficlog);
 7540:       return 1;
 7541:     }
 7542:     weight[i]=dval; 
 7543:     strcpy(line,stra);
 7544: 
 7545:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
 7546:       cutv(stra, strb, line, ' '); 
 7547:       if(strb[0]=='.') { /* Missing value */
 7548: 				lval=-1;
 7549:       }else{
 7550: 				errno=0;
 7551: 				/* what_kind_of_number(strb); */
 7552: 				dval=strtod(strb,&endptr);
 7553: 				/* if(strb != endptr && *endptr == '\0') */
 7554: 				/*   dval=dlval; */
 7555: 				/* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
 7556: 				if( strb[0]=='\0' || (*endptr != '\0')){
 7557: 					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);
 7558: 					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);
 7559: 					return 1;
 7560: 				}
 7561: 				coqvar[iv][i]=dval; 
 7562:       }
 7563:       strcpy(line,stra);
 7564:     }/* end loop nqv */
 7565:     
 7566:     /* Covariate values */
 7567:     for (j=ncovcol;j>=1;j--){
 7568:       cutv(stra, strb,line,' '); 
 7569:       if(strb[0]=='.') { /* Missing covariate value */
 7570: 				lval=-1;
 7571:       }else{
 7572: 				errno=0;
 7573: 				lval=strtol(strb,&endptr,10); 
 7574: 				if( strb[0]=='\0' || (*endptr != '\0')){
 7575: 					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);
 7576: 					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);
 7577: 					return 1;
 7578: 				}
 7579:       }
 7580:       if(lval <-1 || lval >1){
 7581: 				printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 7582:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 7583:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 7584:  For example, for multinomial values like 1, 2 and 3,\n \
 7585:  build V1=0 V2=0 for the reference value (1),\n \
 7586:         V1=1 V2=0 for (2) \n \
 7587:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 7588:  output of IMaCh is often meaningless.\n \
 7589:  Exiting.\n",lval,linei, i,line,j);
 7590: 				fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 7591:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 7592:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 7593:  For example, for multinomial values like 1, 2 and 3,\n \
 7594:  build V1=0 V2=0 for the reference value (1),\n \
 7595:         V1=1 V2=0 for (2) \n \
 7596:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 7597:  output of IMaCh is often meaningless.\n \
 7598:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
 7599: 				return 1;
 7600:       }
 7601:       covar[j][i]=(double)(lval);
 7602:       strcpy(line,stra);
 7603:     }  
 7604:     lstra=strlen(stra);
 7605:      
 7606:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
 7607:       stratrunc = &(stra[lstra-9]);
 7608:       num[i]=atol(stratrunc);
 7609:     }
 7610:     else
 7611:       num[i]=atol(stra);
 7612:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
 7613:       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;}*/
 7614:     
 7615:     i=i+1;
 7616:   } /* End loop reading  data */
 7617: 
 7618:   *imax=i-1; /* Number of individuals */
 7619:   fclose(fic);
 7620:  
 7621:   return (0);
 7622:   /* endread: */
 7623: 	printf("Exiting readdata: ");
 7624: 	fclose(fic);
 7625: 	return (1);
 7626: }
 7627: 
 7628: void removespace(char *str) {
 7629:   char *p1 = str, *p2 = str;
 7630:   do
 7631:     while (*p2 == ' ')
 7632:       p2++;
 7633:   while (*p1++ == *p2++);
 7634: }
 7635: 
 7636: int decodemodel ( char model[], int lastobs)
 7637:  /**< This routine decode the model and returns:
 7638: 	* Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
 7639: 	* - nagesqr = 1 if age*age in the model, otherwise 0.
 7640: 	* - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
 7641: 	* - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
 7642: 	* - cptcovage number of covariates with age*products =2
 7643: 	* - cptcovs number of simple covariates
 7644: 	* - 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
 7645: 	*     which is a new column after the 9 (ncovcol) variables. 
 7646: 	* - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
 7647: 	* - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
 7648: 	*    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
 7649: 	* - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
 7650: 	*/
 7651: {
 7652:   int i, j, k, ks;
 7653:   int  j1, k1, k2;
 7654:   char modelsav[80];
 7655:   char stra[80], strb[80], strc[80], strd[80],stre[80];
 7656:   char *strpt;
 7657: 
 7658:   /*removespace(model);*/
 7659:   if (strlen(model) >1){ /* If there is at least 1 covariate */
 7660:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
 7661:     if (strstr(model,"AGE") !=0){
 7662:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
 7663:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
 7664:       return 1;
 7665:     }
 7666:     if (strstr(model,"v") !=0){
 7667:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
 7668:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
 7669:       return 1;
 7670:     }
 7671:     strcpy(modelsav,model); 
 7672:     if ((strpt=strstr(model,"age*age")) !=0){
 7673:       printf(" strpt=%s, model=%s\n",strpt, model);
 7674:       if(strpt != model){
 7675: 				printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
 7676:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
 7677:  corresponding column of parameters.\n",model);
 7678: 				fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
 7679:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
 7680:  corresponding column of parameters.\n",model); fflush(ficlog);
 7681: 				return 1;
 7682: 			}
 7683: 
 7684:       nagesqr=1;
 7685:       if (strstr(model,"+age*age") !=0)
 7686: 				substrchaine(modelsav, model, "+age*age");
 7687:       else if (strstr(model,"age*age+") !=0)
 7688: 				substrchaine(modelsav, model, "age*age+");
 7689:       else 
 7690: 				substrchaine(modelsav, model, "age*age");
 7691:     }else
 7692:       nagesqr=0;
 7693:     if (strlen(modelsav) >1){
 7694:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
 7695:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
 7696:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
 7697:       cptcovt= j+1; /* Number of total covariates in the model, not including
 7698: 										 * cst, age and age*age 
 7699: 										 * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
 7700: 			/* including age products which are counted in cptcovage.
 7701: 			 * but the covariates which are products must be treated 
 7702: 			 * separately: ncovn=4- 2=2 (V1+V3). */
 7703:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
 7704:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
 7705: 
 7706:     
 7707:       /*   Design
 7708:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
 7709:        *  <          ncovcol=8                >
 7710:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
 7711:        *   k=  1    2      3       4     5       6      7        8
 7712:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
 7713:        *  covar[k,i], value of kth covariate if not including age for individual i:
 7714:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
 7715:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
 7716:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
 7717:        *  Tage[++cptcovage]=k
 7718:        *       if products, new covar are created after ncovcol with k1
 7719:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
 7720:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
 7721:        *  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
 7722:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
 7723:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
 7724:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
 7725:        *  <          ncovcol=8                >
 7726:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
 7727:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
 7728:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
 7729:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 7730:        * p Tprod[1]@2={                         6, 5}
 7731:        *p Tvard[1][1]@4= {7, 8, 5, 6}
 7732:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
 7733:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 7734:        *How to reorganize?
 7735:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
 7736:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 7737:        *       {2,   1,     4,      8,    5,      6,     3,       7}
 7738:        * Struct []
 7739:        */
 7740: 
 7741:       /* This loop fills the array Tvar from the string 'model'.*/
 7742:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
 7743:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
 7744:       /* 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
 7745:       /* 	k=3 V4 Tvar[k=3]= 4 (from V4) */
 7746:       /* 	k=2 V1 Tvar[k=2]= 1 (from V1) */
 7747:       /* 	k=1 Tvar[1]=2 (from V2) */
 7748:       /* 	k=5 Tvar[5] */
 7749:       /* for (k=1; k<=cptcovn;k++) { */
 7750:       /* 	cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 7751:       /* 	} */
 7752:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
 7753:       /*
 7754:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
 7755:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
 7756:         Tvar[k]=0;
 7757:       cptcovage=0;
 7758:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
 7759: 				cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
 7760: 																				 modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
 7761: 				if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
 7762: 				/*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
 7763: 				/*scanf("%d",i);*/
 7764: 				if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
 7765: 					cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
 7766: 					if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
 7767: 						/* covar is not filled and then is empty */
 7768: 						cptcovprod--;
 7769: 						cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
 7770: 						Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
 7771: 						cptcovage++; /* Sums the number of covariates which include age as a product */
 7772: 						Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
 7773: 						/*printf("stre=%s ", stre);*/
 7774: 					} else if (strcmp(strd,"age")==0) { /* or age*Vn */
 7775: 						cptcovprod--;
 7776: 						cutl(stre,strb,strc,'V');
 7777: 						Tvar[k]=atoi(stre);
 7778: 						cptcovage++;
 7779: 						Tage[cptcovage]=k;
 7780: 					} else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
 7781: 						/* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
 7782: 						cptcovn++;
 7783: 						cptcovprodnoage++;k1++;
 7784: 						cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
 7785: 						Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
 7786: 																	 because this model-covariate is a construction we invent a new column
 7787: 																	 ncovcol + k1
 7788: 																	 If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
 7789: 																	 Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
 7790: 						cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
 7791: 						Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
 7792: 						Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
 7793: 						Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
 7794: 						k2=k2+2;
 7795: 						Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
 7796: 						Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
 7797: 						for (i=1; i<=lastobs;i++){
 7798: 							/* Computes the new covariate which is a product of
 7799: 								 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
 7800: 							covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
 7801: 						}
 7802: 					} /* End age is not in the model */
 7803: 				} /* End if model includes a product */
 7804: 				else { /* no more sum */
 7805: 					/*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
 7806: 					/*  scanf("%d",i);*/
 7807: 					cutl(strd,strc,strb,'V');
 7808: 					ks++; /**< Number of simple covariates */
 7809: 					cptcovn++;
 7810: 					Tvar[k]=atoi(strd);
 7811: 				}
 7812: 				strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
 7813: 				/*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
 7814: 					scanf("%d",i);*/
 7815:       } /* end of loop + on total covariates */
 7816:     } /* end if strlen(modelsave == 0) age*age might exist */
 7817:   } /* end if strlen(model == 0) */
 7818:   
 7819:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
 7820:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
 7821: 
 7822:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
 7823: 		 printf("cptcovprod=%d ", cptcovprod);
 7824: 		 fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
 7825: 
 7826: 		 scanf("%d ",i);*/
 7827: /* Dispatching in quantitative and time varying covariates */
 7828: 
 7829: 	for(k=1, ncoveff=0, nqveff=0, ntveff=0, nqtveff=0;k<=cptcovn; k++){ /* or cptocvt */
 7830: 		if (Tvar[k] <=ncovcol){
 7831: 			ncoveff++;
 7832: 		}else if( Tvar[k] <=ncovcol+nqv){
 7833: 			nqveff++;
 7834: 		}else if( Tvar[k] <=ncovcol+nqv+ntv){
 7835: 			ntveff++;
 7836: 		}else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
 7837: 			nqtveff++;
 7838: 		}else
 7839: 			printf("Error in effective covariates \n");
 7840: 	}
 7841: 
 7842:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
 7843:   /*endread:*/
 7844: 	printf("Exiting decodemodel: ");
 7845: 	return (1);
 7846: }
 7847: 
 7848: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
 7849: {
 7850:   int i, m;
 7851:   int firstone=0;
 7852:   
 7853:   for (i=1; i<=imx; i++) {
 7854:     for(m=2; (m<= maxwav); m++) {
 7855:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
 7856: 	anint[m][i]=9999;
 7857: 	if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
 7858: 	  s[m][i]=-1;
 7859:       }
 7860:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
 7861: 	*nberr = *nberr + 1;
 7862: 	if(firstone == 0){
 7863: 	  firstone=1;
 7864: 	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);
 7865: 	}
 7866: 	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);
 7867: 	s[m][i]=-1;
 7868:       }
 7869:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
 7870: 	(*nberr)++;
 7871: 	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]); 
 7872: 	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]); 
 7873: 	s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
 7874:       }
 7875:     }
 7876:   }
 7877: 
 7878:   for (i=1; i<=imx; i++)  {
 7879:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
 7880:     for(m=firstpass; (m<= lastpass); m++){
 7881:       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 */
 7882: 	if (s[m][i] >= nlstate+1) {
 7883: 	  if(agedc[i]>0){
 7884: 	    if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
 7885: 	      agev[m][i]=agedc[i];
 7886: 	      /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
 7887: 	    }else {
 7888: 	      if ((int)andc[i]!=9999){
 7889: 		nbwarn++;
 7890: 		printf("Warning negative age at death: %ld line:%d\n",num[i],i);
 7891: 		fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
 7892: 		agev[m][i]=-1;
 7893: 	      }
 7894: 	    }
 7895: 	  } /* agedc > 0 */
 7896: 	} /* end if */
 7897: 	else if(s[m][i] !=9){ /* Standard case, age in fractional
 7898: 				 years but with the precision of a month */
 7899: 	  agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
 7900: 	  if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
 7901: 	    agev[m][i]=1;
 7902: 	  else if(agev[m][i] < *agemin){ 
 7903: 	    *agemin=agev[m][i];
 7904: 	    printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
 7905: 	  }
 7906: 	  else if(agev[m][i] >*agemax){
 7907: 	    *agemax=agev[m][i];
 7908: 	    /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
 7909: 	  }
 7910: 	  /*agev[m][i]=anint[m][i]-annais[i];*/
 7911: 	  /*	 agev[m][i] = age[i]+2*m;*/
 7912: 	} /* en if 9*/
 7913: 	else { /* =9 */
 7914: 	  /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
 7915: 	  agev[m][i]=1;
 7916: 	  s[m][i]=-1;
 7917: 	}
 7918:       }
 7919:       else if(s[m][i]==0) /*= 0 Unknown */
 7920: 	agev[m][i]=1;
 7921:       else{
 7922: 	printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
 7923: 	fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
 7924: 	agev[m][i]=0;
 7925:       }
 7926:     } /* End for lastpass */
 7927:   }
 7928:     
 7929:   for (i=1; i<=imx; i++)  {
 7930:     for(m=firstpass; (m<=lastpass); m++){
 7931:       if (s[m][i] > (nlstate+ndeath)) {
 7932: 	(*nberr)++;
 7933: 	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);	
 7934: 	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);	
 7935: 	return 1;
 7936:       }
 7937:     }
 7938:   }
 7939: 
 7940:   /*for (i=1; i<=imx; i++){
 7941:   for (m=firstpass; (m<lastpass); m++){
 7942:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
 7943: }
 7944: 
 7945: }*/
 7946: 
 7947: 
 7948:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
 7949:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
 7950: 
 7951:   return (0);
 7952:  /* endread:*/
 7953:     printf("Exiting calandcheckages: ");
 7954:     return (1);
 7955: }
 7956: 
 7957: #if defined(_MSC_VER)
 7958: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 7959: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 7960: //#include "stdafx.h"
 7961: //#include <stdio.h>
 7962: //#include <tchar.h>
 7963: //#include <windows.h>
 7964: //#include <iostream>
 7965: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
 7966: 
 7967: LPFN_ISWOW64PROCESS fnIsWow64Process;
 7968: 
 7969: BOOL IsWow64()
 7970: {
 7971: 	BOOL bIsWow64 = FALSE;
 7972: 
 7973: 	//typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
 7974: 	//  (HANDLE, PBOOL);
 7975: 
 7976: 	//LPFN_ISWOW64PROCESS fnIsWow64Process;
 7977: 
 7978: 	HMODULE module = GetModuleHandle(_T("kernel32"));
 7979: 	const char funcName[] = "IsWow64Process";
 7980: 	fnIsWow64Process = (LPFN_ISWOW64PROCESS)
 7981: 		GetProcAddress(module, funcName);
 7982: 
 7983: 	if (NULL != fnIsWow64Process)
 7984: 	{
 7985: 		if (!fnIsWow64Process(GetCurrentProcess(),
 7986: 			&bIsWow64))
 7987: 			//throw std::exception("Unknown error");
 7988: 			printf("Unknown error\n");
 7989: 	}
 7990: 	return bIsWow64 != FALSE;
 7991: }
 7992: #endif
 7993: 
 7994: void syscompilerinfo(int logged)
 7995:  {
 7996:    /* #include "syscompilerinfo.h"*/
 7997:    /* command line Intel compiler 32bit windows, XP compatible:*/
 7998:    /* /GS /W3 /Gy
 7999:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
 8000:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
 8001:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
 8002:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
 8003:    */ 
 8004:    /* 64 bits */
 8005:    /*
 8006:      /GS /W3 /Gy
 8007:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
 8008:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
 8009:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
 8010:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
 8011:    /* Optimization are useless and O3 is slower than O2 */
 8012:    /*
 8013:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
 8014:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
 8015:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
 8016:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
 8017:    */
 8018:    /* Link is */ /* /OUT:"visual studio
 8019:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
 8020:       /PDB:"visual studio
 8021:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
 8022:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
 8023:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
 8024:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
 8025:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
 8026:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
 8027:       uiAccess='false'"
 8028:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
 8029:       /NOLOGO /TLBID:1
 8030:    */
 8031: #if defined __INTEL_COMPILER
 8032: #if defined(__GNUC__)
 8033: 	struct utsname sysInfo;  /* For Intel on Linux and OS/X */
 8034: #endif
 8035: #elif defined(__GNUC__) 
 8036: #ifndef  __APPLE__
 8037: #include <gnu/libc-version.h>  /* Only on gnu */
 8038: #endif
 8039:    struct utsname sysInfo;
 8040:    int cross = CROSS;
 8041:    if (cross){
 8042: 	   printf("Cross-");
 8043: 	   if(logged) fprintf(ficlog, "Cross-");
 8044:    }
 8045: #endif
 8046: 
 8047: #include <stdint.h>
 8048: 
 8049:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
 8050: #if defined(__clang__)
 8051:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");	/* Clang/LLVM. ---------------------------------------------- */
 8052: #endif
 8053: #if defined(__ICC) || defined(__INTEL_COMPILER)
 8054:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
 8055: #endif
 8056: #if defined(__GNUC__) || defined(__GNUG__)
 8057:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
 8058: #endif
 8059: #if defined(__HP_cc) || defined(__HP_aCC)
 8060:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
 8061: #endif
 8062: #if defined(__IBMC__) || defined(__IBMCPP__)
 8063:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
 8064: #endif
 8065: #if defined(_MSC_VER)
 8066:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
 8067: #endif
 8068: #if defined(__PGI)
 8069:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
 8070: #endif
 8071: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
 8072:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
 8073: #endif
 8074:    printf(" for "); if (logged) fprintf(ficlog, " for ");
 8075:    
 8076: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
 8077: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
 8078:     // Windows (x64 and x86)
 8079:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
 8080: #elif __unix__ // all unices, not all compilers
 8081:     // Unix
 8082:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
 8083: #elif __linux__
 8084:     // linux
 8085:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
 8086: #elif __APPLE__
 8087:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
 8088:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
 8089: #endif
 8090: 
 8091: /*  __MINGW32__	  */
 8092: /*  __CYGWIN__	 */
 8093: /* __MINGW64__  */
 8094: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
 8095: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
 8096: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
 8097: /* _WIN64  // Defined for applications for Win64. */
 8098: /* _M_X64 // Defined for compilations that target x64 processors. */
 8099: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
 8100: 
 8101: #if UINTPTR_MAX == 0xffffffff
 8102:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
 8103: #elif UINTPTR_MAX == 0xffffffffffffffff
 8104:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
 8105: #else
 8106:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
 8107: #endif
 8108: 
 8109: #if defined(__GNUC__)
 8110: # if defined(__GNUC_PATCHLEVEL__)
 8111: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 8112:                             + __GNUC_MINOR__ * 100 \
 8113:                             + __GNUC_PATCHLEVEL__)
 8114: # else
 8115: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 8116:                             + __GNUC_MINOR__ * 100)
 8117: # endif
 8118:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
 8119:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
 8120: 
 8121:    if (uname(&sysInfo) != -1) {
 8122:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 8123: 	 if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 8124:    }
 8125:    else
 8126:       perror("uname() error");
 8127:    //#ifndef __INTEL_COMPILER 
 8128: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
 8129:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
 8130:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
 8131: #endif
 8132: #endif
 8133: 
 8134:    //   void main()
 8135:    //   {
 8136: #if defined(_MSC_VER)
 8137:    if (IsWow64()){
 8138: 	   printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 8139: 	   if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 8140:    }
 8141:    else{
 8142: 	   printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 8143: 	   if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 8144:    }
 8145:    //	   printf("\nPress Enter to continue...");
 8146:    //	   getchar();
 8147:    //   }
 8148: 
 8149: #endif
 8150:    
 8151: 
 8152: }
 8153: 
 8154: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
 8155:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 8156:   int i, j, k, i1 ;
 8157:   /* double ftolpl = 1.e-10; */
 8158:   double age, agebase, agelim;
 8159:   double tot;
 8160: 
 8161:   strcpy(filerespl,"PL_");
 8162:   strcat(filerespl,fileresu);
 8163:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
 8164:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
 8165:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
 8166:   }
 8167:   printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
 8168:   fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
 8169:   pstamp(ficrespl);
 8170:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
 8171:   fprintf(ficrespl,"#Age ");
 8172:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
 8173:   fprintf(ficrespl,"\n");
 8174:   
 8175:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
 8176: 
 8177:   agebase=ageminpar;
 8178:   agelim=agemaxpar;
 8179: 
 8180:   i1=pow(2,ncoveff);
 8181:   if (cptcovn < 1){i1=1;}
 8182: 
 8183:   for(k=1; k<=i1;k++){
 8184:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 8185:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
 8186:     //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 8187:     /* k=k+1; */
 8188:     /* to clean */
 8189:     //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
 8190:     fprintf(ficrespl,"#******");
 8191:     printf("#******");
 8192:     fprintf(ficlog,"#******");
 8193:     for(j=1;j<=nqveff;j++) {
 8194:       fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8195:       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8196:       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8197:     }
 8198:     fprintf(ficrespl,"******\n");
 8199:     printf("******\n");
 8200:     fprintf(ficlog,"******\n");
 8201: 		if(invalidvarcomb[k]){
 8202: 						printf("\nCombination (%d) ignored because no cases \n",k); 
 8203: 						fprintf(ficrespl,"#Combination (%d) ignored because no cases \n",k); 
 8204: 						fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
 8205: 						continue;
 8206: 		}
 8207: 
 8208:     fprintf(ficrespl,"#Age ");
 8209:     for(j=1;j<=nqveff;j++) {
 8210:       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8211:     }
 8212:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
 8213:     fprintf(ficrespl,"Total Years_to_converge\n");
 8214: 	
 8215:     for (age=agebase; age<=agelim; age++){
 8216:       /* for (age=agebase; age<=agebase; age++){ */
 8217:       prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
 8218:       fprintf(ficrespl,"%.0f ",age );
 8219:       for(j=1;j<=nqveff;j++)
 8220: 							fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8221:       tot=0.;
 8222:       for(i=1; i<=nlstate;i++){
 8223: 							tot +=  prlim[i][i];
 8224: 							fprintf(ficrespl," %.5f", prlim[i][i]);
 8225:       }
 8226:       fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
 8227:     } /* Age */
 8228:     /* was end of cptcod */
 8229:   } /* cptcov */
 8230:   return 0;
 8231: }
 8232: 
 8233: 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){
 8234: 	/*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
 8235: 	
 8236: 	/* Computes the back prevalence limit  for any combination	of covariate values 
 8237:    * at any age between ageminpar and agemaxpar
 8238: 	 */
 8239:   int i, j, k, i1 ;
 8240:   /* double ftolpl = 1.e-10; */
 8241:   double age, agebase, agelim;
 8242:   double tot;
 8243:   /* double ***mobaverage; */
 8244:   /* double	 **dnewm, **doldm, **dsavm;  /\* for use *\/ */
 8245: 
 8246:   strcpy(fileresplb,"PLB_");
 8247:   strcat(fileresplb,fileresu);
 8248:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
 8249:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
 8250:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
 8251:   }
 8252:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
 8253:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
 8254:   pstamp(ficresplb);
 8255:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
 8256:   fprintf(ficresplb,"#Age ");
 8257:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
 8258:   fprintf(ficresplb,"\n");
 8259:   
 8260:   
 8261:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
 8262:   
 8263:   agebase=ageminpar;
 8264:   agelim=agemaxpar;
 8265:   
 8266:   
 8267:   i1=pow(2,nqveff);
 8268:   if (cptcovn < 1){i1=1;}
 8269: 
 8270: 	for(k=1; k<=i1;k++){ 
 8271:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 8272:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
 8273:     //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 8274:     /* k=k+1; */
 8275:     /* to clean */
 8276:     //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
 8277:     fprintf(ficresplb,"#******");
 8278:     printf("#******");
 8279:     fprintf(ficlog,"#******");
 8280:     for(j=1;j<=nqveff;j++) {
 8281:       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8282:       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8283:       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8284:     }
 8285:     fprintf(ficresplb,"******\n");
 8286:     printf("******\n");
 8287:     fprintf(ficlog,"******\n");
 8288: 		if(invalidvarcomb[k]){
 8289: 						printf("\nCombination (%d) ignored because no cases \n",k); 
 8290: 						fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
 8291: 						fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
 8292: 						continue;
 8293: 		}
 8294:     
 8295:     fprintf(ficresplb,"#Age ");
 8296:     for(j=1;j<=nqveff;j++) {
 8297:       fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8298:     }
 8299:     for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
 8300:     fprintf(ficresplb,"Total Years_to_converge\n");
 8301:     
 8302:     
 8303:     for (age=agebase; age<=agelim; age++){
 8304:       /* for (age=agebase; age<=agebase; age++){ */
 8305:       if(mobilavproj > 0){
 8306: 	/* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
 8307: 	/* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
 8308: 				bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k);
 8309:       }else if (mobilavproj == 0){
 8310: 				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);
 8311: 				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);
 8312: 				exit(1);
 8313:       }else{
 8314: 				/* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
 8315: 				bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k);
 8316:       }
 8317:       fprintf(ficresplb,"%.0f ",age );
 8318:       for(j=1;j<=nqveff;j++)
 8319: 				fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8320:       tot=0.;
 8321:       for(i=1; i<=nlstate;i++){
 8322: 				tot +=  bprlim[i][i];
 8323: 				fprintf(ficresplb," %.5f", bprlim[i][i]);
 8324:       }
 8325:       fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
 8326:     } /* Age */
 8327:     /* was end of cptcod */
 8328:   } /* cptcov */
 8329:   
 8330:   /* hBijx(p, bage, fage); */
 8331:   /* fclose(ficrespijb); */
 8332:   
 8333:   return 0;
 8334: }
 8335:  
 8336: int hPijx(double *p, int bage, int fage){
 8337:     /*------------- h Pij x at various ages ------------*/
 8338: 
 8339:   int stepsize;
 8340:   int agelim;
 8341:   int hstepm;
 8342:   int nhstepm;
 8343:   int h, i, i1, j, k;
 8344: 
 8345:   double agedeb;
 8346:   double ***p3mat;
 8347: 
 8348:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
 8349:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
 8350:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
 8351:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
 8352:     }
 8353:     printf("Computing pij: result on file '%s' \n", filerespij);
 8354:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
 8355:   
 8356:     stepsize=(int) (stepm+YEARM-1)/YEARM;
 8357:     /*if (stepm<=24) stepsize=2;*/
 8358: 
 8359:     agelim=AGESUP;
 8360:     hstepm=stepsize*YEARM; /* Every year of age */
 8361:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
 8362: 		
 8363:     /* hstepm=1;   aff par mois*/
 8364:     pstamp(ficrespij);
 8365:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
 8366:     i1= pow(2,nqveff);
 8367: 		/* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 8368: 		/*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
 8369: 		/*  	k=k+1;  */
 8370:     for (k=1; k <= (int) pow(2,nqveff); k++){
 8371:       fprintf(ficrespij,"\n#****** ");
 8372:       for(j=1;j<=nqveff;j++) 
 8373: 	fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8374:       fprintf(ficrespij,"******\n");
 8375:       
 8376:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
 8377: 	nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 8378: 	nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 8379: 	
 8380: 	/*	  nhstepm=nhstepm*YEARM; aff par mois*/
 8381: 	
 8382: 	p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 8383: 	oldm=oldms;savm=savms;
 8384: 	hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 8385: 	fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
 8386: 	for(i=1; i<=nlstate;i++)
 8387: 	  for(j=1; j<=nlstate+ndeath;j++)
 8388: 	    fprintf(ficrespij," %1d-%1d",i,j);
 8389: 	fprintf(ficrespij,"\n");
 8390: 	for (h=0; h<=nhstepm; h++){
 8391: 	  /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
 8392: 	  fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
 8393: 	  for(i=1; i<=nlstate;i++)
 8394: 	    for(j=1; j<=nlstate+ndeath;j++)
 8395: 	      fprintf(ficrespij," %.5f", p3mat[i][j][h]);
 8396: 	  fprintf(ficrespij,"\n");
 8397: 	}
 8398: 	free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 8399: 	fprintf(ficrespij,"\n");
 8400:       }
 8401:       /*}*/
 8402:     }
 8403:     return 0;
 8404: }
 8405:  
 8406:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
 8407:     /*------------- h Bij x at various ages ------------*/
 8408: 
 8409:   int stepsize;
 8410:   /* int agelim; */
 8411: 	int ageminl;
 8412:   int hstepm;
 8413:   int nhstepm;
 8414:   int h, i, i1, j, k;
 8415: 	
 8416:   double agedeb;
 8417:   double ***p3mat;
 8418: 	
 8419:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
 8420:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
 8421:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
 8422:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
 8423:   }
 8424:   printf("Computing pij back: result on file '%s' \n", filerespijb);
 8425:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
 8426:   
 8427:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 8428:   /*if (stepm<=24) stepsize=2;*/
 8429:   
 8430:   /* agelim=AGESUP; */
 8431:   ageminl=30;
 8432:   hstepm=stepsize*YEARM; /* Every year of age */
 8433:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
 8434:   
 8435:   /* hstepm=1;   aff par mois*/
 8436:   pstamp(ficrespijb);
 8437:   fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
 8438:   i1= pow(2,nqveff);
 8439:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 8440:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
 8441:   /*  	k=k+1;  */
 8442:   for (k=1; k <= (int) pow(2,nqveff); k++){
 8443:     fprintf(ficrespijb,"\n#****** ");
 8444:     for(j=1;j<=nqveff;j++)
 8445:       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8446:     fprintf(ficrespijb,"******\n");
 8447:     if(invalidvarcomb[k]){
 8448:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
 8449:       continue;
 8450:     }
 8451:     
 8452:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
 8453:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
 8454:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
 8455:       nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
 8456:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
 8457:       
 8458:       /*	  nhstepm=nhstepm*YEARM; aff par mois*/
 8459:       
 8460:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 8461:       /* oldm=oldms;savm=savms; */
 8462:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
 8463:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
 8464:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
 8465:       fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
 8466:       for(i=1; i<=nlstate;i++)
 8467: 	for(j=1; j<=nlstate+ndeath;j++)
 8468: 	  fprintf(ficrespijb," %1d-%1d",i,j);
 8469:       fprintf(ficrespijb,"\n");
 8470:       for (h=0; h<=nhstepm; h++){
 8471: 	/*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
 8472: 	fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
 8473: 	/* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
 8474: 	for(i=1; i<=nlstate;i++)
 8475: 	  for(j=1; j<=nlstate+ndeath;j++)
 8476: 	    fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
 8477: 	fprintf(ficrespijb,"\n");
 8478:       }
 8479:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 8480:       fprintf(ficrespijb,"\n");
 8481:     }
 8482:     /*}*/
 8483:   }
 8484:   return 0;
 8485:  } /*  hBijx */
 8486: 
 8487: 
 8488: /***********************************************/
 8489: /**************** Main Program *****************/
 8490: /***********************************************/
 8491: 
 8492: int main(int argc, char *argv[])
 8493: {
 8494: #ifdef GSL
 8495:   const gsl_multimin_fminimizer_type *T;
 8496:   size_t iteri = 0, it;
 8497:   int rval = GSL_CONTINUE;
 8498:   int status = GSL_SUCCESS;
 8499:   double ssval;
 8500: #endif
 8501:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
 8502:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
 8503:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
 8504:   int jj, ll, li, lj, lk;
 8505:   int numlinepar=0; /* Current linenumber of parameter file */
 8506:   int num_filled;
 8507:   int itimes;
 8508:   int NDIM=2;
 8509:   int vpopbased=0;
 8510: 
 8511:   char ca[32], cb[32];
 8512:   /*  FILE *fichtm; *//* Html File */
 8513:   /* FILE *ficgp;*/ /*Gnuplot File */
 8514:   struct stat info;
 8515:   double agedeb=0.;
 8516: 
 8517:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
 8518:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
 8519: 
 8520:   double fret;
 8521:   double dum=0.; /* Dummy variable */
 8522:   double ***p3mat;
 8523:   /* double ***mobaverage; */
 8524: 
 8525:   char line[MAXLINE];
 8526:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
 8527: 
 8528:   char model[MAXLINE], modeltemp[MAXLINE];
 8529:   char pathr[MAXLINE], pathimach[MAXLINE]; 
 8530:   char *tok, *val; /* pathtot */
 8531:   int firstobs=1, lastobs=10;
 8532:   int c,  h , cpt, c2;
 8533:   int jl=0;
 8534:   int i1, j1, jk, stepsize=0;
 8535:   int count=0;
 8536: 
 8537:   int *tab; 
 8538:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
 8539:   int backcast=0;
 8540:   int mobilav=0,popforecast=0;
 8541:   int hstepm=0, nhstepm=0;
 8542:   int agemortsup;
 8543:   float  sumlpop=0.;
 8544:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
 8545:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
 8546: 
 8547:   double bage=0, fage=110., age, agelim=0., agebase=0.;
 8548:   double ftolpl=FTOL;
 8549:   double **prlim;
 8550:   double **bprlim;
 8551:   double ***param; /* Matrix of parameters */
 8552:   double  *p;
 8553:   double **matcov; /* Matrix of covariance */
 8554:   double **hess; /* Hessian matrix */
 8555:   double ***delti3; /* Scale */
 8556:   double *delti; /* Scale */
 8557:   double ***eij, ***vareij;
 8558:   double **varpl; /* Variances of prevalence limits by age */
 8559:   double *epj, vepp;
 8560: 
 8561:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
 8562:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
 8563: 
 8564:   double **ximort;
 8565:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
 8566:   int *dcwave;
 8567: 
 8568:   char z[1]="c";
 8569: 
 8570:   /*char  *strt;*/
 8571:   char strtend[80];
 8572: 
 8573: 
 8574: /*   setlocale (LC_ALL, ""); */
 8575: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
 8576: /*   textdomain (PACKAGE); */
 8577: /*   setlocale (LC_CTYPE, ""); */
 8578: /*   setlocale (LC_MESSAGES, ""); */
 8579: 
 8580:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
 8581:   rstart_time = time(NULL);  
 8582:   /*  (void) gettimeofday(&start_time,&tzp);*/
 8583:   start_time = *localtime(&rstart_time);
 8584:   curr_time=start_time;
 8585:   /*tml = *localtime(&start_time.tm_sec);*/
 8586:   /* strcpy(strstart,asctime(&tml)); */
 8587:   strcpy(strstart,asctime(&start_time));
 8588: 
 8589: /*  printf("Localtime (at start)=%s",strstart); */
 8590: /*  tp.tm_sec = tp.tm_sec +86400; */
 8591: /*  tm = *localtime(&start_time.tm_sec); */
 8592: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
 8593: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
 8594: /*   tmg.tm_hour=tmg.tm_hour + 1; */
 8595: /*   tp.tm_sec = mktime(&tmg); */
 8596: /*   strt=asctime(&tmg); */
 8597: /*   printf("Time(after) =%s",strstart);  */
 8598: /*  (void) time (&time_value);
 8599: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
 8600: *  tm = *localtime(&time_value);
 8601: *  strstart=asctime(&tm);
 8602: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
 8603: */
 8604: 
 8605:   nberr=0; /* Number of errors and warnings */
 8606:   nbwarn=0;
 8607: #ifdef WIN32
 8608:   _getcwd(pathcd, size);
 8609: #else
 8610:   getcwd(pathcd, size);
 8611: #endif
 8612:   syscompilerinfo(0);
 8613:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
 8614:   if(argc <=1){
 8615:     printf("\nEnter the parameter file name: ");
 8616:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
 8617:       printf("ERROR Empty parameter file name\n");
 8618:       goto end;
 8619:     }
 8620:     i=strlen(pathr);
 8621:     if(pathr[i-1]=='\n')
 8622:       pathr[i-1]='\0';
 8623:     i=strlen(pathr);
 8624:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
 8625:       pathr[i-1]='\0';
 8626:     }
 8627:     i=strlen(pathr);
 8628:     if( i==0 ){
 8629:       printf("ERROR Empty parameter file name\n");
 8630:       goto end;
 8631:     }
 8632:     for (tok = pathr; tok != NULL; ){
 8633:       printf("Pathr |%s|\n",pathr);
 8634:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
 8635:       printf("val= |%s| pathr=%s\n",val,pathr);
 8636:       strcpy (pathtot, val);
 8637:       if(pathr[0] == '\0') break; /* Dirty */
 8638:     }
 8639:   }
 8640:   else{
 8641:     strcpy(pathtot,argv[1]);
 8642:   }
 8643:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
 8644:   /*cygwin_split_path(pathtot,path,optionfile);
 8645:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
 8646:   /* cutv(path,optionfile,pathtot,'\\');*/
 8647: 
 8648:   /* Split argv[0], imach program to get pathimach */
 8649:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
 8650:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 8651:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 8652:  /*   strcpy(pathimach,argv[0]); */
 8653:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
 8654:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
 8655:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
 8656: #ifdef WIN32
 8657:   _chdir(path); /* Can be a relative path */
 8658:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
 8659: #else
 8660:   chdir(path); /* Can be a relative path */
 8661:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
 8662: #endif
 8663:   printf("Current directory %s!\n",pathcd);
 8664:   strcpy(command,"mkdir ");
 8665:   strcat(command,optionfilefiname);
 8666:   if((outcmd=system(command)) != 0){
 8667:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
 8668:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
 8669:     /* fclose(ficlog); */
 8670: /*     exit(1); */
 8671:   }
 8672: /*   if((imk=mkdir(optionfilefiname))<0){ */
 8673: /*     perror("mkdir"); */
 8674: /*   } */
 8675: 
 8676:   /*-------- arguments in the command line --------*/
 8677: 
 8678:   /* Main Log file */
 8679:   strcat(filelog, optionfilefiname);
 8680:   strcat(filelog,".log");    /* */
 8681:   if((ficlog=fopen(filelog,"w"))==NULL)    {
 8682:     printf("Problem with logfile %s\n",filelog);
 8683:     goto end;
 8684:   }
 8685:   fprintf(ficlog,"Log filename:%s\n",filelog);
 8686:   fprintf(ficlog,"Version %s %s",version,fullversion);
 8687:   fprintf(ficlog,"\nEnter the parameter file name: \n");
 8688:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
 8689:  path=%s \n\
 8690:  optionfile=%s\n\
 8691:  optionfilext=%s\n\
 8692:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
 8693: 
 8694:   syscompilerinfo(1);
 8695: 
 8696:   printf("Local time (at start):%s",strstart);
 8697:   fprintf(ficlog,"Local time (at start): %s",strstart);
 8698:   fflush(ficlog);
 8699: /*   (void) gettimeofday(&curr_time,&tzp); */
 8700: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
 8701: 
 8702:   /* */
 8703:   strcpy(fileres,"r");
 8704:   strcat(fileres, optionfilefiname);
 8705:   strcat(fileresu, optionfilefiname); /* Without r in front */
 8706:   strcat(fileres,".txt");    /* Other files have txt extension */
 8707:   strcat(fileresu,".txt");    /* Other files have txt extension */
 8708: 
 8709:   /* Main ---------arguments file --------*/
 8710: 
 8711:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
 8712:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 8713:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 8714:     fflush(ficlog);
 8715:     /* goto end; */
 8716:     exit(70); 
 8717:   }
 8718: 
 8719: 
 8720: 
 8721:   strcpy(filereso,"o");
 8722:   strcat(filereso,fileresu);
 8723:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
 8724:     printf("Problem with Output resultfile: %s\n", filereso);
 8725:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
 8726:     fflush(ficlog);
 8727:     goto end;
 8728:   }
 8729: 
 8730:   /* Reads comments: lines beginning with '#' */
 8731:   numlinepar=0;
 8732: 
 8733:     /* First parameter line */
 8734:   while(fgets(line, MAXLINE, ficpar)) {
 8735:     /* If line starts with a # it is a comment */
 8736:     if (line[0] == '#') {
 8737:       numlinepar++;
 8738:       fputs(line,stdout);
 8739:       fputs(line,ficparo);
 8740:       fputs(line,ficlog);
 8741:       continue;
 8742:     }else
 8743:       break;
 8744:   }
 8745:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
 8746: 			title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
 8747:     if (num_filled != 5) {
 8748:       printf("Should be 5 parameters\n");
 8749:     }
 8750:     numlinepar++;
 8751:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
 8752:   }
 8753:   /* Second parameter line */
 8754:   while(fgets(line, MAXLINE, ficpar)) {
 8755:     /* If line starts with a # it is a comment */
 8756:     if (line[0] == '#') {
 8757:       numlinepar++;
 8758:       fputs(line,stdout);
 8759:       fputs(line,ficparo);
 8760:       fputs(line,ficlog);
 8761:       continue;
 8762:     }else
 8763:       break;
 8764:   }
 8765:   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", \
 8766: 			&ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
 8767:     if (num_filled != 11) {
 8768:       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");
 8769:       printf("but line=%s\n",line);
 8770:     }
 8771:     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);
 8772:   }
 8773:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
 8774:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
 8775:   /* Third parameter line */
 8776:   while(fgets(line, MAXLINE, ficpar)) {
 8777:     /* If line starts with a # it is a comment */
 8778:     if (line[0] == '#') {
 8779:       numlinepar++;
 8780:       fputs(line,stdout);
 8781:       fputs(line,ficparo);
 8782:       fputs(line,ficlog);
 8783:       continue;
 8784:     }else
 8785:       break;
 8786:   }
 8787:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
 8788:     if (num_filled == 0)
 8789:             model[0]='\0';
 8790:     else if (num_filled != 1){
 8791:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
 8792:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
 8793:       model[0]='\0';
 8794:       goto end;
 8795:     }
 8796:     else{
 8797:       if (model[0]=='+'){
 8798: 	for(i=1; i<=strlen(model);i++)
 8799: 	  modeltemp[i-1]=model[i];
 8800: 	strcpy(model,modeltemp); 
 8801:       }
 8802:     }
 8803:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
 8804:     printf("model=1+age+%s\n",model);fflush(stdout);
 8805:   }
 8806:   /* 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); */
 8807:   /* numlinepar=numlinepar+3; /\* In general *\/ */
 8808:   /* 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); */
 8809:   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);
 8810:   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);
 8811:   fflush(ficlog);
 8812:   /* if(model[0]=='#'|| model[0]== '\0'){ */
 8813:   if(model[0]=='#'){
 8814:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
 8815:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
 8816:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");		\
 8817:     if(mle != -1){
 8818:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
 8819:       exit(1);
 8820:     }
 8821:   }
 8822:   while((c=getc(ficpar))=='#' && c!= EOF){
 8823:     ungetc(c,ficpar);
 8824:     fgets(line, MAXLINE, ficpar);
 8825:     numlinepar++;
 8826:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
 8827:       z[0]=line[1];
 8828:     }
 8829:     /* printf("****line [1] = %c \n",line[1]); */
 8830:     fputs(line, stdout);
 8831:     //puts(line);
 8832:     fputs(line,ficparo);
 8833:     fputs(line,ficlog);
 8834:   }
 8835:   ungetc(c,ficpar);
 8836: 
 8837:    
 8838:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
 8839:   coqvar=matrix(1,nqv,1,n);  /**< used in readdata */
 8840:   cotvar=ma3x(1,maxwav,1,ntv,1,n);  /**< used in readdata */
 8841:   cotqvar=ma3x(1,maxwav,1,nqtv,1,n);  /**< used in readdata */
 8842:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
 8843:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
 8844:      v1+v2*age+v2*v3 makes cptcovn = 3
 8845:   */
 8846:   if (strlen(model)>1) 
 8847:     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*/
 8848:   else
 8849:     ncovmodel=2; /* Constant and age */
 8850:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
 8851:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
 8852:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
 8853:     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);
 8854:     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);
 8855:     fflush(stdout);
 8856:     fclose (ficlog);
 8857:     goto end;
 8858:   }
 8859:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 8860:   delti=delti3[1][1];
 8861:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
 8862:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
 8863:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 8864:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 8865:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 8866:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 8867:     fclose (ficparo);
 8868:     fclose (ficlog);
 8869:     goto end;
 8870:     exit(0);
 8871:   }  else if(mle==-5) { /* Main Wizard */
 8872:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 8873:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 8874:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 8875:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 8876:     matcov=matrix(1,npar,1,npar);
 8877:     hess=matrix(1,npar,1,npar);
 8878:   }  else{ /* Begin of mle != -1 or -5 */
 8879:     /* Read guessed parameters */
 8880:     /* Reads comments: lines beginning with '#' */
 8881:     while((c=getc(ficpar))=='#' && c!= EOF){
 8882:       ungetc(c,ficpar);
 8883:       fgets(line, MAXLINE, ficpar);
 8884:       numlinepar++;
 8885:       fputs(line,stdout);
 8886:       fputs(line,ficparo);
 8887:       fputs(line,ficlog);
 8888:     }
 8889:     ungetc(c,ficpar);
 8890:     
 8891:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 8892:     for(i=1; i <=nlstate; i++){
 8893: 			j=0;
 8894:       for(jj=1; jj <=nlstate+ndeath; jj++){
 8895: 				if(jj==i) continue;
 8896: 				j++;
 8897: 				fscanf(ficpar,"%1d%1d",&i1,&j1);
 8898: 				if ((i1 != i) || (j1 != jj)){
 8899: 					printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
 8900: It might be a problem of design; if ncovcol and the model are correct\n \
 8901: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
 8902: 					exit(1);
 8903: 				}
 8904: 				fprintf(ficparo,"%1d%1d",i1,j1);
 8905: 				if(mle==1)
 8906: 					printf("%1d%1d",i,jj);
 8907: 				fprintf(ficlog,"%1d%1d",i,jj);
 8908: 				for(k=1; k<=ncovmodel;k++){
 8909: 					fscanf(ficpar," %lf",&param[i][j][k]);
 8910: 					if(mle==1){
 8911: 						printf(" %lf",param[i][j][k]);
 8912: 						fprintf(ficlog," %lf",param[i][j][k]);
 8913: 					}
 8914: 					else
 8915: 						fprintf(ficlog," %lf",param[i][j][k]);
 8916: 					fprintf(ficparo," %lf",param[i][j][k]);
 8917: 				}
 8918: 				fscanf(ficpar,"\n");
 8919: 				numlinepar++;
 8920: 				if(mle==1)
 8921: 					printf("\n");
 8922: 				fprintf(ficlog,"\n");
 8923: 				fprintf(ficparo,"\n");
 8924:       }
 8925:     }  
 8926:     fflush(ficlog);
 8927: 
 8928:     /* Reads scales values */
 8929:     p=param[1][1];
 8930:     
 8931:     /* Reads comments: lines beginning with '#' */
 8932:     while((c=getc(ficpar))=='#' && c!= EOF){
 8933:       ungetc(c,ficpar);
 8934:       fgets(line, MAXLINE, ficpar);
 8935:       numlinepar++;
 8936:       fputs(line,stdout);
 8937:       fputs(line,ficparo);
 8938:       fputs(line,ficlog);
 8939:     }
 8940:     ungetc(c,ficpar);
 8941: 
 8942:     for(i=1; i <=nlstate; i++){
 8943:       for(j=1; j <=nlstate+ndeath-1; j++){
 8944: 				fscanf(ficpar,"%1d%1d",&i1,&j1);
 8945: 				if ( (i1-i) * (j1-j) != 0){
 8946: 					printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
 8947: 					exit(1);
 8948: 				}
 8949: 				printf("%1d%1d",i,j);
 8950: 				fprintf(ficparo,"%1d%1d",i1,j1);
 8951: 				fprintf(ficlog,"%1d%1d",i1,j1);
 8952: 				for(k=1; k<=ncovmodel;k++){
 8953: 					fscanf(ficpar,"%le",&delti3[i][j][k]);
 8954: 					printf(" %le",delti3[i][j][k]);
 8955: 					fprintf(ficparo," %le",delti3[i][j][k]);
 8956: 					fprintf(ficlog," %le",delti3[i][j][k]);
 8957: 				}
 8958: 				fscanf(ficpar,"\n");
 8959: 				numlinepar++;
 8960: 				printf("\n");
 8961: 				fprintf(ficparo,"\n");
 8962: 				fprintf(ficlog,"\n");
 8963:       }
 8964:     }
 8965:     fflush(ficlog);
 8966: 		
 8967:     /* Reads covariance matrix */
 8968:     delti=delti3[1][1];
 8969: 		
 8970: 		
 8971:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
 8972: 		
 8973:     /* Reads comments: lines beginning with '#' */
 8974:     while((c=getc(ficpar))=='#' && c!= EOF){
 8975:       ungetc(c,ficpar);
 8976:       fgets(line, MAXLINE, ficpar);
 8977:       numlinepar++;
 8978:       fputs(line,stdout);
 8979:       fputs(line,ficparo);
 8980:       fputs(line,ficlog);
 8981:     }
 8982:     ungetc(c,ficpar);
 8983: 		
 8984:     matcov=matrix(1,npar,1,npar);
 8985:     hess=matrix(1,npar,1,npar);
 8986:     for(i=1; i <=npar; i++)
 8987:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
 8988: 		
 8989:     /* Scans npar lines */
 8990:     for(i=1; i <=npar; i++){
 8991:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
 8992:       if(count != 3){
 8993: 				printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
 8994: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
 8995: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
 8996: 				fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
 8997: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
 8998: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
 8999: 				exit(1);
 9000:       }else{
 9001: 				if(mle==1)
 9002: 					printf("%1d%1d%1d",i1,j1,jk);
 9003: 			}
 9004:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
 9005:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
 9006:       for(j=1; j <=i; j++){
 9007: 				fscanf(ficpar," %le",&matcov[i][j]);
 9008: 				if(mle==1){
 9009: 					printf(" %.5le",matcov[i][j]);
 9010: 				}
 9011: 				fprintf(ficlog," %.5le",matcov[i][j]);
 9012: 				fprintf(ficparo," %.5le",matcov[i][j]);
 9013:       }
 9014:       fscanf(ficpar,"\n");
 9015:       numlinepar++;
 9016:       if(mle==1)
 9017: 				printf("\n");
 9018:       fprintf(ficlog,"\n");
 9019:       fprintf(ficparo,"\n");
 9020:     }
 9021:     /* End of read covariance matrix npar lines */
 9022:     for(i=1; i <=npar; i++)
 9023:       for(j=i+1;j<=npar;j++)
 9024: 				matcov[i][j]=matcov[j][i];
 9025:     
 9026:     if(mle==1)
 9027:       printf("\n");
 9028:     fprintf(ficlog,"\n");
 9029:     
 9030:     fflush(ficlog);
 9031:     
 9032:     /*-------- Rewriting parameter file ----------*/
 9033:     strcpy(rfileres,"r");    /* "Rparameterfile */
 9034:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
 9035:     strcat(rfileres,".");    /* */
 9036:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
 9037:     if((ficres =fopen(rfileres,"w"))==NULL) {
 9038:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
 9039:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
 9040:     }
 9041:     fprintf(ficres,"#%s\n",version);
 9042:   }    /* End of mle != -3 */
 9043:   
 9044:   /*  Main data
 9045:    */
 9046:   n= lastobs;
 9047:   num=lvector(1,n);
 9048:   moisnais=vector(1,n);
 9049:   annais=vector(1,n);
 9050:   moisdc=vector(1,n);
 9051:   andc=vector(1,n);
 9052:   weight=vector(1,n);
 9053:   agedc=vector(1,n);
 9054:   cod=ivector(1,n);
 9055:   for(i=1;i<=n;i++){
 9056: 		num[i]=0;
 9057: 		moisnais[i]=0;
 9058: 		annais[i]=0;
 9059: 		moisdc[i]=0;
 9060: 		andc[i]=0;
 9061: 		agedc[i]=0;
 9062: 		cod[i]=0;
 9063: 		weight[i]=1.0; /* Equal weights, 1 by default */
 9064: 	}
 9065:   mint=matrix(1,maxwav,1,n);
 9066:   anint=matrix(1,maxwav,1,n);
 9067:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
 9068:   tab=ivector(1,NCOVMAX);
 9069:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
 9070:   ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
 9071: 
 9072:   /* Reads data from file datafile */
 9073:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
 9074:     goto end;
 9075: 
 9076:   /* Calculation of the number of parameters from char model */
 9077:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
 9078: 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
 9079: 	k=3 V4 Tvar[k=3]= 4 (from V4)
 9080: 	k=2 V1 Tvar[k=2]= 1 (from V1)
 9081: 	k=1 Tvar[1]=2 (from V2)
 9082:     */
 9083:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
 9084:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
 9085:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
 9086:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
 9087:   */
 9088:   /* For model-covariate k tells which data-covariate to use but
 9089:     because this model-covariate is a construction we invent a new column
 9090:     ncovcol + k1
 9091:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
 9092:     Tvar[3=V1*V4]=4+1 etc */
 9093:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
 9094:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
 9095:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
 9096:   */
 9097:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
 9098:   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
 9099: 			    * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
 9100: 			    * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
 9101:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
 9102: 			 4 covariates (3 plus signs)
 9103: 			 Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
 9104: 		      */  
 9105: 
 9106: /* Main decodemodel */
 9107: 
 9108: 
 9109:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
 9110:     goto end;
 9111: 
 9112:   if((double)(lastobs-imx)/(double)imx > 1.10){
 9113:     nbwarn++;
 9114:     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); 
 9115:     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); 
 9116:   }
 9117:     /*  if(mle==1){*/
 9118:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
 9119:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
 9120:   }
 9121: 
 9122:     /*-calculation of age at interview from date of interview and age at death -*/
 9123:   agev=matrix(1,maxwav,1,imx);
 9124: 
 9125:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
 9126:     goto end;
 9127: 
 9128: 
 9129:   agegomp=(int)agemin;
 9130:   free_vector(moisnais,1,n);
 9131:   free_vector(annais,1,n);
 9132:   /* free_matrix(mint,1,maxwav,1,n);
 9133:      free_matrix(anint,1,maxwav,1,n);*/
 9134:   /* free_vector(moisdc,1,n); */
 9135:   /* free_vector(andc,1,n); */
 9136:   /* */
 9137:   
 9138:   wav=ivector(1,imx);
 9139:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
 9140:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
 9141:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
 9142:   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.*/
 9143:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
 9144:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
 9145:    
 9146:   /* Concatenates waves */
 9147:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 9148:      Death is a valid wave (if date is known).
 9149:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
 9150:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 9151:      and mw[mi+1][i]. dh depends on stepm.
 9152:   */
 9153: 
 9154:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
 9155:   /* */
 9156:  
 9157:   free_vector(moisdc,1,n);
 9158:   free_vector(andc,1,n);
 9159: 
 9160:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
 9161:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
 9162:   ncodemax[1]=1;
 9163:   Ndum =ivector(-1,NCOVMAX);  
 9164: 	cptcoveff=0;
 9165:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
 9166:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
 9167: 	}
 9168: 	
 9169: 	ncovcombmax=pow(2,cptcoveff);
 9170: 	invalidvarcomb=ivector(1, ncovcombmax); 
 9171: 	for(i=1;i<ncovcombmax;i++)
 9172: 		invalidvarcomb[i]=0;
 9173: 
 9174:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
 9175:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
 9176:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
 9177: 
 9178:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
 9179:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
 9180:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
 9181:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
 9182:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
 9183:    * (currently 0 or 1) in the data.
 9184:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
 9185:    * corresponding modality (h,j).
 9186:    */
 9187: 
 9188:   h=0;
 9189:   /*if (cptcovn > 0) */
 9190:   m=pow(2,cptcoveff);
 9191:  
 9192: 	  /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
 9193: 	   * For k=4 covariates, h goes from 1 to m=2**k
 9194: 	   * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
 9195:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
 9196: 	   *     h\k   1     2     3     4
 9197: 	   *______________________________  
 9198: 	   *     1 i=1 1 i=1 1 i=1 1 i=1 1
 9199: 	   *     2     2     1     1     1
 9200: 	   *     3 i=2 1     2     1     1
 9201: 	   *     4     2     2     1     1
 9202: 	   *     5 i=3 1 i=2 1     2     1
 9203: 	   *     6     2     1     2     1
 9204: 	   *     7 i=4 1     2     2     1
 9205: 	   *     8     2     2     2     1
 9206: 	   *     9 i=5 1 i=3 1 i=2 1     2
 9207: 	   *    10     2     1     1     2
 9208: 	   *    11 i=6 1     2     1     2
 9209: 	   *    12     2     2     1     2
 9210: 	   *    13 i=7 1 i=4 1     2     2    
 9211: 	   *    14     2     1     2     2
 9212: 	   *    15 i=8 1     2     2     2
 9213: 	   *    16     2     2     2     2
 9214: 	   */
 9215:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
 9216:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
 9217:      * and the value of each covariate?
 9218:      * V1=1, V2=1, V3=2, V4=1 ?
 9219:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
 9220:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
 9221:      * In order to get the real value in the data, we use nbcode
 9222:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
 9223:      * We are keeping this crazy system in order to be able (in the future?) 
 9224:      * to have more than 2 values (0 or 1) for a covariate.
 9225:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
 9226:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
 9227:      *              bbbbbbbb
 9228:      *              76543210     
 9229:      *   h-1        00000101 (6-1=5)
 9230:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
 9231:      *           &
 9232:      *     1        00000001 (1)
 9233:      *              00000000        = 1 & ((h-1) >> (k-1))
 9234:      *          +1= 00000001 =1 
 9235:      *
 9236:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
 9237:      *          h'      1101 =2^3+2^2+0x2^1+2^0
 9238:      *    >>k'            11
 9239:      *          &   00000001
 9240:      *            = 00000001
 9241:      *      +1    = 00000010=2    =  codtabm(14,3)   
 9242:      * Reverse h=6 and m=16?
 9243:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
 9244:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
 9245:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
 9246:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
 9247:      * V3=decodtabm(14,3,2**4)=2
 9248:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
 9249:      *(h-1) >> (j-1)    0011 =13 >> 2
 9250:      *          &1 000000001
 9251:      *           = 000000001
 9252:      *         +1= 000000010 =2
 9253:      *                  2211
 9254:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
 9255:      *                  V3=2
 9256: 		 * codtabm and decodtabm are identical
 9257:      */
 9258: 
 9259: 
 9260:  free_ivector(Ndum,-1,NCOVMAX);
 9261: 
 9262: 
 9263:     
 9264:   /* Initialisation of ----------- gnuplot -------------*/
 9265:   strcpy(optionfilegnuplot,optionfilefiname);
 9266:   if(mle==-3)
 9267:     strcat(optionfilegnuplot,"-MORT_");
 9268:   strcat(optionfilegnuplot,".gp");
 9269: 
 9270:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
 9271:     printf("Problem with file %s",optionfilegnuplot);
 9272:   }
 9273:   else{
 9274:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
 9275:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
 9276:     //fprintf(ficgp,"set missing 'NaNq'\n");
 9277:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
 9278:   }
 9279:   /*  fclose(ficgp);*/
 9280: 
 9281: 
 9282:   /* Initialisation of --------- index.htm --------*/
 9283: 
 9284:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
 9285:   if(mle==-3)
 9286:     strcat(optionfilehtm,"-MORT_");
 9287:   strcat(optionfilehtm,".htm");
 9288:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
 9289:     printf("Problem with %s \n",optionfilehtm);
 9290:     exit(0);
 9291:   }
 9292: 
 9293:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
 9294:   strcat(optionfilehtmcov,"-cov.htm");
 9295:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
 9296:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
 9297:   }
 9298:   else{
 9299:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 9300: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 9301: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
 9302: 	  optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 9303:   }
 9304: 
 9305:   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>  \
 9306: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 9307: <font size=\"2\">IMaCh-%s <br> %s</font> \
 9308: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 9309: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
 9310: \n\
 9311: <hr  size=\"2\" color=\"#EC5E5E\">\
 9312:  <ul><li><h4>Parameter files</h4>\n\
 9313:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
 9314:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
 9315:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
 9316:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
 9317:  - Date and time at start: %s</ul>\n",\
 9318: 	  optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
 9319: 	  optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
 9320: 	  fileres,fileres,\
 9321: 	  filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
 9322:   fflush(fichtm);
 9323: 
 9324:   strcpy(pathr,path);
 9325:   strcat(pathr,optionfilefiname);
 9326: #ifdef WIN32
 9327:   _chdir(optionfilefiname); /* Move to directory named optionfile */
 9328: #else
 9329:   chdir(optionfilefiname); /* Move to directory named optionfile */
 9330: #endif
 9331: 	  
 9332:   
 9333:   /* Calculates basic frequencies. Computes observed prevalence at single age 
 9334: 		 and for any valid combination of covariates
 9335:      and prints on file fileres'p'. */
 9336:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart,	\
 9337: 							firstpass, lastpass,  stepm,  weightopt, model);
 9338: 
 9339:   fprintf(fichtm,"\n");
 9340:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
 9341: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
 9342: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
 9343: 	  imx,agemin,agemax,jmin,jmax,jmean);
 9344:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 9345: 	oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 9346: 	newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 9347: 	savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 9348: 	oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
 9349: 
 9350:   /* For Powell, parameters are in a vector p[] starting at p[1]
 9351:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
 9352:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
 9353: 
 9354:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
 9355:   /* For mortality only */
 9356:   if (mle==-3){
 9357:     ximort=matrix(1,NDIM,1,NDIM); 
 9358: 		for(i=1;i<=NDIM;i++)
 9359: 			for(j=1;j<=NDIM;j++)
 9360: 				ximort[i][j]=0.;
 9361:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
 9362:     cens=ivector(1,n);
 9363:     ageexmed=vector(1,n);
 9364:     agecens=vector(1,n);
 9365:     dcwave=ivector(1,n);
 9366: 		
 9367:     for (i=1; i<=imx; i++){
 9368:       dcwave[i]=-1;
 9369:       for (m=firstpass; m<=lastpass; m++)
 9370: 				if (s[m][i]>nlstate) {
 9371: 					dcwave[i]=m;
 9372: 					/*	printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
 9373: 					break;
 9374: 				}
 9375:     }
 9376: 		
 9377:     for (i=1; i<=imx; i++) {
 9378:       if (wav[i]>0){
 9379: 				ageexmed[i]=agev[mw[1][i]][i];
 9380: 				j=wav[i];
 9381: 				agecens[i]=1.; 
 9382: 				
 9383: 				if (ageexmed[i]> 1 && wav[i] > 0){
 9384: 					agecens[i]=agev[mw[j][i]][i];
 9385: 					cens[i]= 1;
 9386: 				}else if (ageexmed[i]< 1) 
 9387: 					cens[i]= -1;
 9388: 				if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
 9389: 					cens[i]=0 ;
 9390:       }
 9391:       else cens[i]=-1;
 9392:     }
 9393:     
 9394:     for (i=1;i<=NDIM;i++) {
 9395:       for (j=1;j<=NDIM;j++)
 9396: 				ximort[i][j]=(i == j ? 1.0 : 0.0);
 9397:     }
 9398:     
 9399:     /*p[1]=0.0268; p[NDIM]=0.083;*/
 9400:     /*printf("%lf %lf", p[1], p[2]);*/
 9401:     
 9402:     
 9403: #ifdef GSL
 9404:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
 9405: #else
 9406:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
 9407: #endif
 9408:     strcpy(filerespow,"POW-MORT_"); 
 9409:     strcat(filerespow,fileresu);
 9410:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
 9411:       printf("Problem with resultfile: %s\n", filerespow);
 9412:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 9413:     }
 9414: #ifdef GSL
 9415:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
 9416: #else
 9417:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
 9418: #endif
 9419:     /*  for (i=1;i<=nlstate;i++)
 9420: 	for(j=1;j<=nlstate+ndeath;j++)
 9421: 	if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 9422:     */
 9423:     fprintf(ficrespow,"\n");
 9424: #ifdef GSL
 9425:     /* gsl starts here */ 
 9426:     T = gsl_multimin_fminimizer_nmsimplex;
 9427:     gsl_multimin_fminimizer *sfm = NULL;
 9428:     gsl_vector *ss, *x;
 9429:     gsl_multimin_function minex_func;
 9430: 
 9431:     /* Initial vertex size vector */
 9432:     ss = gsl_vector_alloc (NDIM);
 9433:     
 9434:     if (ss == NULL){
 9435:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
 9436:     }
 9437:     /* Set all step sizes to 1 */
 9438:     gsl_vector_set_all (ss, 0.001);
 9439: 
 9440:     /* Starting point */
 9441:     
 9442:     x = gsl_vector_alloc (NDIM);
 9443:     
 9444:     if (x == NULL){
 9445:       gsl_vector_free(ss);
 9446:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
 9447:     }
 9448:   
 9449:     /* Initialize method and iterate */
 9450:     /*     p[1]=0.0268; p[NDIM]=0.083; */
 9451:     /*     gsl_vector_set(x, 0, 0.0268); */
 9452:     /*     gsl_vector_set(x, 1, 0.083); */
 9453:     gsl_vector_set(x, 0, p[1]);
 9454:     gsl_vector_set(x, 1, p[2]);
 9455: 
 9456:     minex_func.f = &gompertz_f;
 9457:     minex_func.n = NDIM;
 9458:     minex_func.params = (void *)&p; /* ??? */
 9459:     
 9460:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
 9461:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
 9462:     
 9463:     printf("Iterations beginning .....\n\n");
 9464:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
 9465: 
 9466:     iteri=0;
 9467:     while (rval == GSL_CONTINUE){
 9468:       iteri++;
 9469:       status = gsl_multimin_fminimizer_iterate(sfm);
 9470:       
 9471:       if (status) printf("error: %s\n", gsl_strerror (status));
 9472:       fflush(0);
 9473:       
 9474:       if (status) 
 9475:         break;
 9476:       
 9477:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
 9478:       ssval = gsl_multimin_fminimizer_size (sfm);
 9479:       
 9480:       if (rval == GSL_SUCCESS)
 9481:         printf ("converged to a local maximum at\n");
 9482:       
 9483:       printf("%5d ", iteri);
 9484:       for (it = 0; it < NDIM; it++){
 9485: 	printf ("%10.5f ", gsl_vector_get (sfm->x, it));
 9486:       }
 9487:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
 9488:     }
 9489:     
 9490:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
 9491:     
 9492:     gsl_vector_free(x); /* initial values */
 9493:     gsl_vector_free(ss); /* inital step size */
 9494:     for (it=0; it<NDIM; it++){
 9495:       p[it+1]=gsl_vector_get(sfm->x,it);
 9496:       fprintf(ficrespow," %.12lf", p[it]);
 9497:     }
 9498:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
 9499: #endif
 9500: #ifdef POWELL
 9501:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
 9502: #endif  
 9503:     fclose(ficrespow);
 9504:     
 9505:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
 9506: 
 9507:     for(i=1; i <=NDIM; i++)
 9508:       for(j=i+1;j<=NDIM;j++)
 9509: 				matcov[i][j]=matcov[j][i];
 9510:     
 9511:     printf("\nCovariance matrix\n ");
 9512:     fprintf(ficlog,"\nCovariance matrix\n ");
 9513:     for(i=1; i <=NDIM; i++) {
 9514:       for(j=1;j<=NDIM;j++){ 
 9515: 				printf("%f ",matcov[i][j]);
 9516: 				fprintf(ficlog,"%f ",matcov[i][j]);
 9517:       }
 9518:       printf("\n ");  fprintf(ficlog,"\n ");
 9519:     }
 9520:     
 9521:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
 9522:     for (i=1;i<=NDIM;i++) {
 9523:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
 9524:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
 9525:     }
 9526:     lsurv=vector(1,AGESUP);
 9527:     lpop=vector(1,AGESUP);
 9528:     tpop=vector(1,AGESUP);
 9529:     lsurv[agegomp]=100000;
 9530:     
 9531:     for (k=agegomp;k<=AGESUP;k++) {
 9532:       agemortsup=k;
 9533:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
 9534:     }
 9535:     
 9536:     for (k=agegomp;k<agemortsup;k++)
 9537:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
 9538:     
 9539:     for (k=agegomp;k<agemortsup;k++){
 9540:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
 9541:       sumlpop=sumlpop+lpop[k];
 9542:     }
 9543:     
 9544:     tpop[agegomp]=sumlpop;
 9545:     for (k=agegomp;k<(agemortsup-3);k++){
 9546:       /*  tpop[k+1]=2;*/
 9547:       tpop[k+1]=tpop[k]-lpop[k];
 9548:     }
 9549:     
 9550:     
 9551:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
 9552:     for (k=agegomp;k<(agemortsup-2);k++) 
 9553:       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]);
 9554:     
 9555:     
 9556:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 9557: 		ageminpar=50;
 9558: 		agemaxpar=100;
 9559:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
 9560:       	printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
 9561: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
 9562: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
 9563:       	fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
 9564: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
 9565: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
 9566:     }else{
 9567: 			printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
 9568: 			fprintf(ficlog,"Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
 9569:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 9570: 		}
 9571:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
 9572: 		     stepm, weightopt,\
 9573: 		     model,imx,p,matcov,agemortsup);
 9574:     
 9575:     free_vector(lsurv,1,AGESUP);
 9576:     free_vector(lpop,1,AGESUP);
 9577:     free_vector(tpop,1,AGESUP);
 9578:     free_matrix(ximort,1,NDIM,1,NDIM);
 9579:     free_ivector(cens,1,n);
 9580:     free_vector(agecens,1,n);
 9581:     free_ivector(dcwave,1,n);
 9582: #ifdef GSL
 9583: #endif
 9584:   } /* Endof if mle==-3 mortality only */
 9585:   /* Standard  */
 9586:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
 9587:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
 9588:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
 9589:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 9590:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 9591:     for (k=1; k<=npar;k++)
 9592:       printf(" %d %8.5f",k,p[k]);
 9593:     printf("\n");
 9594:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
 9595:       /* mlikeli uses func not funcone */
 9596:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
 9597:     }
 9598:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
 9599:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
 9600:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
 9601:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 9602:     }
 9603:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
 9604:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 9605:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 9606:     for (k=1; k<=npar;k++)
 9607:       printf(" %d %8.5f",k,p[k]);
 9608:     printf("\n");
 9609:     
 9610:     /*--------- results files --------------*/
 9611:     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);
 9612:     
 9613:     
 9614:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 9615:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 9616:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 9617:     for(i=1,jk=1; i <=nlstate; i++){
 9618:       for(k=1; k <=(nlstate+ndeath); k++){
 9619: 				if (k != i) {
 9620: 					printf("%d%d ",i,k);
 9621: 					fprintf(ficlog,"%d%d ",i,k);
 9622: 					fprintf(ficres,"%1d%1d ",i,k);
 9623: 					for(j=1; j <=ncovmodel; j++){
 9624: 						printf("%12.7f ",p[jk]);
 9625: 						fprintf(ficlog,"%12.7f ",p[jk]);
 9626: 						fprintf(ficres,"%12.7f ",p[jk]);
 9627: 						jk++; 
 9628: 					}
 9629: 					printf("\n");
 9630: 					fprintf(ficlog,"\n");
 9631: 					fprintf(ficres,"\n");
 9632: 				}
 9633:       }
 9634:     }
 9635:     if(mle != 0){
 9636:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
 9637:       ftolhess=ftol; /* Usually correct */
 9638:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
 9639:       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");
 9640:       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");
 9641:       for(i=1,jk=1; i <=nlstate; i++){
 9642: 				for(k=1; k <=(nlstate+ndeath); k++){
 9643: 					if (k != i) {
 9644: 						printf("%d%d ",i,k);
 9645: 						fprintf(ficlog,"%d%d ",i,k);
 9646: 						for(j=1; j <=ncovmodel; j++){
 9647: 							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]));
 9648: 							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]));
 9649: 							jk++; 
 9650: 						}
 9651: 						printf("\n");
 9652: 						fprintf(ficlog,"\n");
 9653: 					}
 9654: 				}
 9655:       }
 9656:     } /* end of hesscov and Wald tests */
 9657: 		
 9658:     /*  */
 9659:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
 9660:     printf("# Scales (for hessian or gradient estimation)\n");
 9661:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
 9662:     for(i=1,jk=1; i <=nlstate; i++){
 9663:       for(j=1; j <=nlstate+ndeath; j++){
 9664: 				if (j!=i) {
 9665: 					fprintf(ficres,"%1d%1d",i,j);
 9666: 					printf("%1d%1d",i,j);
 9667: 					fprintf(ficlog,"%1d%1d",i,j);
 9668: 					for(k=1; k<=ncovmodel;k++){
 9669: 						printf(" %.5e",delti[jk]);
 9670: 						fprintf(ficlog," %.5e",delti[jk]);
 9671: 						fprintf(ficres," %.5e",delti[jk]);
 9672: 						jk++;
 9673: 					}
 9674: 					printf("\n");
 9675: 					fprintf(ficlog,"\n");
 9676: 					fprintf(ficres,"\n");
 9677: 				}
 9678:       }
 9679:     }
 9680:     
 9681:     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");
 9682:     if(mle >= 1) /* To big for the screen */
 9683:       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");
 9684:     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");
 9685:     /* # 121 Var(a12)\n\ */
 9686:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
 9687:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 9688:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 9689:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 9690:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 9691:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 9692:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 9693:     
 9694:     
 9695:     /* Just to have a covariance matrix which will be more understandable
 9696:        even is we still don't want to manage dictionary of variables
 9697:     */
 9698:     for(itimes=1;itimes<=2;itimes++){
 9699:       jj=0;
 9700:       for(i=1; i <=nlstate; i++){
 9701: 				for(j=1; j <=nlstate+ndeath; j++){
 9702: 					if(j==i) continue;
 9703: 					for(k=1; k<=ncovmodel;k++){
 9704: 						jj++;
 9705: 						ca[0]= k+'a'-1;ca[1]='\0';
 9706: 						if(itimes==1){
 9707: 							if(mle>=1)
 9708: 								printf("#%1d%1d%d",i,j,k);
 9709: 							fprintf(ficlog,"#%1d%1d%d",i,j,k);
 9710: 							fprintf(ficres,"#%1d%1d%d",i,j,k);
 9711: 						}else{
 9712: 							if(mle>=1)
 9713: 								printf("%1d%1d%d",i,j,k);
 9714: 							fprintf(ficlog,"%1d%1d%d",i,j,k);
 9715: 							fprintf(ficres,"%1d%1d%d",i,j,k);
 9716: 						}
 9717: 						ll=0;
 9718: 						for(li=1;li <=nlstate; li++){
 9719: 							for(lj=1;lj <=nlstate+ndeath; lj++){
 9720: 								if(lj==li) continue;
 9721: 								for(lk=1;lk<=ncovmodel;lk++){
 9722: 									ll++;
 9723: 									if(ll<=jj){
 9724: 										cb[0]= lk +'a'-1;cb[1]='\0';
 9725: 										if(ll<jj){
 9726: 											if(itimes==1){
 9727: 												if(mle>=1)
 9728: 													printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 9729: 												fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 9730: 												fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 9731: 											}else{
 9732: 												if(mle>=1)
 9733: 													printf(" %.5e",matcov[jj][ll]); 
 9734: 												fprintf(ficlog," %.5e",matcov[jj][ll]); 
 9735: 												fprintf(ficres," %.5e",matcov[jj][ll]); 
 9736: 											}
 9737: 										}else{
 9738: 											if(itimes==1){
 9739: 												if(mle>=1)
 9740: 													printf(" Var(%s%1d%1d)",ca,i,j);
 9741: 												fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
 9742: 												fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
 9743: 											}else{
 9744: 												if(mle>=1)
 9745: 													printf(" %.7e",matcov[jj][ll]); 
 9746: 												fprintf(ficlog," %.7e",matcov[jj][ll]); 
 9747: 												fprintf(ficres," %.7e",matcov[jj][ll]); 
 9748: 											}
 9749: 										}
 9750: 									}
 9751: 								} /* end lk */
 9752: 							} /* end lj */
 9753: 						} /* end li */
 9754: 						if(mle>=1)
 9755: 							printf("\n");
 9756: 						fprintf(ficlog,"\n");
 9757: 						fprintf(ficres,"\n");
 9758: 						numlinepar++;
 9759: 					} /* end k*/
 9760: 				} /*end j */
 9761:       } /* end i */
 9762:     } /* end itimes */
 9763:     
 9764:     fflush(ficlog);
 9765:     fflush(ficres);
 9766: 		while(fgets(line, MAXLINE, ficpar)) {
 9767: 			/* If line starts with a # it is a comment */
 9768: 			if (line[0] == '#') {
 9769: 				numlinepar++;
 9770: 				fputs(line,stdout);
 9771: 				fputs(line,ficparo);
 9772: 				fputs(line,ficlog);
 9773: 				continue;
 9774: 			}else
 9775: 				break;
 9776: 		}
 9777: 		
 9778:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
 9779:     /*   ungetc(c,ficpar); */
 9780:     /*   fgets(line, MAXLINE, ficpar); */
 9781:     /*   fputs(line,stdout); */
 9782:     /*   fputs(line,ficparo); */
 9783:     /* } */
 9784:     /* ungetc(c,ficpar); */
 9785:     
 9786:     estepm=0;
 9787:     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){
 9788: 			
 9789: 			if (num_filled != 6) {
 9790: 				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);
 9791: 				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);
 9792: 				goto end;
 9793: 			}
 9794: 			printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
 9795: 		}
 9796: 		/* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
 9797: 		/*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
 9798: 		
 9799:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
 9800:     if (estepm==0 || estepm < stepm) estepm=stepm;
 9801:     if (fage <= 2) {
 9802:       bage = ageminpar;
 9803:       fage = agemaxpar;
 9804:     }
 9805:     
 9806:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
 9807:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
 9808:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
 9809: 		
 9810:     /* Other stuffs, more or less useful */    
 9811:     while((c=getc(ficpar))=='#' && c!= EOF){
 9812:       ungetc(c,ficpar);
 9813:       fgets(line, MAXLINE, ficpar);
 9814:       fputs(line,stdout);
 9815:       fputs(line,ficparo);
 9816:     }
 9817:     ungetc(c,ficpar);
 9818:     
 9819:     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);
 9820:     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);
 9821:     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);
 9822:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
 9823:     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);
 9824:     
 9825:     while((c=getc(ficpar))=='#' && c!= EOF){
 9826:       ungetc(c,ficpar);
 9827:       fgets(line, MAXLINE, ficpar);
 9828:       fputs(line,stdout);
 9829:       fputs(line,ficparo);
 9830:     }
 9831:     ungetc(c,ficpar);
 9832:     
 9833:     
 9834:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
 9835:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
 9836:     
 9837:     fscanf(ficpar,"pop_based=%d\n",&popbased);
 9838:     fprintf(ficlog,"pop_based=%d\n",popbased);
 9839:     fprintf(ficparo,"pop_based=%d\n",popbased);   
 9840:     fprintf(ficres,"pop_based=%d\n",popbased);   
 9841:     
 9842:     while((c=getc(ficpar))=='#' && c!= EOF){
 9843:       ungetc(c,ficpar);
 9844:       fgets(line, MAXLINE, ficpar);
 9845:       fputs(line,stdout);
 9846:       fputs(line,ficparo);
 9847:     }
 9848:     ungetc(c,ficpar);
 9849:     
 9850:     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);
 9851:     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);
 9852:     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);
 9853:     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);
 9854:     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);
 9855:     /* day and month of proj2 are not used but only year anproj2.*/
 9856:     
 9857:     while((c=getc(ficpar))=='#' && c!= EOF){
 9858:       ungetc(c,ficpar);
 9859:       fgets(line, MAXLINE, ficpar);
 9860:       fputs(line,stdout);
 9861:       fputs(line,ficparo);
 9862:     }
 9863:     ungetc(c,ficpar);
 9864:     
 9865:     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);
 9866:     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);
 9867:     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);
 9868:     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);
 9869:     /* day and month of proj2 are not used but only year anproj2.*/
 9870:     
 9871:     
 9872: 		/* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
 9873:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
 9874:     
 9875:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 9876:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
 9877: 			printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
 9878: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
 9879: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
 9880: 			fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
 9881: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
 9882: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
 9883:     }else{
 9884:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
 9885:     }
 9886:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
 9887: 								 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
 9888: 								 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
 9889: 		
 9890: 		/*------------ free_vector  -------------*/
 9891: 		/*  chdir(path); */
 9892: 		
 9893:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
 9894:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
 9895:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
 9896:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
 9897:     free_lvector(num,1,n);
 9898:     free_vector(agedc,1,n);
 9899:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
 9900:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
 9901:     fclose(ficparo);
 9902:     fclose(ficres);
 9903: 		
 9904: 		
 9905:     /* Other results (useful)*/
 9906: 		
 9907: 		
 9908:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 9909:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
 9910:     prlim=matrix(1,nlstate,1,nlstate);
 9911:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
 9912:     fclose(ficrespl);
 9913: 
 9914:     /*------------- h Pij x at various ages ------------*/
 9915:     /*#include "hpijx.h"*/
 9916:     hPijx(p, bage, fage);
 9917:     fclose(ficrespij);
 9918: 
 9919:     /* ncovcombmax=  pow(2,cptcoveff); */
 9920:     /*-------------- Variance of one-step probabilities---*/
 9921:     k=1;
 9922:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
 9923: 
 9924:     /* Prevalence for each covariates in probs[age][status][cov] */
 9925:     probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
 9926:     for(i=1;i<=AGESUP;i++)
 9927:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
 9928: 				for(k=1;k<=ncovcombmax;k++)
 9929: 					probs[i][j][k]=0.;
 9930:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 9931:     if (mobilav!=0 ||mobilavproj !=0 ) {
 9932:       mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
 9933: 			for(i=1;i<=AGESUP;i++)
 9934: 				for(j=1;j<=nlstate;j++)
 9935: 					for(k=1;k<=ncovcombmax;k++)
 9936: 						mobaverages[i][j][k]=0.;
 9937:       mobaverage=mobaverages;
 9938:       if (mobilav!=0) {
 9939: 				if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
 9940: 					fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 9941: 					printf(" Error in movingaverage mobilav=%d\n",mobilav);
 9942: 				}
 9943:       }
 9944:       /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
 9945:       /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
 9946:       else if (mobilavproj !=0) {
 9947: 				if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
 9948: 					fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
 9949: 					printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
 9950: 				}
 9951:       }
 9952:     }/* end if moving average */
 9953: 		
 9954:     /*---------- Forecasting ------------------*/
 9955:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
 9956:     if(prevfcast==1){
 9957:       /*    if(stepm ==1){*/
 9958:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, nqveff);
 9959:     }
 9960:     if(backcast==1){
 9961:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath); 	
 9962:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath); 	
 9963:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
 9964: 
 9965:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
 9966: 
 9967:       bprlim=matrix(1,nlstate,1,nlstate);
 9968:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
 9969:       fclose(ficresplb);
 9970: 
 9971:       hBijx(p, bage, fage, mobaverage);
 9972:       fclose(ficrespijb);
 9973:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
 9974: 
 9975:       /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
 9976: 	 bage, fage, firstpass, lastpass, anback2, p, nqveff); */
 9977:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
 9978:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
 9979:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
 9980:     }
 9981:     
 9982:  
 9983:     /* ------ Other prevalence ratios------------ */
 9984: 
 9985:     free_ivector(wav,1,imx);
 9986:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
 9987:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
 9988:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
 9989: 		
 9990: 		
 9991:     /*---------- Health expectancies, no variances ------------*/
 9992: 		
 9993:     strcpy(filerese,"E_");
 9994:     strcat(filerese,fileresu);
 9995:     if((ficreseij=fopen(filerese,"w"))==NULL) {
 9996:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 9997:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 9998:     }
 9999:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
10000:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
10001:  		
10002:     for (k=1; k <= (int) pow(2,nqveff); k++){
10003:       fprintf(ficreseij,"\n#****** ");
10004:       for(j=1;j<=nqveff;j++) {
10005: 				fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
10006:       }
10007:       fprintf(ficreseij,"******\n");
10008:       
10009:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
10010:       oldm=oldms;savm=savms;
10011:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
10012:       
10013:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
10014:     }
10015:     fclose(ficreseij);
10016:     printf("done evsij\n");fflush(stdout);
10017:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
10018: 		
10019:     /*---------- Health expectancies and variances ------------*/
10020: 		
10021: 		
10022:     strcpy(filerest,"T_");
10023:     strcat(filerest,fileresu);
10024:     if((ficrest=fopen(filerest,"w"))==NULL) {
10025:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
10026:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
10027:     }
10028:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
10029:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
10030: 		
10031: 
10032:     strcpy(fileresstde,"STDE_");
10033:     strcat(fileresstde,fileresu);
10034:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
10035:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
10036:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
10037:     }
10038:     printf("  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
10039:     fprintf(ficlog,"  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
10040: 
10041:     strcpy(filerescve,"CVE_");
10042:     strcat(filerescve,fileresu);
10043:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
10044:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
10045:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
10046:     }
10047:     printf("    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
10048:     fprintf(ficlog,"    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
10049: 
10050:     strcpy(fileresv,"V_");
10051:     strcat(fileresv,fileresu);
10052:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
10053:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
10054:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
10055:     }
10056:     printf("      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
10057:     fprintf(ficlog,"      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
10058: 
10059:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
10060:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
10061:           
10062:     for (k=1; k <= (int) pow(2,nqveff); k++){
10063:       fprintf(ficrest,"\n#****** ");
10064:       for(j=1;j<=nqveff;j++) 
10065: 				fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
10066:       fprintf(ficrest,"******\n");
10067:       
10068:       fprintf(ficresstdeij,"\n#****** ");
10069:       fprintf(ficrescveij,"\n#****** ");
10070:       for(j=1;j<=nqveff;j++) {
10071: 				fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
10072: 				fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
10073:       }
10074:       fprintf(ficresstdeij,"******\n");
10075:       fprintf(ficrescveij,"******\n");
10076:       
10077:       fprintf(ficresvij,"\n#****** ");
10078:       for(j=1;j<=nqveff;j++) 
10079: 				fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
10080:       fprintf(ficresvij,"******\n");
10081:       
10082:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
10083:       oldm=oldms;savm=savms;
10084:       printf(" cvevsij %d, ",k);
10085:       fprintf(ficlog, " cvevsij %d, ",k);
10086:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
10087:       printf(" end cvevsij \n ");
10088:       fprintf(ficlog, " end cvevsij \n ");
10089:       
10090:       /*
10091:        */
10092:       /* goto endfree; */
10093:       
10094:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
10095:       pstamp(ficrest);
10096:       
10097:       
10098:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
10099: 				oldm=oldms;savm=savms; /* ZZ Segmentation fault */
10100: 				cptcod= 0; /* To be deleted */
10101: 				printf("varevsij %d \n",vpopbased);
10102: 				fprintf(ficlog, "varevsij %d \n",vpopbased);
10103: 				varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); /* cptcod not initialized Intel */
10104: 				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 ");
10105: 				if(vpopbased==1)
10106: 					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);
10107: 				else
10108: 					fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
10109: 				fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
10110: 				for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
10111: 				fprintf(ficrest,"\n");
10112: 				/* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
10113: 				epj=vector(1,nlstate+1);
10114: 				printf("Computing age specific period (stable) prevalences in each health state \n");
10115: 				fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
10116: 				for(age=bage; age <=fage ;age++){
10117: 					prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
10118: 					if (vpopbased==1) {
10119: 						if(mobilav ==0){
10120: 							for(i=1; i<=nlstate;i++)
10121: 								prlim[i][i]=probs[(int)age][i][k];
10122: 						}else{ /* mobilav */ 
10123: 							for(i=1; i<=nlstate;i++)
10124: 								prlim[i][i]=mobaverage[(int)age][i][k];
10125: 						}
10126: 					}
10127: 	  
10128: 					fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
10129: 					/* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
10130: 					/* printf(" age %4.0f ",age); */
10131: 					for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
10132: 						for(i=1, epj[j]=0.;i <=nlstate;i++) {
10133: 							epj[j] += prlim[i][i]*eij[i][j][(int)age];
10134: 							/*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
10135: 							/* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
10136: 						}
10137: 						epj[nlstate+1] +=epj[j];
10138: 					}
10139: 					/* printf(" age %4.0f \n",age); */
10140: 	  
10141: 					for(i=1, vepp=0.;i <=nlstate;i++)
10142: 						for(j=1;j <=nlstate;j++)
10143: 							vepp += vareij[i][j][(int)age];
10144: 					fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
10145: 					for(j=1;j <=nlstate;j++){
10146: 						fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
10147: 					}
10148: 					fprintf(ficrest,"\n");
10149: 				}
10150:       } /* End vpopbased */
10151:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
10152:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
10153:       free_vector(epj,1,nlstate+1);
10154:       printf("done \n");fflush(stdout);
10155:       fprintf(ficlog,"done\n");fflush(ficlog);
10156:       
10157:       /*}*/
10158:     } /* End k */
10159:     free_vector(weight,1,n);
10160:     free_imatrix(Tvard,1,NCOVMAX,1,2);
10161:     free_imatrix(s,1,maxwav+1,1,n);
10162:     free_matrix(anint,1,maxwav,1,n); 
10163:     free_matrix(mint,1,maxwav,1,n);
10164:     free_ivector(cod,1,n);
10165:     free_ivector(tab,1,NCOVMAX);
10166:     fclose(ficresstdeij);
10167:     fclose(ficrescveij);
10168:     fclose(ficresvij);
10169:     fclose(ficrest);
10170:     printf("done Health expectancies\n");fflush(stdout);
10171:     fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
10172:     fclose(ficpar);
10173:   
10174:     /*------- Variance of period (stable) prevalence------*/   
10175: 
10176:     strcpy(fileresvpl,"VPL_");
10177:     strcat(fileresvpl,fileresu);
10178:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
10179:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
10180:       exit(0);
10181:     }
10182:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
10183:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
10184: 
10185:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
10186:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
10187:           
10188:     for (k=1; k <= (int) pow(2,nqveff); k++){
10189:     	fprintf(ficresvpl,"\n#****** ");
10190: 			for(j=1;j<=nqveff;j++) 
10191: 				fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
10192: 			fprintf(ficresvpl,"******\n");
10193:       
10194: 			varpl=matrix(1,nlstate,(int) bage, (int) fage);
10195: 			oldm=oldms;savm=savms;
10196: 			varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
10197: 			free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
10198:       /*}*/
10199:     }
10200: 		
10201:     fclose(ficresvpl);
10202:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
10203:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
10204: 
10205:     /*---------- End : free ----------------*/
10206:     if (mobilav!=0 ||mobilavproj !=0)
10207:       free_ma3x(mobaverages,1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
10208:     free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
10209:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
10210:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
10211:   }  /* mle==-3 arrives here for freeing */
10212:  /* endfree:*/
10213:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
10214:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
10215:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
10216:     free_ma3x(cotqvar,1,maxwav,1,nqtv,1,n);
10217:     free_ma3x(cotvar,1,maxwav,1,ntv,1,n);
10218:     free_matrix(coqvar,1,maxwav,1,n);
10219:     free_matrix(covar,0,NCOVMAX,1,n);
10220:     free_matrix(matcov,1,npar,1,npar);
10221:     free_matrix(hess,1,npar,1,npar);
10222:     /*free_vector(delti,1,npar);*/
10223:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
10224:     free_matrix(agev,1,maxwav,1,imx);
10225:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
10226: 
10227:     free_ivector(ncodemax,1,NCOVMAX);
10228:     free_ivector(ncodemaxwundef,1,NCOVMAX);
10229:     free_ivector(Tvar,1,NCOVMAX);
10230:     free_ivector(Tprod,1,NCOVMAX);
10231:     free_ivector(Tvaraff,1,NCOVMAX);
10232:     free_ivector(invalidvarcomb,1,ncovcombmax);
10233:     free_ivector(Tage,1,NCOVMAX);
10234: 
10235:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
10236:     /* free_imatrix(codtab,1,100,1,10); */
10237:   fflush(fichtm);
10238:   fflush(ficgp);
10239:   
10240: 
10241:   if((nberr >0) || (nbwarn>0)){
10242:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
10243:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d. Please look at the log file for details.\n",nberr,nbwarn);
10244:   }else{
10245:     printf("End of Imach\n");
10246:     fprintf(ficlog,"End of Imach\n");
10247:   }
10248:   printf("See log file on %s\n",filelog);
10249:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
10250:   /*(void) gettimeofday(&end_time,&tzp);*/
10251:   rend_time = time(NULL);  
10252:   end_time = *localtime(&rend_time);
10253:   /* tml = *localtime(&end_time.tm_sec); */
10254:   strcpy(strtend,asctime(&end_time));
10255:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
10256:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
10257:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
10258: 
10259:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
10260:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
10261:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
10262:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
10263: /*   if(fileappend(fichtm,optionfilehtm)){ */
10264:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
10265:   fclose(fichtm);
10266:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
10267:   fclose(fichtmcov);
10268:   fclose(ficgp);
10269:   fclose(ficlog);
10270:   /*------ End -----------*/
10271: 
10272: 
10273:    printf("Before Current directory %s!\n",pathcd);
10274: #ifdef WIN32
10275:    if (_chdir(pathcd) != 0)
10276: 	   printf("Can't move to directory %s!\n",path);
10277:    if(_getcwd(pathcd,MAXLINE) > 0)
10278: #else
10279:    if(chdir(pathcd) != 0)
10280: 	   printf("Can't move to directory %s!\n", path);
10281:    if (getcwd(pathcd, MAXLINE) > 0)
10282: #endif 
10283:     printf("Current directory %s!\n",pathcd);
10284:   /*strcat(plotcmd,CHARSEPARATOR);*/
10285:   sprintf(plotcmd,"gnuplot");
10286: #ifdef _WIN32
10287:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
10288: #endif
10289:   if(!stat(plotcmd,&info)){
10290:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
10291:     if(!stat(getenv("GNUPLOTBIN"),&info)){
10292:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
10293:     }else
10294:       strcpy(pplotcmd,plotcmd);
10295: #ifdef __unix
10296:     strcpy(plotcmd,GNUPLOTPROGRAM);
10297:     if(!stat(plotcmd,&info)){
10298:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
10299:     }else
10300:       strcpy(pplotcmd,plotcmd);
10301: #endif
10302:   }else
10303:     strcpy(pplotcmd,plotcmd);
10304:   
10305:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
10306:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
10307: 
10308:   if((outcmd=system(plotcmd)) != 0){
10309:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
10310:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
10311:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
10312:     if((outcmd=system(plotcmd)) != 0)
10313:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
10314:   }
10315:   printf(" Successful, please wait...");
10316:   while (z[0] != 'q') {
10317:     /* chdir(path); */
10318:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
10319:     scanf("%s",z);
10320: /*     if (z[0] == 'c') system("./imach"); */
10321:     if (z[0] == 'e') {
10322: #ifdef __APPLE__
10323:       sprintf(pplotcmd, "open %s", optionfilehtm);
10324: #elif __linux
10325:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
10326: #else
10327:       sprintf(pplotcmd, "%s", optionfilehtm);
10328: #endif
10329:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
10330:       system(pplotcmd);
10331:     }
10332:     else if (z[0] == 'g') system(plotcmd);
10333:     else if (z[0] == 'q') exit(0);
10334:   }
10335:   end:
10336:   while (z[0] != 'q') {
10337:     printf("\nType  q for exiting: "); fflush(stdout);
10338:     scanf("%s",z);
10339:   }
10340: }

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