File:  [Local Repository] / imach / src / imach.c
Revision 1.242: download - view: text, annotated - select for diffs
Tue Aug 30 15:01:20 2016 UTC (7 years, 8 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
Summary: Fixing a lots

    1: /* $Id: imach.c,v 1.242 2016/08/30 15:01:20 brouard Exp $
    2:   $State: Exp $
    3:   $Log: imach.c,v $
    4:   Revision 1.242  2016/08/30 15:01:20  brouard
    5:   Summary: Fixing a lots
    6: 
    7:   Revision 1.241  2016/08/29 17:17:25  brouard
    8:   Summary: gnuplot problem in Back projection to fix
    9: 
   10:   Revision 1.240  2016/08/29 07:53:18  brouard
   11:   Summary: Better
   12: 
   13:   Revision 1.239  2016/08/26 15:51:03  brouard
   14:   Summary: Improvement in Powell output in order to copy and paste
   15: 
   16:   Author:
   17: 
   18:   Revision 1.238  2016/08/26 14:23:35  brouard
   19:   Summary: Starting tests of 0.99
   20: 
   21:   Revision 1.237  2016/08/26 09:20:19  brouard
   22:   Summary: to valgrind
   23: 
   24:   Revision 1.236  2016/08/25 10:50:18  brouard
   25:   *** empty log message ***
   26: 
   27:   Revision 1.235  2016/08/25 06:59:23  brouard
   28:   *** empty log message ***
   29: 
   30:   Revision 1.234  2016/08/23 16:51:20  brouard
   31:   *** empty log message ***
   32: 
   33:   Revision 1.233  2016/08/23 07:40:50  brouard
   34:   Summary: not working
   35: 
   36:   Revision 1.232  2016/08/22 14:20:21  brouard
   37:   Summary: not working
   38: 
   39:   Revision 1.231  2016/08/22 07:17:15  brouard
   40:   Summary: not working
   41: 
   42:   Revision 1.230  2016/08/22 06:55:53  brouard
   43:   Summary: Not working
   44: 
   45:   Revision 1.229  2016/07/23 09:45:53  brouard
   46:   Summary: Completing for func too
   47: 
   48:   Revision 1.228  2016/07/22 17:45:30  brouard
   49:   Summary: Fixing some arrays, still debugging
   50: 
   51:   Revision 1.226  2016/07/12 18:42:34  brouard
   52:   Summary: temp
   53: 
   54:   Revision 1.225  2016/07/12 08:40:03  brouard
   55:   Summary: saving but not running
   56: 
   57:   Revision 1.224  2016/07/01 13:16:01  brouard
   58:   Summary: Fixes
   59: 
   60:   Revision 1.223  2016/02/19 09:23:35  brouard
   61:   Summary: temporary
   62: 
   63:   Revision 1.222  2016/02/17 08:14:50  brouard
   64:   Summary: Probably last 0.98 stable version 0.98r6
   65: 
   66:   Revision 1.221  2016/02/15 23:35:36  brouard
   67:   Summary: minor bug
   68: 
   69:   Revision 1.219  2016/02/15 00:48:12  brouard
   70:   *** empty log message ***
   71: 
   72:   Revision 1.218  2016/02/12 11:29:23  brouard
   73:   Summary: 0.99 Back projections
   74: 
   75:   Revision 1.217  2015/12/23 17:18:31  brouard
   76:   Summary: Experimental backcast
   77: 
   78:   Revision 1.216  2015/12/18 17:32:11  brouard
   79:   Summary: 0.98r4 Warning and status=-2
   80: 
   81:   Version 0.98r4 is now:
   82:    - displaying an error when status is -1, date of interview unknown and date of death known;
   83:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
   84:   Older changes concerning s=-2, dating from 2005 have been supersed.
   85: 
   86:   Revision 1.215  2015/12/16 08:52:24  brouard
   87:   Summary: 0.98r4 working
   88: 
   89:   Revision 1.214  2015/12/16 06:57:54  brouard
   90:   Summary: temporary not working
   91: 
   92:   Revision 1.213  2015/12/11 18:22:17  brouard
   93:   Summary: 0.98r4
   94: 
   95:   Revision 1.212  2015/11/21 12:47:24  brouard
   96:   Summary: minor typo
   97: 
   98:   Revision 1.211  2015/11/21 12:41:11  brouard
   99:   Summary: 0.98r3 with some graph of projected cross-sectional
  100: 
  101:   Author: Nicolas Brouard
  102: 
  103:   Revision 1.210  2015/11/18 17:41:20  brouard
  104:   Summary: Start working on projected prevalences
  105: 
  106:   Revision 1.209  2015/11/17 22:12:03  brouard
  107:   Summary: Adding ftolpl parameter
  108:   Author: N Brouard
  109: 
  110:   We had difficulties to get smoothed confidence intervals. It was due
  111:   to the period prevalence which wasn't computed accurately. The inner
  112:   parameter ftolpl is now an outer parameter of the .imach parameter
  113:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
  114:   computation are long.
  115: 
  116:   Revision 1.208  2015/11/17 14:31:57  brouard
  117:   Summary: temporary
  118: 
  119:   Revision 1.207  2015/10/27 17:36:57  brouard
  120:   *** empty log message ***
  121: 
  122:   Revision 1.206  2015/10/24 07:14:11  brouard
  123:   *** empty log message ***
  124: 
  125:   Revision 1.205  2015/10/23 15:50:53  brouard
  126:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
  127: 
  128:   Revision 1.204  2015/10/01 16:20:26  brouard
  129:   Summary: Some new graphs of contribution to likelihood
  130: 
  131:   Revision 1.203  2015/09/30 17:45:14  brouard
  132:   Summary: looking at better estimation of the hessian
  133: 
  134:   Also a better criteria for convergence to the period prevalence And
  135:   therefore adding the number of years needed to converge. (The
  136:   prevalence in any alive state shold sum to one
  137: 
  138:   Revision 1.202  2015/09/22 19:45:16  brouard
  139:   Summary: Adding some overall graph on contribution to likelihood. Might change
  140: 
  141:   Revision 1.201  2015/09/15 17:34:58  brouard
  142:   Summary: 0.98r0
  143: 
  144:   - Some new graphs like suvival functions
  145:   - Some bugs fixed like model=1+age+V2.
  146: 
  147:   Revision 1.200  2015/09/09 16:53:55  brouard
  148:   Summary: Big bug thanks to Flavia
  149: 
  150:   Even model=1+age+V2. did not work anymore
  151: 
  152:   Revision 1.199  2015/09/07 14:09:23  brouard
  153:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
  154: 
  155:   Revision 1.198  2015/09/03 07:14:39  brouard
  156:   Summary: 0.98q5 Flavia
  157: 
  158:   Revision 1.197  2015/09/01 18:24:39  brouard
  159:   *** empty log message ***
  160: 
  161:   Revision 1.196  2015/08/18 23:17:52  brouard
  162:   Summary: 0.98q5
  163: 
  164:   Revision 1.195  2015/08/18 16:28:39  brouard
  165:   Summary: Adding a hack for testing purpose
  166: 
  167:   After reading the title, ftol and model lines, if the comment line has
  168:   a q, starting with #q, the answer at the end of the run is quit. It
  169:   permits to run test files in batch with ctest. The former workaround was
  170:   $ echo q | imach foo.imach
  171: 
  172:   Revision 1.194  2015/08/18 13:32:00  brouard
  173:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
  174: 
  175:   Revision 1.193  2015/08/04 07:17:42  brouard
  176:   Summary: 0.98q4
  177: 
  178:   Revision 1.192  2015/07/16 16:49:02  brouard
  179:   Summary: Fixing some outputs
  180: 
  181:   Revision 1.191  2015/07/14 10:00:33  brouard
  182:   Summary: Some fixes
  183: 
  184:   Revision 1.190  2015/05/05 08:51:13  brouard
  185:   Summary: Adding digits in output parameters (7 digits instead of 6)
  186: 
  187:   Fix 1+age+.
  188: 
  189:   Revision 1.189  2015/04/30 14:45:16  brouard
  190:   Summary: 0.98q2
  191: 
  192:   Revision 1.188  2015/04/30 08:27:53  brouard
  193:   *** empty log message ***
  194: 
  195:   Revision 1.187  2015/04/29 09:11:15  brouard
  196:   *** empty log message ***
  197: 
  198:   Revision 1.186  2015/04/23 12:01:52  brouard
  199:   Summary: V1*age is working now, version 0.98q1
  200: 
  201:   Some codes had been disabled in order to simplify and Vn*age was
  202:   working in the optimization phase, ie, giving correct MLE parameters,
  203:   but, as usual, outputs were not correct and program core dumped.
  204: 
  205:   Revision 1.185  2015/03/11 13:26:42  brouard
  206:   Summary: Inclusion of compile and links command line for Intel Compiler
  207: 
  208:   Revision 1.184  2015/03/11 11:52:39  brouard
  209:   Summary: Back from Windows 8. Intel Compiler
  210: 
  211:   Revision 1.183  2015/03/10 20:34:32  brouard
  212:   Summary: 0.98q0, trying with directest, mnbrak fixed
  213: 
  214:   We use directest instead of original Powell test; probably no
  215:   incidence on the results, but better justifications;
  216:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
  217:   wrong results.
  218: 
  219:   Revision 1.182  2015/02/12 08:19:57  brouard
  220:   Summary: Trying to keep directest which seems simpler and more general
  221:   Author: Nicolas Brouard
  222: 
  223:   Revision 1.181  2015/02/11 23:22:24  brouard
  224:   Summary: Comments on Powell added
  225: 
  226:   Author:
  227: 
  228:   Revision 1.180  2015/02/11 17:33:45  brouard
  229:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
  230: 
  231:   Revision 1.179  2015/01/04 09:57:06  brouard
  232:   Summary: back to OS/X
  233: 
  234:   Revision 1.178  2015/01/04 09:35:48  brouard
  235:   *** empty log message ***
  236: 
  237:   Revision 1.177  2015/01/03 18:40:56  brouard
  238:   Summary: Still testing ilc32 on OSX
  239: 
  240:   Revision 1.176  2015/01/03 16:45:04  brouard
  241:   *** empty log message ***
  242: 
  243:   Revision 1.175  2015/01/03 16:33:42  brouard
  244:   *** empty log message ***
  245: 
  246:   Revision 1.174  2015/01/03 16:15:49  brouard
  247:   Summary: Still in cross-compilation
  248: 
  249:   Revision 1.173  2015/01/03 12:06:26  brouard
  250:   Summary: trying to detect cross-compilation
  251: 
  252:   Revision 1.172  2014/12/27 12:07:47  brouard
  253:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
  254: 
  255:   Revision 1.171  2014/12/23 13:26:59  brouard
  256:   Summary: Back from Visual C
  257: 
  258:   Still problem with utsname.h on Windows
  259: 
  260:   Revision 1.170  2014/12/23 11:17:12  brouard
  261:   Summary: Cleaning some \%% back to %%
  262: 
  263:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
  264: 
  265:   Revision 1.169  2014/12/22 23:08:31  brouard
  266:   Summary: 0.98p
  267: 
  268:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
  269: 
  270:   Revision 1.168  2014/12/22 15:17:42  brouard
  271:   Summary: update
  272: 
  273:   Revision 1.167  2014/12/22 13:50:56  brouard
  274:   Summary: Testing uname and compiler version and if compiled 32 or 64
  275: 
  276:   Testing on Linux 64
  277: 
  278:   Revision 1.166  2014/12/22 11:40:47  brouard
  279:   *** empty log message ***
  280: 
  281:   Revision 1.165  2014/12/16 11:20:36  brouard
  282:   Summary: After compiling on Visual C
  283: 
  284:   * imach.c (Module): Merging 1.61 to 1.162
  285: 
  286:   Revision 1.164  2014/12/16 10:52:11  brouard
  287:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
  288: 
  289:   * imach.c (Module): Merging 1.61 to 1.162
  290: 
  291:   Revision 1.163  2014/12/16 10:30:11  brouard
  292:   * imach.c (Module): Merging 1.61 to 1.162
  293: 
  294:   Revision 1.162  2014/09/25 11:43:39  brouard
  295:   Summary: temporary backup 0.99!
  296: 
  297:   Revision 1.1  2014/09/16 11:06:58  brouard
  298:   Summary: With some code (wrong) for nlopt
  299: 
  300:   Author:
  301: 
  302:   Revision 1.161  2014/09/15 20:41:41  brouard
  303:   Summary: Problem with macro SQR on Intel compiler
  304: 
  305:   Revision 1.160  2014/09/02 09:24:05  brouard
  306:   *** empty log message ***
  307: 
  308:   Revision 1.159  2014/09/01 10:34:10  brouard
  309:   Summary: WIN32
  310:   Author: Brouard
  311: 
  312:   Revision 1.158  2014/08/27 17:11:51  brouard
  313:   *** empty log message ***
  314: 
  315:   Revision 1.157  2014/08/27 16:26:55  brouard
  316:   Summary: Preparing windows Visual studio version
  317:   Author: Brouard
  318: 
  319:   In order to compile on Visual studio, time.h is now correct and time_t
  320:   and tm struct should be used. difftime should be used but sometimes I
  321:   just make the differences in raw time format (time(&now).
  322:   Trying to suppress #ifdef LINUX
  323:   Add xdg-open for __linux in order to open default browser.
  324: 
  325:   Revision 1.156  2014/08/25 20:10:10  brouard
  326:   *** empty log message ***
  327: 
  328:   Revision 1.155  2014/08/25 18:32:34  brouard
  329:   Summary: New compile, minor changes
  330:   Author: Brouard
  331: 
  332:   Revision 1.154  2014/06/20 17:32:08  brouard
  333:   Summary: Outputs now all graphs of convergence to period prevalence
  334: 
  335:   Revision 1.153  2014/06/20 16:45:46  brouard
  336:   Summary: If 3 live state, convergence to period prevalence on same graph
  337:   Author: Brouard
  338: 
  339:   Revision 1.152  2014/06/18 17:54:09  brouard
  340:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
  341: 
  342:   Revision 1.151  2014/06/18 16:43:30  brouard
  343:   *** empty log message ***
  344: 
  345:   Revision 1.150  2014/06/18 16:42:35  brouard
  346:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
  347:   Author: brouard
  348: 
  349:   Revision 1.149  2014/06/18 15:51:14  brouard
  350:   Summary: Some fixes in parameter files errors
  351:   Author: Nicolas Brouard
  352: 
  353:   Revision 1.148  2014/06/17 17:38:48  brouard
  354:   Summary: Nothing new
  355:   Author: Brouard
  356: 
  357:   Just a new packaging for OS/X version 0.98nS
  358: 
  359:   Revision 1.147  2014/06/16 10:33:11  brouard
  360:   *** empty log message ***
  361: 
  362:   Revision 1.146  2014/06/16 10:20:28  brouard
  363:   Summary: Merge
  364:   Author: Brouard
  365: 
  366:   Merge, before building revised version.
  367: 
  368:   Revision 1.145  2014/06/10 21:23:15  brouard
  369:   Summary: Debugging with valgrind
  370:   Author: Nicolas Brouard
  371: 
  372:   Lot of changes in order to output the results with some covariates
  373:   After the Edimburgh REVES conference 2014, it seems mandatory to
  374:   improve the code.
  375:   No more memory valgrind error but a lot has to be done in order to
  376:   continue the work of splitting the code into subroutines.
  377:   Also, decodemodel has been improved. Tricode is still not
  378:   optimal. nbcode should be improved. Documentation has been added in
  379:   the source code.
  380: 
  381:   Revision 1.143  2014/01/26 09:45:38  brouard
  382:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
  383: 
  384:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  385:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
  386: 
  387:   Revision 1.142  2014/01/26 03:57:36  brouard
  388:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
  389: 
  390:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  391: 
  392:   Revision 1.141  2014/01/26 02:42:01  brouard
  393:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  394: 
  395:   Revision 1.140  2011/09/02 10:37:54  brouard
  396:   Summary: times.h is ok with mingw32 now.
  397: 
  398:   Revision 1.139  2010/06/14 07:50:17  brouard
  399:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
  400:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
  401: 
  402:   Revision 1.138  2010/04/30 18:19:40  brouard
  403:   *** empty log message ***
  404: 
  405:   Revision 1.137  2010/04/29 18:11:38  brouard
  406:   (Module): Checking covariates for more complex models
  407:   than V1+V2. A lot of change to be done. Unstable.
  408: 
  409:   Revision 1.136  2010/04/26 20:30:53  brouard
  410:   (Module): merging some libgsl code. Fixing computation
  411:   of likelione (using inter/intrapolation if mle = 0) in order to
  412:   get same likelihood as if mle=1.
  413:   Some cleaning of code and comments added.
  414: 
  415:   Revision 1.135  2009/10/29 15:33:14  brouard
  416:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  417: 
  418:   Revision 1.134  2009/10/29 13:18:53  brouard
  419:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  420: 
  421:   Revision 1.133  2009/07/06 10:21:25  brouard
  422:   just nforces
  423: 
  424:   Revision 1.132  2009/07/06 08:22:05  brouard
  425:   Many tings
  426: 
  427:   Revision 1.131  2009/06/20 16:22:47  brouard
  428:   Some dimensions resccaled
  429: 
  430:   Revision 1.130  2009/05/26 06:44:34  brouard
  431:   (Module): Max Covariate is now set to 20 instead of 8. A
  432:   lot of cleaning with variables initialized to 0. Trying to make
  433:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
  434: 
  435:   Revision 1.129  2007/08/31 13:49:27  lievre
  436:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
  437: 
  438:   Revision 1.128  2006/06/30 13:02:05  brouard
  439:   (Module): Clarifications on computing e.j
  440: 
  441:   Revision 1.127  2006/04/28 18:11:50  brouard
  442:   (Module): Yes the sum of survivors was wrong since
  443:   imach-114 because nhstepm was no more computed in the age
  444:   loop. Now we define nhstepma in the age loop.
  445:   (Module): In order to speed up (in case of numerous covariates) we
  446:   compute health expectancies (without variances) in a first step
  447:   and then all the health expectancies with variances or standard
  448:   deviation (needs data from the Hessian matrices) which slows the
  449:   computation.
  450:   In the future we should be able to stop the program is only health
  451:   expectancies and graph are needed without standard deviations.
  452: 
  453:   Revision 1.126  2006/04/28 17:23:28  brouard
  454:   (Module): Yes the sum of survivors was wrong since
  455:   imach-114 because nhstepm was no more computed in the age
  456:   loop. Now we define nhstepma in the age loop.
  457:   Version 0.98h
  458: 
  459:   Revision 1.125  2006/04/04 15:20:31  lievre
  460:   Errors in calculation of health expectancies. Age was not initialized.
  461:   Forecasting file added.
  462: 
  463:   Revision 1.124  2006/03/22 17:13:53  lievre
  464:   Parameters are printed with %lf instead of %f (more numbers after the comma).
  465:   The log-likelihood is printed in the log file
  466: 
  467:   Revision 1.123  2006/03/20 10:52:43  brouard
  468:   * imach.c (Module): <title> changed, corresponds to .htm file
  469:   name. <head> headers where missing.
  470: 
  471:   * imach.c (Module): Weights can have a decimal point as for
  472:   English (a comma might work with a correct LC_NUMERIC environment,
  473:   otherwise the weight is truncated).
  474:   Modification of warning when the covariates values are not 0 or
  475:   1.
  476:   Version 0.98g
  477: 
  478:   Revision 1.122  2006/03/20 09:45:41  brouard
  479:   (Module): Weights can have a decimal point as for
  480:   English (a comma might work with a correct LC_NUMERIC environment,
  481:   otherwise the weight is truncated).
  482:   Modification of warning when the covariates values are not 0 or
  483:   1.
  484:   Version 0.98g
  485: 
  486:   Revision 1.121  2006/03/16 17:45:01  lievre
  487:   * imach.c (Module): Comments concerning covariates added
  488: 
  489:   * imach.c (Module): refinements in the computation of lli if
  490:   status=-2 in order to have more reliable computation if stepm is
  491:   not 1 month. Version 0.98f
  492: 
  493:   Revision 1.120  2006/03/16 15:10:38  lievre
  494:   (Module): refinements in the computation of lli if
  495:   status=-2 in order to have more reliable computation if stepm is
  496:   not 1 month. Version 0.98f
  497: 
  498:   Revision 1.119  2006/03/15 17:42:26  brouard
  499:   (Module): Bug if status = -2, the loglikelihood was
  500:   computed as likelihood omitting the logarithm. Version O.98e
  501: 
  502:   Revision 1.118  2006/03/14 18:20:07  brouard
  503:   (Module): varevsij Comments added explaining the second
  504:   table of variances if popbased=1 .
  505:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  506:   (Module): Function pstamp added
  507:   (Module): Version 0.98d
  508: 
  509:   Revision 1.117  2006/03/14 17:16:22  brouard
  510:   (Module): varevsij Comments added explaining the second
  511:   table of variances if popbased=1 .
  512:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  513:   (Module): Function pstamp added
  514:   (Module): Version 0.98d
  515: 
  516:   Revision 1.116  2006/03/06 10:29:27  brouard
  517:   (Module): Variance-covariance wrong links and
  518:   varian-covariance of ej. is needed (Saito).
  519: 
  520:   Revision 1.115  2006/02/27 12:17:45  brouard
  521:   (Module): One freematrix added in mlikeli! 0.98c
  522: 
  523:   Revision 1.114  2006/02/26 12:57:58  brouard
  524:   (Module): Some improvements in processing parameter
  525:   filename with strsep.
  526: 
  527:   Revision 1.113  2006/02/24 14:20:24  brouard
  528:   (Module): Memory leaks checks with valgrind and:
  529:   datafile was not closed, some imatrix were not freed and on matrix
  530:   allocation too.
  531: 
  532:   Revision 1.112  2006/01/30 09:55:26  brouard
  533:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
  534: 
  535:   Revision 1.111  2006/01/25 20:38:18  brouard
  536:   (Module): Lots of cleaning and bugs added (Gompertz)
  537:   (Module): Comments can be added in data file. Missing date values
  538:   can be a simple dot '.'.
  539: 
  540:   Revision 1.110  2006/01/25 00:51:50  brouard
  541:   (Module): Lots of cleaning and bugs added (Gompertz)
  542: 
  543:   Revision 1.109  2006/01/24 19:37:15  brouard
  544:   (Module): Comments (lines starting with a #) are allowed in data.
  545: 
  546:   Revision 1.108  2006/01/19 18:05:42  lievre
  547:   Gnuplot problem appeared...
  548:   To be fixed
  549: 
  550:   Revision 1.107  2006/01/19 16:20:37  brouard
  551:   Test existence of gnuplot in imach path
  552: 
  553:   Revision 1.106  2006/01/19 13:24:36  brouard
  554:   Some cleaning and links added in html output
  555: 
  556:   Revision 1.105  2006/01/05 20:23:19  lievre
  557:   *** empty log message ***
  558: 
  559:   Revision 1.104  2005/09/30 16:11:43  lievre
  560:   (Module): sump fixed, loop imx fixed, and simplifications.
  561:   (Module): If the status is missing at the last wave but we know
  562:   that the person is alive, then we can code his/her status as -2
  563:   (instead of missing=-1 in earlier versions) and his/her
  564:   contributions to the likelihood is 1 - Prob of dying from last
  565:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
  566:   the healthy state at last known wave). Version is 0.98
  567: 
  568:   Revision 1.103  2005/09/30 15:54:49  lievre
  569:   (Module): sump fixed, loop imx fixed, and simplifications.
  570: 
  571:   Revision 1.102  2004/09/15 17:31:30  brouard
  572:   Add the possibility to read data file including tab characters.
  573: 
  574:   Revision 1.101  2004/09/15 10:38:38  brouard
  575:   Fix on curr_time
  576: 
  577:   Revision 1.100  2004/07/12 18:29:06  brouard
  578:   Add version for Mac OS X. Just define UNIX in Makefile
  579: 
  580:   Revision 1.99  2004/06/05 08:57:40  brouard
  581:   *** empty log message ***
  582: 
  583:   Revision 1.98  2004/05/16 15:05:56  brouard
  584:   New version 0.97 . First attempt to estimate force of mortality
  585:   directly from the data i.e. without the need of knowing the health
  586:   state at each age, but using a Gompertz model: log u =a + b*age .
  587:   This is the basic analysis of mortality and should be done before any
  588:   other analysis, in order to test if the mortality estimated from the
  589:   cross-longitudinal survey is different from the mortality estimated
  590:   from other sources like vital statistic data.
  591: 
  592:   The same imach parameter file can be used but the option for mle should be -3.
  593: 
  594:   Agnès, who wrote this part of the code, tried to keep most of the
  595:   former routines in order to include the new code within the former code.
  596: 
  597:   The output is very simple: only an estimate of the intercept and of
  598:   the slope with 95% confident intervals.
  599: 
  600:   Current limitations:
  601:   A) Even if you enter covariates, i.e. with the
  602:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
  603:   B) There is no computation of Life Expectancy nor Life Table.
  604: 
  605:   Revision 1.97  2004/02/20 13:25:42  lievre
  606:   Version 0.96d. Population forecasting command line is (temporarily)
  607:   suppressed.
  608: 
  609:   Revision 1.96  2003/07/15 15:38:55  brouard
  610:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
  611:   rewritten within the same printf. Workaround: many printfs.
  612: 
  613:   Revision 1.95  2003/07/08 07:54:34  brouard
  614:   * imach.c (Repository):
  615:   (Repository): Using imachwizard code to output a more meaningful covariance
  616:   matrix (cov(a12,c31) instead of numbers.
  617: 
  618:   Revision 1.94  2003/06/27 13:00:02  brouard
  619:   Just cleaning
  620: 
  621:   Revision 1.93  2003/06/25 16:33:55  brouard
  622:   (Module): On windows (cygwin) function asctime_r doesn't
  623:   exist so I changed back to asctime which exists.
  624:   (Module): Version 0.96b
  625: 
  626:   Revision 1.92  2003/06/25 16:30:45  brouard
  627:   (Module): On windows (cygwin) function asctime_r doesn't
  628:   exist so I changed back to asctime which exists.
  629: 
  630:   Revision 1.91  2003/06/25 15:30:29  brouard
  631:   * imach.c (Repository): Duplicated warning errors corrected.
  632:   (Repository): Elapsed time after each iteration is now output. It
  633:   helps to forecast when convergence will be reached. Elapsed time
  634:   is stamped in powell.  We created a new html file for the graphs
  635:   concerning matrix of covariance. It has extension -cov.htm.
  636: 
  637:   Revision 1.90  2003/06/24 12:34:15  brouard
  638:   (Module): Some bugs corrected for windows. Also, when
  639:   mle=-1 a template is output in file "or"mypar.txt with the design
  640:   of the covariance matrix to be input.
  641: 
  642:   Revision 1.89  2003/06/24 12:30:52  brouard
  643:   (Module): Some bugs corrected for windows. Also, when
  644:   mle=-1 a template is output in file "or"mypar.txt with the design
  645:   of the covariance matrix to be input.
  646: 
  647:   Revision 1.88  2003/06/23 17:54:56  brouard
  648:   * 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.
  649: 
  650:   Revision 1.87  2003/06/18 12:26:01  brouard
  651:   Version 0.96
  652: 
  653:   Revision 1.86  2003/06/17 20:04:08  brouard
  654:   (Module): Change position of html and gnuplot routines and added
  655:   routine fileappend.
  656: 
  657:   Revision 1.85  2003/06/17 13:12:43  brouard
  658:   * imach.c (Repository): Check when date of death was earlier that
  659:   current date of interview. It may happen when the death was just
  660:   prior to the death. In this case, dh was negative and likelihood
  661:   was wrong (infinity). We still send an "Error" but patch by
  662:   assuming that the date of death was just one stepm after the
  663:   interview.
  664:   (Repository): Because some people have very long ID (first column)
  665:   we changed int to long in num[] and we added a new lvector for
  666:   memory allocation. But we also truncated to 8 characters (left
  667:   truncation)
  668:   (Repository): No more line truncation errors.
  669: 
  670:   Revision 1.84  2003/06/13 21:44:43  brouard
  671:   * imach.c (Repository): Replace "freqsummary" at a correct
  672:   place. It differs from routine "prevalence" which may be called
  673:   many times. Probs is memory consuming and must be used with
  674:   parcimony.
  675:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
  676: 
  677:   Revision 1.83  2003/06/10 13:39:11  lievre
  678:   *** empty log message ***
  679: 
  680:   Revision 1.82  2003/06/05 15:57:20  brouard
  681:   Add log in  imach.c and  fullversion number is now printed.
  682: 
  683: */
  684: /*
  685:    Interpolated Markov Chain
  686: 
  687:   Short summary of the programme:
  688:   
  689:   This program computes Healthy Life Expectancies or State-specific
  690:   (if states aren't health statuses) Expectancies from
  691:   cross-longitudinal data. Cross-longitudinal data consist in: 
  692: 
  693:   -1- a first survey ("cross") where individuals from different ages
  694:   are interviewed on their health status or degree of disability (in
  695:   the case of a health survey which is our main interest)
  696: 
  697:   -2- at least a second wave of interviews ("longitudinal") which
  698:   measure each change (if any) in individual health status.  Health
  699:   expectancies are computed from the time spent in each health state
  700:   according to a model. More health states you consider, more time is
  701:   necessary to reach the Maximum Likelihood of the parameters involved
  702:   in the model.  The simplest model is the multinomial logistic model
  703:   where pij is the probability to be observed in state j at the second
  704:   wave conditional to be observed in state i at the first
  705:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
  706:   etc , where 'age' is age and 'sex' is a covariate. If you want to
  707:   have a more complex model than "constant and age", you should modify
  708:   the program where the markup *Covariates have to be included here
  709:   again* invites you to do it.  More covariates you add, slower the
  710:   convergence.
  711: 
  712:   The advantage of this computer programme, compared to a simple
  713:   multinomial logistic model, is clear when the delay between waves is not
  714:   identical for each individual. Also, if a individual missed an
  715:   intermediate interview, the information is lost, but taken into
  716:   account using an interpolation or extrapolation.  
  717: 
  718:   hPijx is the probability to be observed in state i at age x+h
  719:   conditional to the observed state i at age x. The delay 'h' can be
  720:   split into an exact number (nh*stepm) of unobserved intermediate
  721:   states. This elementary transition (by month, quarter,
  722:   semester or year) is modelled as a multinomial logistic.  The hPx
  723:   matrix is simply the matrix product of nh*stepm elementary matrices
  724:   and the contribution of each individual to the likelihood is simply
  725:   hPijx.
  726: 
  727:   Also this programme outputs the covariance matrix of the parameters but also
  728:   of the life expectancies. It also computes the period (stable) prevalence.
  729: 
  730: Back prevalence and projections:
  731: 
  732:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
  733:    double agemaxpar, double ftolpl, int *ncvyearp, double
  734:    dateprev1,double dateprev2, int firstpass, int lastpass, int
  735:    mobilavproj)
  736: 
  737:     Computes the back prevalence limit for any combination of
  738:     covariate values k at any age between ageminpar and agemaxpar and
  739:     returns it in **bprlim. In the loops,
  740: 
  741:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
  742:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
  743: 
  744:    - hBijx Back Probability to be in state i at age x-h being in j at x
  745:    Computes for any combination of covariates k and any age between bage and fage 
  746:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
  747:  			oldm=oldms;savm=savms;
  748: 
  749:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
  750:      Computes the transition matrix starting at age 'age' over
  751:      'nhstepm*hstepm*stepm' months (i.e. until
  752:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
  753:      nhstepm*hstepm matrices. 
  754: 
  755:      Returns p3mat[i][j][h] after calling
  756:      p3mat[i][j][h]=matprod2(newm,
  757:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
  758:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
  759:      oldm);
  760: 
  761: Important routines
  762: 
  763: - func (or funcone), computes logit (pij) distinguishing
  764:   o fixed variables (single or product dummies or quantitative);
  765:   o varying variables by:
  766:    (1) wave (single, product dummies, quantitative), 
  767:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
  768:        % fixed dummy (treated) or quantitative (not done because time-consuming);
  769:        % varying dummy (not done) or quantitative (not done);
  770: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
  771:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
  772: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
  773:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
  774:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
  775: 
  776: 
  777:   
  778:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
  779:            Institut national d'études démographiques, Paris.
  780:   This software have been partly granted by Euro-REVES, a concerted action
  781:   from the European Union.
  782:   It is copyrighted identically to a GNU software product, ie programme and
  783:   software can be distributed freely for non commercial use. Latest version
  784:   can be accessed at http://euroreves.ined.fr/imach .
  785: 
  786:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
  787:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
  788:   
  789:   **********************************************************************/
  790: /*
  791:   main
  792:   read parameterfile
  793:   read datafile
  794:   concatwav
  795:   freqsummary
  796:   if (mle >= 1)
  797:     mlikeli
  798:   print results files
  799:   if mle==1 
  800:      computes hessian
  801:   read end of parameter file: agemin, agemax, bage, fage, estepm
  802:       begin-prev-date,...
  803:   open gnuplot file
  804:   open html file
  805:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
  806:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
  807:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
  808:     freexexit2 possible for memory heap.
  809: 
  810:   h Pij x                         | pij_nom  ficrestpij
  811:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
  812:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
  813:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
  814: 
  815:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
  816:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
  817:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
  818:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
  819:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
  820: 
  821:   forecasting if prevfcast==1 prevforecast call prevalence()
  822:   health expectancies
  823:   Variance-covariance of DFLE
  824:   prevalence()
  825:    movingaverage()
  826:   varevsij() 
  827:   if popbased==1 varevsij(,popbased)
  828:   total life expectancies
  829:   Variance of period (stable) prevalence
  830:  end
  831: */
  832: 
  833: /* #define DEBUG */
  834: /* #define DEBUGBRENT */
  835: /* #define DEBUGLINMIN */
  836: /* #define DEBUGHESS */
  837: #define DEBUGHESSIJ
  838: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
  839: #define POWELL /* Instead of NLOPT */
  840: #define POWELLNOF3INFF1TEST /* Skip test */
  841: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
  842: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
  843: 
  844: #include <math.h>
  845: #include <stdio.h>
  846: #include <stdlib.h>
  847: #include <string.h>
  848: #include <ctype.h>
  849: 
  850: #ifdef _WIN32
  851: #include <io.h>
  852: #include <windows.h>
  853: #include <tchar.h>
  854: #else
  855: #include <unistd.h>
  856: #endif
  857: 
  858: #include <limits.h>
  859: #include <sys/types.h>
  860: 
  861: #if defined(__GNUC__)
  862: #include <sys/utsname.h> /* Doesn't work on Windows */
  863: #endif
  864: 
  865: #include <sys/stat.h>
  866: #include <errno.h>
  867: /* extern int errno; */
  868: 
  869: /* #ifdef LINUX */
  870: /* #include <time.h> */
  871: /* #include "timeval.h" */
  872: /* #else */
  873: /* #include <sys/time.h> */
  874: /* #endif */
  875: 
  876: #include <time.h>
  877: 
  878: #ifdef GSL
  879: #include <gsl/gsl_errno.h>
  880: #include <gsl/gsl_multimin.h>
  881: #endif
  882: 
  883: 
  884: #ifdef NLOPT
  885: #include <nlopt.h>
  886: typedef struct {
  887:   double (* function)(double [] );
  888: } myfunc_data ;
  889: #endif
  890: 
  891: /* #include <libintl.h> */
  892: /* #define _(String) gettext (String) */
  893: 
  894: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
  895: 
  896: #define GNUPLOTPROGRAM "gnuplot"
  897: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
  898: #define FILENAMELENGTH 132
  899: 
  900: #define	GLOCK_ERROR_NOPATH		-1	/* empty path */
  901: #define	GLOCK_ERROR_GETCWD		-2	/* cannot get cwd */
  902: 
  903: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
  904: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
  905: 
  906: #define NINTERVMAX 8
  907: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
  908: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
  909: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
  910: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
  911: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
  912: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
  913: #define MAXN 20000
  914: #define YEARM 12. /**< Number of months per year */
  915: /* #define AGESUP 130 */
  916: #define AGESUP 150
  917: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
  918: #define AGEBASE 40
  919: #define AGEOVERFLOW 1.e20
  920: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
  921: #ifdef _WIN32
  922: #define DIRSEPARATOR '\\'
  923: #define CHARSEPARATOR "\\"
  924: #define ODIRSEPARATOR '/'
  925: #else
  926: #define DIRSEPARATOR '/'
  927: #define CHARSEPARATOR "/"
  928: #define ODIRSEPARATOR '\\'
  929: #endif
  930: 
  931: /* $Id: imach.c,v 1.242 2016/08/30 15:01:20 brouard Exp $ */
  932: /* $State: Exp $ */
  933: #include "version.h"
  934: char version[]=__IMACH_VERSION__;
  935: 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";
  936: char fullversion[]="$Revision: 1.242 $ $Date: 2016/08/30 15:01:20 $"; 
  937: char strstart[80];
  938: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
  939: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
  940: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
  941: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
  942: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
  943: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
  944: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
  945: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
  946: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
  947: int cptcovprodnoage=0; /**< Number of covariate products without age */   
  948: int cptcoveff=0; /* Total number of covariates to vary for printing results */
  949: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
  950: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
  951: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
  952: int nsd=0; /**< Total number of single dummy variables (output) */
  953: int nsq=0; /**< Total number of single quantitative variables (output) */
  954: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
  955: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
  956: int ntveff=0; /**< ntveff number of effective time varying variables */
  957: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
  958: int cptcov=0; /* Working variable */
  959: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
  960: int npar=NPARMAX;
  961: int nlstate=2; /* Number of live states */
  962: int ndeath=1; /* Number of dead states */
  963: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
  964: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
  965: int popbased=0;
  966: 
  967: int *wav; /* Number of waves for this individuual 0 is possible */
  968: int maxwav=0; /* Maxim number of waves */
  969: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
  970: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
  971: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
  972: 		   to the likelihood and the sum of weights (done by funcone)*/
  973: int mle=1, weightopt=0;
  974: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
  975: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
  976: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
  977: 	   * wave mi and wave mi+1 is not an exact multiple of stepm. */
  978: int countcallfunc=0;  /* Count the number of calls to func */
  979: int selected(int kvar); /* Is covariate kvar selected for printing results */
  980: 
  981: double jmean=1; /* Mean space between 2 waves */
  982: double **matprod2(); /* test */
  983: double **oldm, **newm, **savm; /* Working pointers to matrices */
  984: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
  985: double	 **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
  986: 
  987: /*FILE *fic ; */ /* Used in readdata only */
  988: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
  989: FILE *ficlog, *ficrespow;
  990: int globpr=0; /* Global variable for printing or not */
  991: double fretone; /* Only one call to likelihood */
  992: long ipmx=0; /* Number of contributions */
  993: double sw; /* Sum of weights */
  994: char filerespow[FILENAMELENGTH];
  995: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
  996: FILE *ficresilk;
  997: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
  998: FILE *ficresprobmorprev;
  999: FILE *fichtm, *fichtmcov; /* Html File */
 1000: FILE *ficreseij;
 1001: char filerese[FILENAMELENGTH];
 1002: FILE *ficresstdeij;
 1003: char fileresstde[FILENAMELENGTH];
 1004: FILE *ficrescveij;
 1005: char filerescve[FILENAMELENGTH];
 1006: FILE  *ficresvij;
 1007: char fileresv[FILENAMELENGTH];
 1008: FILE  *ficresvpl;
 1009: char fileresvpl[FILENAMELENGTH];
 1010: char title[MAXLINE];
 1011: char model[MAXLINE]; /**< The model line */
 1012: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
 1013: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
 1014: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
 1015: char command[FILENAMELENGTH];
 1016: int  outcmd=0;
 1017: 
 1018: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
 1019: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
 1020: char filelog[FILENAMELENGTH]; /* Log file */
 1021: char filerest[FILENAMELENGTH];
 1022: char fileregp[FILENAMELENGTH];
 1023: char popfile[FILENAMELENGTH];
 1024: 
 1025: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
 1026: 
 1027: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
 1028: /* struct timezone tzp; */
 1029: /* extern int gettimeofday(); */
 1030: struct tm tml, *gmtime(), *localtime();
 1031: 
 1032: extern time_t time();
 1033: 
 1034: struct tm start_time, end_time, curr_time, last_time, forecast_time;
 1035: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
 1036: struct tm tm;
 1037: 
 1038: char strcurr[80], strfor[80];
 1039: 
 1040: char *endptr;
 1041: long lval;
 1042: double dval;
 1043: 
 1044: #define NR_END 1
 1045: #define FREE_ARG char*
 1046: #define FTOL 1.0e-10
 1047: 
 1048: #define NRANSI 
 1049: #define ITMAX 200
 1050: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
 1051: 
 1052: #define TOL 2.0e-4 
 1053: 
 1054: #define CGOLD 0.3819660 
 1055: #define ZEPS 1.0e-10 
 1056: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
 1057: 
 1058: #define GOLD 1.618034 
 1059: #define GLIMIT 100.0 
 1060: #define TINY 1.0e-20 
 1061: 
 1062: static double maxarg1,maxarg2;
 1063: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
 1064: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
 1065:   
 1066: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
 1067: #define rint(a) floor(a+0.5)
 1068: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
 1069: #define mytinydouble 1.0e-16
 1070: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
 1071: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
 1072: /* static double dsqrarg; */
 1073: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
 1074: static double sqrarg;
 1075: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
 1076: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
 1077: int agegomp= AGEGOMP;
 1078: 
 1079: int imx; 
 1080: int stepm=1;
 1081: /* Stepm, step in month: minimum step interpolation*/
 1082: 
 1083: int estepm;
 1084: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
 1085: 
 1086: int m,nb;
 1087: long *num;
 1088: int firstpass=0, lastpass=4,*cod, *cens;
 1089: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
 1090: 		   covariate for which somebody answered excluding 
 1091: 		   undefined. Usually 2: 0 and 1. */
 1092: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
 1093: 			     covariate for which somebody answered including 
 1094: 			     undefined. Usually 3: -1, 0 and 1. */
 1095: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
 1096: double **pmmij, ***probs; /* Global pointer */
 1097: double ***mobaverage, ***mobaverages; /* New global variable */
 1098: double *ageexmed,*agecens;
 1099: double dateintmean=0;
 1100: 
 1101: double *weight;
 1102: int **s; /* Status */
 1103: double *agedc;
 1104: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
 1105: 		  * covar=matrix(0,NCOVMAX,1,n); 
 1106: 		  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
 1107: double **coqvar; /* Fixed quantitative covariate iqv */
 1108: double ***cotvar; /* Time varying covariate itv */
 1109: double ***cotqvar; /* Time varying quantitative covariate itqv */
 1110: double  idx; 
 1111: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
 1112: /*           V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1113: /*k          1  2   3   4     5    6    7     8    9 */
 1114: /*Tvar[k]=   5  4   3   6     5    2    7     1    1 */
 1115: /* Tndvar[k]    1   2   3               4          5 */
 1116: /*TDvar         4   3   6               7          1 */ /* For outputs only; combination of dummies fixed or varying */
 1117: /* Tns[k]    1  2   2              4               5 */ /* Number of single cova */
 1118: /* TvarsD[k]    1   2                              3 */ /* Number of single dummy cova */
 1119: /* TvarsDind    2   3                              9 */ /* position K of single dummy cova */
 1120: /* TvarsQ[k] 1                     2                 */ /* Number of single quantitative cova */
 1121: /* TvarsQind 1                     6                 */ /* position K of single quantitative cova */
 1122: /* Tprod[i]=k           4               7            */
 1123: /* Tage[i]=k                  5               8      */
 1124: /* */
 1125: /* Type                    */
 1126: /* V         1  2  3  4  5 */
 1127: /*           F  F  V  V  V */
 1128: /*           D  Q  D  D  Q */
 1129: /*                         */
 1130: int *TvarsD;
 1131: int *TvarsDind;
 1132: int *TvarsQ;
 1133: int *TvarsQind;
 1134: 
 1135: #define MAXRESULTLINES 10
 1136: int nresult=0;
 1137: int TKresult[MAXRESULTLINES];
 1138: int Tresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
 1139: int Tinvresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
 1140: int Tvresult[MAXRESULTLINES][NCOVMAX]; /* For dummy variable , variable # (output) */
 1141: double Tqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
 1142: double Tqinvresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
 1143: int Tvqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , variable # (output) */
 1144: 
 1145: /* int *TDvar; /\**< TDvar[1]=4,  TDvarF[2]=3, TDvar[3]=6  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
 1146: int *TvarF; /**< TvarF[1]=Tvar[6]=2,  TvarF[2]=Tvar[7]=7, TvarF[3]=Tvar[9]=1  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1147: int *TvarFind; /**< TvarFind[1]=6,  TvarFind[2]=7, Tvarind[3]=9  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1148: int *TvarV; /**< TvarV[1]=Tvar[1]=5, TvarV[2]=Tvar[2]=4  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1149: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1150: int *TvarA; /**< TvarA[1]=Tvar[5]=5, TvarA[2]=Tvar[8]=1  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1151: int *TvarAind; /**< TvarindA[1]=5, TvarAind[2]=8  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1152: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1153: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1154: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
 1155: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
 1156: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
 1157: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
 1158: int *TvarVQ; /* TvarVQ[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying quantitative variable */
 1159: int *TvarVQind; /* TvarVQind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying quantitative variable */
 1160: 
 1161: int *Tvarsel; /**< Selected covariates for output */
 1162: double *Tvalsel; /**< Selected modality value of covariate for output */
 1163: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
 1164: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
 1165: int *Dummy; /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
 1166: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
 1167: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
 1168: int *Tage;
 1169: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
 1170: int *Tmodelind; /** Tmodelind[Tvaraff[3]]=9 for V1 position,Tvaraff[1]@9={4, 3, 1, 0, 0, 0, 0, 0, 0}, model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
 1171: int *TmodelInvind; /** Tmodelind[Tvaraff[3]]=9 for V1 position,Tvaraff[1]@9={4, 3, 1, 0, 0, 0, 0, 0, 0}, model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/ 
 1172: int *TmodelInvQind; /** Tmodelqind[1]=1 for V5(quantitative varying) position,Tvaraff[1]@9={4, 3, 1, 0, 0, 0, 0, 0, 0}, model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1  */
 1173: int *Ndum; /** Freq of modality (tricode */
 1174: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
 1175: int **Tvard;
 1176: int *Tprod;/**< Gives the k position of the k1 product */
 1177: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
 1178: int *Tposprod; /**< Gives the k1 product from the k position */
 1179:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
 1180:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
 1181: int cptcovprod, *Tvaraff, *invalidvarcomb;
 1182: double *lsurv, *lpop, *tpop;
 1183: 
 1184: #define FD 1; /* Fixed dummy covariate */
 1185: #define FQ 2; /* Fixed quantitative covariate */
 1186: #define FP 3; /* Fixed product covariate */
 1187: #define FPDD 7; /* Fixed product dummy*dummy covariate */
 1188: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
 1189: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
 1190: #define VD 10; /* Varying dummy covariate */
 1191: #define VQ 11; /* Varying quantitative covariate */
 1192: #define VP 12; /* Varying product covariate */
 1193: #define VPDD 13; /* Varying product dummy*dummy covariate */
 1194: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
 1195: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
 1196: #define APFD 16; /* Age product * fixed dummy covariate */
 1197: #define APFQ 17; /* Age product * fixed quantitative covariate */
 1198: #define APVD 18; /* Age product * varying dummy covariate */
 1199: #define APVQ 19; /* Age product * varying quantitative covariate */
 1200: 
 1201: #define FTYPE 1; /* Fixed covariate */
 1202: #define VTYPE 2; /* Varying covariate (loop in wave) */
 1203: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
 1204: 
 1205: struct kmodel{
 1206: 	int maintype; /* main type */
 1207: 	int subtype; /* subtype */
 1208: };
 1209: struct kmodel modell[NCOVMAX];
 1210: 
 1211: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
 1212: double ftolhess; /**< Tolerance for computing hessian */
 1213: 
 1214: /**************** split *************************/
 1215: static	int split( char *path, char *dirc, char *name, char *ext, char *finame )
 1216: {
 1217:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
 1218:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
 1219:   */ 
 1220:   char	*ss;				/* pointer */
 1221:   int	l1=0, l2=0;				/* length counters */
 1222: 
 1223:   l1 = strlen(path );			/* length of path */
 1224:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
 1225:   ss= strrchr( path, DIRSEPARATOR );		/* find last / */
 1226:   if ( ss == NULL ) {			/* no directory, so determine current directory */
 1227:     strcpy( name, path );		/* we got the fullname name because no directory */
 1228:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
 1229:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
 1230:     /* get current working directory */
 1231:     /*    extern  char* getcwd ( char *buf , int len);*/
 1232: #ifdef WIN32
 1233:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
 1234: #else
 1235: 	if (getcwd(dirc, FILENAME_MAX) == NULL) {
 1236: #endif
 1237:       return( GLOCK_ERROR_GETCWD );
 1238:     }
 1239:     /* got dirc from getcwd*/
 1240:     printf(" DIRC = %s \n",dirc);
 1241:   } else {				/* strip directory from path */
 1242:     ss++;				/* after this, the filename */
 1243:     l2 = strlen( ss );			/* length of filename */
 1244:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
 1245:     strcpy( name, ss );		/* save file name */
 1246:     strncpy( dirc, path, l1 - l2 );	/* now the directory */
 1247:     dirc[l1-l2] = '\0';			/* add zero */
 1248:     printf(" DIRC2 = %s \n",dirc);
 1249:   }
 1250:   /* We add a separator at the end of dirc if not exists */
 1251:   l1 = strlen( dirc );			/* length of directory */
 1252:   if( dirc[l1-1] != DIRSEPARATOR ){
 1253:     dirc[l1] =  DIRSEPARATOR;
 1254:     dirc[l1+1] = 0; 
 1255:     printf(" DIRC3 = %s \n",dirc);
 1256:   }
 1257:   ss = strrchr( name, '.' );		/* find last / */
 1258:   if (ss >0){
 1259:     ss++;
 1260:     strcpy(ext,ss);			/* save extension */
 1261:     l1= strlen( name);
 1262:     l2= strlen(ss)+1;
 1263:     strncpy( finame, name, l1-l2);
 1264:     finame[l1-l2]= 0;
 1265:   }
 1266: 
 1267:   return( 0 );				/* we're done */
 1268: }
 1269: 
 1270: 
 1271: /******************************************/
 1272: 
 1273: void replace_back_to_slash(char *s, char*t)
 1274: {
 1275:   int i;
 1276:   int lg=0;
 1277:   i=0;
 1278:   lg=strlen(t);
 1279:   for(i=0; i<= lg; i++) {
 1280:     (s[i] = t[i]);
 1281:     if (t[i]== '\\') s[i]='/';
 1282:   }
 1283: }
 1284: 
 1285: char *trimbb(char *out, char *in)
 1286: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
 1287:   char *s;
 1288:   s=out;
 1289:   while (*in != '\0'){
 1290:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
 1291:       in++;
 1292:     }
 1293:     *out++ = *in++;
 1294:   }
 1295:   *out='\0';
 1296:   return s;
 1297: }
 1298: 
 1299: /* char *substrchaine(char *out, char *in, char *chain) */
 1300: /* { */
 1301: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
 1302: /*   char *s, *t; */
 1303: /*   t=in;s=out; */
 1304: /*   while ((*in != *chain) && (*in != '\0')){ */
 1305: /*     *out++ = *in++; */
 1306: /*   } */
 1307: 
 1308: /*   /\* *in matches *chain *\/ */
 1309: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
 1310: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1311: /*   } */
 1312: /*   in--; chain--; */
 1313: /*   while ( (*in != '\0')){ */
 1314: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1315: /*     *out++ = *in++; */
 1316: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1317: /*   } */
 1318: /*   *out='\0'; */
 1319: /*   out=s; */
 1320: /*   return out; */
 1321: /* } */
 1322: char *substrchaine(char *out, char *in, char *chain)
 1323: {
 1324:   /* Substract chain 'chain' from 'in', return and output 'out' */
 1325:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
 1326: 
 1327:   char *strloc;
 1328: 
 1329:   strcpy (out, in); 
 1330:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
 1331:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
 1332:   if(strloc != NULL){ 
 1333:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
 1334:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
 1335:     /* strcpy (strloc, strloc +strlen(chain));*/
 1336:   }
 1337:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
 1338:   return out;
 1339: }
 1340: 
 1341: 
 1342: char *cutl(char *blocc, char *alocc, char *in, char occ)
 1343: {
 1344:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
 1345:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
 1346:      gives blocc="abcdef" and alocc="ghi2j".
 1347:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
 1348:   */
 1349:   char *s, *t;
 1350:   t=in;s=in;
 1351:   while ((*in != occ) && (*in != '\0')){
 1352:     *alocc++ = *in++;
 1353:   }
 1354:   if( *in == occ){
 1355:     *(alocc)='\0';
 1356:     s=++in;
 1357:   }
 1358:  
 1359:   if (s == t) {/* occ not found */
 1360:     *(alocc-(in-s))='\0';
 1361:     in=s;
 1362:   }
 1363:   while ( *in != '\0'){
 1364:     *blocc++ = *in++;
 1365:   }
 1366: 
 1367:   *blocc='\0';
 1368:   return t;
 1369: }
 1370: char *cutv(char *blocc, char *alocc, char *in, char occ)
 1371: {
 1372:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
 1373:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
 1374:      gives blocc="abcdef2ghi" and alocc="j".
 1375:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
 1376:   */
 1377:   char *s, *t;
 1378:   t=in;s=in;
 1379:   while (*in != '\0'){
 1380:     while( *in == occ){
 1381:       *blocc++ = *in++;
 1382:       s=in;
 1383:     }
 1384:     *blocc++ = *in++;
 1385:   }
 1386:   if (s == t) /* occ not found */
 1387:     *(blocc-(in-s))='\0';
 1388:   else
 1389:     *(blocc-(in-s)-1)='\0';
 1390:   in=s;
 1391:   while ( *in != '\0'){
 1392:     *alocc++ = *in++;
 1393:   }
 1394: 
 1395:   *alocc='\0';
 1396:   return s;
 1397: }
 1398: 
 1399: int nbocc(char *s, char occ)
 1400: {
 1401:   int i,j=0;
 1402:   int lg=20;
 1403:   i=0;
 1404:   lg=strlen(s);
 1405:   for(i=0; i<= lg; i++) {
 1406:     if  (s[i] == occ ) j++;
 1407:   }
 1408:   return j;
 1409: }
 1410: 
 1411: /* void cutv(char *u,char *v, char*t, char occ) */
 1412: /* { */
 1413: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
 1414: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
 1415: /*      gives u="abcdef2ghi" and v="j" *\/ */
 1416: /*   int i,lg,j,p=0; */
 1417: /*   i=0; */
 1418: /*   lg=strlen(t); */
 1419: /*   for(j=0; j<=lg-1; j++) { */
 1420: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
 1421: /*   } */
 1422: 
 1423: /*   for(j=0; j<p; j++) { */
 1424: /*     (u[j] = t[j]); */
 1425: /*   } */
 1426: /*      u[p]='\0'; */
 1427: 
 1428: /*    for(j=0; j<= lg; j++) { */
 1429: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
 1430: /*   } */
 1431: /* } */
 1432: 
 1433: #ifdef _WIN32
 1434: char * strsep(char **pp, const char *delim)
 1435: {
 1436:   char *p, *q;
 1437:          
 1438:   if ((p = *pp) == NULL)
 1439:     return 0;
 1440:   if ((q = strpbrk (p, delim)) != NULL)
 1441:   {
 1442:     *pp = q + 1;
 1443:     *q = '\0';
 1444:   }
 1445:   else
 1446:     *pp = 0;
 1447:   return p;
 1448: }
 1449: #endif
 1450: 
 1451: /********************** nrerror ********************/
 1452: 
 1453: void nrerror(char error_text[])
 1454: {
 1455:   fprintf(stderr,"ERREUR ...\n");
 1456:   fprintf(stderr,"%s\n",error_text);
 1457:   exit(EXIT_FAILURE);
 1458: }
 1459: /*********************** vector *******************/
 1460: double *vector(int nl, int nh)
 1461: {
 1462:   double *v;
 1463:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
 1464:   if (!v) nrerror("allocation failure in vector");
 1465:   return v-nl+NR_END;
 1466: }
 1467: 
 1468: /************************ free vector ******************/
 1469: void free_vector(double*v, int nl, int nh)
 1470: {
 1471:   free((FREE_ARG)(v+nl-NR_END));
 1472: }
 1473: 
 1474: /************************ivector *******************************/
 1475: int *ivector(long nl,long nh)
 1476: {
 1477:   int *v;
 1478:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
 1479:   if (!v) nrerror("allocation failure in ivector");
 1480:   return v-nl+NR_END;
 1481: }
 1482: 
 1483: /******************free ivector **************************/
 1484: void free_ivector(int *v, long nl, long nh)
 1485: {
 1486:   free((FREE_ARG)(v+nl-NR_END));
 1487: }
 1488: 
 1489: /************************lvector *******************************/
 1490: long *lvector(long nl,long nh)
 1491: {
 1492:   long *v;
 1493:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
 1494:   if (!v) nrerror("allocation failure in ivector");
 1495:   return v-nl+NR_END;
 1496: }
 1497: 
 1498: /******************free lvector **************************/
 1499: void free_lvector(long *v, long nl, long nh)
 1500: {
 1501:   free((FREE_ARG)(v+nl-NR_END));
 1502: }
 1503: 
 1504: /******************* imatrix *******************************/
 1505: int **imatrix(long nrl, long nrh, long ncl, long nch) 
 1506:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
 1507: { 
 1508:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
 1509:   int **m; 
 1510:   
 1511:   /* allocate pointers to rows */ 
 1512:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
 1513:   if (!m) nrerror("allocation failure 1 in matrix()"); 
 1514:   m += NR_END; 
 1515:   m -= nrl; 
 1516:   
 1517:   
 1518:   /* allocate rows and set pointers to them */ 
 1519:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
 1520:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
 1521:   m[nrl] += NR_END; 
 1522:   m[nrl] -= ncl; 
 1523:   
 1524:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
 1525:   
 1526:   /* return pointer to array of pointers to rows */ 
 1527:   return m; 
 1528: } 
 1529: 
 1530: /****************** free_imatrix *************************/
 1531: void free_imatrix(m,nrl,nrh,ncl,nch)
 1532:       int **m;
 1533:       long nch,ncl,nrh,nrl; 
 1534:      /* free an int matrix allocated by imatrix() */ 
 1535: { 
 1536:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
 1537:   free((FREE_ARG) (m+nrl-NR_END)); 
 1538: } 
 1539: 
 1540: /******************* matrix *******************************/
 1541: double **matrix(long nrl, long nrh, long ncl, long nch)
 1542: {
 1543:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
 1544:   double **m;
 1545: 
 1546:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1547:   if (!m) nrerror("allocation failure 1 in matrix()");
 1548:   m += NR_END;
 1549:   m -= nrl;
 1550: 
 1551:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1552:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1553:   m[nrl] += NR_END;
 1554:   m[nrl] -= ncl;
 1555: 
 1556:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1557:   return m;
 1558:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
 1559: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
 1560: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
 1561:    */
 1562: }
 1563: 
 1564: /*************************free matrix ************************/
 1565: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
 1566: {
 1567:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1568:   free((FREE_ARG)(m+nrl-NR_END));
 1569: }
 1570: 
 1571: /******************* ma3x *******************************/
 1572: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
 1573: {
 1574:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
 1575:   double ***m;
 1576: 
 1577:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1578:   if (!m) nrerror("allocation failure 1 in matrix()");
 1579:   m += NR_END;
 1580:   m -= nrl;
 1581: 
 1582:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1583:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1584:   m[nrl] += NR_END;
 1585:   m[nrl] -= ncl;
 1586: 
 1587:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1588: 
 1589:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
 1590:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
 1591:   m[nrl][ncl] += NR_END;
 1592:   m[nrl][ncl] -= nll;
 1593:   for (j=ncl+1; j<=nch; j++) 
 1594:     m[nrl][j]=m[nrl][j-1]+nlay;
 1595:   
 1596:   for (i=nrl+1; i<=nrh; i++) {
 1597:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
 1598:     for (j=ncl+1; j<=nch; j++) 
 1599:       m[i][j]=m[i][j-1]+nlay;
 1600:   }
 1601:   return m; 
 1602:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
 1603:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
 1604:   */
 1605: }
 1606: 
 1607: /*************************free ma3x ************************/
 1608: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
 1609: {
 1610:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
 1611:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1612:   free((FREE_ARG)(m+nrl-NR_END));
 1613: }
 1614: 
 1615: /*************** function subdirf ***********/
 1616: char *subdirf(char fileres[])
 1617: {
 1618:   /* Caution optionfilefiname is hidden */
 1619:   strcpy(tmpout,optionfilefiname);
 1620:   strcat(tmpout,"/"); /* Add to the right */
 1621:   strcat(tmpout,fileres);
 1622:   return tmpout;
 1623: }
 1624: 
 1625: /*************** function subdirf2 ***********/
 1626: char *subdirf2(char fileres[], char *preop)
 1627: {
 1628:   
 1629:   /* Caution optionfilefiname is hidden */
 1630:   strcpy(tmpout,optionfilefiname);
 1631:   strcat(tmpout,"/");
 1632:   strcat(tmpout,preop);
 1633:   strcat(tmpout,fileres);
 1634:   return tmpout;
 1635: }
 1636: 
 1637: /*************** function subdirf3 ***********/
 1638: char *subdirf3(char fileres[], char *preop, char *preop2)
 1639: {
 1640:   
 1641:   /* Caution optionfilefiname is hidden */
 1642:   strcpy(tmpout,optionfilefiname);
 1643:   strcat(tmpout,"/");
 1644:   strcat(tmpout,preop);
 1645:   strcat(tmpout,preop2);
 1646:   strcat(tmpout,fileres);
 1647:   return tmpout;
 1648: }
 1649:  
 1650: /*************** function subdirfext ***********/
 1651: char *subdirfext(char fileres[], char *preop, char *postop)
 1652: {
 1653:   
 1654:   strcpy(tmpout,preop);
 1655:   strcat(tmpout,fileres);
 1656:   strcat(tmpout,postop);
 1657:   return tmpout;
 1658: }
 1659: 
 1660: /*************** function subdirfext3 ***********/
 1661: char *subdirfext3(char fileres[], char *preop, char *postop)
 1662: {
 1663:   
 1664:   /* Caution optionfilefiname is hidden */
 1665:   strcpy(tmpout,optionfilefiname);
 1666:   strcat(tmpout,"/");
 1667:   strcat(tmpout,preop);
 1668:   strcat(tmpout,fileres);
 1669:   strcat(tmpout,postop);
 1670:   return tmpout;
 1671: }
 1672:  
 1673: char *asc_diff_time(long time_sec, char ascdiff[])
 1674: {
 1675:   long sec_left, days, hours, minutes;
 1676:   days = (time_sec) / (60*60*24);
 1677:   sec_left = (time_sec) % (60*60*24);
 1678:   hours = (sec_left) / (60*60) ;
 1679:   sec_left = (sec_left) %(60*60);
 1680:   minutes = (sec_left) /60;
 1681:   sec_left = (sec_left) % (60);
 1682:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
 1683:   return ascdiff;
 1684: }
 1685: 
 1686: /***************** f1dim *************************/
 1687: extern int ncom; 
 1688: extern double *pcom,*xicom;
 1689: extern double (*nrfunc)(double []); 
 1690:  
 1691: double f1dim(double x) 
 1692: { 
 1693:   int j; 
 1694:   double f;
 1695:   double *xt; 
 1696:  
 1697:   xt=vector(1,ncom); 
 1698:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
 1699:   f=(*nrfunc)(xt); 
 1700:   free_vector(xt,1,ncom); 
 1701:   return f; 
 1702: } 
 1703: 
 1704: /*****************brent *************************/
 1705: double brent(double ax, double bx, double cx, double (*f)(double), double tol, 	double *xmin) 
 1706: {
 1707:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
 1708:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
 1709:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
 1710:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
 1711:    * returned function value. 
 1712:   */
 1713:   int iter; 
 1714:   double a,b,d,etemp;
 1715:   double fu=0,fv,fw,fx;
 1716:   double ftemp=0.;
 1717:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
 1718:   double e=0.0; 
 1719:  
 1720:   a=(ax < cx ? ax : cx); 
 1721:   b=(ax > cx ? ax : cx); 
 1722:   x=w=v=bx; 
 1723:   fw=fv=fx=(*f)(x); 
 1724:   for (iter=1;iter<=ITMAX;iter++) { 
 1725:     xm=0.5*(a+b); 
 1726:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
 1727:     /*		if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
 1728:     printf(".");fflush(stdout);
 1729:     fprintf(ficlog,".");fflush(ficlog);
 1730: #ifdef DEBUGBRENT
 1731:     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);
 1732:     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);
 1733:     /*		if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
 1734: #endif
 1735:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
 1736:       *xmin=x; 
 1737:       return fx; 
 1738:     } 
 1739:     ftemp=fu;
 1740:     if (fabs(e) > tol1) { 
 1741:       r=(x-w)*(fx-fv); 
 1742:       q=(x-v)*(fx-fw); 
 1743:       p=(x-v)*q-(x-w)*r; 
 1744:       q=2.0*(q-r); 
 1745:       if (q > 0.0) p = -p; 
 1746:       q=fabs(q); 
 1747:       etemp=e; 
 1748:       e=d; 
 1749:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
 1750: 				d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1751:       else { 
 1752: 				d=p/q; 
 1753: 				u=x+d; 
 1754: 				if (u-a < tol2 || b-u < tol2) 
 1755: 					d=SIGN(tol1,xm-x); 
 1756:       } 
 1757:     } else { 
 1758:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1759:     } 
 1760:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
 1761:     fu=(*f)(u); 
 1762:     if (fu <= fx) { 
 1763:       if (u >= x) a=x; else b=x; 
 1764:       SHFT(v,w,x,u) 
 1765:       SHFT(fv,fw,fx,fu) 
 1766:     } else { 
 1767:       if (u < x) a=u; else b=u; 
 1768:       if (fu <= fw || w == x) { 
 1769: 				v=w; 
 1770: 				w=u; 
 1771: 				fv=fw; 
 1772: 				fw=fu; 
 1773:       } else if (fu <= fv || v == x || v == w) { 
 1774: 				v=u; 
 1775: 				fv=fu; 
 1776:       } 
 1777:     } 
 1778:   } 
 1779:   nrerror("Too many iterations in brent"); 
 1780:   *xmin=x; 
 1781:   return fx; 
 1782: } 
 1783: 
 1784: /****************** mnbrak ***********************/
 1785: 
 1786: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
 1787: 	    double (*func)(double)) 
 1788: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
 1789: the downhill direction (defined by the function as evaluated at the initial points) and returns
 1790: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
 1791: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
 1792:    */
 1793:   double ulim,u,r,q, dum;
 1794:   double fu; 
 1795: 
 1796:   double scale=10.;
 1797:   int iterscale=0;
 1798: 
 1799:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
 1800:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
 1801: 
 1802: 
 1803:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
 1804:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
 1805:   /*   *bx = *ax - (*ax - *bx)/scale; */
 1806:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
 1807:   /* } */
 1808: 
 1809:   if (*fb > *fa) { 
 1810:     SHFT(dum,*ax,*bx,dum) 
 1811:     SHFT(dum,*fb,*fa,dum) 
 1812:   } 
 1813:   *cx=(*bx)+GOLD*(*bx-*ax); 
 1814:   *fc=(*func)(*cx); 
 1815: #ifdef DEBUG
 1816:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
 1817:   fprintf(ficlog,"mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
 1818: #endif
 1819:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc. If fc=inf it exits and if flat fb=fc it exits too.*/
 1820:     r=(*bx-*ax)*(*fb-*fc); 
 1821:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
 1822:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
 1823:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
 1824:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
 1825:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
 1826:       fu=(*func)(u); 
 1827: #ifdef DEBUG
 1828:       /* f(x)=A(x-u)**2+f(u) */
 1829:       double A, fparabu; 
 1830:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 1831:       fparabu= *fa - A*(*ax-u)*(*ax-u);
 1832:       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);
 1833:       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);
 1834:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
 1835:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
 1836:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
 1837:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
 1838: #endif 
 1839: #ifdef MNBRAKORIGINAL
 1840: #else
 1841: /*       if (fu > *fc) { */
 1842: /* #ifdef DEBUG */
 1843: /*       printf("mnbrak4  fu > fc \n"); */
 1844: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
 1845: /* #endif */
 1846: /* 	/\* 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 *\\/  *\/ */
 1847: /* 	/\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
 1848: /* 	dum=u; /\* Shifting c and u *\/ */
 1849: /* 	u = *cx; */
 1850: /* 	*cx = dum; */
 1851: /* 	dum = fu; */
 1852: /* 	fu = *fc; */
 1853: /* 	*fc =dum; */
 1854: /*       } else { /\* end *\/ */
 1855: /* #ifdef DEBUG */
 1856: /*       printf("mnbrak3  fu < fc \n"); */
 1857: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
 1858: /* #endif */
 1859: /* 	dum=u; /\* Shifting c and u *\/ */
 1860: /* 	u = *cx; */
 1861: /* 	*cx = dum; */
 1862: /* 	dum = fu; */
 1863: /* 	fu = *fc; */
 1864: /* 	*fc =dum; */
 1865: /*       } */
 1866: #ifdef DEBUGMNBRAK
 1867: 		 double A, fparabu; 
 1868:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 1869:      fparabu= *fa - A*(*ax-u)*(*ax-u);
 1870:      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);
 1871:      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);
 1872: #endif
 1873:       dum=u; /* Shifting c and u */
 1874:       u = *cx;
 1875:       *cx = dum;
 1876:       dum = fu;
 1877:       fu = *fc;
 1878:       *fc =dum;
 1879: #endif
 1880:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
 1881: #ifdef DEBUG
 1882:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
 1883:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
 1884: #endif
 1885:       fu=(*func)(u); 
 1886:       if (fu < *fc) { 
 1887: #ifdef DEBUG
 1888: 				printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
 1889: 			  fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
 1890: #endif
 1891: 			  SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
 1892: 				SHFT(*fb,*fc,fu,(*func)(u)) 
 1893: #ifdef DEBUG
 1894: 					printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
 1895: #endif
 1896:       } 
 1897:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
 1898: #ifdef DEBUG
 1899:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
 1900:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
 1901: #endif
 1902:       u=ulim; 
 1903:       fu=(*func)(u); 
 1904:     } else { /* u could be left to b (if r > q parabola has a maximum) */
 1905: #ifdef DEBUG
 1906:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
 1907:       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);
 1908: #endif
 1909:       u=(*cx)+GOLD*(*cx-*bx); 
 1910:       fu=(*func)(u); 
 1911: #ifdef DEBUG
 1912:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
 1913:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
 1914: #endif
 1915:     } /* end tests */
 1916:     SHFT(*ax,*bx,*cx,u) 
 1917:     SHFT(*fa,*fb,*fc,fu) 
 1918: #ifdef DEBUG
 1919:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
 1920:       fprintf(ficlog, "\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
 1921: #endif
 1922:   } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
 1923: } 
 1924: 
 1925: /*************** linmin ************************/
 1926: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
 1927: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
 1928: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
 1929: the value of func at the returned location p . This is actually all accomplished by calling the
 1930: routines mnbrak and brent .*/
 1931: int ncom; 
 1932: double *pcom,*xicom;
 1933: double (*nrfunc)(double []); 
 1934:  
 1935: #ifdef LINMINORIGINAL
 1936: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
 1937: #else
 1938: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
 1939: #endif
 1940: { 
 1941:   double brent(double ax, double bx, double cx, 
 1942: 	       double (*f)(double), double tol, double *xmin); 
 1943:   double f1dim(double x); 
 1944:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
 1945: 	      double *fc, double (*func)(double)); 
 1946:   int j; 
 1947:   double xx,xmin,bx,ax; 
 1948:   double fx,fb,fa;
 1949: 
 1950: #ifdef LINMINORIGINAL
 1951: #else
 1952:   double scale=10., axs, xxs; /* Scale added for infinity */
 1953: #endif
 1954:   
 1955:   ncom=n; 
 1956:   pcom=vector(1,n); 
 1957:   xicom=vector(1,n); 
 1958:   nrfunc=func; 
 1959:   for (j=1;j<=n;j++) { 
 1960:     pcom[j]=p[j]; 
 1961:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
 1962:   } 
 1963: 
 1964: #ifdef LINMINORIGINAL
 1965:   xx=1.;
 1966: #else
 1967:   axs=0.0;
 1968:   xxs=1.;
 1969:   do{
 1970:     xx= xxs;
 1971: #endif
 1972:     ax=0.;
 1973:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
 1974:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
 1975:     /* 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))   */
 1976:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
 1977:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
 1978:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
 1979:     /* 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]]*/
 1980: #ifdef LINMINORIGINAL
 1981: #else
 1982:     if (fx != fx){
 1983: 			xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
 1984: 			printf("|");
 1985: 			fprintf(ficlog,"|");
 1986: #ifdef DEBUGLINMIN
 1987: 			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);
 1988: #endif
 1989:     }
 1990:   }while(fx != fx && xxs > 1.e-5);
 1991: #endif
 1992:   
 1993: #ifdef DEBUGLINMIN
 1994:   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);
 1995:   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);
 1996: #endif
 1997: #ifdef LINMINORIGINAL
 1998: #else
 1999: 	if(fb == fx){ /* Flat function in the direction */
 2000: 		xmin=xx;
 2001:     *flat=1;
 2002: 	}else{
 2003:     *flat=0;
 2004: #endif
 2005: 		/*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
 2006:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
 2007:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
 2008:   /* fmin = f(p[j] + xmin * xi[j]) */
 2009:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
 2010:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
 2011: #ifdef DEBUG
 2012:   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);
 2013:   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);
 2014: #endif
 2015: #ifdef LINMINORIGINAL
 2016: #else
 2017: 			}
 2018: #endif
 2019: #ifdef DEBUGLINMIN
 2020:   printf("linmin end ");
 2021:   fprintf(ficlog,"linmin end ");
 2022: #endif
 2023:   for (j=1;j<=n;j++) { 
 2024: #ifdef LINMINORIGINAL
 2025:     xi[j] *= xmin; 
 2026: #else
 2027: #ifdef DEBUGLINMIN
 2028:     if(xxs <1.0)
 2029:       printf(" before xi[%d]=%12.8f", j,xi[j]);
 2030: #endif
 2031:     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) */
 2032: #ifdef DEBUGLINMIN
 2033:     if(xxs <1.0)
 2034:       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 );
 2035: #endif
 2036: #endif
 2037:     p[j] += xi[j]; /* Parameters values are updated accordingly */
 2038:   } 
 2039: #ifdef DEBUGLINMIN
 2040:   printf("\n");
 2041:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
 2042:   fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
 2043:   for (j=1;j<=n;j++) { 
 2044:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
 2045:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
 2046:     if(j % ncovmodel == 0){
 2047:       printf("\n");
 2048:       fprintf(ficlog,"\n");
 2049:     }
 2050:   }
 2051: #else
 2052: #endif
 2053:   free_vector(xicom,1,n); 
 2054:   free_vector(pcom,1,n); 
 2055: } 
 2056: 
 2057: 
 2058: /*************** powell ************************/
 2059: /*
 2060: Minimization of a function func of n variables. Input consists of an initial starting point
 2061: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
 2062: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
 2063: such that failure to decrease by more than this amount on one iteration signals doneness. On
 2064: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
 2065: function value at p , and iter is the number of iterations taken. The routine linmin is used.
 2066:  */
 2067: #ifdef LINMINORIGINAL
 2068: #else
 2069: 	int *flatdir; /* Function is vanishing in that direction */
 2070: 	int flat=0, flatd=0; /* Function is vanishing in that direction */
 2071: #endif
 2072: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
 2073: 	    double (*func)(double [])) 
 2074: { 
 2075: #ifdef LINMINORIGINAL
 2076:  void linmin(double p[], double xi[], int n, double *fret, 
 2077: 	      double (*func)(double [])); 
 2078: #else 
 2079:  void linmin(double p[], double xi[], int n, double *fret,
 2080: 	     double (*func)(double []),int *flat); 
 2081: #endif
 2082:  int i,ibig,j,jk,k; 
 2083:   double del,t,*pt,*ptt,*xit;
 2084:   double directest;
 2085:   double fp,fptt;
 2086:   double *xits;
 2087:   int niterf, itmp;
 2088: #ifdef LINMINORIGINAL
 2089: #else
 2090: 
 2091:   flatdir=ivector(1,n); 
 2092:   for (j=1;j<=n;j++) flatdir[j]=0; 
 2093: #endif
 2094: 
 2095:   pt=vector(1,n); 
 2096:   ptt=vector(1,n); 
 2097:   xit=vector(1,n); 
 2098:   xits=vector(1,n); 
 2099:   *fret=(*func)(p); 
 2100:   for (j=1;j<=n;j++) pt[j]=p[j]; 
 2101:   rcurr_time = time(NULL);  
 2102:   for (*iter=1;;++(*iter)) { 
 2103:     fp=(*fret); /* From former iteration or initial value */
 2104:     ibig=0; 
 2105:     del=0.0; 
 2106:     rlast_time=rcurr_time;
 2107:     /* (void) gettimeofday(&curr_time,&tzp); */
 2108:     rcurr_time = time(NULL);  
 2109:     curr_time = *localtime(&rcurr_time);
 2110:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
 2111:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
 2112: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
 2113:     for (i=1;i<=n;i++) {
 2114:       fprintf(ficrespow," %.12lf", p[i]);
 2115:     }
 2116:     fprintf(ficrespow,"\n");fflush(ficrespow);
 2117:     printf("\n#model=  1      +     age ");
 2118:     fprintf(ficlog,"\n#model=  1      +     age ");
 2119:     if(nagesqr==1){
 2120: 	printf("  + age*age  ");
 2121: 	fprintf(ficlog,"  + age*age  ");
 2122:     }
 2123:     for(j=1;j <=ncovmodel-2;j++){
 2124:       if(Typevar[j]==0) {
 2125: 	printf("  +      V%d  ",Tvar[j]);
 2126: 	fprintf(ficlog,"  +      V%d  ",Tvar[j]);
 2127:       }else if(Typevar[j]==1) {
 2128: 	printf("  +    V%d*age ",Tvar[j]);
 2129: 	fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
 2130:       }else if(Typevar[j]==2) {
 2131: 	printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
 2132: 	fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
 2133:       }
 2134:     }
 2135:     printf("\n");
 2136: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
 2137: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
 2138:     fprintf(ficlog,"\n");
 2139:     for(i=1,jk=1; i <=nlstate; i++){
 2140:       for(k=1; k <=(nlstate+ndeath); k++){
 2141: 	if (k != i) {
 2142: 	  printf("%d%d ",i,k);
 2143: 	  fprintf(ficlog,"%d%d ",i,k);
 2144: 	  for(j=1; j <=ncovmodel; j++){
 2145: 	    printf("%12.7f ",p[jk]);
 2146: 	    fprintf(ficlog,"%12.7f ",p[jk]);
 2147: 	    jk++; 
 2148: 	  }
 2149: 	  printf("\n");
 2150: 	  fprintf(ficlog,"\n");
 2151: 	}
 2152:       }
 2153:     }
 2154:     if(*iter <=3 && *iter >1){
 2155:       tml = *localtime(&rcurr_time);
 2156:       strcpy(strcurr,asctime(&tml));
 2157:       rforecast_time=rcurr_time; 
 2158:       itmp = strlen(strcurr);
 2159:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
 2160: 	strcurr[itmp-1]='\0';
 2161:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 2162:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 2163:       for(niterf=10;niterf<=30;niterf+=10){
 2164: 	rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
 2165: 	forecast_time = *localtime(&rforecast_time);
 2166: 	strcpy(strfor,asctime(&forecast_time));
 2167: 	itmp = strlen(strfor);
 2168: 	if(strfor[itmp-1]=='\n')
 2169: 	  strfor[itmp-1]='\0';
 2170: 	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);
 2171: 	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);
 2172:       }
 2173:     }
 2174:     for (i=1;i<=n;i++) { /* For each direction i */
 2175:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
 2176:       fptt=(*fret); 
 2177: #ifdef DEBUG
 2178:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 2179:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 2180: #endif
 2181:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
 2182:       fprintf(ficlog,"%d",i);fflush(ficlog);
 2183: #ifdef LINMINORIGINAL
 2184:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
 2185: #else
 2186:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
 2187: 			flatdir[i]=flat; /* Function is vanishing in that direction i */
 2188: #endif
 2189: 			/* Outputs are fret(new point p) p is updated and xit rescaled */
 2190:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
 2191: 				/* because that direction will be replaced unless the gain del is small */
 2192: 				/* in comparison with the 'probable' gain, mu^2, with the last average direction. */
 2193: 				/* Unless the n directions are conjugate some gain in the determinant may be obtained */
 2194: 				/* with the new direction. */
 2195: 				del=fabs(fptt-(*fret)); 
 2196: 				ibig=i; 
 2197:       } 
 2198: #ifdef DEBUG
 2199:       printf("%d %.12e",i,(*fret));
 2200:       fprintf(ficlog,"%d %.12e",i,(*fret));
 2201:       for (j=1;j<=n;j++) {
 2202: 				xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
 2203: 				printf(" x(%d)=%.12e",j,xit[j]);
 2204: 				fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
 2205:       }
 2206:       for(j=1;j<=n;j++) {
 2207: 				printf(" p(%d)=%.12e",j,p[j]);
 2208: 				fprintf(ficlog," p(%d)=%.12e",j,p[j]);
 2209:       }
 2210:       printf("\n");
 2211:       fprintf(ficlog,"\n");
 2212: #endif
 2213:     } /* end loop on each direction i */
 2214:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
 2215:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
 2216:     /* New value of last point Pn is not computed, P(n-1) */
 2217:       for(j=1;j<=n;j++) {
 2218: 				if(flatdir[j] >0){
 2219: 					printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
 2220: 					fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
 2221: 				}
 2222: 				/* printf("\n"); */
 2223: 				/* fprintf(ficlog,"\n"); */
 2224: 			}
 2225:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
 2226:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
 2227:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
 2228:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
 2229:       /* decreased of more than 3.84  */
 2230:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
 2231:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
 2232:       /* By adding 10 parameters more the gain should be 18.31 */
 2233: 			
 2234:       /* Starting the program with initial values given by a former maximization will simply change */
 2235:       /* the scales of the directions and the directions, because the are reset to canonical directions */
 2236:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
 2237:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
 2238: #ifdef DEBUG
 2239:       int k[2],l;
 2240:       k[0]=1;
 2241:       k[1]=-1;
 2242:       printf("Max: %.12e",(*func)(p));
 2243:       fprintf(ficlog,"Max: %.12e",(*func)(p));
 2244:       for (j=1;j<=n;j++) {
 2245: 	printf(" %.12e",p[j]);
 2246: 	fprintf(ficlog," %.12e",p[j]);
 2247:       }
 2248:       printf("\n");
 2249:       fprintf(ficlog,"\n");
 2250:       for(l=0;l<=1;l++) {
 2251: 	for (j=1;j<=n;j++) {
 2252: 	  ptt[j]=p[j]+(p[j]-pt[j])*k[l];
 2253: 	  printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 2254: 	  fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 2255: 	}
 2256: 	printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 2257: 	fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 2258:       }
 2259: #endif
 2260: 
 2261: #ifdef LINMINORIGINAL
 2262: #else
 2263:       free_ivector(flatdir,1,n); 
 2264: #endif
 2265:       free_vector(xit,1,n); 
 2266:       free_vector(xits,1,n); 
 2267:       free_vector(ptt,1,n); 
 2268:       free_vector(pt,1,n); 
 2269:       return; 
 2270:     } /* enough precision */ 
 2271:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
 2272:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
 2273:       ptt[j]=2.0*p[j]-pt[j]; 
 2274:       xit[j]=p[j]-pt[j]; 
 2275:       pt[j]=p[j]; 
 2276:     } 
 2277:     fptt=(*func)(ptt); /* f_3 */
 2278: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
 2279: 		if (*iter <=4) {
 2280: #else
 2281: #endif
 2282: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
 2283: #else
 2284:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
 2285: #endif
 2286:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
 2287:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
 2288:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
 2289:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
 2290:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
 2291:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
 2292:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
 2293:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
 2294:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
 2295:       /*  Even if f3 <f1, directest can be negative and t >0 */
 2296:       /* mu² and del² are equal when f3=f1 */
 2297: 			/* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
 2298: 			/* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
 2299: 			/* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
 2300: 			/* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
 2301: #ifdef NRCORIGINAL
 2302:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
 2303: #else
 2304:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
 2305:       t= t- del*SQR(fp-fptt);
 2306: #endif
 2307:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
 2308: #ifdef DEBUG
 2309:       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);
 2310:       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);
 2311:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 2312: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 2313:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 2314: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 2315:       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);
 2316:       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);
 2317: #endif
 2318: #ifdef POWELLORIGINAL
 2319:       if (t < 0.0) { /* Then we use it for new direction */
 2320: #else
 2321:       if (directest*t < 0.0) { /* Contradiction between both tests */
 2322: 				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);
 2323:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 2324:         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);
 2325:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 2326:       } 
 2327:       if (directest < 0.0) { /* Then we use it for new direction */
 2328: #endif
 2329: #ifdef DEBUGLINMIN
 2330: 	printf("Before linmin in direction P%d-P0\n",n);
 2331: 	for (j=1;j<=n;j++) {
 2332: 	  printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2333: 	  fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2334: 	  if(j % ncovmodel == 0){
 2335: 	    printf("\n");
 2336: 	    fprintf(ficlog,"\n");
 2337: 	  }
 2338: 	}
 2339: #endif
 2340: #ifdef LINMINORIGINAL
 2341: 	linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
 2342: #else
 2343: 	linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
 2344: 	flatdir[i]=flat; /* Function is vanishing in that direction i */
 2345: #endif
 2346: 	
 2347: #ifdef DEBUGLINMIN
 2348: 	for (j=1;j<=n;j++) { 
 2349: 	  printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2350: 	  fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2351: 	  if(j % ncovmodel == 0){
 2352: 	    printf("\n");
 2353: 	    fprintf(ficlog,"\n");
 2354: 	  }
 2355: 	}
 2356: #endif
 2357: 	for (j=1;j<=n;j++) { 
 2358: 	  xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
 2359: 	  xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
 2360: 	}
 2361: #ifdef LINMINORIGINAL
 2362: #else
 2363: 	for (j=1, flatd=0;j<=n;j++) {
 2364: 	  if(flatdir[j]>0)
 2365: 	    flatd++;
 2366: 	}
 2367: 	if(flatd >0){
 2368: 	  printf("%d flat directions\n",flatd);
 2369: 	  fprintf(ficlog,"%d flat directions\n",flatd);
 2370: 	  for (j=1;j<=n;j++) { 
 2371: 	    if(flatdir[j]>0){
 2372: 	      printf("%d ",j);
 2373: 	      fprintf(ficlog,"%d ",j);
 2374: 	    }
 2375: 	  }
 2376: 	  printf("\n");
 2377: 	  fprintf(ficlog,"\n");
 2378: 	}
 2379: #endif
 2380: 	printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 2381: 	fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 2382: 	
 2383: #ifdef DEBUG
 2384: 	printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 2385: 	fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 2386: 	for(j=1;j<=n;j++){
 2387: 	  printf(" %lf",xit[j]);
 2388: 	  fprintf(ficlog," %lf",xit[j]);
 2389: 	}
 2390: 	printf("\n");
 2391: 	fprintf(ficlog,"\n");
 2392: #endif
 2393:       } /* end of t or directest negative */
 2394: #ifdef POWELLNOF3INFF1TEST
 2395: #else
 2396:       } /* end if (fptt < fp)  */
 2397: #endif
 2398: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
 2399:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
 2400: #else
 2401: #endif
 2402: 		} /* loop iteration */ 
 2403: } 
 2404:   
 2405: /**** Prevalence limit (stable or period prevalence)  ****************/
 2406:   
 2407:   double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij, int nres)
 2408:   {
 2409:     /* Computes the prevalence limit in each live state at age x and for covariate combination ij 
 2410:        (and selected quantitative values in nres)
 2411:        by left multiplying the unit
 2412:        matrix by transitions matrix until convergence is reached with precision ftolpl */
 2413:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
 2414:   /* Wx is row vector: population in state 1, population in state 2, population dead */
 2415:   /* or prevalence in state 1, prevalence in state 2, 0 */
 2416:   /* newm is the matrix after multiplications, its rows are identical at a factor */
 2417:   /* Initial matrix pimij */
 2418:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
 2419:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
 2420:   /*  0,                   0                  , 1} */
 2421:   /*
 2422:    * and after some iteration: */
 2423:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
 2424:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
 2425:   /*  0,                   0                  , 1} */
 2426:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
 2427:   /* {0.51571254859325999, 0.4842874514067399, */
 2428:   /*  0.51326036147820708, 0.48673963852179264} */
 2429:   /* If we start from prlim again, prlim tends to a constant matrix */
 2430:     
 2431:   int i, ii,j,k;
 2432:   double *min, *max, *meandiff, maxmax,sumnew=0.;
 2433:   /* double **matprod2(); */ /* test */
 2434:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
 2435:   double **newm;
 2436:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
 2437:   int ncvloop=0;
 2438:   
 2439:   min=vector(1,nlstate);
 2440:   max=vector(1,nlstate);
 2441:   meandiff=vector(1,nlstate);
 2442: 
 2443: 	/* Starting with matrix unity */
 2444:   for (ii=1;ii<=nlstate+ndeath;ii++)
 2445:     for (j=1;j<=nlstate+ndeath;j++){
 2446:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2447:     }
 2448:   
 2449:   cov[1]=1.;
 2450:   
 2451:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2452:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
 2453:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
 2454:     ncvloop++;
 2455:     newm=savm;
 2456:     /* Covariates have to be included here again */
 2457:     cov[2]=agefin;
 2458:     if(nagesqr==1)
 2459:       cov[3]= agefin*agefin;;
 2460:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
 2461:  			/* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
 2462:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
 2463:       /* printf("prevalim Dummy combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov=%lf codtabm(%d,Tvar[%d])=%d \n",ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,k)],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,k)); */
 2464:     }
 2465:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
 2466:  			/* Here comes the value of quantitative after renumbering k with single quantitative covariates */
 2467:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
 2468:       /* printf("prevalim Quantitative k=%d  TvarsQind[%d]=%d, TvarsQ[%d]=V%d,Tqresult[%d][%d]=%f\n",k,k,TvarsQind[k],k,TvarsQ[k],nres,k,Tqresult[nres][k]); */
 2469:     }
 2470:     for (k=1; k<=cptcovage;k++){  /* For product with age */
 2471:       if(Dummy[Tvar[Tage[k]]]){
 2472: 	cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 2473:       } else{
 2474: 	cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
 2475:       }
 2476:       /* printf("prevalim Age combi=%d k=%d  Tage[%d]=V%d Tqresult[%d][%d]=%f\n",ij,k,k,Tage[k],nres,k,Tqresult[nres][k]); */
 2477:     }
 2478:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
 2479:       /* printf("prevalim Prod ij=%d k=%d  Tprod[%d]=%d Tvard[%d][1]=V%d, Tvard[%d][2]=V%d\n",ij,k,k,Tprod[k], k,Tvard[k][1], k,Tvard[k][2]); */
 2480:       if(Dummy[Tvard[k][1]==0]){
 2481: 	if(Dummy[Tvard[k][2]==0]){
 2482: 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
 2483: 	}else{
 2484: 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
 2485: 	}
 2486:       }else{
 2487: 	if(Dummy[Tvard[k][2]==0]){
 2488: 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
 2489: 	}else{
 2490: 	  cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
 2491: 	}
 2492:       }
 2493:     }
 2494:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 2495:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 2496:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 2497:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2498:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 2499: 		/* age and covariate values of ij are in 'cov' */
 2500:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
 2501:     
 2502:     savm=oldm;
 2503:     oldm=newm;
 2504: 
 2505:     for(j=1; j<=nlstate; j++){
 2506:       max[j]=0.;
 2507:       min[j]=1.;
 2508:     }
 2509:     for(i=1;i<=nlstate;i++){
 2510:       sumnew=0;
 2511:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
 2512:       for(j=1; j<=nlstate; j++){ 
 2513: 	prlim[i][j]= newm[i][j]/(1-sumnew);
 2514: 	max[j]=FMAX(max[j],prlim[i][j]);
 2515: 	min[j]=FMIN(min[j],prlim[i][j]);
 2516:       }
 2517:     }
 2518: 
 2519:     maxmax=0.;
 2520:     for(j=1; j<=nlstate; j++){
 2521:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
 2522:       maxmax=FMAX(maxmax,meandiff[j]);
 2523:       /* 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); */
 2524:     } /* j loop */
 2525:     *ncvyear= (int)age- (int)agefin;
 2526:     /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
 2527:     if(maxmax < ftolpl){
 2528:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
 2529:       free_vector(min,1,nlstate);
 2530:       free_vector(max,1,nlstate);
 2531:       free_vector(meandiff,1,nlstate);
 2532:       return prlim;
 2533:     }
 2534:   } /* age loop */
 2535:     /* After some age loop it doesn't converge */
 2536:   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\
 2537: 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);
 2538:   /* 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); */
 2539:   free_vector(min,1,nlstate);
 2540:   free_vector(max,1,nlstate);
 2541:   free_vector(meandiff,1,nlstate);
 2542:   
 2543:   return prlim; /* should not reach here */
 2544: }
 2545: 
 2546: 
 2547:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
 2548: 
 2549:  /* 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) */
 2550:  /* 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) */
 2551:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
 2552: {
 2553:   /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
 2554:      matrix by transitions matrix until convergence is reached with precision ftolpl */
 2555:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
 2556:   /* Wx is row vector: population in state 1, population in state 2, population dead */
 2557:   /* or prevalence in state 1, prevalence in state 2, 0 */
 2558:   /* newm is the matrix after multiplications, its rows are identical at a factor */
 2559:   /* Initial matrix pimij */
 2560:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
 2561:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
 2562:   /*  0,                   0                  , 1} */
 2563:   /*
 2564:    * and after some iteration: */
 2565:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
 2566:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
 2567:   /*  0,                   0                  , 1} */
 2568:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
 2569:   /* {0.51571254859325999, 0.4842874514067399, */
 2570:   /*  0.51326036147820708, 0.48673963852179264} */
 2571:   /* If we start from prlim again, prlim tends to a constant matrix */
 2572: 
 2573:   int i, ii,j,k;
 2574:   double *min, *max, *meandiff, maxmax,sumnew=0.;
 2575:   /* double **matprod2(); */ /* test */
 2576:   double **out, cov[NCOVMAX+1], **bmij();
 2577:   double **newm;
 2578:   double	 **dnewm, **doldm, **dsavm;  /* for use */
 2579:   double	 **oldm, **savm;  /* for use */
 2580: 
 2581:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
 2582:   int ncvloop=0;
 2583:   
 2584:   min=vector(1,nlstate);
 2585:   max=vector(1,nlstate);
 2586:   meandiff=vector(1,nlstate);
 2587: 
 2588: 	dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
 2589: 	oldm=oldms; savm=savms;
 2590: 
 2591: 	/* Starting with matrix unity */
 2592: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2593: 		for (j=1;j<=nlstate+ndeath;j++){
 2594:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2595:     }
 2596:   
 2597:   cov[1]=1.;
 2598:   
 2599:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2600:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
 2601:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
 2602:   for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
 2603:     ncvloop++;
 2604:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
 2605: 		/* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
 2606:     /* Covariates have to be included here again */
 2607:     cov[2]=agefin;
 2608:     if(nagesqr==1)
 2609:       cov[3]= agefin*agefin;;
 2610:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
 2611:  			/* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
 2612:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
 2613:       /* printf("bprevalim Dummy combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov=%lf codtabm(%d,Tvar[%d])=%d \n",ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,k)],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,k)); */
 2614:     }
 2615:     /* for (k=1; k<=cptcovn;k++) { */
 2616:     /*   /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
 2617:     /*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
 2618:     /*   /\* 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])]); *\/ */
 2619:     /* } */
 2620:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
 2621:  			/* Here comes the value of quantitative after renumbering k with single quantitative covariates */
 2622:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
 2623:       /* printf("prevalim Quantitative k=%d  TvarsQind[%d]=%d, TvarsQ[%d]=V%d,Tqresult[%d][%d]=%f\n",k,k,TvarsQind[k],k,TvarsQ[k],nres,k,Tqresult[nres][k]); */
 2624:     }
 2625:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; */
 2626:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
 2627:     /*   /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\/ */
 2628:     /*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
 2629:     for (k=1; k<=cptcovage;k++){  /* For product with age */
 2630:       if(Dummy[Tvar[Tage[k]]]){
 2631: 	cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 2632:       } else{
 2633: 	cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
 2634:       }
 2635:       /* printf("prevalim Age combi=%d k=%d  Tage[%d]=V%d Tqresult[%d][%d]=%f\n",ij,k,k,Tage[k],nres,k,Tqresult[nres][k]); */
 2636:     }
 2637:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
 2638:       /* printf("prevalim Prod ij=%d k=%d  Tprod[%d]=%d Tvard[%d][1]=V%d, Tvard[%d][2]=V%d\n",ij,k,k,Tprod[k], k,Tvard[k][1], k,Tvard[k][2]); */
 2639:       if(Dummy[Tvard[k][1]==0]){
 2640: 	if(Dummy[Tvard[k][2]==0]){
 2641: 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
 2642: 	}else{
 2643: 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
 2644: 	}
 2645:       }else{
 2646: 	if(Dummy[Tvard[k][2]==0]){
 2647: 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
 2648: 	}else{
 2649: 	  cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
 2650: 	}
 2651:       }
 2652:     }
 2653:     
 2654:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 2655:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 2656:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 2657:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2658:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 2659: 		/* ij should be linked to the correct index of cov */
 2660: 		/* age and covariate values ij are in 'cov', but we need to pass
 2661: 		 * ij for the observed prevalence at age and status and covariate
 2662: 		 * number:  prevacurrent[(int)agefin][ii][ij]
 2663: 		 */
 2664:     /* 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 *\/ */
 2665:     /* 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 *\/ */
 2666:     out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij)); /* Bug Valgrind */
 2667:     savm=oldm;
 2668:     oldm=newm;
 2669:     for(j=1; j<=nlstate; j++){
 2670:       max[j]=0.;
 2671:       min[j]=1.;
 2672:     }
 2673:     for(j=1; j<=nlstate; j++){ 
 2674:       for(i=1;i<=nlstate;i++){
 2675: 	/* bprlim[i][j]= newm[i][j]/(1-sumnew); */
 2676: 	bprlim[i][j]= newm[i][j];
 2677: 	max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
 2678: 	min[i]=FMIN(min[i],bprlim[i][j]);
 2679:       }
 2680:     }
 2681: 		
 2682:     maxmax=0.;
 2683:     for(i=1; i<=nlstate; i++){
 2684:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
 2685:       maxmax=FMAX(maxmax,meandiff[i]);
 2686:       /* 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); */
 2687:     } /* j loop */
 2688:     *ncvyear= -( (int)age- (int)agefin);
 2689:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
 2690:     if(maxmax < ftolpl){
 2691:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
 2692:       free_vector(min,1,nlstate);
 2693:       free_vector(max,1,nlstate);
 2694:       free_vector(meandiff,1,nlstate);
 2695:       return bprlim;
 2696:     }
 2697:   } /* age loop */
 2698:     /* After some age loop it doesn't converge */
 2699:   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\
 2700: 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);
 2701:   /* 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); */
 2702:   free_vector(min,1,nlstate);
 2703:   free_vector(max,1,nlstate);
 2704:   free_vector(meandiff,1,nlstate);
 2705:   
 2706:   return bprlim; /* should not reach here */
 2707: }
 2708: 
 2709: /*************** transition probabilities ***************/ 
 2710: 
 2711: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 2712: {
 2713:   /* According to parameters values stored in x and the covariate's values stored in cov,
 2714:      computes the probability to be observed in state j being in state i by appying the
 2715:      model to the ncovmodel covariates (including constant and age).
 2716:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 2717:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 2718:      ncth covariate in the global vector x is given by the formula:
 2719:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 2720:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 2721:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 2722:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 2723:      Outputs ps[i][j] the probability to be observed in j being in j according to
 2724:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 2725:   */
 2726:   double s1, lnpijopii;
 2727:   /*double t34;*/
 2728:   int i,j, nc, ii, jj;
 2729: 
 2730:   for(i=1; i<= nlstate; i++){
 2731:     for(j=1; j<i;j++){
 2732:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2733: 	/*lnpijopii += param[i][j][nc]*cov[nc];*/
 2734: 	lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 2735: 	/* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2736:       }
 2737:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2738:       /* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2739:     }
 2740:     for(j=i+1; j<=nlstate+ndeath;j++){
 2741:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2742: 	/*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 2743: 	lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 2744: 	/* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 2745:       }
 2746:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2747:     }
 2748:   }
 2749:   
 2750:   for(i=1; i<= nlstate; i++){
 2751:     s1=0;
 2752:     for(j=1; j<i; j++){
 2753:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2754:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2755:     }
 2756:     for(j=i+1; j<=nlstate+ndeath; j++){
 2757:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2758:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2759:     }
 2760:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 2761:     ps[i][i]=1./(s1+1.);
 2762:     /* Computing other pijs */
 2763:     for(j=1; j<i; j++)
 2764:       ps[i][j]= exp(ps[i][j])*ps[i][i];
 2765:     for(j=i+1; j<=nlstate+ndeath; j++)
 2766:       ps[i][j]= exp(ps[i][j])*ps[i][i];
 2767:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 2768:   } /* end i */
 2769:   
 2770:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 2771:     for(jj=1; jj<= nlstate+ndeath; jj++){
 2772:       ps[ii][jj]=0;
 2773:       ps[ii][ii]=1;
 2774:     }
 2775:   }
 2776:   
 2777:   
 2778:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 2779:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 2780:   /* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 2781:   /*   } */
 2782:   /*   printf("\n "); */
 2783:   /* } */
 2784:   /* printf("\n ");printf("%lf ",cov[2]);*/
 2785:   /*
 2786:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
 2787: 		goto end;*/
 2788:   return ps;
 2789: }
 2790: 
 2791: /*************** backward transition probabilities ***************/ 
 2792: 
 2793:  /* 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 ) */
 2794: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
 2795:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
 2796: {
 2797:   /* Computes the backward probability at age agefin and covariate ij
 2798:    * and returns in **ps as well as **bmij.
 2799:    */
 2800:   int i, ii, j,k;
 2801:   
 2802:   double **out, **pmij();
 2803:   double sumnew=0.;
 2804:   double agefin;
 2805:   
 2806:   double **dnewm, **dsavm, **doldm;
 2807:   double **bbmij;
 2808:   
 2809:   doldm=ddoldms; /* global pointers */
 2810:   dnewm=ddnewms;
 2811:   dsavm=ddsavms;
 2812:   
 2813:   agefin=cov[2];
 2814:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
 2815:      the observed prevalence (with this covariate ij) */
 2816:   dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
 2817:   /* We do have the matrix Px in savm  and we need pij */
 2818:   for (j=1;j<=nlstate+ndeath;j++){
 2819:     sumnew=0.; /* w1 p11 + w2 p21 only on live states */
 2820:     for (ii=1;ii<=nlstate;ii++){
 2821:       sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
 2822:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
 2823:     for (ii=1;ii<=nlstate+ndeath;ii++){
 2824:       if(sumnew >= 1.e-10){
 2825: 	/* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
 2826: 	/* 	doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
 2827: 	/* }else if(agefin >= agemaxpar+stepm/YEARM){ */
 2828: 	/* 	doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
 2829: 	/* }else */
 2830: 	doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
 2831:       }else{
 2832: 	;
 2833: 	/* 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); */
 2834:       }
 2835:     } /*End ii */
 2836:   } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
 2837:   /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
 2838:   bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
 2839:   /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
 2840:   /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
 2841:   /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
 2842:   /* left Product of this matrix by diag matrix of prevalences (savm) */
 2843:   for (j=1;j<=nlstate+ndeath;j++){
 2844:     for (ii=1;ii<=nlstate+ndeath;ii++){
 2845:       dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
 2846:     }
 2847:   } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
 2848:   ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
 2849:   /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
 2850:   /* end bmij */
 2851:   return ps; 
 2852: }
 2853: /*************** transition probabilities ***************/ 
 2854: 
 2855: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 2856: {
 2857:   /* According to parameters values stored in x and the covariate's values stored in cov,
 2858:      computes the probability to be observed in state j being in state i by appying the
 2859:      model to the ncovmodel covariates (including constant and age).
 2860:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 2861:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 2862:      ncth covariate in the global vector x is given by the formula:
 2863:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 2864:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 2865:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 2866:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 2867:      Outputs ps[i][j] the probability to be observed in j being in j according to
 2868:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 2869:   */
 2870:   double s1, lnpijopii;
 2871:   /*double t34;*/
 2872:   int i,j, nc, ii, jj;
 2873: 
 2874:   for(i=1; i<= nlstate; i++){
 2875:     for(j=1; j<i;j++){
 2876:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2877: 	/*lnpijopii += param[i][j][nc]*cov[nc];*/
 2878: 	lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 2879: 	/* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2880:       }
 2881:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2882:       /* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2883:     }
 2884:     for(j=i+1; j<=nlstate+ndeath;j++){
 2885:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2886: 	/*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 2887: 	lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 2888: 	/* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 2889:       }
 2890:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2891:     }
 2892:   }
 2893:   
 2894:   for(i=1; i<= nlstate; i++){
 2895:     s1=0;
 2896:     for(j=1; j<i; j++){
 2897:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2898:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2899:     }
 2900:     for(j=i+1; j<=nlstate+ndeath; j++){
 2901:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2902:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2903:     }
 2904:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 2905:     ps[i][i]=1./(s1+1.);
 2906:     /* Computing other pijs */
 2907:     for(j=1; j<i; j++)
 2908:       ps[i][j]= exp(ps[i][j])*ps[i][i];
 2909:     for(j=i+1; j<=nlstate+ndeath; j++)
 2910:       ps[i][j]= exp(ps[i][j])*ps[i][i];
 2911:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 2912:   } /* end i */
 2913:   
 2914:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 2915:     for(jj=1; jj<= nlstate+ndeath; jj++){
 2916:       ps[ii][jj]=0;
 2917:       ps[ii][ii]=1;
 2918:     }
 2919:   }
 2920:   /* Added for backcast */ /* Transposed matrix too */
 2921:   for(jj=1; jj<= nlstate+ndeath; jj++){
 2922:     s1=0.;
 2923:     for(ii=1; ii<= nlstate+ndeath; ii++){
 2924:       s1+=ps[ii][jj];
 2925:     }
 2926:     for(ii=1; ii<= nlstate; ii++){
 2927:       ps[ii][jj]=ps[ii][jj]/s1;
 2928:     }
 2929:   }
 2930:   /* Transposition */
 2931:   for(jj=1; jj<= nlstate+ndeath; jj++){
 2932:     for(ii=jj; ii<= nlstate+ndeath; ii++){
 2933:       s1=ps[ii][jj];
 2934:       ps[ii][jj]=ps[jj][ii];
 2935:       ps[jj][ii]=s1;
 2936:     }
 2937:   }
 2938:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 2939:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 2940:   /* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 2941:   /*   } */
 2942:   /*   printf("\n "); */
 2943:   /* } */
 2944:   /* printf("\n ");printf("%lf ",cov[2]);*/
 2945:   /*
 2946:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
 2947:     goto end;*/
 2948:   return ps;
 2949: }
 2950: 
 2951: 
 2952: /**************** Product of 2 matrices ******************/
 2953: 
 2954: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
 2955: {
 2956:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
 2957:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
 2958:   /* in, b, out are matrice of pointers which should have been initialized 
 2959:      before: only the contents of out is modified. The function returns
 2960:      a pointer to pointers identical to out */
 2961:   int i, j, k;
 2962:   for(i=nrl; i<= nrh; i++)
 2963:     for(k=ncolol; k<=ncoloh; k++){
 2964:       out[i][k]=0.;
 2965:       for(j=ncl; j<=nch; j++)
 2966:   	out[i][k] +=in[i][j]*b[j][k];
 2967:     }
 2968:   return out;
 2969: }
 2970: 
 2971: 
 2972: /************* Higher Matrix Product ***************/
 2973: 
 2974: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij, int nres )
 2975: {
 2976:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
 2977:      'nhstepm*hstepm*stepm' months (i.e. until
 2978:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
 2979:      nhstepm*hstepm matrices. 
 2980:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
 2981:      (typically every 2 years instead of every month which is too big 
 2982:      for the memory).
 2983:      Model is determined by parameters x and covariates have to be 
 2984:      included manually here. 
 2985: 
 2986:      */
 2987: 
 2988:   int i, j, d, h, k;
 2989:   double **out, cov[NCOVMAX+1];
 2990:   double **newm;
 2991:   double agexact;
 2992:   double agebegin, ageend;
 2993: 
 2994:   /* Hstepm could be zero and should return the unit matrix */
 2995:   for (i=1;i<=nlstate+ndeath;i++)
 2996:     for (j=1;j<=nlstate+ndeath;j++){
 2997:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 2998:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 2999:     }
 3000:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 3001:   for(h=1; h <=nhstepm; h++){
 3002:     for(d=1; d <=hstepm; d++){
 3003:       newm=savm;
 3004:       /* Covariates have to be included here again */
 3005:       cov[1]=1.;
 3006:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
 3007:       cov[2]=agexact;
 3008:       if(nagesqr==1)
 3009: 	cov[3]= agexact*agexact;
 3010:       for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
 3011:  			/* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
 3012: 	cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
 3013: 	/* printf("hpxij Dummy combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov=%lf codtabm(%d,Tvar[%d])=%d \n",ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,k)],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,k)); */
 3014:       }
 3015:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
 3016: 	/* Here comes the value of quantitative after renumbering k with single quantitative covariates */
 3017: 	cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
 3018: 	/* printf("hPxij Quantitative k=%d  TvarsQind[%d]=%d, TvarsQ[%d]=V%d,Tqresult[%d][%d]=%f\n",k,k,TvarsQind[k],k,TvarsQ[k],nres,k,Tqresult[nres][k]); */
 3019:       }
 3020:       for (k=1; k<=cptcovage;k++){
 3021: 	if(Dummy[Tvar[Tage[k]]]){
 3022: 	  cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 3023: 	} else{
 3024: 	  cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
 3025: 	}
 3026: 	/* printf("hPxij Age combi=%d k=%d  Tage[%d]=V%d Tqresult[%d][%d]=%f\n",ij,k,k,Tage[k],nres,k,Tqresult[nres][k]); */
 3027:       }
 3028:       for (k=1; k<=cptcovprod;k++){ /*  */
 3029: 	/* printf("hPxij Prod ij=%d k=%d  Tprod[%d]=%d Tvard[%d][1]=V%d, Tvard[%d][2]=V%d\n",ij,k,k,Tprod[k], k,Tvard[k][1], k,Tvard[k][2]); */
 3030: 	cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
 3031:       }
 3032:       /* for (k=1; k<=cptcovn;k++)  */
 3033:       /* 	cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
 3034:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
 3035:       /* 	cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
 3036:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
 3037:       /* 	cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
 3038:       
 3039:       
 3040:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 3041:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 3042: 			/* right multiplication of oldm by the current matrix */
 3043:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
 3044: 		   pmij(pmmij,cov,ncovmodel,x,nlstate));
 3045:       /* if((int)age == 70){ */
 3046:       /* 	printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
 3047:       /* 	for(i=1; i<=nlstate+ndeath; i++) { */
 3048:       /* 	  printf("%d pmmij ",i); */
 3049:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 3050:       /* 	    printf("%f ",pmmij[i][j]); */
 3051:       /* 	  } */
 3052:       /* 	  printf(" oldm "); */
 3053:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 3054:       /* 	    printf("%f ",oldm[i][j]); */
 3055:       /* 	  } */
 3056:       /* 	  printf("\n"); */
 3057:       /* 	} */
 3058:       /* } */
 3059:       savm=oldm;
 3060:       oldm=newm;
 3061:     }
 3062:     for(i=1; i<=nlstate+ndeath; i++)
 3063:       for(j=1;j<=nlstate+ndeath;j++) {
 3064: 				po[i][j][h]=newm[i][j];
 3065: 				/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 3066:       }
 3067:     /*printf("h=%d ",h);*/
 3068:   } /* end h */
 3069: 	/*     printf("\n H=%d \n",h); */
 3070:   return po;
 3071: }
 3072: 
 3073: /************* Higher Back Matrix Product ***************/
 3074: /* 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 ) */
 3075: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
 3076: {
 3077:   /* Computes the transition matrix starting at age 'age' over
 3078:      'nhstepm*hstepm*stepm' months (i.e. until
 3079:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
 3080:      nhstepm*hstepm matrices.
 3081:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
 3082:      (typically every 2 years instead of every month which is too big
 3083:      for the memory).
 3084:      Model is determined by parameters x and covariates have to be
 3085:      included manually here.
 3086: 
 3087:   */
 3088: 
 3089:   int i, j, d, h, k;
 3090:   double **out, cov[NCOVMAX+1];
 3091:   double **newm;
 3092:   double agexact;
 3093:   double agebegin, ageend;
 3094:   double **oldm, **savm;
 3095: 
 3096:   oldm=oldms;savm=savms;
 3097:   /* Hstepm could be zero and should return the unit matrix */
 3098:   for (i=1;i<=nlstate+ndeath;i++)
 3099:     for (j=1;j<=nlstate+ndeath;j++){
 3100:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 3101:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 3102:     }
 3103:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 3104:   for(h=1; h <=nhstepm; h++){
 3105:     for(d=1; d <=hstepm; d++){
 3106:       newm=savm;
 3107:       /* Covariates have to be included here again */
 3108:       cov[1]=1.;
 3109:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
 3110:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
 3111:       cov[2]=agexact;
 3112:       if(nagesqr==1)
 3113: 	cov[3]= agexact*agexact;
 3114:       for (k=1; k<=cptcovn;k++)
 3115: 	cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 3116:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 3117:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
 3118: 	/* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 3119: 	cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 3120:       /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
 3121:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
 3122: 	cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
 3123:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 3124: 			
 3125: 			
 3126:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 3127:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 3128:       /* Careful transposed matrix */
 3129:       /* age is in cov[2] */
 3130:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
 3131:       /* 						 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
 3132:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
 3133: 		   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
 3134:       /* if((int)age == 70){ */
 3135:       /* 	printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
 3136:       /* 	for(i=1; i<=nlstate+ndeath; i++) { */
 3137:       /* 	  printf("%d pmmij ",i); */
 3138:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 3139:       /* 	    printf("%f ",pmmij[i][j]); */
 3140:       /* 	  } */
 3141:       /* 	  printf(" oldm "); */
 3142:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 3143:       /* 	    printf("%f ",oldm[i][j]); */
 3144:       /* 	  } */
 3145:       /* 	  printf("\n"); */
 3146:       /* 	} */
 3147:       /* } */
 3148:       savm=oldm;
 3149:       oldm=newm;
 3150:     }
 3151:     for(i=1; i<=nlstate+ndeath; i++)
 3152:       for(j=1;j<=nlstate+ndeath;j++) {
 3153: 	po[i][j][h]=newm[i][j];
 3154: 	/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 3155:       }
 3156:     /*printf("h=%d ",h);*/
 3157:   } /* end h */
 3158:   /*     printf("\n H=%d \n",h); */
 3159:   return po;
 3160: }
 3161: 
 3162: 
 3163: #ifdef NLOPT
 3164:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
 3165:   double fret;
 3166:   double *xt;
 3167:   int j;
 3168:   myfunc_data *d2 = (myfunc_data *) pd;
 3169: /* xt = (p1-1); */
 3170:   xt=vector(1,n); 
 3171:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
 3172: 
 3173:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
 3174:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
 3175:   printf("Function = %.12lf ",fret);
 3176:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
 3177:   printf("\n");
 3178:  free_vector(xt,1,n);
 3179:   return fret;
 3180: }
 3181: #endif
 3182: 
 3183: /*************** log-likelihood *************/
 3184: double func( double *x)
 3185: {
 3186:   int i, ii, j, k, mi, d, kk;
 3187:   int ioffset=0;
 3188:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 3189:   double **out;
 3190:   double lli; /* Individual log likelihood */
 3191:   int s1, s2;
 3192:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
 3193:   double bbh, survp;
 3194:   long ipmx;
 3195:   double agexact;
 3196:   /*extern weight */
 3197:   /* We are differentiating ll according to initial status */
 3198:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 3199:   /*for(i=1;i<imx;i++) 
 3200:     printf(" %d\n",s[4][i]);
 3201:   */
 3202: 
 3203:   ++countcallfunc;
 3204: 
 3205:   cov[1]=1.;
 3206: 
 3207:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 3208:   ioffset=0;
 3209:   if(mle==1){
 3210:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3211:       /* Computes the values of the ncovmodel covariates of the model
 3212: 	 depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
 3213: 	 Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
 3214: 	 to be observed in j being in i according to the model.
 3215:       */
 3216:       ioffset=2+nagesqr+cptcovage;
 3217:    /* Fixed */
 3218:       for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
 3219: 	cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (k=6)*/
 3220:       }
 3221:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
 3222: 	 is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
 3223: 	 has been calculated etc */
 3224:       /* For an individual i, wav[i] gives the number of effective waves */
 3225:       /* We compute the contribution to Likelihood of each effective transition
 3226: 	 mw[mi][i] is real wave of the mi th effectve wave */
 3227:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
 3228: 	 s2=s[mw[mi+1][i]][i];
 3229: 	 And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
 3230: 	 But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
 3231: 	 meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
 3232:       */
 3233:       for(mi=1; mi<= wav[i]-1; mi++){
 3234: 	for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
 3235: 	  /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
 3236: 	  cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
 3237: 	}
 3238: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 3239: 	  for (j=1;j<=nlstate+ndeath;j++){
 3240: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3241: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3242: 	  }
 3243: 	for(d=0; d<dh[mi][i]; d++){
 3244: 	  newm=savm;
 3245: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3246: 	  cov[2]=agexact;
 3247: 	  if(nagesqr==1)
 3248: 	    cov[3]= agexact*agexact;  /* Should be changed here */
 3249: 	  for (kk=1; kk<=cptcovage;kk++) {
 3250: 	  if(!FixedV[Tvar[Tage[kk]]])
 3251: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
 3252: 	  else
 3253: 	    cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
 3254: 	  }
 3255: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3256: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3257: 	  savm=oldm;
 3258: 	  oldm=newm;
 3259: 	} /* end mult */
 3260: 	
 3261: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 3262: 	/* But now since version 0.9 we anticipate for bias at large stepm.
 3263: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 3264: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
 3265: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
 3266: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 3267: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
 3268: 	 * probability in order to take into account the bias as a fraction of the way
 3269: 				 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
 3270: 				 * -stepm/2 to stepm/2 .
 3271: 				 * For stepm=1 the results are the same as for previous versions of Imach.
 3272: 				 * For stepm > 1 the results are less biased than in previous versions. 
 3273: 				 */
 3274: 	s1=s[mw[mi][i]][i];
 3275: 	s2=s[mw[mi+1][i]][i];
 3276: 	bbh=(double)bh[mi][i]/(double)stepm; 
 3277: 	/* bias bh is positive if real duration
 3278: 	 * is higher than the multiple of stepm and negative otherwise.
 3279: 	 */
 3280: 	/* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
 3281: 	if( s2 > nlstate){ 
 3282: 	  /* i.e. if s2 is a death state and if the date of death is known 
 3283: 	     then the contribution to the likelihood is the probability to 
 3284: 	     die between last step unit time and current  step unit time, 
 3285: 	     which is also equal to probability to die before dh 
 3286: 	     minus probability to die before dh-stepm . 
 3287: 	     In version up to 0.92 likelihood was computed
 3288: 	     as if date of death was unknown. Death was treated as any other
 3289: 	     health state: the date of the interview describes the actual state
 3290: 	     and not the date of a change in health state. The former idea was
 3291: 	     to consider that at each interview the state was recorded
 3292: 	     (healthy, disable or death) and IMaCh was corrected; but when we
 3293: 	     introduced the exact date of death then we should have modified
 3294: 	     the contribution of an exact death to the likelihood. This new
 3295: 	     contribution is smaller and very dependent of the step unit
 3296: 	     stepm. It is no more the probability to die between last interview
 3297: 	     and month of death but the probability to survive from last
 3298: 	     interview up to one month before death multiplied by the
 3299: 	     probability to die within a month. Thanks to Chris
 3300: 	     Jackson for correcting this bug.  Former versions increased
 3301: 	     mortality artificially. The bad side is that we add another loop
 3302: 	     which slows down the processing. The difference can be up to 10%
 3303: 	     lower mortality.
 3304: 	  */
 3305: 	  /* If, at the beginning of the maximization mostly, the
 3306: 	     cumulative probability or probability to be dead is
 3307: 	     constant (ie = 1) over time d, the difference is equal to
 3308: 	     0.  out[s1][3] = savm[s1][3]: probability, being at state
 3309: 	     s1 at precedent wave, to be dead a month before current
 3310: 	     wave is equal to probability, being at state s1 at
 3311: 	     precedent wave, to be dead at mont of the current
 3312: 	     wave. Then the observed probability (that this person died)
 3313: 	     is null according to current estimated parameter. In fact,
 3314: 	     it should be very low but not zero otherwise the log go to
 3315: 	     infinity.
 3316: 	  */
 3317: /* #ifdef INFINITYORIGINAL */
 3318: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 3319: /* #else */
 3320: /* 	  if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
 3321: /* 	    lli=log(mytinydouble); */
 3322: /* 	  else */
 3323: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 3324: /* #endif */
 3325: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 3326: 	  
 3327: 	} else if  ( s2==-1 ) { /* alive */
 3328: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 3329: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 3330: 	  /*survp += out[s1][j]; */
 3331: 	  lli= log(survp);
 3332: 	}
 3333: 	else if  (s2==-4) { 
 3334: 	  for (j=3,survp=0. ; j<=nlstate; j++)  
 3335: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 3336: 	  lli= log(survp); 
 3337: 	} 
 3338: 	else if  (s2==-5) { 
 3339: 	  for (j=1,survp=0. ; j<=2; j++)  
 3340: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 3341: 	  lli= log(survp); 
 3342: 	} 
 3343: 	else{
 3344: 	  lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 3345: 	  /*  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 */
 3346: 	} 
 3347: 	/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 3348: 	/*if(lli ==000.0)*/
 3349: 	/*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); */
 3350: 	ipmx +=1;
 3351: 	sw += weight[i];
 3352: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3353: 	/* if (lli < log(mytinydouble)){ */
 3354: 	/*   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); */
 3355: 	/*   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]); */
 3356: 	/* } */
 3357:       } /* end of wave */
 3358:     } /* end of individual */
 3359:   }  else if(mle==2){
 3360:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3361:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 3362:       for(mi=1; mi<= wav[i]-1; mi++){
 3363: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 3364: 	  for (j=1;j<=nlstate+ndeath;j++){
 3365: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3366: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3367: 	  }
 3368: 	for(d=0; d<=dh[mi][i]; d++){
 3369: 	  newm=savm;
 3370: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3371: 	  cov[2]=agexact;
 3372: 	  if(nagesqr==1)
 3373: 	    cov[3]= agexact*agexact;
 3374: 	  for (kk=1; kk<=cptcovage;kk++) {
 3375: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3376: 	  }
 3377: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3378: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3379: 	  savm=oldm;
 3380: 	  oldm=newm;
 3381: 	} /* end mult */
 3382:       
 3383: 	s1=s[mw[mi][i]][i];
 3384: 	s2=s[mw[mi+1][i]][i];
 3385: 	bbh=(double)bh[mi][i]/(double)stepm; 
 3386: 	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 */
 3387: 	ipmx +=1;
 3388: 	sw += weight[i];
 3389: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3390:       } /* end of wave */
 3391:     } /* end of individual */
 3392:   }  else if(mle==3){  /* exponential inter-extrapolation */
 3393:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3394:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 3395:       for(mi=1; mi<= wav[i]-1; mi++){
 3396: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 3397: 	  for (j=1;j<=nlstate+ndeath;j++){
 3398: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3399: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3400: 	  }
 3401: 	for(d=0; d<dh[mi][i]; d++){
 3402: 	  newm=savm;
 3403: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3404: 	  cov[2]=agexact;
 3405: 	  if(nagesqr==1)
 3406: 	    cov[3]= agexact*agexact;
 3407: 	  for (kk=1; kk<=cptcovage;kk++) {
 3408: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3409: 	  }
 3410: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3411: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3412: 	  savm=oldm;
 3413: 	  oldm=newm;
 3414: 	} /* end mult */
 3415:       
 3416: 	s1=s[mw[mi][i]][i];
 3417: 	s2=s[mw[mi+1][i]][i];
 3418: 	bbh=(double)bh[mi][i]/(double)stepm; 
 3419: 	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 */
 3420: 	ipmx +=1;
 3421: 	sw += weight[i];
 3422: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3423:       } /* end of wave */
 3424:     } /* end of individual */
 3425:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
 3426:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3427:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 3428:       for(mi=1; mi<= wav[i]-1; mi++){
 3429: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 3430: 	  for (j=1;j<=nlstate+ndeath;j++){
 3431: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3432: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3433: 	  }
 3434: 	for(d=0; d<dh[mi][i]; d++){
 3435: 	  newm=savm;
 3436: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3437: 	  cov[2]=agexact;
 3438: 	  if(nagesqr==1)
 3439: 	    cov[3]= agexact*agexact;
 3440: 	  for (kk=1; kk<=cptcovage;kk++) {
 3441: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3442: 	  }
 3443: 	
 3444: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3445: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3446: 	  savm=oldm;
 3447: 	  oldm=newm;
 3448: 	} /* end mult */
 3449:       
 3450: 	s1=s[mw[mi][i]][i];
 3451: 	s2=s[mw[mi+1][i]][i];
 3452: 	if( s2 > nlstate){ 
 3453: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 3454: 	} else if  ( s2==-1 ) { /* alive */
 3455: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 3456: 	    survp += out[s1][j];
 3457: 	  lli= log(survp);
 3458: 	}else{
 3459: 	  lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 3460: 	}
 3461: 	ipmx +=1;
 3462: 	sw += weight[i];
 3463: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3464: /* 	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]); */
 3465:       } /* end of wave */
 3466:     } /* end of individual */
 3467:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
 3468:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3469:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 3470:       for(mi=1; mi<= wav[i]-1; mi++){
 3471: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 3472: 	  for (j=1;j<=nlstate+ndeath;j++){
 3473: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3474: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3475: 	  }
 3476: 	for(d=0; d<dh[mi][i]; d++){
 3477: 	  newm=savm;
 3478: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3479: 	  cov[2]=agexact;
 3480: 	  if(nagesqr==1)
 3481: 	    cov[3]= agexact*agexact;
 3482: 	  for (kk=1; kk<=cptcovage;kk++) {
 3483: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3484: 	  }
 3485: 	
 3486: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3487: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3488: 	  savm=oldm;
 3489: 	  oldm=newm;
 3490: 	} /* end mult */
 3491:       
 3492: 	s1=s[mw[mi][i]][i];
 3493: 	s2=s[mw[mi+1][i]][i];
 3494: 	lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 3495: 	ipmx +=1;
 3496: 	sw += weight[i];
 3497: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3498: 	/*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]);*/
 3499:       } /* end of wave */
 3500:     } /* end of individual */
 3501:   } /* End of if */
 3502:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 3503:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 3504:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 3505:   return -l;
 3506: }
 3507: 
 3508: /*************** log-likelihood *************/
 3509: double funcone( double *x)
 3510: {
 3511:   /* Same as func but slower because of a lot of printf and if */
 3512:   int i, ii, j, k, mi, d, kk;
 3513:   int ioffset=0;
 3514:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 3515:   double **out;
 3516:   double lli; /* Individual log likelihood */
 3517:   double llt;
 3518:   int s1, s2;
 3519:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
 3520: 
 3521:   double bbh, survp;
 3522:   double agexact;
 3523:   double agebegin, ageend;
 3524:   /*extern weight */
 3525:   /* We are differentiating ll according to initial status */
 3526:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 3527:   /*for(i=1;i<imx;i++) 
 3528:     printf(" %d\n",s[4][i]);
 3529:   */
 3530:   cov[1]=1.;
 3531: 
 3532:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 3533:   ioffset=0;
 3534:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3535:     ioffset=2+nagesqr+cptcovage;
 3536:     /* Fixed */
 3537:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
 3538:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
 3539:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
 3540:       cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (k=6)*/
 3541: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
 3542: /*    cov[2+6]=covar[Tvar[6]][i];  */
 3543: /*    cov[2+6]=covar[2][i]; V2  */
 3544: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
 3545: /*    cov[2+7]=covar[Tvar[7]][i];  */
 3546: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
 3547: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
 3548: /*    cov[2+9]=covar[Tvar[9]][i];  */
 3549: /*    cov[2+9]=covar[1][i]; V1  */
 3550:     }
 3551:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
 3552:     /*   cov[++ioffset]=coqvar[TvarFQ[k]][i];/\* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V2 and V1*V2 is fixed (k=6 and 7?)*\/ */
 3553:     /* } */
 3554:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
 3555:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
 3556:     /* } */
 3557:     
 3558: 
 3559:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
 3560:     /* Wave varying (but not age varying) */
 3561:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
 3562: 	/* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
 3563: 	cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
 3564:       }
 3565:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
 3566:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
 3567:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
 3568:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
 3569:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
 3570:       /* printf(" i=%d,mi=%d,itv=%d,TmodelInvind[itv]=%d,cotvar[mw[mi][i]][TmodelInvind[itv]][i]=%f\n", i, mi, itv, TmodelInvind[itv],cotvar[mw[mi][i]][TmodelInvind[itv]][i]); */
 3571:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
 3572:       /* 	iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
 3573:       /* 	/\* printf(" i=%d,mi=%d,iqtv=%d,TmodelInvQind[iqtv]=%d,cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]=%f\n", i, mi, iqtv, TmodelInvQind[iqtv],cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]); *\/ */
 3574:       /* 	cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
 3575:       /* } */
 3576:       for (ii=1;ii<=nlstate+ndeath;ii++)
 3577: 	for (j=1;j<=nlstate+ndeath;j++){
 3578: 	  oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3579: 	  savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3580: 	}
 3581:       
 3582:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
 3583:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
 3584:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
 3585: 	/*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 3586: 	  and mw[mi+1][i]. dh depends on stepm.*/
 3587: 	newm=savm;
 3588: 	agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3589: 	cov[2]=agexact;
 3590: 	if(nagesqr==1)
 3591: 	  cov[3]= agexact*agexact;
 3592: 	for (kk=1; kk<=cptcovage;kk++) {
 3593: 	  if(!FixedV[Tvar[Tage[kk]]])
 3594: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3595: 	  else
 3596: 	    cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
 3597: 	}
 3598: 	/* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
 3599: 	/* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 3600: 	out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3601: 		     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3602: 	/* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
 3603: 	/* 	     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
 3604: 	savm=oldm;
 3605: 	oldm=newm;
 3606:       } /* end mult */
 3607:       
 3608:       s1=s[mw[mi][i]][i];
 3609:       s2=s[mw[mi+1][i]][i];
 3610:       /* if(s2==-1){ */
 3611:       /* 	printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
 3612:       /* 	/\* exit(1); *\/ */
 3613:       /* } */
 3614:       bbh=(double)bh[mi][i]/(double)stepm; 
 3615:       /* bias is positive if real duration
 3616:        * is higher than the multiple of stepm and negative otherwise.
 3617:        */
 3618:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
 3619: 	lli=log(out[s1][s2] - savm[s1][s2]);
 3620:       } else if  ( s2==-1 ) { /* alive */
 3621: 	for (j=1,survp=0. ; j<=nlstate; j++) 
 3622: 	  survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 3623: 	lli= log(survp);
 3624:       }else if (mle==1){
 3625: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 3626:       } else if(mle==2){
 3627: 	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 */
 3628:       } else if(mle==3){  /* exponential inter-extrapolation */
 3629: 	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 */
 3630:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
 3631: 	lli=log(out[s1][s2]); /* Original formula */
 3632:       } else{  /* mle=0 back to 1 */
 3633: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 3634: 	/*lli=log(out[s1][s2]); */ /* Original formula */
 3635:       } /* End of if */
 3636:       ipmx +=1;
 3637:       sw += weight[i];
 3638:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3639:       /*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]); */
 3640:       if(globpr){
 3641: 	fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
 3642:  %11.6f %11.6f %11.6f ", \
 3643: 		num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
 3644: 		2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
 3645: 	for(k=1,llt=0.,l=0.; k<=nlstate; k++){
 3646: 	  llt +=ll[k]*gipmx/gsw;
 3647: 	  fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
 3648: 	}
 3649: 	fprintf(ficresilk," %10.6f\n", -llt);
 3650:       }
 3651: 	} /* end of wave */
 3652: } /* end of individual */
 3653: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 3654: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 3655: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 3656: if(globpr==0){ /* First time we count the contributions and weights */
 3657: 	gipmx=ipmx;
 3658: 	gsw=sw;
 3659: }
 3660: return -l;
 3661: }
 3662: 
 3663: 
 3664: /*************** function likelione ***********/
 3665: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
 3666: {
 3667:   /* This routine should help understanding what is done with 
 3668:      the selection of individuals/waves and
 3669:      to check the exact contribution to the likelihood.
 3670:      Plotting could be done.
 3671:    */
 3672:   int k;
 3673: 
 3674:   if(*globpri !=0){ /* Just counts and sums, no printings */
 3675:     strcpy(fileresilk,"ILK_"); 
 3676:     strcat(fileresilk,fileresu);
 3677:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
 3678:       printf("Problem with resultfile: %s\n", fileresilk);
 3679:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
 3680:     }
 3681:     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");
 3682:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
 3683:     /* 	i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
 3684:     for(k=1; k<=nlstate; k++) 
 3685:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
 3686:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
 3687:   }
 3688: 
 3689:   *fretone=(*funcone)(p);
 3690:   if(*globpri !=0){
 3691:     fclose(ficresilk);
 3692:     if (mle ==0)
 3693:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
 3694:     else if(mle >=1)
 3695:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
 3696:     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));
 3697:     
 3698:       
 3699:     for (k=1; k<= nlstate ; k++) {
 3700:       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> \
 3701: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
 3702:     }
 3703:     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> \
 3704: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
 3705:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
 3706: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
 3707:     fflush(fichtm);
 3708:   }
 3709:   return;
 3710: }
 3711: 
 3712: 
 3713: /*********** Maximum Likelihood Estimation ***************/
 3714: 
 3715: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
 3716: {
 3717:   int i,j, iter=0;
 3718:   double **xi;
 3719:   double fret;
 3720:   double fretone; /* Only one call to likelihood */
 3721:   /*  char filerespow[FILENAMELENGTH];*/
 3722: 
 3723: #ifdef NLOPT
 3724:   int creturn;
 3725:   nlopt_opt opt;
 3726:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
 3727:   double *lb;
 3728:   double minf; /* the minimum objective value, upon return */
 3729:   double * p1; /* Shifted parameters from 0 instead of 1 */
 3730:   myfunc_data dinst, *d = &dinst;
 3731: #endif
 3732: 
 3733: 
 3734:   xi=matrix(1,npar,1,npar);
 3735:   for (i=1;i<=npar;i++)
 3736:     for (j=1;j<=npar;j++)
 3737:       xi[i][j]=(i==j ? 1.0 : 0.0);
 3738:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
 3739:   strcpy(filerespow,"POW_"); 
 3740:   strcat(filerespow,fileres);
 3741:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
 3742:     printf("Problem with resultfile: %s\n", filerespow);
 3743:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 3744:   }
 3745:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
 3746:   for (i=1;i<=nlstate;i++)
 3747:     for(j=1;j<=nlstate+ndeath;j++)
 3748:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 3749:   fprintf(ficrespow,"\n");
 3750: #ifdef POWELL
 3751:   powell(p,xi,npar,ftol,&iter,&fret,func);
 3752: #endif
 3753: 
 3754: #ifdef NLOPT
 3755: #ifdef NEWUOA
 3756:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
 3757: #else
 3758:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
 3759: #endif
 3760:   lb=vector(0,npar-1);
 3761:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
 3762:   nlopt_set_lower_bounds(opt, lb);
 3763:   nlopt_set_initial_step1(opt, 0.1);
 3764:   
 3765:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
 3766:   d->function = func;
 3767:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
 3768:   nlopt_set_min_objective(opt, myfunc, d);
 3769:   nlopt_set_xtol_rel(opt, ftol);
 3770:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
 3771:     printf("nlopt failed! %d\n",creturn); 
 3772:   }
 3773:   else {
 3774:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
 3775:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
 3776:     iter=1; /* not equal */
 3777:   }
 3778:   nlopt_destroy(opt);
 3779: #endif
 3780:   free_matrix(xi,1,npar,1,npar);
 3781:   fclose(ficrespow);
 3782:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 3783:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 3784:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 3785: 
 3786: }
 3787: 
 3788: /**** Computes Hessian and covariance matrix ***/
 3789: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
 3790: {
 3791:   double  **a,**y,*x,pd;
 3792:   /* double **hess; */
 3793:   int i, j;
 3794:   int *indx;
 3795: 
 3796:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
 3797:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
 3798:   void lubksb(double **a, int npar, int *indx, double b[]) ;
 3799:   void ludcmp(double **a, int npar, int *indx, double *d) ;
 3800:   double gompertz(double p[]);
 3801:   /* hess=matrix(1,npar,1,npar); */
 3802: 
 3803:   printf("\nCalculation of the hessian matrix. Wait...\n");
 3804:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
 3805:   for (i=1;i<=npar;i++){
 3806:     printf("%d-",i);fflush(stdout);
 3807:     fprintf(ficlog,"%d-",i);fflush(ficlog);
 3808:    
 3809:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
 3810:     
 3811:     /*  printf(" %f ",p[i]);
 3812: 	printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
 3813:   }
 3814:   
 3815:   for (i=1;i<=npar;i++) {
 3816:     for (j=1;j<=npar;j++)  {
 3817:       if (j>i) { 
 3818: 	printf(".%d-%d",i,j);fflush(stdout);
 3819: 	fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
 3820: 	hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
 3821: 	
 3822: 	hess[j][i]=hess[i][j];    
 3823: 	/*printf(" %lf ",hess[i][j]);*/
 3824:       }
 3825:     }
 3826:   }
 3827:   printf("\n");
 3828:   fprintf(ficlog,"\n");
 3829: 
 3830:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
 3831:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
 3832:   
 3833:   a=matrix(1,npar,1,npar);
 3834:   y=matrix(1,npar,1,npar);
 3835:   x=vector(1,npar);
 3836:   indx=ivector(1,npar);
 3837:   for (i=1;i<=npar;i++)
 3838:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
 3839:   ludcmp(a,npar,indx,&pd);
 3840: 
 3841:   for (j=1;j<=npar;j++) {
 3842:     for (i=1;i<=npar;i++) x[i]=0;
 3843:     x[j]=1;
 3844:     lubksb(a,npar,indx,x);
 3845:     for (i=1;i<=npar;i++){ 
 3846:       matcov[i][j]=x[i];
 3847:     }
 3848:   }
 3849: 
 3850:   printf("\n#Hessian matrix#\n");
 3851:   fprintf(ficlog,"\n#Hessian matrix#\n");
 3852:   for (i=1;i<=npar;i++) { 
 3853:     for (j=1;j<=npar;j++) { 
 3854:       printf("%.6e ",hess[i][j]);
 3855:       fprintf(ficlog,"%.6e ",hess[i][j]);
 3856:     }
 3857:     printf("\n");
 3858:     fprintf(ficlog,"\n");
 3859:   }
 3860: 
 3861:   /* printf("\n#Covariance matrix#\n"); */
 3862:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
 3863:   /* for (i=1;i<=npar;i++) {  */
 3864:   /*   for (j=1;j<=npar;j++) {  */
 3865:   /*     printf("%.6e ",matcov[i][j]); */
 3866:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
 3867:   /*   } */
 3868:   /*   printf("\n"); */
 3869:   /*   fprintf(ficlog,"\n"); */
 3870:   /* } */
 3871: 
 3872:   /* Recompute Inverse */
 3873:   /* for (i=1;i<=npar;i++) */
 3874:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
 3875:   /* ludcmp(a,npar,indx,&pd); */
 3876: 
 3877:   /*  printf("\n#Hessian matrix recomputed#\n"); */
 3878: 
 3879:   /* for (j=1;j<=npar;j++) { */
 3880:   /*   for (i=1;i<=npar;i++) x[i]=0; */
 3881:   /*   x[j]=1; */
 3882:   /*   lubksb(a,npar,indx,x); */
 3883:   /*   for (i=1;i<=npar;i++){  */
 3884:   /*     y[i][j]=x[i]; */
 3885:   /*     printf("%.3e ",y[i][j]); */
 3886:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
 3887:   /*   } */
 3888:   /*   printf("\n"); */
 3889:   /*   fprintf(ficlog,"\n"); */
 3890:   /* } */
 3891: 
 3892:   /* Verifying the inverse matrix */
 3893: #ifdef DEBUGHESS
 3894:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
 3895: 
 3896:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
 3897:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
 3898: 
 3899:   for (j=1;j<=npar;j++) {
 3900:     for (i=1;i<=npar;i++){ 
 3901:       printf("%.2f ",y[i][j]);
 3902:       fprintf(ficlog,"%.2f ",y[i][j]);
 3903:     }
 3904:     printf("\n");
 3905:     fprintf(ficlog,"\n");
 3906:   }
 3907: #endif
 3908: 
 3909:   free_matrix(a,1,npar,1,npar);
 3910:   free_matrix(y,1,npar,1,npar);
 3911:   free_vector(x,1,npar);
 3912:   free_ivector(indx,1,npar);
 3913:   /* free_matrix(hess,1,npar,1,npar); */
 3914: 
 3915: 
 3916: }
 3917: 
 3918: /*************** hessian matrix ****************/
 3919: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
 3920: { /* Around values of x, computes the function func and returns the scales delti and hessian */
 3921:   int i;
 3922:   int l=1, lmax=20;
 3923:   double k1,k2, res, fx;
 3924:   double p2[MAXPARM+1]; /* identical to x */
 3925:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 3926:   int k=0,kmax=10;
 3927:   double l1;
 3928: 
 3929:   fx=func(x);
 3930:   for (i=1;i<=npar;i++) p2[i]=x[i];
 3931:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
 3932:     l1=pow(10,l);
 3933:     delts=delt;
 3934:     for(k=1 ; k <kmax; k=k+1){
 3935:       delt = delta*(l1*k);
 3936:       p2[theta]=x[theta] +delt;
 3937:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
 3938:       p2[theta]=x[theta]-delt;
 3939:       k2=func(p2)-fx;
 3940:       /*res= (k1-2.0*fx+k2)/delt/delt; */
 3941:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
 3942:       
 3943: #ifdef DEBUGHESSII
 3944:       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);
 3945:       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);
 3946: #endif
 3947:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
 3948:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 3949: 	k=kmax;
 3950:       }
 3951:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
 3952: 	k=kmax; l=lmax*10;
 3953:       }
 3954:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
 3955: 	delts=delt;
 3956:       }
 3957:     } /* End loop k */
 3958:   }
 3959:   delti[theta]=delts;
 3960:   return res; 
 3961:   
 3962: }
 3963: 
 3964: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
 3965: {
 3966:   int i;
 3967:   int l=1, lmax=20;
 3968:   double k1,k2,k3,k4,res,fx;
 3969:   double p2[MAXPARM+1];
 3970:   int k, kmax=1;
 3971:   double v1, v2, cv12, lc1, lc2;
 3972: 
 3973:   int firstime=0;
 3974:   
 3975:   fx=func(x);
 3976:   for (k=1; k<=kmax; k=k+10) {
 3977:     for (i=1;i<=npar;i++) p2[i]=x[i];
 3978:     p2[thetai]=x[thetai]+delti[thetai]*k;
 3979:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
 3980:     k1=func(p2)-fx;
 3981:   
 3982:     p2[thetai]=x[thetai]+delti[thetai]*k;
 3983:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
 3984:     k2=func(p2)-fx;
 3985:   
 3986:     p2[thetai]=x[thetai]-delti[thetai]*k;
 3987:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
 3988:     k3=func(p2)-fx;
 3989:   
 3990:     p2[thetai]=x[thetai]-delti[thetai]*k;
 3991:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
 3992:     k4=func(p2)-fx;
 3993:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
 3994:     if(k1*k2*k3*k4 <0.){
 3995:       firstime=1;
 3996:       kmax=kmax+10;
 3997:     }
 3998:     if(kmax >=10 || firstime ==1){
 3999:       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);
 4000:       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);
 4001:       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);
 4002:       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);
 4003:     }
 4004: #ifdef DEBUGHESSIJ
 4005:     v1=hess[thetai][thetai];
 4006:     v2=hess[thetaj][thetaj];
 4007:     cv12=res;
 4008:     /* Computing eigen value of Hessian matrix */
 4009:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 4010:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 4011:     if ((lc2 <0) || (lc1 <0) ){
 4012:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
 4013:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
 4014:       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);
 4015:       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);
 4016:     }
 4017: #endif
 4018:   }
 4019:   return res;
 4020: }
 4021: 
 4022:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
 4023: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
 4024: /* { */
 4025: /*   int i; */
 4026: /*   int l=1, lmax=20; */
 4027: /*   double k1,k2,k3,k4,res,fx; */
 4028: /*   double p2[MAXPARM+1]; */
 4029: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
 4030: /*   int k=0,kmax=10; */
 4031: /*   double l1; */
 4032:   
 4033: /*   fx=func(x); */
 4034: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
 4035: /*     l1=pow(10,l); */
 4036: /*     delts=delt; */
 4037: /*     for(k=1 ; k <kmax; k=k+1){ */
 4038: /*       delt = delti*(l1*k); */
 4039: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
 4040: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
 4041: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
 4042: /*       k1=func(p2)-fx; */
 4043:       
 4044: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
 4045: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
 4046: /*       k2=func(p2)-fx; */
 4047:       
 4048: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
 4049: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
 4050: /*       k3=func(p2)-fx; */
 4051:       
 4052: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
 4053: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
 4054: /*       k4=func(p2)-fx; */
 4055: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
 4056: /* #ifdef DEBUGHESSIJ */
 4057: /*       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); */
 4058: /*       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); */
 4059: /* #endif */
 4060: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
 4061: /* 	k=kmax; */
 4062: /*       } */
 4063: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
 4064: /* 	k=kmax; l=lmax*10; */
 4065: /*       } */
 4066: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
 4067: /* 	delts=delt; */
 4068: /*       } */
 4069: /*     } /\* End loop k *\/ */
 4070: /*   } */
 4071: /*   delti[theta]=delts; */
 4072: /*   return res;  */
 4073: /* } */
 4074: 
 4075: 
 4076: /************** Inverse of matrix **************/
 4077: void ludcmp(double **a, int n, int *indx, double *d) 
 4078: { 
 4079:   int i,imax,j,k; 
 4080:   double big,dum,sum,temp; 
 4081:   double *vv; 
 4082:  
 4083:   vv=vector(1,n); 
 4084:   *d=1.0; 
 4085:   for (i=1;i<=n;i++) { 
 4086:     big=0.0; 
 4087:     for (j=1;j<=n;j++) 
 4088:       if ((temp=fabs(a[i][j])) > big) big=temp; 
 4089:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
 4090:     vv[i]=1.0/big; 
 4091:   } 
 4092:   for (j=1;j<=n;j++) { 
 4093:     for (i=1;i<j;i++) { 
 4094:       sum=a[i][j]; 
 4095:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
 4096:       a[i][j]=sum; 
 4097:     } 
 4098:     big=0.0; 
 4099:     for (i=j;i<=n;i++) { 
 4100:       sum=a[i][j]; 
 4101:       for (k=1;k<j;k++) 
 4102: 	sum -= a[i][k]*a[k][j]; 
 4103:       a[i][j]=sum; 
 4104:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
 4105: 	big=dum; 
 4106: 	imax=i; 
 4107:       } 
 4108:     } 
 4109:     if (j != imax) { 
 4110:       for (k=1;k<=n;k++) { 
 4111: 	dum=a[imax][k]; 
 4112: 	a[imax][k]=a[j][k]; 
 4113: 	a[j][k]=dum; 
 4114:       } 
 4115:       *d = -(*d); 
 4116:       vv[imax]=vv[j]; 
 4117:     } 
 4118:     indx[j]=imax; 
 4119:     if (a[j][j] == 0.0) a[j][j]=TINY; 
 4120:     if (j != n) { 
 4121:       dum=1.0/(a[j][j]); 
 4122:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
 4123:     } 
 4124:   } 
 4125:   free_vector(vv,1,n);  /* Doesn't work */
 4126: ;
 4127: } 
 4128: 
 4129: void lubksb(double **a, int n, int *indx, double b[]) 
 4130: { 
 4131:   int i,ii=0,ip,j; 
 4132:   double sum; 
 4133:  
 4134:   for (i=1;i<=n;i++) { 
 4135:     ip=indx[i]; 
 4136:     sum=b[ip]; 
 4137:     b[ip]=b[i]; 
 4138:     if (ii) 
 4139:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
 4140:     else if (sum) ii=i; 
 4141:     b[i]=sum; 
 4142:   } 
 4143:   for (i=n;i>=1;i--) { 
 4144:     sum=b[i]; 
 4145:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
 4146:     b[i]=sum/a[i][i]; 
 4147:   } 
 4148: } 
 4149: 
 4150: void pstamp(FILE *fichier)
 4151: {
 4152:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
 4153: }
 4154: 
 4155: /************ Frequencies ********************/
 4156: void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
 4157: 		  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[],	\
 4158: 		  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
 4159: {  /* Some frequencies */
 4160:   
 4161:   int i, m, jk, j1, bool, z1,j, k, iv;
 4162:   int iind=0, iage=0;
 4163:   int mi; /* Effective wave */
 4164:   int first;
 4165:   double ***freq; /* Frequencies */
 4166:   double *meanq;
 4167:   double **meanqt;
 4168:   double *pp, **prop, *posprop, *pospropt;
 4169:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
 4170:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
 4171:   double agebegin, ageend;
 4172:     
 4173:   pp=vector(1,nlstate);
 4174:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
 4175:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
 4176:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
 4177:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
 4178:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
 4179:   meanqt=matrix(1,lastpass,1,nqtveff);
 4180:   strcpy(fileresp,"P_");
 4181:   strcat(fileresp,fileresu);
 4182:   /*strcat(fileresphtm,fileresu);*/
 4183:   if((ficresp=fopen(fileresp,"w"))==NULL) {
 4184:     printf("Problem with prevalence resultfile: %s\n", fileresp);
 4185:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
 4186:     exit(0);
 4187:   }
 4188:   
 4189:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
 4190:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
 4191:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
 4192:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
 4193:     fflush(ficlog);
 4194:     exit(70); 
 4195:   }
 4196:   else{
 4197:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 4198: <hr size=\"2\" color=\"#EC5E5E\"> \n					\
 4199: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
 4200: 	    fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 4201:   }
 4202:   fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies and prevalence by age at begin of transition and dummy covariate value at beginning of transition</h4>\n",fileresphtm, fileresphtm);
 4203:   
 4204:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
 4205:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
 4206:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
 4207:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
 4208:     fflush(ficlog);
 4209:     exit(70); 
 4210:   } else{
 4211:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 4212: <hr size=\"2\" color=\"#EC5E5E\"> \n					\
 4213: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
 4214: 	    fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 4215:   }
 4216:   fprintf(ficresphtmfr,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies of all effective transitions of the model, by age at begin of transition, and covariate value at the begin of transition (if the covariate is a varying covariate) </h4>Unknown status is -1<br/>\n",fileresphtmfr, fileresphtmfr);
 4217:   
 4218:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
 4219:   j1=0;
 4220:   
 4221:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
 4222:   j=cptcoveff;  /* Only dummy covariates of the model */
 4223:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 4224:   
 4225:   first=1;
 4226:   
 4227:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
 4228:      reference=low_education V1=0,V2=0
 4229:      med_educ                V1=1 V2=0, 
 4230:      high_educ               V1=0 V2=1
 4231:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
 4232:   */
 4233:   
 4234:   for (j1 = 1; j1 <= (int) pow(2,j); j1++){ /* Loop on covariates combination in order of model, excluding quantitatives V4=0, V3=0 for example, fixed or varying covariates */
 4235:     posproptt=0.;
 4236:     /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
 4237:       scanf("%d", i);*/
 4238:     for (i=-5; i<=nlstate+ndeath; i++)  
 4239:       for (jk=-5; jk<=nlstate+ndeath; jk++)  
 4240: 	for(m=iagemin; m <= iagemax+3; m++)
 4241: 	  freq[i][jk][m]=0;
 4242:     
 4243:     for (i=1; i<=nlstate; i++)  {
 4244:       for(m=iagemin; m <= iagemax+3; m++)
 4245: 	prop[i][m]=0;
 4246:       posprop[i]=0;
 4247:       pospropt[i]=0;
 4248:     }
 4249:     /* for (z1=1; z1<= nqfveff; z1++) {   */
 4250:     /*   meanq[z1]+=0.; */
 4251:     /*   for(m=1;m<=lastpass;m++){ */
 4252:     /* 	meanqt[m][z1]=0.; */
 4253:     /*   } */
 4254:     /* } */
 4255:     
 4256:     dateintsum=0;
 4257:     k2cpt=0;
 4258:     /* For that combination of covariate j1, we count and print the frequencies in one pass */
 4259:     for (iind=1; iind<=imx; iind++) { /* For each individual iind */
 4260:       bool=1;
 4261:       if(anyvaryingduminmodel==0){ /* If All fixed covariates */
 4262: 	if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
 4263: 	  /* for (z1=1; z1<= nqfveff; z1++) {   */
 4264: 	  /*   meanq[z1]+=coqvar[Tvar[z1]][iind];  /\* Computes mean of quantitative with selected filter *\/ */
 4265: 	  /* } */
 4266: 	  for (z1=1; z1<=cptcoveff; z1++) {  
 4267: 	    /* if(Tvaraff[z1] ==-20){ */
 4268: 	    /* 	 /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
 4269: 	    /* }else  if(Tvaraff[z1] ==-10){ */
 4270: 	    /* 	 /\* sumnew+=coqvar[z1][iind]; *\/ */
 4271: 	    /* }else  */
 4272: 	    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
 4273: 	      /* Tests if this individual iind responded to j1 (V4=1 V3=0) */
 4274: 	      bool=0;
 4275: 	      /* 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", 
 4276: 		 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
 4277: 		 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
 4278: 	      /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
 4279: 	    } /* Onlyf fixed */
 4280: 	  } /* end z1 */
 4281: 	} /* cptcovn > 0 */
 4282:       } /* end any */
 4283:       if (bool==1){ /* We selected an individual iind satisfying combination j1 or all fixed */
 4284: 	/* for(m=firstpass; m<=lastpass; m++){ */
 4285: 	for(mi=1; mi<wav[iind];mi++){ /* For that wave */
 4286: 	  m=mw[mi][iind];
 4287: 	  if(anyvaryingduminmodel==1){ /* Some are varying covariates */
 4288: 	    for (z1=1; z1<=cptcoveff; z1++) {
 4289: 	      if( Fixed[Tmodelind[z1]]==1){
 4290: 		iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
 4291: 		if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
 4292: 		  bool=0;
 4293: 	      }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
 4294: 		if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
 4295: 		  bool=0;
 4296: 		}
 4297: 	      }
 4298: 	    }
 4299: 	  }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
 4300: 	  /* bool =0 we keep that guy which corresponds to the combination of dummy values */
 4301: 	  if(bool==1){
 4302: 	    /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
 4303: 	       and mw[mi+1][iind]. dh depends on stepm. */
 4304: 	    agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
 4305: 	    ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
 4306: 	    if(m >=firstpass && m <=lastpass){
 4307: 	      k2=anint[m][iind]+(mint[m][iind]/12.);
 4308: 	      /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
 4309: 	      if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
 4310: 	      if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
 4311: 	      if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
 4312: 		prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
 4313: 	      if (m<lastpass) {
 4314: 		/* if(s[m][iind]==4 && s[m+1][iind]==4) */
 4315: 		/*   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]); */
 4316: 		if(s[m][iind]==-1)
 4317: 		  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.));
 4318: 		freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
 4319: 		/* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
 4320: 		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 */
 4321: 	      }
 4322: 	    } /* end if between passes */  
 4323: 	    if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99)) {
 4324: 	      dateintsum=dateintsum+k2;
 4325: 	      k2cpt++;
 4326: 	      /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
 4327: 	    }
 4328: 	  } /* end bool 2 */
 4329: 	} /* end m */
 4330:       } /* end bool */
 4331:     } /* end iind = 1 to imx */
 4332:     /* prop[s][age] is feeded for any initial and valid live state as well as
 4333:        freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
 4334:     
 4335:     
 4336:     /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 4337:     pstamp(ficresp);
 4338:     if  (cptcoveff>0){
 4339:       fprintf(ficresp, "\n#********** Variable "); 
 4340:       fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
 4341:       fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
 4342:       fprintf(ficlog, "\n#********** Variable "); 
 4343:       for (z1=1; z1<=cptcoveff; z1++){
 4344: 	if(DummyV[z1]){
 4345: 	  fprintf(ficresp, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 4346: 	  fprintf(ficresphtm, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 4347: 	  fprintf(ficresphtmfr, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 4348: 	  fprintf(ficlog, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 4349: 	}else{
 4350: 	  fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 4351: 	  fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 4352: 	  fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 4353: 	  fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 4354: 	}
 4355:       }
 4356:       fprintf(ficresp, "**********\n#");
 4357:       fprintf(ficresphtm, "**********</h3>\n");
 4358:       fprintf(ficresphtmfr, "**********</h3>\n");
 4359:       fprintf(ficlog, "**********\n");
 4360:     }
 4361:     fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
 4362:     for(i=1; i<=nlstate;i++) {
 4363:       fprintf(ficresp, " Age Prev(%d)  N(%d)  N  ",i,i);
 4364:       fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
 4365:     }
 4366:     fprintf(ficresp, "\n");
 4367:     fprintf(ficresphtm, "\n");
 4368:     
 4369:     /* Header of frequency table by age */
 4370:     fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
 4371:     fprintf(ficresphtmfr,"<th>Age</th> ");
 4372:     for(jk=-1; jk <=nlstate+ndeath; jk++){
 4373:       for(m=-1; m <=nlstate+ndeath; m++){
 4374: 	if(jk!=0 && m!=0)
 4375: 	  fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
 4376:       }
 4377:     }
 4378:     fprintf(ficresphtmfr, "\n");
 4379:     
 4380:     /* For each age */
 4381:     for(iage=iagemin; iage <= iagemax+3; iage++){
 4382:       fprintf(ficresphtm,"<tr>");
 4383:       if(iage==iagemax+1){
 4384: 	fprintf(ficlog,"1");
 4385: 	fprintf(ficresphtmfr,"<tr><th>0</th> ");
 4386:       }else if(iage==iagemax+2){
 4387: 	fprintf(ficlog,"0");
 4388: 	fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
 4389:       }else if(iage==iagemax+3){
 4390: 	fprintf(ficlog,"Total");
 4391: 	fprintf(ficresphtmfr,"<tr><th>Total</th> ");
 4392:       }else{
 4393: 	if(first==1){
 4394: 	  first=0;
 4395: 	  printf("See log file for details...\n");
 4396: 	}
 4397: 	fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
 4398: 	fprintf(ficlog,"Age %d", iage);
 4399:       }
 4400:       for(jk=1; jk <=nlstate ; jk++){
 4401: 	for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
 4402: 	  pp[jk] += freq[jk][m][iage]; 
 4403:       }
 4404:       for(jk=1; jk <=nlstate ; jk++){
 4405: 	for(m=-1, pos=0; m <=0 ; m++)
 4406: 	  pos += freq[jk][m][iage];
 4407: 	if(pp[jk]>=1.e-10){
 4408: 	  if(first==1){
 4409: 	    printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 4410: 	  }
 4411: 	  fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 4412: 	}else{
 4413: 	  if(first==1)
 4414: 	    printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 4415: 	  fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 4416: 	}
 4417:       }
 4418:       
 4419:       for(jk=1; jk <=nlstate ; jk++){ 
 4420: 	/* posprop[jk]=0; */
 4421: 	for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
 4422: 	  pp[jk] += freq[jk][m][iage];
 4423:       }	/* pp[jk] is the total number of transitions starting from state jk and any ending status until this age */
 4424:       
 4425:       for(jk=1,pos=0, pospropta=0.; jk <=nlstate ; jk++){
 4426: 	pos += pp[jk]; /* pos is the total number of transitions until this age */
 4427: 	posprop[jk] += prop[jk][iage]; /* prop is the number of transitions from a live state
 4428: 					  from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
 4429: 	pospropta += prop[jk][iage]; /* prop is the number of transitions from a live state
 4430: 					from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
 4431:       }
 4432:       for(jk=1; jk <=nlstate ; jk++){
 4433: 	if(pos>=1.e-5){
 4434: 	  if(first==1)
 4435: 	    printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 4436: 	  fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 4437: 	}else{
 4438: 	  if(first==1)
 4439: 	    printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 4440: 	  fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 4441: 	}
 4442: 	if( iage <= iagemax){
 4443: 	  if(pos>=1.e-5){
 4444: 	    fprintf(ficresp," %d %.5f %.0f %.0f",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
 4445: 	    fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
 4446: 	    /*probs[iage][jk][j1]= pp[jk]/pos;*/
 4447: 	    /*printf("\niage=%d jk=%d j1=%d %.5f %.0f %.0f %f",iage,jk,j1,pp[jk]/pos, pp[jk],pos,probs[iage][jk][j1]);*/
 4448: 	  }
 4449: 	  else{
 4450: 	    fprintf(ficresp," %d NaNq %.0f %.0f",iage,prop[jk][iage],pospropta);
 4451: 	    fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[jk][iage],pospropta);
 4452: 	  }
 4453: 	}
 4454: 	pospropt[jk] +=posprop[jk];
 4455:       } /* end loop jk */
 4456:       /* pospropt=0.; */
 4457:       for(jk=-1; jk <=nlstate+ndeath; jk++){
 4458: 	for(m=-1; m <=nlstate+ndeath; m++){
 4459: 	  if(freq[jk][m][iage] !=0 ) { /* minimizing output */
 4460: 	    if(first==1){
 4461: 	      printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]);
 4462: 	    }
 4463: 	    fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iage]);
 4464: 	  }
 4465: 	  if(jk!=0 && m!=0)
 4466: 	    fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][iage]);
 4467: 	}
 4468:       } /* end loop jk */
 4469:       posproptt=0.; 
 4470:       for(jk=1; jk <=nlstate; jk++){
 4471: 	posproptt += pospropt[jk];
 4472:       }
 4473:       fprintf(ficresphtmfr,"</tr>\n ");
 4474:       if(iage <= iagemax){
 4475: 	fprintf(ficresp,"\n");
 4476: 	fprintf(ficresphtm,"</tr>\n");
 4477:       }
 4478:       if(first==1)
 4479: 	printf("Others in log...\n");
 4480:       fprintf(ficlog,"\n");
 4481:     } /* end loop age iage */
 4482:     fprintf(ficresphtm,"<tr><th>Tot</th>");
 4483:     for(jk=1; jk <=nlstate ; jk++){
 4484:       if(posproptt < 1.e-5){
 4485: 	fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[jk],posproptt);	
 4486:       }else{
 4487: 	fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[jk]/posproptt,pospropt[jk],posproptt);	
 4488:       }
 4489:     }
 4490:     fprintf(ficresphtm,"</tr>\n");
 4491:     fprintf(ficresphtm,"</table>\n");
 4492:     fprintf(ficresphtmfr,"</table>\n");
 4493:     if(posproptt < 1.e-5){
 4494:       fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
 4495:       fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
 4496:       fprintf(ficres,"\n  This combination (%d) is not valid and no result will be produced\n\n",j1);
 4497:       invalidvarcomb[j1]=1;
 4498:     }else{
 4499:       fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
 4500:       invalidvarcomb[j1]=0;
 4501:     }
 4502:     fprintf(ficresphtmfr,"</table>\n");
 4503:   } /* end selected combination of covariate j1 */
 4504:   dateintmean=dateintsum/k2cpt; 
 4505:   
 4506:   fclose(ficresp);
 4507:   fclose(ficresphtm);
 4508:   fclose(ficresphtmfr);
 4509:   free_vector(meanq,1,nqfveff);
 4510:   free_matrix(meanqt,1,lastpass,1,nqtveff);
 4511:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);
 4512:   free_vector(pospropt,1,nlstate);
 4513:   free_vector(posprop,1,nlstate);
 4514:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);
 4515:   free_vector(pp,1,nlstate);
 4516:   /* End of freqsummary */
 4517: }
 4518: 
 4519: /************ Prevalence ********************/
 4520: 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)
 4521: {  
 4522:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 4523:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 4524:      We still use firstpass and lastpass as another selection.
 4525:   */
 4526:  
 4527:   int i, m, jk, j1, bool, z1,j, iv;
 4528:   int mi; /* Effective wave */
 4529:   int iage;
 4530:   double agebegin, ageend;
 4531: 
 4532:   double **prop;
 4533:   double posprop; 
 4534:   double  y2; /* in fractional years */
 4535:   int iagemin, iagemax;
 4536:   int first; /** to stop verbosity which is redirected to log file */
 4537: 
 4538:   iagemin= (int) agemin;
 4539:   iagemax= (int) agemax;
 4540:   /*pp=vector(1,nlstate);*/
 4541:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
 4542:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
 4543:   j1=0;
 4544:   
 4545:   /*j=cptcoveff;*/
 4546:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 4547:   
 4548:   first=1;
 4549:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
 4550:     for (i=1; i<=nlstate; i++)  
 4551:       for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)
 4552: 	prop[i][iage]=0.0;
 4553:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
 4554:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
 4555:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
 4556:     
 4557:     for (i=1; i<=imx; i++) { /* Each individual */
 4558:       bool=1;
 4559:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
 4560:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
 4561: 	m=mw[mi][i];
 4562: 	/* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
 4563: 	/* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
 4564: 	for (z1=1; z1<=cptcoveff; z1++){
 4565: 	  if( Fixed[Tmodelind[z1]]==1){
 4566: 	    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
 4567: 	    if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
 4568: 	      bool=0;
 4569: 	  }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
 4570: 	    if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
 4571: 	      bool=0;
 4572: 	    }
 4573: 	}
 4574: 	if(bool==1){ /* Otherwise we skip that wave/person */
 4575: 	  agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
 4576: 	  /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
 4577: 	  if(m >=firstpass && m <=lastpass){
 4578: 	    y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
 4579: 	    if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
 4580: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 4581: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 4582: 	      if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){
 4583: 		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); 
 4584: 		exit(1);
 4585: 	      }
 4586: 	      if (s[m][i]>0 && s[m][i]<=nlstate) { 
 4587: 		/*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]]);*/
 4588: 		prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
 4589: 		prop[s[m][i]][iagemax+3] += weight[i]; 
 4590: 	      } /* end valid statuses */ 
 4591: 	    } /* end selection of dates */
 4592: 	  } /* end selection of waves */
 4593: 	} /* end bool */
 4594:       } /* end wave */
 4595:     } /* end individual */
 4596:     for(i=iagemin; i <= iagemax+3; i++){  
 4597:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
 4598: 	posprop += prop[jk][i]; 
 4599:       } 
 4600:       
 4601:       for(jk=1; jk <=nlstate ; jk++){	    
 4602: 	if( i <=  iagemax){ 
 4603: 	  if(posprop>=1.e-5){ 
 4604: 	    probs[i][jk][j1]= prop[jk][i]/posprop;
 4605: 	  } else{
 4606: 	    if(first==1){
 4607: 	      first=0;
 4608: 	      printf("Warning Observed prevalence probs[%d][%d][%d]=%lf because of lack of cases\nSee others in log file...\n",jk,i,j1,probs[i][jk][j1]);
 4609: 	    }
 4610: 	  }
 4611: 	} 
 4612:       }/* end jk */ 
 4613:     }/* end i */ 
 4614:      /*} *//* end i1 */
 4615:   } /* end j1 */
 4616:   
 4617:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
 4618:   /*free_vector(pp,1,nlstate);*/
 4619:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);
 4620: }  /* End of prevalence */
 4621: 
 4622: /************* Waves Concatenation ***************/
 4623: 
 4624: 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)
 4625: {
 4626:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 4627:      Death is a valid wave (if date is known).
 4628:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
 4629:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 4630:      and mw[mi+1][i]. dh depends on stepm.
 4631:   */
 4632: 
 4633:   int i=0, mi=0, m=0, mli=0;
 4634:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
 4635:      double sum=0., jmean=0.;*/
 4636:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
 4637:   int j, k=0,jk, ju, jl;
 4638:   double sum=0.;
 4639:   first=0;
 4640:   firstwo=0;
 4641:   firsthree=0;
 4642:   firstfour=0;
 4643:   jmin=100000;
 4644:   jmax=-1;
 4645:   jmean=0.;
 4646: 
 4647: /* Treating live states */
 4648:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
 4649:     mi=0;  /* First valid wave */
 4650:     mli=0; /* Last valid wave */
 4651:     m=firstpass;
 4652:     while(s[m][i] <= nlstate){  /* a live state */
 4653:       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 */
 4654: 	mli=m-1;/* mw[++mi][i]=m-1; */
 4655:       }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 */
 4656: 	mw[++mi][i]=m;
 4657: 	mli=m;
 4658:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
 4659:       if(m < lastpass){ /* m < lastpass, standard case */
 4660: 	m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
 4661:       }
 4662:       else{ /* m >= lastpass, eventual special issue with warning */
 4663: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
 4664: 	break;
 4665: #else
 4666: 	if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
 4667: 	  if(firsthree == 0){
 4668: 	    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);
 4669: 	    firsthree=1;
 4670: 	  }
 4671: 	  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);
 4672: 	  mw[++mi][i]=m;
 4673: 	  mli=m;
 4674: 	}
 4675: 	if(s[m][i]==-2){ /* Vital status is really unknown */
 4676: 	  nbwarn++;
 4677: 	  if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
 4678: 	    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);
 4679: 	    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);
 4680: 	  }
 4681: 	  break;
 4682: 	}
 4683: 	break;
 4684: #endif
 4685:       }/* End m >= lastpass */
 4686:     }/* end while */
 4687: 
 4688:     /* mi is the last effective wave, m is lastpass, mw[j][i] gives the # of j-th effective wave for individual i */
 4689:     /* After last pass */
 4690: /* Treating death states */
 4691:     if (s[m][i] > nlstate){  /* In a death state */
 4692:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
 4693:       /* } */
 4694:       mi++;	/* Death is another wave */
 4695:       /* if(mi==0)  never been interviewed correctly before death */
 4696:       /* Only death is a correct wave */
 4697:       mw[mi][i]=m;
 4698:     }
 4699: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
 4700:     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 */
 4701:       /* m++; */
 4702:       /* mi++; */
 4703:       /* s[m][i]=nlstate+1;  /\* We are setting the status to the last of non live state *\/ */
 4704:       /* mw[mi][i]=m; */
 4705:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
 4706: 	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 */
 4707: 	  nbwarn++;
 4708: 	  if(firstfiv==0){
 4709: 	    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 );
 4710: 	    firstfiv=1;
 4711: 	  }else{
 4712: 	    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 );
 4713: 	  }
 4714: 	}else{ /* Death occured afer last wave potential bias */
 4715: 	  nberr++;
 4716: 	  if(firstwo==0){
 4717: 	    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 );
 4718: 	    firstwo=1;
 4719: 	  }
 4720: 	  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 );
 4721: 	}
 4722:       }else{ /* end date of interview is known */
 4723: 	/* death is known but not confirmed by death status at any wave */
 4724: 	if(firstfour==0){
 4725: 	  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 );
 4726: 	  firstfour=1;
 4727: 	}
 4728: 	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 );
 4729:       }
 4730:     } /* end if date of death is known */
 4731: #endif
 4732:     wav[i]=mi; /* mi should be the last effective wave (or mli) */
 4733:     /* wav[i]=mw[mi][i]; */
 4734:     if(mi==0){
 4735:       nbwarn++;
 4736:       if(first==0){
 4737: 	printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
 4738: 	first=1;
 4739:       }
 4740:       if(first==1){
 4741: 	fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
 4742:       }
 4743:     } /* end mi==0 */
 4744:   } /* End individuals */
 4745:   /* wav and mw are no more changed */
 4746: 	
 4747:   
 4748:   for(i=1; i<=imx; i++){
 4749:     for(mi=1; mi<wav[i];mi++){
 4750:       if (stepm <=0)
 4751: 	dh[mi][i]=1;
 4752:       else{
 4753: 	if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
 4754: 	  if (agedc[i] < 2*AGESUP) {
 4755: 	    j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
 4756: 	    if(j==0) j=1;  /* Survives at least one month after exam */
 4757: 	    else if(j<0){
 4758: 	      nberr++;
 4759: 	      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]);
 4760: 	      j=1; /* Temporary Dangerous patch */
 4761: 	      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);
 4762: 	      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]);
 4763: 	      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);
 4764: 	    }
 4765: 	    k=k+1;
 4766: 	    if (j >= jmax){
 4767: 	      jmax=j;
 4768: 	      ijmax=i;
 4769: 	    }
 4770: 	    if (j <= jmin){
 4771: 	      jmin=j;
 4772: 	      ijmin=i;
 4773: 	    }
 4774: 	    sum=sum+j;
 4775: 	    /*if (j<0) printf("j=%d num=%d \n",j,i);*/
 4776: 	    /*	  printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
 4777: 	  }
 4778: 	}
 4779: 	else{
 4780: 	  j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 4781: /* 	  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]); */
 4782: 					
 4783: 	  k=k+1;
 4784: 	  if (j >= jmax) {
 4785: 	    jmax=j;
 4786: 	    ijmax=i;
 4787: 	  }
 4788: 	  else if (j <= jmin){
 4789: 	    jmin=j;
 4790: 	    ijmin=i;
 4791: 	  }
 4792: 	  /*	    if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
 4793: 	  /*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]);*/
 4794: 	  if(j<0){
 4795: 	    nberr++;
 4796: 	    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]);
 4797: 	    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]);
 4798: 	  }
 4799: 	  sum=sum+j;
 4800: 	}
 4801: 	jk= j/stepm;
 4802: 	jl= j -jk*stepm;
 4803: 	ju= j -(jk+1)*stepm;
 4804: 	if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
 4805: 	  if(jl==0){
 4806: 	    dh[mi][i]=jk;
 4807: 	    bh[mi][i]=0;
 4808: 	  }else{ /* We want a negative bias in order to only have interpolation ie
 4809: 		  * to avoid the price of an extra matrix product in likelihood */
 4810: 	    dh[mi][i]=jk+1;
 4811: 	    bh[mi][i]=ju;
 4812: 	  }
 4813: 	}else{
 4814: 	  if(jl <= -ju){
 4815: 	    dh[mi][i]=jk;
 4816: 	    bh[mi][i]=jl;	/* bias is positive if real duration
 4817: 				 * is higher than the multiple of stepm and negative otherwise.
 4818: 				 */
 4819: 	  }
 4820: 	  else{
 4821: 	    dh[mi][i]=jk+1;
 4822: 	    bh[mi][i]=ju;
 4823: 	  }
 4824: 	  if(dh[mi][i]==0){
 4825: 	    dh[mi][i]=1; /* At least one step */
 4826: 	    bh[mi][i]=ju; /* At least one step */
 4827: 	    /*  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);*/
 4828: 	  }
 4829: 	} /* end if mle */
 4830:       }
 4831:     } /* end wave */
 4832:   }
 4833:   jmean=sum/k;
 4834:   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);
 4835:   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);
 4836: }
 4837: 
 4838: /*********** Tricode ****************************/
 4839:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
 4840:  {
 4841:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
 4842:    /*	  Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
 4843:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
 4844:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
 4845:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
 4846:     */
 4847: 
 4848:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
 4849:    int modmaxcovj=0; /* Modality max of covariates j */
 4850:    int cptcode=0; /* Modality max of covariates j */
 4851:    int modmincovj=0; /* Modality min of covariates j */
 4852: 
 4853: 
 4854:    /* cptcoveff=0;  */
 4855:    /* *cptcov=0; */
 4856:  
 4857:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
 4858: 
 4859:    /* Loop on covariates without age and products and no quantitative variable */
 4860:    /* for (j=1; j<=(cptcovs); j++) { /\* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only *\/ */
 4861:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
 4862:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
 4863:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
 4864:        switch(Fixed[k]) {
 4865:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
 4866: 	 for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the  modality of this covariate Vj*/
 4867: 	   ij=(int)(covar[Tvar[k]][i]);
 4868: 	   /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
 4869: 	    * If product of Vn*Vm, still boolean *:
 4870: 	    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
 4871: 	    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
 4872: 	   /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
 4873: 	      modality of the nth covariate of individual i. */
 4874: 	   if (ij > modmaxcovj)
 4875: 	     modmaxcovj=ij; 
 4876: 	   else if (ij < modmincovj) 
 4877: 	     modmincovj=ij; 
 4878: 	   if ((ij < -1) && (ij > NCOVMAX)){
 4879: 	     printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
 4880: 	     exit(1);
 4881: 	   }else
 4882: 	     Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
 4883: 	   /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
 4884: 	   /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
 4885: 	   /* getting the maximum value of the modality of the covariate
 4886: 	      (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
 4887: 	      female ies 1, then modmaxcovj=1.
 4888: 	   */
 4889: 	 } /* end for loop on individuals i */
 4890: 	 printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
 4891: 	 fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
 4892: 	 cptcode=modmaxcovj;
 4893: 	 /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
 4894: 	 /*for (i=0; i<=cptcode; i++) {*/
 4895: 	 for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
 4896: 	   printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
 4897: 	   fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
 4898: 	   if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
 4899: 	     if( j != -1){
 4900: 	       ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
 4901: 				  covariate for which somebody answered excluding 
 4902: 				  undefined. Usually 2: 0 and 1. */
 4903: 	     }
 4904: 	     ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
 4905: 				     covariate for which somebody answered including 
 4906: 				     undefined. Usually 3: -1, 0 and 1. */
 4907: 	   }	/* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
 4908: 		 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
 4909: 	 } /* Ndum[-1] number of undefined modalities */
 4910: 			
 4911: 	 /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
 4912: 	 /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
 4913: 	 /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
 4914: 	 /* modmincovj=3; modmaxcovj = 7; */
 4915: 	 /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
 4916: 	 /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
 4917: 	 /*		 defining two dummy variables: variables V1_1 and V1_2.*/
 4918: 	 /* nbcode[Tvar[j]][ij]=k; */
 4919: 	 /* nbcode[Tvar[j]][1]=0; */
 4920: 	 /* nbcode[Tvar[j]][2]=1; */
 4921: 	 /* nbcode[Tvar[j]][3]=2; */
 4922: 	 /* To be continued (not working yet). */
 4923: 	 ij=0; /* ij is similar to i but can jump over null modalities */
 4924: 	 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*/
 4925: 	   if (Ndum[i] == 0) { /* If nobody responded to this modality k */
 4926: 	     break;
 4927: 	   }
 4928: 	   ij++;
 4929: 	   nbcode[Tvar[k]][ij]=i;  /* stores the original value of modality i in an array nbcode, ij modality from 1 to last non-nul modality. nbcode[1][1]=0 nbcode[1][2]=1*/
 4930: 	   cptcode = ij; /* New max modality for covar j */
 4931: 	 } /* end of loop on modality i=-1 to 1 or more */
 4932: 	 break;
 4933:        case 1: /* Testing on varying covariate, could be simple and
 4934: 		* should look at waves or product of fixed *
 4935: 		* varying. No time to test -1, assuming 0 and 1 only */
 4936: 	 ij=0;
 4937: 	 for(i=0; i<=1;i++){
 4938: 	   nbcode[Tvar[k]][++ij]=i;
 4939: 	 }
 4940: 	 break;
 4941:        default:
 4942: 	 break;
 4943:        } /* end switch */
 4944:      } /* end dummy test */
 4945:     
 4946:      /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
 4947:      /* 	/\*recode from 0 *\/ */
 4948:      /* 				     k is a modality. If we have model=V1+V1*sex  */
 4949:      /* 				     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
 4950:      /* 				  But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
 4951:      /* 	} */
 4952:      /* 	/\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
 4953:      /* 	if (ij > ncodemax[j]) { */
 4954:      /* 	  printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
 4955:      /* 	  fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
 4956:      /* 	  break; */
 4957:      /* 	} */
 4958:      /*   }  /\* end of loop on modality k *\/ */
 4959:    } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
 4960:   
 4961:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
 4962:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
 4963:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
 4964:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
 4965:      ij=Tvar[i]; /* Tvar 5,4,3,6,5,7,1,4 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V4*age */ 
 4966:      Ndum[ij]++; /* Count the # of 1, 2 etc: {1,1,1,2,2,1,1} because V1 once, V2 once, two V4 and V5 in above */
 4967:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
 4968:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
 4969:   
 4970:    ij=0;
 4971:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
 4972:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
 4973:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
 4974:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
 4975:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
 4976:        /* If product not in single variable we don't print results */
 4977:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
 4978:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
 4979:        Tvaraff[ij]=Tvar[k]; /* For printing combination *//* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, Tvar {5, 4, 3, 6, 5, 2, 7, 1, 1} Tvaraff={4, 3, 1} V4, V3, V1*/
 4980:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
 4981:        TmodelInvind[ij]=Tvar[k]- ncovcol-nqv; /* Inverse TmodelInvind[2=V4]=2 second dummy varying cov (V4)4-1-1 {0, 2, 1, } TmodelInvind[3]=1 */
 4982:        if(Fixed[k]!=0)
 4983: 	 anyvaryingduminmodel=1;
 4984:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
 4985:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
 4986:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
 4987:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
 4988:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
 4989:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
 4990:      } 
 4991:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
 4992:    /* ij--; */
 4993:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
 4994:    *cptcov=ij; /*Number of total real effective covariates: effective
 4995: 		* because they can be excluded from the model and real
 4996: 		* if in the model but excluded because missing values, but how to get k from ij?*/
 4997:    for(j=ij+1; j<= cptcovt; j++){
 4998:      Tvaraff[j]=0;
 4999:      Tmodelind[j]=0;
 5000:    }
 5001:    for(j=ntveff+1; j<= cptcovt; j++){
 5002:      TmodelInvind[j]=0;
 5003:    }
 5004:    /* To be sorted */
 5005:    ;
 5006:  }
 5007: 
 5008: 
 5009: /*********** Health Expectancies ****************/
 5010: 
 5011:  void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[], int nres )
 5012: 
 5013: {
 5014:   /* Health expectancies, no variances */
 5015:   int i, j, nhstepm, hstepm, h, nstepm;
 5016:   int nhstepma, nstepma; /* Decreasing with age */
 5017:   double age, agelim, hf;
 5018:   double ***p3mat;
 5019:   double eip;
 5020: 
 5021:   /* pstamp(ficreseij); */
 5022:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
 5023:   fprintf(ficreseij,"# Age");
 5024:   for(i=1; i<=nlstate;i++){
 5025:     for(j=1; j<=nlstate;j++){
 5026:       fprintf(ficreseij," e%1d%1d ",i,j);
 5027:     }
 5028:     fprintf(ficreseij," e%1d. ",i);
 5029:   }
 5030:   fprintf(ficreseij,"\n");
 5031: 
 5032:   
 5033:   if(estepm < stepm){
 5034:     printf ("Problem %d lower than %d\n",estepm, stepm);
 5035:   }
 5036:   else  hstepm=estepm;   
 5037:   /* We compute the life expectancy from trapezoids spaced every estepm months
 5038:    * This is mainly to measure the difference between two models: for example
 5039:    * if stepm=24 months pijx are given only every 2 years and by summing them
 5040:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 5041:    * progression in between and thus overestimating or underestimating according
 5042:    * to the curvature of the survival function. If, for the same date, we 
 5043:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 5044:    * to compare the new estimate of Life expectancy with the same linear 
 5045:    * hypothesis. A more precise result, taking into account a more precise
 5046:    * curvature will be obtained if estepm is as small as stepm. */
 5047: 
 5048:   /* For example we decided to compute the life expectancy with the smallest unit */
 5049:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 5050:      nhstepm is the number of hstepm from age to agelim 
 5051:      nstepm is the number of stepm from age to agelin. 
 5052:      Look at hpijx to understand the reason of that which relies in memory size
 5053:      and note for a fixed period like estepm months */
 5054:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 5055:      survival function given by stepm (the optimization length). Unfortunately it
 5056:      means that if the survival funtion is printed only each two years of age and if
 5057:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 5058:      results. So we changed our mind and took the option of the best precision.
 5059:   */
 5060:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 5061: 
 5062:   agelim=AGESUP;
 5063:   /* If stepm=6 months */
 5064:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
 5065:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 5066:     
 5067: /* nhstepm age range expressed in number of stepm */
 5068:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 5069:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 5070:   /* if (stepm >= YEARM) hstepm=1;*/
 5071:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 5072:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5073: 
 5074:   for (age=bage; age<=fage; age ++){ 
 5075:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 5076:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 5077:     /* if (stepm >= YEARM) hstepm=1;*/
 5078:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 5079: 
 5080:     /* If stepm=6 months */
 5081:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 5082:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 5083:     
 5084:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
 5085:     
 5086:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 5087:     
 5088:     printf("%d|",(int)age);fflush(stdout);
 5089:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 5090:     
 5091:     /* Computing expectancies */
 5092:     for(i=1; i<=nlstate;i++)
 5093:       for(j=1; j<=nlstate;j++)
 5094: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 5095: 	  eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
 5096: 	  
 5097: 	  /* 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]);*/
 5098: 
 5099: 	}
 5100: 
 5101:     fprintf(ficreseij,"%3.0f",age );
 5102:     for(i=1; i<=nlstate;i++){
 5103:       eip=0;
 5104:       for(j=1; j<=nlstate;j++){
 5105: 	eip +=eij[i][j][(int)age];
 5106: 	fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
 5107:       }
 5108:       fprintf(ficreseij,"%9.4f", eip );
 5109:     }
 5110:     fprintf(ficreseij,"\n");
 5111:     
 5112:   }
 5113:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5114:   printf("\n");
 5115:   fprintf(ficlog,"\n");
 5116:   
 5117: }
 5118: 
 5119:  void cvevsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,double delti[],double **matcov,char strstart[], int nres )
 5120: 
 5121: {
 5122:   /* Covariances of health expectancies eij and of total life expectancies according
 5123:      to initial status i, ei. .
 5124:   */
 5125:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
 5126:   int nhstepma, nstepma; /* Decreasing with age */
 5127:   double age, agelim, hf;
 5128:   double ***p3matp, ***p3matm, ***varhe;
 5129:   double **dnewm,**doldm;
 5130:   double *xp, *xm;
 5131:   double **gp, **gm;
 5132:   double ***gradg, ***trgradg;
 5133:   int theta;
 5134: 
 5135:   double eip, vip;
 5136: 
 5137:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
 5138:   xp=vector(1,npar);
 5139:   xm=vector(1,npar);
 5140:   dnewm=matrix(1,nlstate*nlstate,1,npar);
 5141:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
 5142:   
 5143:   pstamp(ficresstdeij);
 5144:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
 5145:   fprintf(ficresstdeij,"# Age");
 5146:   for(i=1; i<=nlstate;i++){
 5147:     for(j=1; j<=nlstate;j++)
 5148:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
 5149:     fprintf(ficresstdeij," e%1d. ",i);
 5150:   }
 5151:   fprintf(ficresstdeij,"\n");
 5152: 
 5153:   pstamp(ficrescveij);
 5154:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
 5155:   fprintf(ficrescveij,"# Age");
 5156:   for(i=1; i<=nlstate;i++)
 5157:     for(j=1; j<=nlstate;j++){
 5158:       cptj= (j-1)*nlstate+i;
 5159:       for(i2=1; i2<=nlstate;i2++)
 5160: 	for(j2=1; j2<=nlstate;j2++){
 5161: 	  cptj2= (j2-1)*nlstate+i2;
 5162: 	  if(cptj2 <= cptj)
 5163: 	    fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
 5164: 	}
 5165:     }
 5166:   fprintf(ficrescveij,"\n");
 5167:   
 5168:   if(estepm < stepm){
 5169:     printf ("Problem %d lower than %d\n",estepm, stepm);
 5170:   }
 5171:   else  hstepm=estepm;   
 5172:   /* We compute the life expectancy from trapezoids spaced every estepm months
 5173:    * This is mainly to measure the difference between two models: for example
 5174:    * if stepm=24 months pijx are given only every 2 years and by summing them
 5175:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 5176:    * progression in between and thus overestimating or underestimating according
 5177:    * to the curvature of the survival function. If, for the same date, we 
 5178:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 5179:    * to compare the new estimate of Life expectancy with the same linear 
 5180:    * hypothesis. A more precise result, taking into account a more precise
 5181:    * curvature will be obtained if estepm is as small as stepm. */
 5182: 
 5183:   /* For example we decided to compute the life expectancy with the smallest unit */
 5184:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 5185:      nhstepm is the number of hstepm from age to agelim 
 5186:      nstepm is the number of stepm from age to agelin. 
 5187:      Look at hpijx to understand the reason of that which relies in memory size
 5188:      and note for a fixed period like estepm months */
 5189:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 5190:      survival function given by stepm (the optimization length). Unfortunately it
 5191:      means that if the survival funtion is printed only each two years of age and if
 5192:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 5193:      results. So we changed our mind and took the option of the best precision.
 5194:   */
 5195:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 5196: 
 5197:   /* If stepm=6 months */
 5198:   /* nhstepm age range expressed in number of stepm */
 5199:   agelim=AGESUP;
 5200:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
 5201:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 5202:   /* if (stepm >= YEARM) hstepm=1;*/
 5203:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 5204:   
 5205:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5206:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5207:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
 5208:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
 5209:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
 5210:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
 5211: 
 5212:   for (age=bage; age<=fage; age ++){ 
 5213:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 5214:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 5215:     /* if (stepm >= YEARM) hstepm=1;*/
 5216:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 5217: 		
 5218:     /* If stepm=6 months */
 5219:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 5220:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 5221:     
 5222:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 5223: 		
 5224:     /* Computing  Variances of health expectancies */
 5225:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
 5226:        decrease memory allocation */
 5227:     for(theta=1; theta <=npar; theta++){
 5228:       for(i=1; i<=npar; i++){ 
 5229: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 5230: 	xm[i] = x[i] - (i==theta ?delti[theta]:0);
 5231:       }
 5232:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
 5233:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
 5234: 			
 5235:       for(j=1; j<= nlstate; j++){
 5236: 	for(i=1; i<=nlstate; i++){
 5237: 	  for(h=0; h<=nhstepm-1; h++){
 5238: 	    gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
 5239: 	    gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
 5240: 	  }
 5241: 	}
 5242:       }
 5243: 			
 5244:       for(ij=1; ij<= nlstate*nlstate; ij++)
 5245: 	for(h=0; h<=nhstepm-1; h++){
 5246: 	  gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
 5247: 	}
 5248:     }/* End theta */
 5249:     
 5250:     
 5251:     for(h=0; h<=nhstepm-1; h++)
 5252:       for(j=1; j<=nlstate*nlstate;j++)
 5253: 	for(theta=1; theta <=npar; theta++)
 5254: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 5255:     
 5256: 		
 5257:     for(ij=1;ij<=nlstate*nlstate;ij++)
 5258:       for(ji=1;ji<=nlstate*nlstate;ji++)
 5259: 	varhe[ij][ji][(int)age] =0.;
 5260: 		
 5261:     printf("%d|",(int)age);fflush(stdout);
 5262:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 5263:     for(h=0;h<=nhstepm-1;h++){
 5264:       for(k=0;k<=nhstepm-1;k++){
 5265: 	matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
 5266: 	matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
 5267: 	for(ij=1;ij<=nlstate*nlstate;ij++)
 5268: 	  for(ji=1;ji<=nlstate*nlstate;ji++)
 5269: 	    varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
 5270:       }
 5271:     }
 5272: 		
 5273:     /* Computing expectancies */
 5274:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
 5275:     for(i=1; i<=nlstate;i++)
 5276:       for(j=1; j<=nlstate;j++)
 5277: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 5278: 	  eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
 5279: 					
 5280: 	  /* 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]);*/
 5281: 					
 5282: 	}
 5283: 		
 5284:     fprintf(ficresstdeij,"%3.0f",age );
 5285:     for(i=1; i<=nlstate;i++){
 5286:       eip=0.;
 5287:       vip=0.;
 5288:       for(j=1; j<=nlstate;j++){
 5289: 	eip += eij[i][j][(int)age];
 5290: 	for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
 5291: 	  vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
 5292: 	fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
 5293:       }
 5294:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
 5295:     }
 5296:     fprintf(ficresstdeij,"\n");
 5297: 		
 5298:     fprintf(ficrescveij,"%3.0f",age );
 5299:     for(i=1; i<=nlstate;i++)
 5300:       for(j=1; j<=nlstate;j++){
 5301: 	cptj= (j-1)*nlstate+i;
 5302: 	for(i2=1; i2<=nlstate;i2++)
 5303: 	  for(j2=1; j2<=nlstate;j2++){
 5304: 	    cptj2= (j2-1)*nlstate+i2;
 5305: 	    if(cptj2 <= cptj)
 5306: 	      fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
 5307: 	  }
 5308:       }
 5309:     fprintf(ficrescveij,"\n");
 5310: 		
 5311:   }
 5312:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
 5313:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
 5314:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
 5315:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
 5316:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5317:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5318:   printf("\n");
 5319:   fprintf(ficlog,"\n");
 5320: 	
 5321:   free_vector(xm,1,npar);
 5322:   free_vector(xp,1,npar);
 5323:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
 5324:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
 5325:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
 5326: }
 5327:  
 5328: /************ Variance ******************/
 5329:  void varevsij(char optionfilefiname[], double ***vareij, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int *ncvyearp, int ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[], int nres)
 5330:  {
 5331:    /* Variance of health expectancies */
 5332:    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
 5333:    /* double **newm;*/
 5334:    /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
 5335:   
 5336:    /* int movingaverage(); */
 5337:    double **dnewm,**doldm;
 5338:    double **dnewmp,**doldmp;
 5339:    int i, j, nhstepm, hstepm, h, nstepm ;
 5340:    int k;
 5341:    double *xp;
 5342:    double **gp, **gm;  /* for var eij */
 5343:    double ***gradg, ***trgradg; /*for var eij */
 5344:    double **gradgp, **trgradgp; /* for var p point j */
 5345:    double *gpp, *gmp; /* for var p point j */
 5346:    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
 5347:    double ***p3mat;
 5348:    double age,agelim, hf;
 5349:    /* double ***mobaverage; */
 5350:    int theta;
 5351:    char digit[4];
 5352:    char digitp[25];
 5353: 
 5354:    char fileresprobmorprev[FILENAMELENGTH];
 5355: 
 5356:    if(popbased==1){
 5357:      if(mobilav!=0)
 5358:        strcpy(digitp,"-POPULBASED-MOBILAV_");
 5359:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
 5360:    }
 5361:    else 
 5362:      strcpy(digitp,"-STABLBASED_");
 5363: 
 5364:    /* if (mobilav!=0) { */
 5365:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 5366:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
 5367:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
 5368:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
 5369:    /*   } */
 5370:    /* } */
 5371: 
 5372:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
 5373:    sprintf(digit,"%-d",ij);
 5374:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
 5375:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
 5376:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
 5377:    strcat(fileresprobmorprev,fileresu);
 5378:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
 5379:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
 5380:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
 5381:    }
 5382:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 5383:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 5384:    pstamp(ficresprobmorprev);
 5385:    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);
 5386:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
 5387:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
 5388:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
 5389:    }
 5390:    for(j=1;j<=cptcoveff;j++) 
 5391:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,j)]);
 5392:    fprintf(ficresprobmorprev,"\n");
 5393: 
 5394:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
 5395:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 5396:      fprintf(ficresprobmorprev," p.%-d SE",j);
 5397:      for(i=1; i<=nlstate;i++)
 5398:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 5399:    }  
 5400:    fprintf(ficresprobmorprev,"\n");
 5401:   
 5402:    fprintf(ficgp,"\n# Routine varevsij");
 5403:    fprintf(ficgp,"\nunset title \n");
 5404:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
 5405:    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");
 5406:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
 5407:    /*   } */
 5408:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 5409:    pstamp(ficresvij);
 5410:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
 5411:    if(popbased==1)
 5412:      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);
 5413:    else
 5414:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
 5415:    fprintf(ficresvij,"# Age");
 5416:    for(i=1; i<=nlstate;i++)
 5417:      for(j=1; j<=nlstate;j++)
 5418:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
 5419:    fprintf(ficresvij,"\n");
 5420: 
 5421:    xp=vector(1,npar);
 5422:    dnewm=matrix(1,nlstate,1,npar);
 5423:    doldm=matrix(1,nlstate,1,nlstate);
 5424:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
 5425:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 5426: 
 5427:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
 5428:    gpp=vector(nlstate+1,nlstate+ndeath);
 5429:    gmp=vector(nlstate+1,nlstate+ndeath);
 5430:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 5431:   
 5432:    if(estepm < stepm){
 5433:      printf ("Problem %d lower than %d\n",estepm, stepm);
 5434:    }
 5435:    else  hstepm=estepm;   
 5436:    /* For example we decided to compute the life expectancy with the smallest unit */
 5437:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 5438:       nhstepm is the number of hstepm from age to agelim 
 5439:       nstepm is the number of stepm from age to agelim. 
 5440:       Look at function hpijx to understand why because of memory size limitations, 
 5441:       we decided (b) to get a life expectancy respecting the most precise curvature of the
 5442:       survival function given by stepm (the optimization length). Unfortunately it
 5443:       means that if the survival funtion is printed every two years of age and if
 5444:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 5445:       results. So we changed our mind and took the option of the best precision.
 5446:    */
 5447:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 5448:    agelim = AGESUP;
 5449:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 5450:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 5451:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 5452:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5453:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
 5454:      gp=matrix(0,nhstepm,1,nlstate);
 5455:      gm=matrix(0,nhstepm,1,nlstate);
 5456: 		
 5457: 		
 5458:      for(theta=1; theta <=npar; theta++){
 5459:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
 5460: 	 xp[i] = x[i] + (i==theta ?delti[theta]:0);
 5461:        }
 5462: 			
 5463:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
 5464: 			
 5465:        if (popbased==1) {
 5466: 	 if(mobilav ==0){
 5467: 	   for(i=1; i<=nlstate;i++)
 5468: 	     prlim[i][i]=probs[(int)age][i][ij];
 5469: 	 }else{ /* mobilav */ 
 5470: 	   for(i=1; i<=nlstate;i++)
 5471: 	     prlim[i][i]=mobaverage[(int)age][i][ij];
 5472: 	 }
 5473:        }
 5474: 			
 5475:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
 5476:        for(j=1; j<= nlstate; j++){
 5477: 	 for(h=0; h<=nhstepm; h++){
 5478: 	   for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 5479: 	     gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 5480: 	 }
 5481:        }
 5482:        /* Next for computing probability of death (h=1 means
 5483: 	  computed over hstepm matrices product = hstepm*stepm months) 
 5484: 	  as a weighted average of prlim.
 5485:        */
 5486:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
 5487: 	 for(i=1,gpp[j]=0.; i<= nlstate; i++)
 5488: 	   gpp[j] += prlim[i][i]*p3mat[i][j][1];
 5489:        }    
 5490:        /* end probability of death */
 5491: 			
 5492:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
 5493: 	 xp[i] = x[i] - (i==theta ?delti[theta]:0);
 5494: 			
 5495:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
 5496: 			
 5497:        if (popbased==1) {
 5498: 	 if(mobilav ==0){
 5499: 	   for(i=1; i<=nlstate;i++)
 5500: 	     prlim[i][i]=probs[(int)age][i][ij];
 5501: 	 }else{ /* mobilav */ 
 5502: 	   for(i=1; i<=nlstate;i++)
 5503: 	     prlim[i][i]=mobaverage[(int)age][i][ij];
 5504: 	 }
 5505:        }
 5506: 			
 5507:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
 5508: 			
 5509:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
 5510: 	 for(h=0; h<=nhstepm; h++){
 5511: 	   for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 5512: 	     gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 5513: 	 }
 5514:        }
 5515:        /* This for computing probability of death (h=1 means
 5516: 	  computed over hstepm matrices product = hstepm*stepm months) 
 5517: 	  as a weighted average of prlim.
 5518:        */
 5519:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
 5520: 	 for(i=1,gmp[j]=0.; i<= nlstate; i++)
 5521: 	   gmp[j] += prlim[i][i]*p3mat[i][j][1];
 5522:        }    
 5523:        /* end probability of death */
 5524: 			
 5525:        for(j=1; j<= nlstate; j++) /* vareij */
 5526: 	 for(h=0; h<=nhstepm; h++){
 5527: 	   gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 5528: 	 }
 5529: 			
 5530:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
 5531: 	 gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
 5532:        }
 5533: 			
 5534:      } /* End theta */
 5535: 		
 5536:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
 5537: 		
 5538:      for(h=0; h<=nhstepm; h++) /* veij */
 5539:        for(j=1; j<=nlstate;j++)
 5540: 	 for(theta=1; theta <=npar; theta++)
 5541: 	   trgradg[h][j][theta]=gradg[h][theta][j];
 5542: 		
 5543:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
 5544:        for(theta=1; theta <=npar; theta++)
 5545: 	 trgradgp[j][theta]=gradgp[theta][j];
 5546: 		
 5547: 		
 5548:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 5549:      for(i=1;i<=nlstate;i++)
 5550:        for(j=1;j<=nlstate;j++)
 5551: 	 vareij[i][j][(int)age] =0.;
 5552: 		
 5553:      for(h=0;h<=nhstepm;h++){
 5554:        for(k=0;k<=nhstepm;k++){
 5555: 	 matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 5556: 	 matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
 5557: 	 for(i=1;i<=nlstate;i++)
 5558: 	   for(j=1;j<=nlstate;j++)
 5559: 	     vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
 5560:        }
 5561:      }
 5562: 		
 5563:      /* pptj */
 5564:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
 5565:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
 5566:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
 5567:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
 5568: 	 varppt[j][i]=doldmp[j][i];
 5569:      /* end ppptj */
 5570:      /*  x centered again */
 5571: 		
 5572:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
 5573: 		
 5574:      if (popbased==1) {
 5575:        if(mobilav ==0){
 5576: 	 for(i=1; i<=nlstate;i++)
 5577: 	   prlim[i][i]=probs[(int)age][i][ij];
 5578:        }else{ /* mobilav */ 
 5579: 	 for(i=1; i<=nlstate;i++)
 5580: 	   prlim[i][i]=mobaverage[(int)age][i][ij];
 5581:        }
 5582:      }
 5583: 		
 5584:      /* This for computing probability of death (h=1 means
 5585: 	computed over hstepm (estepm) matrices product = hstepm*stepm months) 
 5586: 	as a weighted average of prlim.
 5587:      */
 5588:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
 5589:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
 5590:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
 5591: 	 gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
 5592:      }    
 5593:      /* end probability of death */
 5594: 		
 5595:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
 5596:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 5597:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
 5598:        for(i=1; i<=nlstate;i++){
 5599: 	 fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 5600:        }
 5601:      } 
 5602:      fprintf(ficresprobmorprev,"\n");
 5603: 		
 5604:      fprintf(ficresvij,"%.0f ",age );
 5605:      for(i=1; i<=nlstate;i++)
 5606:        for(j=1; j<=nlstate;j++){
 5607: 	 fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
 5608:        }
 5609:      fprintf(ficresvij,"\n");
 5610:      free_matrix(gp,0,nhstepm,1,nlstate);
 5611:      free_matrix(gm,0,nhstepm,1,nlstate);
 5612:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 5613:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 5614:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5615:    } /* End age */
 5616:    free_vector(gpp,nlstate+1,nlstate+ndeath);
 5617:    free_vector(gmp,nlstate+1,nlstate+ndeath);
 5618:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
 5619:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 5620:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
 5621:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
 5622:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
 5623:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
 5624:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
 5625:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
 5626:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
 5627:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
 5628:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
 5629:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
 5630:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
 5631:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
 5632:    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);
 5633:    /*  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);
 5634:     */
 5635:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
 5636:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
 5637: 
 5638:    free_vector(xp,1,npar);
 5639:    free_matrix(doldm,1,nlstate,1,nlstate);
 5640:    free_matrix(dnewm,1,nlstate,1,npar);
 5641:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 5642:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
 5643:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 5644:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 5645:    fclose(ficresprobmorprev);
 5646:    fflush(ficgp);
 5647:    fflush(fichtm); 
 5648:  }  /* end varevsij */
 5649: 
 5650: /************ Variance of prevlim ******************/
 5651:  void varprevlim(char fileres[], double **varpl, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int *ncvyearp, int ij, char strstart[], int nres)
 5652: {
 5653:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
 5654:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 5655: 
 5656:   double **dnewm,**doldm;
 5657:   int i, j, nhstepm, hstepm;
 5658:   double *xp;
 5659:   double *gp, *gm;
 5660:   double **gradg, **trgradg;
 5661:   double **mgm, **mgp;
 5662:   double age,agelim;
 5663:   int theta;
 5664:   
 5665:   pstamp(ficresvpl);
 5666:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
 5667:   fprintf(ficresvpl,"# Age ");
 5668:   if(nresult >=1)
 5669:     fprintf(ficresvpl," Result# ");
 5670:   for(i=1; i<=nlstate;i++)
 5671:       fprintf(ficresvpl," %1d-%1d",i,i);
 5672:   fprintf(ficresvpl,"\n");
 5673: 
 5674:   xp=vector(1,npar);
 5675:   dnewm=matrix(1,nlstate,1,npar);
 5676:   doldm=matrix(1,nlstate,1,nlstate);
 5677:   
 5678:   hstepm=1*YEARM; /* Every year of age */
 5679:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 5680:   agelim = AGESUP;
 5681:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 5682:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 5683:     if (stepm >= YEARM) hstepm=1;
 5684:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 5685:     gradg=matrix(1,npar,1,nlstate);
 5686:     mgp=matrix(1,npar,1,nlstate);
 5687:     mgm=matrix(1,npar,1,nlstate);
 5688:     gp=vector(1,nlstate);
 5689:     gm=vector(1,nlstate);
 5690: 
 5691:     for(theta=1; theta <=npar; theta++){
 5692:       for(i=1; i<=npar; i++){ /* Computes gradient */
 5693: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 5694:       }
 5695:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
 5696: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
 5697:       else
 5698: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
 5699:       for(i=1;i<=nlstate;i++){
 5700: 	gp[i] = prlim[i][i];
 5701: 	mgp[theta][i] = prlim[i][i];
 5702:       }
 5703:       for(i=1; i<=npar; i++) /* Computes gradient */
 5704: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 5705:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
 5706: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
 5707:       else
 5708: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
 5709:       for(i=1;i<=nlstate;i++){
 5710: 	gm[i] = prlim[i][i];
 5711: 	mgm[theta][i] = prlim[i][i];
 5712:       }
 5713:       for(i=1;i<=nlstate;i++)
 5714: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 5715:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
 5716:     } /* End theta */
 5717: 
 5718:     trgradg =matrix(1,nlstate,1,npar);
 5719: 
 5720:     for(j=1; j<=nlstate;j++)
 5721:       for(theta=1; theta <=npar; theta++)
 5722: 	trgradg[j][theta]=gradg[theta][j];
 5723:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
 5724:     /*   printf("\nmgm mgp %d ",(int)age); */
 5725:     /*   for(j=1; j<=nlstate;j++){ */
 5726:     /* 	printf(" %d ",j); */
 5727:     /* 	for(theta=1; theta <=npar; theta++) */
 5728:     /* 	  printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
 5729:     /* 	printf("\n "); */
 5730:     /*   } */
 5731:     /* } */
 5732:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
 5733:     /*   printf("\n gradg %d ",(int)age); */
 5734:     /*   for(j=1; j<=nlstate;j++){ */
 5735:     /* 	printf("%d ",j); */
 5736:     /* 	for(theta=1; theta <=npar; theta++) */
 5737:     /* 	  printf("%d %lf ",theta,gradg[theta][j]); */
 5738:     /* 	printf("\n "); */
 5739:     /*   } */
 5740:     /* } */
 5741: 
 5742:     for(i=1;i<=nlstate;i++)
 5743:       varpl[i][(int)age] =0.;
 5744:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
 5745:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 5746:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 5747:     }else{
 5748:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 5749:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 5750:     }
 5751:     for(i=1;i<=nlstate;i++)
 5752:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 5753: 
 5754:     fprintf(ficresvpl,"%.0f ",age );
 5755:     if(nresult >=1)
 5756:       fprintf(ficresvpl,"%d ",nres );
 5757:     for(i=1; i<=nlstate;i++)
 5758:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
 5759:     fprintf(ficresvpl,"\n");
 5760:     free_vector(gp,1,nlstate);
 5761:     free_vector(gm,1,nlstate);
 5762:     free_matrix(mgm,1,npar,1,nlstate);
 5763:     free_matrix(mgp,1,npar,1,nlstate);
 5764:     free_matrix(gradg,1,npar,1,nlstate);
 5765:     free_matrix(trgradg,1,nlstate,1,npar);
 5766:   } /* End age */
 5767: 
 5768:   free_vector(xp,1,npar);
 5769:   free_matrix(doldm,1,nlstate,1,npar);
 5770:   free_matrix(dnewm,1,nlstate,1,nlstate);
 5771: 
 5772: }
 5773: 
 5774: /************ Variance of one-step probabilities  ******************/
 5775: 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[])
 5776:  {
 5777:    int i, j=0,  k1, l1, tj;
 5778:    int k2, l2, j1,  z1;
 5779:    int k=0, l;
 5780:    int first=1, first1, first2;
 5781:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
 5782:    double **dnewm,**doldm;
 5783:    double *xp;
 5784:    double *gp, *gm;
 5785:    double **gradg, **trgradg;
 5786:    double **mu;
 5787:    double age, cov[NCOVMAX+1];
 5788:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
 5789:    int theta;
 5790:    char fileresprob[FILENAMELENGTH];
 5791:    char fileresprobcov[FILENAMELENGTH];
 5792:    char fileresprobcor[FILENAMELENGTH];
 5793:    double ***varpij;
 5794: 
 5795:    strcpy(fileresprob,"PROB_"); 
 5796:    strcat(fileresprob,fileres);
 5797:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
 5798:      printf("Problem with resultfile: %s\n", fileresprob);
 5799:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
 5800:    }
 5801:    strcpy(fileresprobcov,"PROBCOV_"); 
 5802:    strcat(fileresprobcov,fileresu);
 5803:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
 5804:      printf("Problem with resultfile: %s\n", fileresprobcov);
 5805:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 5806:    }
 5807:    strcpy(fileresprobcor,"PROBCOR_"); 
 5808:    strcat(fileresprobcor,fileresu);
 5809:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 5810:      printf("Problem with resultfile: %s\n", fileresprobcor);
 5811:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 5812:    }
 5813:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 5814:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 5815:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 5816:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 5817:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 5818:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 5819:    pstamp(ficresprob);
 5820:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
 5821:    fprintf(ficresprob,"# Age");
 5822:    pstamp(ficresprobcov);
 5823:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
 5824:    fprintf(ficresprobcov,"# Age");
 5825:    pstamp(ficresprobcor);
 5826:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 5827:    fprintf(ficresprobcor,"# Age");
 5828: 
 5829: 
 5830:    for(i=1; i<=nlstate;i++)
 5831:      for(j=1; j<=(nlstate+ndeath);j++){
 5832:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
 5833:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
 5834:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
 5835:      }  
 5836:    /* fprintf(ficresprob,"\n");
 5837:       fprintf(ficresprobcov,"\n");
 5838:       fprintf(ficresprobcor,"\n");
 5839:    */
 5840:    xp=vector(1,npar);
 5841:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 5842:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 5843:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
 5844:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 5845:    first=1;
 5846:    fprintf(ficgp,"\n# Routine varprob");
 5847:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
 5848:    fprintf(fichtm,"\n");
 5849: 
 5850:    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);
 5851:    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);
 5852:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
 5853: and drawn. It helps understanding how is the covariance between two incidences.\
 5854:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
 5855:    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. \
 5856: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
 5857: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
 5858: standard deviations wide on each axis. <br>\
 5859:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
 5860:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 5861: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
 5862: 
 5863:    cov[1]=1;
 5864:    /* tj=cptcoveff; */
 5865:    tj = (int) pow(2,cptcoveff);
 5866:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
 5867:    j1=0;
 5868:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
 5869:      if  (cptcovn>0) {
 5870:        fprintf(ficresprob, "\n#********** Variable "); 
 5871:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5872:        fprintf(ficresprob, "**********\n#\n");
 5873:        fprintf(ficresprobcov, "\n#********** Variable "); 
 5874:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5875:        fprintf(ficresprobcov, "**********\n#\n");
 5876: 			
 5877:        fprintf(ficgp, "\n#********** Variable "); 
 5878:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5879:        fprintf(ficgp, "**********\n#\n");
 5880: 			
 5881: 			
 5882:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
 5883:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5884:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
 5885: 			
 5886:        fprintf(ficresprobcor, "\n#********** Variable ");    
 5887:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5888:        fprintf(ficresprobcor, "**********\n#");    
 5889:        if(invalidvarcomb[j1]){
 5890: 	 fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
 5891: 	 fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
 5892: 	 continue;
 5893:        }
 5894:      }
 5895:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
 5896:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 5897:      gp=vector(1,(nlstate)*(nlstate+ndeath));
 5898:      gm=vector(1,(nlstate)*(nlstate+ndeath));
 5899:      for (age=bage; age<=fage; age ++){ 
 5900:        cov[2]=age;
 5901:        if(nagesqr==1)
 5902: 	 cov[3]= age*age;
 5903:        for (k=1; k<=cptcovn;k++) {
 5904: 	 cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
 5905: 	 /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
 5906: 								    * 1  1 1 1 1
 5907: 								    * 2  2 1 1 1
 5908: 								    * 3  1 2 1 1
 5909: 								    */
 5910: 	 /* nbcode[1][1]=0 nbcode[1][2]=1;*/
 5911:        }
 5912:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 5913:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 5914:        for (k=1; k<=cptcovprod;k++)
 5915: 	 cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
 5916: 			
 5917: 			
 5918:        for(theta=1; theta <=npar; theta++){
 5919: 	 for(i=1; i<=npar; i++)
 5920: 	   xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
 5921: 				
 5922: 	 pmij(pmmij,cov,ncovmodel,xp,nlstate);
 5923: 				
 5924: 	 k=0;
 5925: 	 for(i=1; i<= (nlstate); i++){
 5926: 	   for(j=1; j<=(nlstate+ndeath);j++){
 5927: 	     k=k+1;
 5928: 	     gp[k]=pmmij[i][j];
 5929: 	   }
 5930: 	 }
 5931: 				
 5932: 	 for(i=1; i<=npar; i++)
 5933: 	   xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
 5934: 				
 5935: 	 pmij(pmmij,cov,ncovmodel,xp,nlstate);
 5936: 	 k=0;
 5937: 	 for(i=1; i<=(nlstate); i++){
 5938: 	   for(j=1; j<=(nlstate+ndeath);j++){
 5939: 	     k=k+1;
 5940: 	     gm[k]=pmmij[i][j];
 5941: 	   }
 5942: 	 }
 5943: 				
 5944: 	 for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
 5945: 	   gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
 5946:        }
 5947: 
 5948:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
 5949: 	 for(theta=1; theta <=npar; theta++)
 5950: 	   trgradg[j][theta]=gradg[theta][j];
 5951: 			
 5952:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
 5953:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
 5954: 			
 5955:        pmij(pmmij,cov,ncovmodel,x,nlstate);
 5956: 			
 5957:        k=0;
 5958:        for(i=1; i<=(nlstate); i++){
 5959: 	 for(j=1; j<=(nlstate+ndeath);j++){
 5960: 	   k=k+1;
 5961: 	   mu[k][(int) age]=pmmij[i][j];
 5962: 	 }
 5963:        }
 5964:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 5965: 	 for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 5966: 	   varpij[i][j][(int)age] = doldm[i][j];
 5967: 			
 5968:        /*printf("\n%d ",(int)age);
 5969: 	 for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 5970: 	 printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 5971: 	 fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 5972: 	 }*/
 5973: 			
 5974:        fprintf(ficresprob,"\n%d ",(int)age);
 5975:        fprintf(ficresprobcov,"\n%d ",(int)age);
 5976:        fprintf(ficresprobcor,"\n%d ",(int)age);
 5977: 			
 5978:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
 5979: 	 fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
 5980:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 5981: 	 fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
 5982: 	 fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
 5983:        }
 5984:        i=0;
 5985:        for (k=1; k<=(nlstate);k++){
 5986: 	 for (l=1; l<=(nlstate+ndeath);l++){ 
 5987: 	   i++;
 5988: 	   fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 5989: 	   fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
 5990: 	   for (j=1; j<=i;j++){
 5991: 	     /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
 5992: 	     fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
 5993: 	     fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
 5994: 	   }
 5995: 	 }
 5996:        }/* end of loop for state */
 5997:      } /* end of loop for age */
 5998:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
 5999:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 6000:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 6001:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 6002:     
 6003:      /* Confidence intervalle of pij  */
 6004:      /*
 6005:        fprintf(ficgp,"\nunset parametric;unset label");
 6006:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
 6007:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 6008:        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);
 6009:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
 6010:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
 6011:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
 6012:      */
 6013: 		
 6014:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
 6015:      first1=1;first2=2;
 6016:      for (k2=1; k2<=(nlstate);k2++){
 6017:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
 6018: 	 if(l2==k2) continue;
 6019: 	 j=(k2-1)*(nlstate+ndeath)+l2;
 6020: 	 for (k1=1; k1<=(nlstate);k1++){
 6021: 	   for (l1=1; l1<=(nlstate+ndeath);l1++){ 
 6022: 	     if(l1==k1) continue;
 6023: 	     i=(k1-1)*(nlstate+ndeath)+l1;
 6024: 	     if(i<=j) continue;
 6025: 	     for (age=bage; age<=fage; age ++){ 
 6026: 	       if ((int)age %5==0){
 6027: 		 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
 6028: 		 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
 6029: 		 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
 6030: 		 mu1=mu[i][(int) age]/stepm*YEARM ;
 6031: 		 mu2=mu[j][(int) age]/stepm*YEARM;
 6032: 		 c12=cv12/sqrt(v1*v2);
 6033: 		 /* Computing eigen value of matrix of covariance */
 6034: 		 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 6035: 		 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 6036: 		 if ((lc2 <0) || (lc1 <0) ){
 6037: 		   if(first2==1){
 6038: 		     first1=0;
 6039: 		     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);
 6040: 		   }
 6041: 		   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);
 6042: 		   /* lc1=fabs(lc1); */ /* If we want to have them positive */
 6043: 		   /* lc2=fabs(lc2); */
 6044: 		 }
 6045: 								
 6046: 		 /* Eigen vectors */
 6047: 		 v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
 6048: 		 /*v21=sqrt(1.-v11*v11); *//* error */
 6049: 		 v21=(lc1-v1)/cv12*v11;
 6050: 		 v12=-v21;
 6051: 		 v22=v11;
 6052: 		 tnalp=v21/v11;
 6053: 		 if(first1==1){
 6054: 		   first1=0;
 6055: 		   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);
 6056: 		 }
 6057: 		 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);
 6058: 		 /*printf(fignu*/
 6059: 		 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
 6060: 		 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
 6061: 		 if(first==1){
 6062: 		   first=0;
 6063: 		   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
 6064: 		   fprintf(ficgp,"\nset parametric;unset label");
 6065: 		   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);
 6066: 		   fprintf(ficgp,"\nset ter svg size 640, 480");
 6067: 		   fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
 6068:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">																		\
 6069: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
 6070: 			   subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,	\
 6071: 			   subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 6072: 		   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 6073: 		   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
 6074: 		   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 6075: 		   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 6076: 		   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 6077: 		   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",	\
 6078: 			   mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),										\
 6079: 			   mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 6080: 		 }else{
 6081: 		   first=0;
 6082: 		   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
 6083: 		   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 6084: 		   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 6085: 		   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", \
 6086: 			   mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),					\
 6087: 			   mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 6088: 		 }/* if first */
 6089: 	       } /* age mod 5 */
 6090: 	     } /* end loop age */
 6091: 	     fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 6092: 	     first=1;
 6093: 	   } /*l12 */
 6094: 	 } /* k12 */
 6095:        } /*l1 */
 6096:      }/* k1 */
 6097:    }  /* loop on combination of covariates j1 */
 6098:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 6099:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
 6100:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 6101:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
 6102:    free_vector(xp,1,npar);
 6103:    fclose(ficresprob);
 6104:    fclose(ficresprobcov);
 6105:    fclose(ficresprobcor);
 6106:    fflush(ficgp);
 6107:    fflush(fichtmcov);
 6108:  }
 6109: 
 6110: 
 6111: /******************* Printing html file ***********/
 6112: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
 6113: 		  int lastpass, int stepm, int weightopt, char model[],\
 6114: 		  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 6115: 		  int popforecast, int prevfcast, int backcast, int estepm , \
 6116: 		  double jprev1, double mprev1,double anprev1, double dateprev1, \
 6117: 		  double jprev2, double mprev2,double anprev2, double dateprev2){
 6118:   int jj1, k1, i1, cpt, k4, nres;
 6119: 
 6120:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
 6121:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
 6122: </ul>");
 6123:    fprintf(fichtm,"<ul><li> model=1+age+%s\n \
 6124: </ul>", model);
 6125:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
 6126:    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",
 6127: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
 6128:    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) ",
 6129: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
 6130:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
 6131:    fprintf(fichtm,"\
 6132:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 6133: 	   stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
 6134:    fprintf(fichtm,"\
 6135:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 6136: 	   stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
 6137:    fprintf(fichtm,"\
 6138:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 6139: 	   subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
 6140:    fprintf(fichtm,"\
 6141:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 6142: 	   subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
 6143:    fprintf(fichtm,"\
 6144:  - (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): \
 6145:    <a href=\"%s\">%s</a> <br>\n",
 6146: 	   estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
 6147:    if(prevfcast==1){
 6148:      fprintf(fichtm,"\
 6149:  - Prevalence projections by age and states:				\
 6150:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
 6151:    }
 6152: 
 6153:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
 6154: 
 6155:    m=pow(2,cptcoveff);
 6156:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 6157: 
 6158:    jj1=0;
 6159: 
 6160:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
 6161:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
 6162:      if(TKresult[nres]!= k1)
 6163:        continue;
 6164: 
 6165:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
 6166:      jj1++;
 6167:      if (cptcovn > 0) {
 6168:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 6169:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
 6170: 	 fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
 6171: 	 printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
 6172: 	 /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
 6173: 	 /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
 6174:        }
 6175:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 6176: 	fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6177: 	printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
 6178:       }
 6179:        
 6180:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
 6181:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 6182:        if(invalidvarcomb[k1]){
 6183: 	 fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
 6184: 	 printf("\nCombination (%d) ignored because no cases \n",k1); 
 6185: 	 continue;
 6186:        }
 6187:      }
 6188:      /* aij, bij */
 6189:      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-%d.svg\">%s_%d-1-%d.svg</a><br> \
 6190: <img src=\"%s_%d-1-%d.svg\">",model,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres);
 6191:      /* Pij */
 6192:      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-%d.svg\">%s_%d-2-%d.svg</a><br> \
 6193: <img src=\"%s_%d-2-%d.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres);     
 6194:      /* Quasi-incidences */
 6195:      fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
 6196:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
 6197:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
 6198: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3-%d.svg\">%s_%d-3-%d.svg</a><br> \
 6199: <img src=\"%s_%d-3-%d.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres); 
 6200:      /* Survival functions (period) in state j */
 6201:      for(cpt=1; cpt<=nlstate;cpt++){
 6202:        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-%d.svg\">%s_%d-%d-%d.svg</a><br> \
 6203: <img src=\"%s_%d-%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
 6204:      }
 6205:      /* State specific survival functions (period) */
 6206:      for(cpt=1; cpt<=nlstate;cpt++){
 6207:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
 6208:  Or probability to survive in various states (1 to %d) being in state %d at different ages.	\
 6209:  <a href=\"%s_%d-%d-%d.svg\">%s_%d%d-%d.svg</a><br> <img src=\"%s_%d-%d-%d.svg\">", cpt, nlstate, cpt, subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
 6210:      }
 6211:      /* Period (stable) prevalence in each health state */
 6212:      for(cpt=1; cpt<=nlstate;cpt++){
 6213:        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-%d.svg\">%s_%d-%d-%d.svg</a><br> \
 6214: <img src=\"%s_%d-%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,k1,nres,subdirf2(optionfilefiname,"P_"),cpt,k1,nres,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
 6215:      }
 6216:      if(backcast==1){
 6217:        /* Period (stable) back prevalence in each health state */
 6218:        for(cpt=1; cpt<=nlstate;cpt++){
 6219: 	 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-%d.svg\">%s_%d-%d-%d.svg</a><br> \
 6220: <img src=\"%s_%d-%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,k1,nres,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
 6221:        }
 6222:      }
 6223:      if(prevfcast==1){
 6224:        /* Projection of prevalence up to period (stable) prevalence in each health state */
 6225:        for(cpt=1; cpt<=nlstate;cpt++){
 6226: 	 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-%d.svg\">%s_%d-%d-%d.svg</a><br> \
 6227: <img src=\"%s_%d-%d-%d.svg\">", dateprev1, dateprev2, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
 6228:        }
 6229:      }
 6230: 	 
 6231:      for(cpt=1; cpt<=nlstate;cpt++) {
 6232:        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-%d.svg\">%s_%d-%d-%d.svg</a> <br> \
 6233: <img src=\"%s_%d-%d-%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
 6234:      }
 6235:      /* } /\* end i1 *\/ */
 6236:    }/* End k1 */
 6237:    fprintf(fichtm,"</ul>");
 6238: 
 6239:    fprintf(fichtm,"\
 6240: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
 6241:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
 6242:  - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
 6243: But because parameters are usually highly correlated (a higher incidence of disability \
 6244: and a higher incidence of recovery can give very close observed transition) it might \
 6245: be very useful to look not only at linear confidence intervals estimated from the \
 6246: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
 6247: (parameters) of the logistic regression, it might be more meaningful to visualize the \
 6248: covariance matrix of the one-step probabilities. \
 6249: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
 6250: 
 6251:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 6252: 	   subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
 6253:    fprintf(fichtm,"\
 6254:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 6255: 	   subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
 6256: 
 6257:    fprintf(fichtm,"\
 6258:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 6259: 	   subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
 6260:    fprintf(fichtm,"\
 6261:  - 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): \
 6262:    <a href=\"%s\">%s</a> <br>\n</li>",
 6263: 	   estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
 6264:    fprintf(fichtm,"\
 6265:  - (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): \
 6266:    <a href=\"%s\">%s</a> <br>\n</li>",
 6267: 	   estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
 6268:    fprintf(fichtm,"\
 6269:  - 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",
 6270: 	   estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
 6271:    fprintf(fichtm,"\
 6272:  - 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",
 6273: 	   estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
 6274:    fprintf(fichtm,"\
 6275:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
 6276: 	   subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
 6277: 
 6278: /*  if(popforecast==1) fprintf(fichtm,"\n */
 6279: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
 6280: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
 6281: /* 	<br>",fileres,fileres,fileres,fileres); */
 6282: /*  else  */
 6283: /*    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); */
 6284:    fflush(fichtm);
 6285:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
 6286: 
 6287:    m=pow(2,cptcoveff);
 6288:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 6289: 
 6290:    jj1=0;
 6291: 
 6292:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 6293:    for(k1=1; k1<=m;k1++){
 6294:      if(TKresult[nres]!= k1)
 6295:        continue;
 6296:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
 6297:      jj1++;
 6298:      if (cptcovn > 0) {
 6299:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 6300:        for (cpt=1; cpt<=cptcoveff;cpt++)  /**< cptcoveff number of variables */
 6301: 	 fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
 6302: 	 /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
 6303:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 6304: 	fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6305:       }
 6306: 
 6307:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 6308: 
 6309:        if(invalidvarcomb[k1]){
 6310: 	 fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
 6311: 	 continue;
 6312:        }
 6313:      }
 6314:      for(cpt=1; cpt<=nlstate;cpt++) {
 6315:        fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
 6316: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d-%d.svg\"> %s_%d-%d-%d.svg</a>\n <br>\
 6317: <img src=\"%s_%d-%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,k1,nres,subdirf2(optionfilefiname,"V_"),cpt,k1,nres,subdirf2(optionfilefiname,"V_"),cpt,k1,nres);  
 6318:      }
 6319:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
 6320: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
 6321: true period expectancies (those weighted with period prevalences are also\
 6322:  drawn in addition to the population based expectancies computed using\
 6323:  observed and cahotic prevalences:  <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a>\n<br>\
 6324: <img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres);
 6325:      /* } /\* end i1 *\/ */
 6326:    }/* End k1 */
 6327:   }/* End nres */
 6328:    fprintf(fichtm,"</ul>");
 6329:    fflush(fichtm);
 6330: }
 6331: 
 6332: /******************* Gnuplot file **************/
 6333: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
 6334: 
 6335:   char dirfileres[132],optfileres[132];
 6336:   char gplotcondition[132];
 6337:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,k4=0,ij=0, ijp=0, l=0;
 6338:   int lv=0, vlv=0, kl=0;
 6339:   int ng=0;
 6340:   int vpopbased;
 6341:   int ioffset; /* variable offset for columns */
 6342:   int nres=0; /* Index of resultline */
 6343: 
 6344: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
 6345: /*     printf("Problem with file %s",optionfilegnuplot); */
 6346: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
 6347: /*   } */
 6348: 
 6349:   /*#ifdef windows */
 6350:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 6351:   /*#endif */
 6352:   m=pow(2,cptcoveff);
 6353: 
 6354:   /* Contribution to likelihood */
 6355:   /* Plot the probability implied in the likelihood */
 6356:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
 6357:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
 6358:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
 6359:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
 6360: /* nice for mle=4 plot by number of matrix products.
 6361:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
 6362: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
 6363:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
 6364:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
 6365:   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));
 6366:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
 6367:   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));
 6368:   for (i=1; i<= nlstate ; i ++) {
 6369:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
 6370:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
 6371:     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);
 6372:     for (j=2; j<= nlstate+ndeath ; j ++) {
 6373:       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);
 6374:     }
 6375:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
 6376:   }
 6377:   /* 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 */		 
 6378:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
 6379:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
 6380:   fprintf(ficgp,"\nset out;unset log\n");
 6381:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
 6382: 
 6383:   strcpy(dirfileres,optionfilefiname);
 6384:   strcpy(optfileres,"vpl");
 6385:   /* 1eme*/
 6386:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
 6387:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
 6388:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 6389: 	/* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
 6390: 	if(TKresult[nres]!= k1)
 6391: 	  continue;
 6392: 	/* We are interested in selected combination by the resultline */
 6393: 	printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt);
 6394: 	fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
 6395: 	for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 6396: 	  lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
 6397: 	  /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6398: 	  /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6399: 	  /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6400: 	  vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
 6401: 	  /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
 6402: 	  printf(" V%d=%d ",Tvaraff[k],vlv);
 6403: 	  fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6404: 	}
 6405: 	for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 6406: 	  printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6407: 	  fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6408: 	}	
 6409: 	printf("\n#\n");
 6410: 	fprintf(ficgp,"\n#\n");
 6411: 	if(invalidvarcomb[k1]){
 6412: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6413: 	  continue;
 6414: 	}
 6415:       
 6416: 	fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
 6417: 	fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
 6418: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nset ter svg size 640, 480\nplot [%.f:%.f] \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1,nres);
 6419:       
 6420: 	for (i=1; i<= nlstate ; i ++) {
 6421: 	  if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 6422: 	  else        fprintf(ficgp," %%*lf (%%*lf)");
 6423: 	}
 6424: 	fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2==%d ? $3+1.96*$4 : 1/0) \"%%lf %%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1,nres);
 6425: 	for (i=1; i<= nlstate ; i ++) {
 6426: 	  if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 6427: 	  else fprintf(ficgp," %%*lf (%%*lf)");
 6428: 	} 
 6429: 	fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2==%d ? $3-1.96*$4 : 1/0) \"%%lf %%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1,nres); 
 6430: 	for (i=1; i<= nlstate ; i ++) {
 6431: 	  if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 6432: 	  else fprintf(ficgp," %%*lf (%%*lf)");
 6433: 	}  
 6434: 	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));
 6435: 	if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
 6436: 	  /* 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); */
 6437: 	  fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
 6438: 	  if(cptcoveff ==0){
 6439: 	    fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line ",	 2+(cpt-1),  cpt );
 6440: 	  }else{
 6441: 	    kl=0;
 6442: 	    for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
 6443: 	      lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
 6444: 	      /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6445: 	      /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6446: 	      /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6447: 	      vlv= nbcode[Tvaraff[k]][lv];
 6448: 	      kl++;
 6449: 	      /* 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 *\/ */
 6450: 	      /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
 6451: 	      /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
 6452: 	      /* ''  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*/
 6453: 	      if(k==cptcoveff){
 6454: 		fprintf(ficgp,"$%d==%d && $%d==%d)? $%d : 1/0) t 'Backward prevalence in state %d' ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv], \
 6455: 			2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
 6456: 	      }else{
 6457: 		fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
 6458: 		kl++;
 6459: 	      }
 6460: 	    } /* end covariate */
 6461: 	  } /* end if no covariate */
 6462: 	} /* end if backcast */
 6463: 	fprintf(ficgp,"\nset out \n");
 6464:       } /* nres */
 6465:     } /* k1 */
 6466:   } /* cpt */
 6467: 
 6468:   
 6469:   /*2 eme*/
 6470:   for (k1=1; k1<= m ; k1 ++){  
 6471:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 6472:       if(TKresult[nres]!= k1)
 6473: 	continue;
 6474:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
 6475:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 6476: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 6477: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6478: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6479: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6480: 	vlv= nbcode[Tvaraff[k]][lv];
 6481: 	fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6482:       }
 6483:       /* for(k=1; k <= ncovds; k++){ */
 6484:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 6485: 	printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6486: 	fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6487:       }
 6488:       fprintf(ficgp,"\n#\n");
 6489:       if(invalidvarcomb[k1]){
 6490: 	fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6491: 	continue;
 6492:       }
 6493: 			
 6494:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
 6495:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 6496: 	if(vpopbased==0)
 6497: 	  fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
 6498: 	else
 6499: 	  fprintf(ficgp,"\nreplot ");
 6500: 	for (i=1; i<= nlstate+1 ; i ++) {
 6501: 	  k=2*i;
 6502: 	  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);
 6503: 	  for (j=1; j<= nlstate+1 ; j ++) {
 6504: 	    if (j==i) fprintf(ficgp," %%lf (%%lf)");
 6505: 	    else fprintf(ficgp," %%*lf (%%*lf)");
 6506: 	  }   
 6507: 	  if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
 6508: 	  else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
 6509: 	  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);
 6510: 	  for (j=1; j<= nlstate+1 ; j ++) {
 6511: 	    if (j==i) fprintf(ficgp," %%lf (%%lf)");
 6512: 	    else fprintf(ficgp," %%*lf (%%*lf)");
 6513: 	  }   
 6514: 	  fprintf(ficgp,"\" t\"\" w l lt 0,");
 6515: 	  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);
 6516: 	  for (j=1; j<= nlstate+1 ; j ++) {
 6517: 	    if (j==i) fprintf(ficgp," %%lf (%%lf)");
 6518: 	    else fprintf(ficgp," %%*lf (%%*lf)");
 6519: 	  }   
 6520: 	  if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
 6521: 	  else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
 6522: 	} /* state */
 6523:       } /* vpopbased */
 6524:       fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
 6525:     } /* end nres */
 6526:   } /* k1 end 2 eme*/
 6527: 	
 6528: 	
 6529:   /*3eme*/
 6530:   for (k1=1; k1<= m ; k1 ++){
 6531:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 6532:       if(TKresult[nres]!= k1)
 6533: 	continue;
 6534: 
 6535:       for (cpt=1; cpt<= nlstate ; cpt ++) {
 6536: 	fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
 6537: 	for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 6538: 	  lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 6539: 	  /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6540: 	  /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6541: 	  /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6542: 	  vlv= nbcode[Tvaraff[k]][lv];
 6543: 	  fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6544: 	}
 6545: 	for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 6546: 	  fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6547: 	}	
 6548: 	fprintf(ficgp,"\n#\n");
 6549: 	if(invalidvarcomb[k1]){
 6550: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6551: 	  continue;
 6552: 	}
 6553: 			
 6554: 	/*       k=2+nlstate*(2*cpt-2); */
 6555: 	k=2+(nlstate+1)*(cpt-1);
 6556: 	fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
 6557: 	fprintf(ficgp,"set ter svg size 640, 480\n\
 6558: 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);
 6559: 	/*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 6560: 	  for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 6561: 	  fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 6562: 	  fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 6563: 	  for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 6564: 	  fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 6565: 				
 6566: 	*/
 6567: 	for (i=1; i< nlstate ; i ++) {
 6568: 	  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);
 6569: 	  /*	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);*/
 6570: 				
 6571: 	} 
 6572: 	fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
 6573:       }
 6574:     } /* end nres */
 6575:   } /* end kl 3eme */
 6576:   
 6577:   /* 4eme */
 6578:   /* Survival functions (period) from state i in state j by initial state i */
 6579:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
 6580:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 6581:       if(TKresult[nres]!= k1)
 6582: 	continue;
 6583:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
 6584: 	fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
 6585: 	for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 6586: 	  lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 6587: 	  /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6588: 	  /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6589: 	  /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6590: 	  vlv= nbcode[Tvaraff[k]][lv];
 6591: 	  fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6592: 	}
 6593: 	for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 6594: 	  fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6595: 	}	
 6596: 	fprintf(ficgp,"\n#\n");
 6597: 	if(invalidvarcomb[k1]){
 6598: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6599: 	  continue;
 6600: 	}
 6601:       
 6602: 	fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
 6603: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
 6604: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
 6605: 	k=3;
 6606: 	for (i=1; i<= nlstate ; i ++){
 6607: 	  if(i==1){
 6608: 	    fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 6609: 	  }else{
 6610: 	    fprintf(ficgp,", '' ");
 6611: 	  }
 6612: 	  l=(nlstate+ndeath)*(i-1)+1;
 6613: 	  fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 6614: 	  for (j=2; j<= nlstate+ndeath ; j ++)
 6615: 	    fprintf(ficgp,"+$%d",k+l+j-1);
 6616: 	  fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
 6617: 	} /* nlstate */
 6618: 	fprintf(ficgp,"\nset out\n");
 6619:       } /* end cpt state*/ 
 6620:     } /* end nres */
 6621:   } /* end covariate k1 */  
 6622: 
 6623: /* 5eme */
 6624:   /* Survival functions (period) from state i in state j by final state j */
 6625:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
 6626:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 6627:       if(TKresult[nres]!= k1)
 6628: 	continue;
 6629:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
 6630: 	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);
 6631: 	for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 6632: 	  lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 6633: 	  /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6634: 	  /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6635: 	  /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6636: 	  vlv= nbcode[Tvaraff[k]][lv];
 6637: 	  fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6638: 	}
 6639: 	for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 6640: 	  fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6641: 	}	
 6642: 	fprintf(ficgp,"\n#\n");
 6643: 	if(invalidvarcomb[k1]){
 6644: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6645: 	  continue;
 6646: 	}
 6647:       
 6648: 	fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
 6649: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
 6650: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
 6651: 	k=3;
 6652: 	for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
 6653: 	  if(j==1)
 6654: 	    fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 6655: 	  else
 6656: 	    fprintf(ficgp,", '' ");
 6657: 	  l=(nlstate+ndeath)*(cpt-1) +j;
 6658: 	  fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
 6659: 	  /* for (i=2; i<= nlstate+ndeath ; i ++) */
 6660: 	  /*   fprintf(ficgp,"+$%d",k+l+i-1); */
 6661: 	  fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
 6662: 	} /* nlstate */
 6663: 	fprintf(ficgp,", '' ");
 6664: 	fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
 6665: 	for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
 6666: 	  l=(nlstate+ndeath)*(cpt-1) +j;
 6667: 	  if(j < nlstate)
 6668: 	    fprintf(ficgp,"$%d +",k+l);
 6669: 	  else
 6670: 	    fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
 6671: 	}
 6672: 	fprintf(ficgp,"\nset out\n");
 6673:       } /* end cpt state*/ 
 6674:     } /* end covariate */  
 6675:   } /* end nres */
 6676:   
 6677: /* 6eme */
 6678:   /* CV preval stable (period) for each covariate */
 6679:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
 6680:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 6681:     if(TKresult[nres]!= k1)
 6682:       continue;
 6683:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 6684:       
 6685:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
 6686:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 6687: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 6688: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6689: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6690: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6691: 	vlv= nbcode[Tvaraff[k]][lv];
 6692: 	fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6693:       }
 6694:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 6695: 	fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6696:       }	
 6697:       fprintf(ficgp,"\n#\n");
 6698:       if(invalidvarcomb[k1]){
 6699: 	fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6700: 	continue;
 6701:       }
 6702:       
 6703:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
 6704:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 6705: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
 6706:       k=3; /* Offset */
 6707:       for (i=1; i<= nlstate ; i ++){
 6708: 	if(i==1)
 6709: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 6710: 	else
 6711: 	  fprintf(ficgp,", '' ");
 6712: 	l=(nlstate+ndeath)*(i-1)+1;
 6713: 	fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 6714: 	for (j=2; j<= nlstate ; j ++)
 6715: 	  fprintf(ficgp,"+$%d",k+l+j-1);
 6716: 	fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
 6717:       } /* nlstate */
 6718:       fprintf(ficgp,"\nset out\n");
 6719:     } /* end cpt state*/ 
 6720:   } /* end covariate */  
 6721:   
 6722:   
 6723: /* 7eme */
 6724:   if(backcast == 1){
 6725:     /* CV back preval stable (period) for each covariate */
 6726:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
 6727:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 6728:       if(TKresult[nres]!= k1)
 6729: 	continue;
 6730:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 6731: 	fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
 6732: 	for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 6733: 	  lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 6734: 	  /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6735: 	  /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6736: 	  /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6737: 	  vlv= nbcode[Tvaraff[k]][lv];
 6738: 	  fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6739: 	}
 6740: 	for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 6741: 	  fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6742: 	}	
 6743: 	fprintf(ficgp,"\n#\n");
 6744: 	if(invalidvarcomb[k1]){
 6745: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6746: 	  continue;
 6747: 	}
 6748: 	
 6749: 	fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
 6750: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 6751: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
 6752: 	k=3; /* Offset */
 6753: 	for (i=1; i<= nlstate ; i ++){
 6754: 	  if(i==1)
 6755: 	    fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
 6756: 	  else
 6757: 	    fprintf(ficgp,", '' ");
 6758: 	  /* l=(nlstate+ndeath)*(i-1)+1; */
 6759: 	  l=(nlstate+ndeath)*(cpt-1)+1;
 6760: 	  /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
 6761: 	  /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
 6762: 	  fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */
 6763: 	  /* for (j=2; j<= nlstate ; j ++) */
 6764: 	  /* 	fprintf(ficgp,"+$%d",k+l+j-1); */
 6765: 	  /* 	/\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
 6766: 	  fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
 6767: 	} /* nlstate */
 6768: 	fprintf(ficgp,"\nset out\n");
 6769:       } /* end cpt state*/ 
 6770:     } /* end covariate */  
 6771:   } /* End if backcast */
 6772:   
 6773:   /* 8eme */
 6774:   if(prevfcast==1){
 6775:     /* Projection from cross-sectional to stable (period) for each covariate */
 6776:     
 6777:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
 6778:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 6779:       if(TKresult[nres]!= k1)
 6780: 	continue;
 6781:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 6782: 	fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
 6783: 	for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
 6784: 	  lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
 6785: 	  /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6786: 	  /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6787: 	  /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6788: 	  vlv= nbcode[Tvaraff[k]][lv];
 6789: 	  fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6790: 	}
 6791: 	for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 6792: 	  fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6793: 	}	
 6794: 	fprintf(ficgp,"\n#\n");
 6795: 	if(invalidvarcomb[k1]){
 6796: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6797: 	  continue;
 6798: 	}
 6799: 	
 6800: 	fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
 6801: 	fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
 6802: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
 6803: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
 6804: 	for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
 6805: 	  /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 6806: 	  /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 6807: 	  /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 6808: 	  /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 6809: 	  if(i==1){
 6810: 	    fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
 6811: 	  }else{
 6812: 	    fprintf(ficgp,",\\\n '' ");
 6813: 	  }
 6814: 	  if(cptcoveff ==0){ /* No covariate */
 6815: 	    ioffset=2; /* Age is in 2 */
 6816: 	    /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
 6817: 	    /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
 6818: 	    /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
 6819: 	    /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
 6820: 	    fprintf(ficgp," u %d:(", ioffset); 
 6821: 	    if(i==nlstate+1)
 6822: 	      fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ",	\
 6823: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
 6824: 	    else
 6825: 	      fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",	\
 6826: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
 6827: 	  }else{ /* more than 2 covariates */
 6828: 	    if(cptcoveff ==1){
 6829: 	      ioffset=4; /* Age is in 4 */
 6830: 	    }else{
 6831: 	      ioffset=6; /* Age is in 6 */
 6832: 	      /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 6833: 	      /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
 6834: 	    }   
 6835: 	    fprintf(ficgp," u %d:(",ioffset); 
 6836: 	    kl=0;
 6837: 	    strcpy(gplotcondition,"(");
 6838: 	    for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
 6839: 	      lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
 6840: 	      /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6841: 	      /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6842: 	      /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6843: 	      vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
 6844: 	      kl++;
 6845: 	      sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
 6846: 	      kl++;
 6847: 	      if(k <cptcoveff && cptcoveff>1)
 6848: 		sprintf(gplotcondition+strlen(gplotcondition)," && ");
 6849: 	    }
 6850: 	    strcpy(gplotcondition+strlen(gplotcondition),")");
 6851: 	    /* 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 *\/ */
 6852: 	    /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
 6853: 	    /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
 6854: 	    /* ''  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*/
 6855: 	    if(i==nlstate+1){
 6856: 	      fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ", gplotcondition, \
 6857: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
 6858: 	    }else{
 6859: 	      fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
 6860: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
 6861: 	    }
 6862: 	  } /* end if covariate */
 6863: 	} /* nlstate */
 6864: 	fprintf(ficgp,"\nset out\n");
 6865:       } /* end cpt state*/
 6866:     } /* end covariate */
 6867:   } /* End if prevfcast */
 6868:   
 6869:   
 6870:   /* 9eme writing MLE parameters */
 6871:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
 6872:   for(i=1,jk=1; i <=nlstate; i++){
 6873:     fprintf(ficgp,"# initial state %d\n",i);
 6874:     for(k=1; k <=(nlstate+ndeath); k++){
 6875:       if (k != i) {
 6876: 	fprintf(ficgp,"#   current state %d\n",k);
 6877: 	for(j=1; j <=ncovmodel; j++){
 6878: 	  fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
 6879: 	  jk++; 
 6880: 	}
 6881: 	fprintf(ficgp,"\n");
 6882:       }
 6883:     }
 6884:   }
 6885:   fprintf(ficgp,"##############\n#\n");
 6886:   
 6887:   /*goto avoid;*/
 6888:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
 6889:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
 6890:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
 6891:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
 6892:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
 6893:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
 6894:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 6895:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 6896:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 6897:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 6898:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
 6899:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 6900:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
 6901:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
 6902:   fprintf(ficgp,"#\n");
 6903:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
 6904:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
 6905:     fprintf(ficgp,"#model=%s \n",model);
 6906:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
 6907:     fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
 6908:     for(jk=1; jk <=m; jk++)  /* For each combination of covariate */
 6909:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 6910:       if(TKresult[nres]!= jk)
 6911: 	continue;
 6912:       fprintf(ficgp,"# Combination of dummy  jk=%d and ",jk);
 6913:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 6914: 	fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 6915:       }	
 6916:       fprintf(ficgp,"\n#\n");
 6917:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng,nres);
 6918:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
 6919:       if (ng==1){
 6920: 	fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
 6921: 	fprintf(ficgp,"\nunset log y");
 6922:       }else if (ng==2){
 6923: 	fprintf(ficgp,"\nset ylabel \"Probability\"\n");
 6924: 	fprintf(ficgp,"\nset log y");
 6925:       }else if (ng==3){
 6926: 	fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
 6927: 	fprintf(ficgp,"\nset log y");
 6928:       }else
 6929: 	fprintf(ficgp,"\nunset title ");
 6930:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
 6931:       i=1;
 6932:       for(k2=1; k2<=nlstate; k2++) {
 6933: 	k3=i;
 6934: 	for(k=1; k<=(nlstate+ndeath); k++) {
 6935: 	  if (k != k2){
 6936: 	    switch( ng) {
 6937: 	    case 1:
 6938: 	      if(nagesqr==0)
 6939: 		fprintf(ficgp," p%d+p%d*x",i,i+1);
 6940: 	      else /* nagesqr =1 */
 6941: 		fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
 6942: 	      break;
 6943: 	    case 2: /* ng=2 */
 6944: 	      if(nagesqr==0)
 6945: 		fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
 6946: 	      else /* nagesqr =1 */
 6947: 		fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
 6948: 	      break;
 6949: 	    case 3:
 6950: 	      if(nagesqr==0)
 6951: 		fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
 6952: 	      else /* nagesqr =1 */
 6953: 		fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
 6954: 	      break;
 6955: 	    }
 6956: 	    ij=1;/* To be checked else nbcode[0][0] wrong */
 6957: 	    ijp=1; /* product no age */
 6958: 	    /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
 6959: 	    for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
 6960: 	      /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
 6961: 	      if(j==Tage[ij]) { /* Product by age */
 6962: 		if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
 6963: 		  if(DummyV[j]==0){
 6964: 		    fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
 6965: 		  }else{ /* quantitative */
 6966: 		    fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
 6967: 		    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
 6968: 		  }
 6969: 		  ij++;
 6970: 		}
 6971: 	      }else if(j==Tprod[ijp]) { /* */ 
 6972: 		/* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
 6973: 		if(ijp <=cptcovprod) { /* Product */
 6974: 		  if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
 6975: 		    if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
 6976: 		      /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(jk,j)],nbcode[Tvard[ijp][2]][codtabm(jk,j)]); */
 6977: 		      fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
 6978: 		    }else{ /* Vn is dummy and Vm is quanti */
 6979: 		      /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(jk,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
 6980: 		      fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
 6981: 		    }
 6982: 		  }else{ /* Vn*Vm Vn is quanti */
 6983: 		    if(DummyV[Tvard[ijp][2]]==0){
 6984: 		      fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
 6985: 		    }else{ /* Both quanti */
 6986: 		      fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
 6987: 		    }
 6988: 		  }
 6989: 		  ijp++;
 6990:   		}
 6991: 	      } else{  /* simple covariate */
 6992: 		/* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(jk,j)]); /\* Valgrind bug nbcode *\/ */
 6993: 		if(Dummy[j]==0){
 6994: 		  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
 6995: 		}else{ /* quantitative */
 6996: 		  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
 6997: 		  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
 6998: 		}
 6999: 	      } /* end simple */
 7000: 	    } /* end j */
 7001: 	  }else{
 7002: 	    i=i-ncovmodel;
 7003: 	    if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
 7004: 	      fprintf(ficgp," (1.");
 7005: 	  }
 7006: 	  
 7007: 	  if(ng != 1){
 7008: 	    fprintf(ficgp,")/(1");
 7009: 	    
 7010: 	    for(k1=1; k1 <=nlstate; k1++){ 
 7011: 	      if(nagesqr==0)
 7012: 		fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
 7013: 	      else /* nagesqr =1 */
 7014: 		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);
 7015: 	       
 7016: 	      ij=1;
 7017: 	      for(j=3; j <=ncovmodel-nagesqr; j++){
 7018: 		if((j-2)==Tage[ij]) { /* Bug valgrind */
 7019: 		  if(ij <=cptcovage) { /* Bug valgrind */
 7020: 		    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
 7021: 		    /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
 7022: 		    ij++;
 7023: 		  }
 7024: 		}
 7025: 		else
 7026: 		  fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);/* Valgrind bug nbcode */
 7027: 	      }
 7028: 	      fprintf(ficgp,")");
 7029: 	    }
 7030: 	    fprintf(ficgp,")");
 7031: 	    if(ng ==2)
 7032: 	      fprintf(ficgp," t \"p%d%d\" ", k2,k);
 7033: 	    else /* ng= 3 */
 7034: 	      fprintf(ficgp," t \"i%d%d\" ", k2,k);
 7035: 	  }else{ /* end ng <> 1 */
 7036: 	    if( k !=k2) /* logit p11 is hard to draw */
 7037: 	      fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
 7038: 	  }
 7039: 	  if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
 7040: 	    fprintf(ficgp,",");
 7041: 	  if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
 7042: 	    fprintf(ficgp,",");
 7043: 	  i=i+ncovmodel;
 7044: 	} /* end k */
 7045:       } /* end k2 */
 7046:       fprintf(ficgp,"\n set out\n");
 7047:     } /* end jk */
 7048:   } /* end ng */
 7049:   /* avoid: */
 7050:   fflush(ficgp); 
 7051: }  /* end gnuplot */
 7052: 
 7053: 
 7054: /*************** Moving average **************/
 7055: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
 7056:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
 7057:    
 7058:    int i, cpt, cptcod;
 7059:    int modcovmax =1;
 7060:    int mobilavrange, mob;
 7061:    int iage=0;
 7062: 
 7063:    double sum=0.;
 7064:    double age;
 7065:    double *sumnewp, *sumnewm;
 7066:    double *agemingood, *agemaxgood; /* Currently identical for all covariates */
 7067:   
 7068:   
 7069:    /* modcovmax=2*cptcoveff;/\* Max number of modalities. We suppose  */
 7070:    /* 		   a covariate has 2 modalities, should be equal to ncovcombmax  *\/ */
 7071: 
 7072:    sumnewp = vector(1,ncovcombmax);
 7073:    sumnewm = vector(1,ncovcombmax);
 7074:    agemingood = vector(1,ncovcombmax);	
 7075:    agemaxgood = vector(1,ncovcombmax);
 7076: 
 7077:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
 7078:      sumnewm[cptcod]=0.;
 7079:      sumnewp[cptcod]=0.;
 7080:      agemingood[cptcod]=0;
 7081:      agemaxgood[cptcod]=0;
 7082:    }
 7083:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
 7084:   
 7085:    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
 7086:      if(mobilav==1) mobilavrange=5; /* default */
 7087:      else mobilavrange=mobilav;
 7088:      for (age=bage; age<=fage; age++)
 7089:        for (i=1; i<=nlstate;i++)
 7090: 	 for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
 7091: 	   mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 7092:      /* We keep the original values on the extreme ages bage, fage and for 
 7093: 	fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
 7094: 	we use a 5 terms etc. until the borders are no more concerned. 
 7095:      */ 
 7096:      for (mob=3;mob <=mobilavrange;mob=mob+2){
 7097:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
 7098: 	 for (i=1; i<=nlstate;i++){
 7099: 	   for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
 7100: 	     mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
 7101: 	     for (cpt=1;cpt<=(mob-1)/2;cpt++){
 7102: 	       mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
 7103: 	       mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
 7104: 	     }
 7105: 	     mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
 7106: 	   }
 7107: 	 }
 7108:        }/* end age */
 7109:      }/* end mob */
 7110:    }else
 7111:      return -1;
 7112:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
 7113:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
 7114:      if(invalidvarcomb[cptcod]){
 7115:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
 7116:        continue;
 7117:      }
 7118: 
 7119:      agemingood[cptcod]=fage-(mob-1)/2;
 7120:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
 7121:        sumnewm[cptcod]=0.;
 7122:        for (i=1; i<=nlstate;i++){
 7123: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 7124:        }
 7125:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
 7126: 	 agemingood[cptcod]=age;
 7127:        }else{ /* bad */
 7128: 	 for (i=1; i<=nlstate;i++){
 7129: 	   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
 7130: 	 } /* i */
 7131:        } /* end bad */
 7132:      }/* age */
 7133:      sum=0.;
 7134:      for (i=1; i<=nlstate;i++){
 7135:        sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
 7136:      }
 7137:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
 7138:        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);
 7139:        /* for (i=1; i<=nlstate;i++){ */
 7140:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
 7141:        /* } /\* i *\/ */
 7142:      } /* end bad */
 7143:      /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
 7144:      /* From youngest, finding the oldest wrong */
 7145:      agemaxgood[cptcod]=bage+(mob-1)/2;
 7146:      for (age=bage+(mob-1)/2; age<=fage; age++){
 7147:        sumnewm[cptcod]=0.;
 7148:        for (i=1; i<=nlstate;i++){
 7149: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 7150:        }
 7151:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
 7152: 	 agemaxgood[cptcod]=age;
 7153:        }else{ /* bad */
 7154: 	 for (i=1; i<=nlstate;i++){
 7155: 	   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
 7156: 	 } /* i */
 7157:        } /* end bad */
 7158:      }/* age */
 7159:      sum=0.;
 7160:      for (i=1; i<=nlstate;i++){
 7161:        sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
 7162:      }
 7163:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
 7164:        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);
 7165:        /* for (i=1; i<=nlstate;i++){ */
 7166:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
 7167:        /* } /\* i *\/ */
 7168:      } /* end bad */
 7169: 		
 7170:      for (age=bage; age<=fage; age++){
 7171:        /* printf("%d %d ", cptcod, (int)age); */
 7172:        sumnewp[cptcod]=0.;
 7173:        sumnewm[cptcod]=0.;
 7174:        for (i=1; i<=nlstate;i++){
 7175: 	 sumnewp[cptcod]+=probs[(int)age][i][cptcod];
 7176: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 7177: 	 /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
 7178:        }
 7179:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
 7180:      }
 7181:      /* printf("\n"); */
 7182:      /* } */
 7183:      /* brutal averaging */
 7184:      for (i=1; i<=nlstate;i++){
 7185:        for (age=1; age<=bage; age++){
 7186: 	 mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
 7187: 	 /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
 7188:        }	
 7189:        for (age=fage; age<=AGESUP; age++){
 7190: 	 mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
 7191: 	 /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
 7192:        }
 7193:      } /* end i status */
 7194:      for (i=nlstate+1; i<=nlstate+ndeath;i++){
 7195:        for (age=1; age<=AGESUP; age++){
 7196: 	 /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
 7197: 	 mobaverage[(int)age][i][cptcod]=0.;
 7198:        }
 7199:      }
 7200:    }/* end cptcod */
 7201:    free_vector(sumnewm,1, ncovcombmax);
 7202:    free_vector(sumnewp,1, ncovcombmax);
 7203:    free_vector(agemaxgood,1, ncovcombmax);
 7204:    free_vector(agemingood,1, ncovcombmax);
 7205:    return 0;
 7206:  }/* End movingaverage */
 7207:  
 7208: 
 7209: /************** Forecasting ******************/
 7210:  void prevforecast(char fileres[], double anproj1, double mproj1, double jproj1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anproj2, double p[], int cptcoveff){
 7211:   /* proj1, year, month, day of starting projection 
 7212:      agemin, agemax range of age
 7213:      dateprev1 dateprev2 range of dates during which prevalence is computed
 7214:      anproj2 year of en of projection (same day and month as proj1).
 7215:   */
 7216:    int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
 7217:   double agec; /* generic age */
 7218:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
 7219:   double *popeffectif,*popcount;
 7220:   double ***p3mat;
 7221:   /* double ***mobaverage; */
 7222:   char fileresf[FILENAMELENGTH];
 7223: 
 7224:   agelim=AGESUP;
 7225:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 7226:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 7227:      We still use firstpass and lastpass as another selection.
 7228:   */
 7229:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
 7230:   /* 	      firstpass, lastpass,  stepm,  weightopt, model); */
 7231:  
 7232:   strcpy(fileresf,"F_"); 
 7233:   strcat(fileresf,fileresu);
 7234:   if((ficresf=fopen(fileresf,"w"))==NULL) {
 7235:     printf("Problem with forecast resultfile: %s\n", fileresf);
 7236:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
 7237:   }
 7238:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
 7239:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
 7240: 
 7241:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 7242: 
 7243: 
 7244:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 7245:   if (stepm<=12) stepsize=1;
 7246:   if(estepm < stepm){
 7247:     printf ("Problem %d lower than %d\n",estepm, stepm);
 7248:   }
 7249:   else  hstepm=estepm;   
 7250: 
 7251:   hstepm=hstepm/stepm; 
 7252:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
 7253:                                fractional in yp1 */
 7254:   anprojmean=yp;
 7255:   yp2=modf((yp1*12),&yp);
 7256:   mprojmean=yp;
 7257:   yp1=modf((yp2*30.5),&yp);
 7258:   jprojmean=yp;
 7259:   if(jprojmean==0) jprojmean=1;
 7260:   if(mprojmean==0) jprojmean=1;
 7261: 
 7262:   i1=pow(2,cptcoveff);
 7263:   if (cptcovn < 1){i1=1;}
 7264:   
 7265:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
 7266:   
 7267:   fprintf(ficresf,"#****** Routine prevforecast **\n");
 7268:   
 7269: /* 	      if (h==(int)(YEARM*yearp)){ */
 7270:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
 7271:   for(k=1; k<=i1;k++){
 7272:     if(TKresult[nres]!= k)
 7273:       continue;
 7274:     if(invalidvarcomb[k]){
 7275:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
 7276:       continue;
 7277:     }
 7278:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
 7279:     for(j=1;j<=cptcoveff;j++) {
 7280:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7281:     }
 7282:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 7283:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 7284:     }
 7285:     fprintf(ficresf," yearproj age");
 7286:     for(j=1; j<=nlstate+ndeath;j++){ 
 7287:       for(i=1; i<=nlstate;i++) 	      
 7288: 	fprintf(ficresf," p%d%d",i,j);
 7289:       fprintf(ficresf," wp.%d",j);
 7290:     }
 7291:     for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
 7292:       fprintf(ficresf,"\n");
 7293:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
 7294:       for (agec=fage; agec>=(ageminpar-1); agec--){ 
 7295: 	nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
 7296: 	nhstepm = nhstepm/hstepm; 
 7297: 	p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 7298: 	oldm=oldms;savm=savms;
 7299: 	hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
 7300: 	
 7301: 	for (h=0; h<=nhstepm; h++){
 7302: 	  if (h*hstepm/YEARM*stepm ==yearp) {
 7303: 	    fprintf(ficresf,"\n");
 7304: 	    for(j=1;j<=cptcoveff;j++) 
 7305: 	      fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 7306: 	    fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
 7307: 	  } 
 7308: 	  for(j=1; j<=nlstate+ndeath;j++) {
 7309: 	    ppij=0.;
 7310: 	    for(i=1; i<=nlstate;i++) {
 7311: 	      if (mobilav==1) 
 7312: 		ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][k];
 7313: 	      else {
 7314: 		ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
 7315: 	      }
 7316: 	      if (h*hstepm/YEARM*stepm== yearp) {
 7317: 		fprintf(ficresf," %.3f", p3mat[i][j][h]);
 7318: 	      }
 7319: 	    } /* end i */
 7320: 	    if (h*hstepm/YEARM*stepm==yearp) {
 7321: 	      fprintf(ficresf," %.3f", ppij);
 7322: 	    }
 7323: 	  }/* end j */
 7324: 	} /* end h */
 7325: 	free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 7326:       } /* end agec */
 7327:     } /* end yearp */
 7328:   } /* end  k */
 7329: 	
 7330:   fclose(ficresf);
 7331:   printf("End of Computing forecasting \n");
 7332:   fprintf(ficlog,"End of Computing forecasting\n");
 7333: 
 7334: }
 7335: 
 7336: /* /\************** Back Forecasting ******************\/ */
 7337: /* void prevbackforecast(char fileres[], double anback1, double mback1, double jback1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anback2, double p[], int cptcoveff){ */
 7338: /*   /\* back1, year, month, day of starting backection  */
 7339: /*      agemin, agemax range of age */
 7340: /*      dateprev1 dateprev2 range of dates during which prevalence is computed */
 7341: /*      anback2 year of en of backection (same day and month as back1). */
 7342: /*   *\/ */
 7343: /*   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
 7344: /*   double agec; /\* generic age *\/ */
 7345: /*   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
 7346: /*   double *popeffectif,*popcount; */
 7347: /*   double ***p3mat; */
 7348: /*   /\* double ***mobaverage; *\/ */
 7349: /*   char fileresfb[FILENAMELENGTH]; */
 7350: 	
 7351: /*   agelim=AGESUP; */
 7352: /*   /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
 7353: /*      in each health status at the date of interview (if between dateprev1 and dateprev2). */
 7354: /*      We still use firstpass and lastpass as another selection. */
 7355: /*   *\/ */
 7356: /*   /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
 7357: /*   /\* 	      firstpass, lastpass,  stepm,  weightopt, model); *\/ */
 7358: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
 7359: 	
 7360: /*   strcpy(fileresfb,"FB_");  */
 7361: /*   strcat(fileresfb,fileresu); */
 7362: /*   if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
 7363: /*     printf("Problem with back forecast resultfile: %s\n", fileresfb); */
 7364: /*     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
 7365: /*   } */
 7366: /*   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
 7367: /*   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
 7368: 	
 7369: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
 7370: 	
 7371: /*   /\* if (mobilav!=0) { *\/ */
 7372: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
 7373: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
 7374: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
 7375: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
 7376: /*   /\*   } *\/ */
 7377: /*   /\* } *\/ */
 7378: 	
 7379: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
 7380: /*   if (stepm<=12) stepsize=1; */
 7381: /*   if(estepm < stepm){ */
 7382: /*     printf ("Problem %d lower than %d\n",estepm, stepm); */
 7383: /*   } */
 7384: /*   else  hstepm=estepm;    */
 7385: 	
 7386: /*   hstepm=hstepm/stepm;  */
 7387: /*   yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
 7388: /*                                fractional in yp1 *\/ */
 7389: /*   anprojmean=yp; */
 7390: /*   yp2=modf((yp1*12),&yp); */
 7391: /*   mprojmean=yp; */
 7392: /*   yp1=modf((yp2*30.5),&yp); */
 7393: /*   jprojmean=yp; */
 7394: /*   if(jprojmean==0) jprojmean=1; */
 7395: /*   if(mprojmean==0) jprojmean=1; */
 7396: 	
 7397: /*   i1=cptcoveff; */
 7398: /*   if (cptcovn < 1){i1=1;} */
 7399:   
 7400: /*   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);  */
 7401:   
 7402: /*   fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
 7403: 	
 7404: /* 	/\* 	      if (h==(int)(YEARM*yearp)){ *\/ */
 7405: /*   for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
 7406: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
 7407: /*       k=k+1; */
 7408: /*       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
 7409: /*       for(j=1;j<=cptcoveff;j++) { */
 7410: /* 				fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
 7411: /*       } */
 7412: /*       fprintf(ficresfb," yearbproj age"); */
 7413: /*       for(j=1; j<=nlstate+ndeath;j++){  */
 7414: /* 				for(i=1; i<=nlstate;i++) 	       */
 7415: /*           fprintf(ficresfb," p%d%d",i,j); */
 7416: /* 				fprintf(ficresfb," p.%d",j); */
 7417: /*       } */
 7418: /*       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {  */
 7419: /* 				/\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  *\/ */
 7420: /* 				fprintf(ficresfb,"\n"); */
 7421: /* 				fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);    */
 7422: /* 				for (agec=fage; agec>=(ageminpar-1); agec--){  */
 7423: /* 					nhstepm=(int) rint((agelim-agec)*YEARM/stepm);  */
 7424: /* 					nhstepm = nhstepm/hstepm;  */
 7425: /* 					p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
 7426: /* 					oldm=oldms;savm=savms; */
 7427: /* 					hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k); 	 */
 7428: /* 					for (h=0; h<=nhstepm; h++){ */
 7429: /* 						if (h*hstepm/YEARM*stepm ==yearp) { */
 7430: /*               fprintf(ficresfb,"\n"); */
 7431: /*               for(j=1;j<=cptcoveff;j++)  */
 7432: /*                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
 7433: /* 							fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
 7434: /* 						}  */
 7435: /* 						for(j=1; j<=nlstate+ndeath;j++) { */
 7436: /* 							ppij=0.; */
 7437: /* 							for(i=1; i<=nlstate;i++) { */
 7438: /* 								if (mobilav==1)  */
 7439: /* 									ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
 7440: /* 								else { */
 7441: /* 									ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
 7442: /* 								} */
 7443: /* 								if (h*hstepm/YEARM*stepm== yearp) { */
 7444: /* 									fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
 7445: /* 								} */
 7446: /* 							} /\* end i *\/ */
 7447: /* 							if (h*hstepm/YEARM*stepm==yearp) { */
 7448: /* 								fprintf(ficresfb," %.3f", ppij); */
 7449: /* 							} */
 7450: /* 						}/\* end j *\/ */
 7451: /* 					} /\* end h *\/ */
 7452: /* 					free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
 7453: /* 				} /\* end agec *\/ */
 7454: /*       } /\* end yearp *\/ */
 7455: /*     } /\* end cptcod *\/ */
 7456: /*   } /\* end  cptcov *\/ */
 7457: 	
 7458: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
 7459: 	
 7460: /*   fclose(ficresfb); */
 7461: /*   printf("End of Computing Back forecasting \n"); */
 7462: /*   fprintf(ficlog,"End of Computing Back forecasting\n"); */
 7463: 	
 7464: /* } */
 7465: 
 7466: /************** Forecasting *****not tested NB*************/
 7467: /* void populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2s, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){ */
 7468:   
 7469: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
 7470: /*   int *popage; */
 7471: /*   double calagedatem, agelim, kk1, kk2; */
 7472: /*   double *popeffectif,*popcount; */
 7473: /*   double ***p3mat,***tabpop,***tabpopprev; */
 7474: /*   /\* double ***mobaverage; *\/ */
 7475: /*   char filerespop[FILENAMELENGTH]; */
 7476: 
 7477: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 7478: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 7479: /*   agelim=AGESUP; */
 7480: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
 7481:   
 7482: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
 7483:   
 7484:   
 7485: /*   strcpy(filerespop,"POP_");  */
 7486: /*   strcat(filerespop,fileresu); */
 7487: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
 7488: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
 7489: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
 7490: /*   } */
 7491: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
 7492: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
 7493: 
 7494: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
 7495: 
 7496: /*   /\* if (mobilav!=0) { *\/ */
 7497: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
 7498: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
 7499: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
 7500: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
 7501: /*   /\*   } *\/ */
 7502: /*   /\* } *\/ */
 7503: 
 7504: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
 7505: /*   if (stepm<=12) stepsize=1; */
 7506:   
 7507: /*   agelim=AGESUP; */
 7508:   
 7509: /*   hstepm=1; */
 7510: /*   hstepm=hstepm/stepm;  */
 7511: 	
 7512: /*   if (popforecast==1) { */
 7513: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
 7514: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
 7515: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
 7516: /*     }  */
 7517: /*     popage=ivector(0,AGESUP); */
 7518: /*     popeffectif=vector(0,AGESUP); */
 7519: /*     popcount=vector(0,AGESUP); */
 7520:     
 7521: /*     i=1;    */
 7522: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
 7523:     
 7524: /*     imx=i; */
 7525: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
 7526: /*   } */
 7527:   
 7528: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
 7529: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
 7530: /*       k=k+1; */
 7531: /*       fprintf(ficrespop,"\n#******"); */
 7532: /*       for(j=1;j<=cptcoveff;j++) { */
 7533: /* 	fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
 7534: /*       } */
 7535: /*       fprintf(ficrespop,"******\n"); */
 7536: /*       fprintf(ficrespop,"# Age"); */
 7537: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
 7538: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
 7539:       
 7540: /*       for (cpt=0; cpt<=0;cpt++) {  */
 7541: /* 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
 7542: 	
 7543: /* 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
 7544: /* 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
 7545: /* 	  nhstepm = nhstepm/hstepm;  */
 7546: 	  
 7547: /* 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
 7548: /* 	  oldm=oldms;savm=savms; */
 7549: /* 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
 7550: 	  
 7551: /* 	  for (h=0; h<=nhstepm; h++){ */
 7552: /* 	    if (h==(int) (calagedatem+YEARM*cpt)) { */
 7553: /* 	      fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
 7554: /* 	    }  */
 7555: /* 	    for(j=1; j<=nlstate+ndeath;j++) { */
 7556: /* 	      kk1=0.;kk2=0; */
 7557: /* 	      for(i=1; i<=nlstate;i++) {	       */
 7558: /* 		if (mobilav==1)  */
 7559: /* 		  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
 7560: /* 		else { */
 7561: /* 		  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
 7562: /* 		} */
 7563: /* 	      } */
 7564: /* 	      if (h==(int)(calagedatem+12*cpt)){ */
 7565: /* 		tabpop[(int)(agedeb)][j][cptcod]=kk1; */
 7566: /* 		/\*fprintf(ficrespop," %.3f", kk1); */
 7567: /* 		  if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
 7568: /* 	      } */
 7569: /* 	    } */
 7570: /* 	    for(i=1; i<=nlstate;i++){ */
 7571: /* 	      kk1=0.; */
 7572: /* 	      for(j=1; j<=nlstate;j++){ */
 7573: /* 		kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
 7574: /* 	      } */
 7575: /* 	      tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
 7576: /* 	    } */
 7577: 	    
 7578: /* 	    if (h==(int)(calagedatem+12*cpt)) */
 7579: /* 	      for(j=1; j<=nlstate;j++)  */
 7580: /* 		fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
 7581: /* 	  } */
 7582: /* 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
 7583: /* 	} */
 7584: /*       } */
 7585:       
 7586: /*       /\******\/ */
 7587:       
 7588: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
 7589: /* 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
 7590: /* 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
 7591: /* 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
 7592: /* 	  nhstepm = nhstepm/hstepm;  */
 7593: 	  
 7594: /* 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
 7595: /* 	  oldm=oldms;savm=savms; */
 7596: /* 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
 7597: /* 	  for (h=0; h<=nhstepm; h++){ */
 7598: /* 	    if (h==(int) (calagedatem+YEARM*cpt)) { */
 7599: /* 	      fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
 7600: /* 	    }  */
 7601: /* 	    for(j=1; j<=nlstate+ndeath;j++) { */
 7602: /* 	      kk1=0.;kk2=0; */
 7603: /* 	      for(i=1; i<=nlstate;i++) {	       */
 7604: /* 		kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];	 */
 7605: /* 	      } */
 7606: /* 	      if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);	 */
 7607: /* 	    } */
 7608: /* 	  } */
 7609: /* 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
 7610: /* 	} */
 7611: /*       } */
 7612: /*     }  */
 7613: /*   } */
 7614:   
 7615: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
 7616:   
 7617: /*   if (popforecast==1) { */
 7618: /*     free_ivector(popage,0,AGESUP); */
 7619: /*     free_vector(popeffectif,0,AGESUP); */
 7620: /*     free_vector(popcount,0,AGESUP); */
 7621: /*   } */
 7622: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 7623: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 7624: /*   fclose(ficrespop); */
 7625: /* } /\* End of popforecast *\/ */
 7626:  
 7627: int fileappend(FILE *fichier, char *optionfich)
 7628: {
 7629:   if((fichier=fopen(optionfich,"a"))==NULL) {
 7630:     printf("Problem with file: %s\n", optionfich);
 7631:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
 7632:     return (0);
 7633:   }
 7634:   fflush(fichier);
 7635:   return (1);
 7636: }
 7637: 
 7638: 
 7639: /**************** function prwizard **********************/
 7640: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
 7641: {
 7642: 
 7643:   /* Wizard to print covariance matrix template */
 7644: 
 7645:   char ca[32], cb[32];
 7646:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
 7647:   int numlinepar;
 7648: 
 7649:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 7650:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 7651:   for(i=1; i <=nlstate; i++){
 7652:     jj=0;
 7653:     for(j=1; j <=nlstate+ndeath; j++){
 7654:       if(j==i) continue;
 7655:       jj++;
 7656:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
 7657:       printf("%1d%1d",i,j);
 7658:       fprintf(ficparo,"%1d%1d",i,j);
 7659:       for(k=1; k<=ncovmodel;k++){
 7660: 	/* 	  printf(" %lf",param[i][j][k]); */
 7661: 	/* 	  fprintf(ficparo," %lf",param[i][j][k]); */
 7662: 	printf(" 0.");
 7663: 	fprintf(ficparo," 0.");
 7664:       }
 7665:       printf("\n");
 7666:       fprintf(ficparo,"\n");
 7667:     }
 7668:   }
 7669:   printf("# Scales (for hessian or gradient estimation)\n");
 7670:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
 7671:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
 7672:   for(i=1; i <=nlstate; i++){
 7673:     jj=0;
 7674:     for(j=1; j <=nlstate+ndeath; j++){
 7675:       if(j==i) continue;
 7676:       jj++;
 7677:       fprintf(ficparo,"%1d%1d",i,j);
 7678:       printf("%1d%1d",i,j);
 7679:       fflush(stdout);
 7680:       for(k=1; k<=ncovmodel;k++){
 7681: 	/* 	printf(" %le",delti3[i][j][k]); */
 7682: 	/* 	fprintf(ficparo," %le",delti3[i][j][k]); */
 7683: 	printf(" 0.");
 7684: 	fprintf(ficparo," 0.");
 7685:       }
 7686:       numlinepar++;
 7687:       printf("\n");
 7688:       fprintf(ficparo,"\n");
 7689:     }
 7690:   }
 7691:   printf("# Covariance matrix\n");
 7692: /* # 121 Var(a12)\n\ */
 7693: /* # 122 Cov(b12,a12) Var(b12)\n\ */
 7694: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 7695: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 7696: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 7697: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 7698: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 7699: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 7700:   fflush(stdout);
 7701:   fprintf(ficparo,"# Covariance matrix\n");
 7702:   /* # 121 Var(a12)\n\ */
 7703:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
 7704:   /* #   ...\n\ */
 7705:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
 7706:   
 7707:   for(itimes=1;itimes<=2;itimes++){
 7708:     jj=0;
 7709:     for(i=1; i <=nlstate; i++){
 7710:       for(j=1; j <=nlstate+ndeath; j++){
 7711: 	if(j==i) continue;
 7712: 	for(k=1; k<=ncovmodel;k++){
 7713: 	  jj++;
 7714: 	  ca[0]= k+'a'-1;ca[1]='\0';
 7715: 	  if(itimes==1){
 7716: 	    printf("#%1d%1d%d",i,j,k);
 7717: 	    fprintf(ficparo,"#%1d%1d%d",i,j,k);
 7718: 	  }else{
 7719: 	    printf("%1d%1d%d",i,j,k);
 7720: 	    fprintf(ficparo,"%1d%1d%d",i,j,k);
 7721: 	    /* 	printf(" %.5le",matcov[i][j]); */
 7722: 	  }
 7723: 	  ll=0;
 7724: 	  for(li=1;li <=nlstate; li++){
 7725: 	    for(lj=1;lj <=nlstate+ndeath; lj++){
 7726: 	      if(lj==li) continue;
 7727: 	      for(lk=1;lk<=ncovmodel;lk++){
 7728: 		ll++;
 7729: 		if(ll<=jj){
 7730: 		  cb[0]= lk +'a'-1;cb[1]='\0';
 7731: 		  if(ll<jj){
 7732: 		    if(itimes==1){
 7733: 		      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 7734: 		      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 7735: 		    }else{
 7736: 		      printf(" 0.");
 7737: 		      fprintf(ficparo," 0.");
 7738: 		    }
 7739: 		  }else{
 7740: 		    if(itimes==1){
 7741: 		      printf(" Var(%s%1d%1d)",ca,i,j);
 7742: 		      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
 7743: 		    }else{
 7744: 		      printf(" 0.");
 7745: 		      fprintf(ficparo," 0.");
 7746: 		    }
 7747: 		  }
 7748: 		}
 7749: 	      } /* end lk */
 7750: 	    } /* end lj */
 7751: 	  } /* end li */
 7752: 	  printf("\n");
 7753: 	  fprintf(ficparo,"\n");
 7754: 	  numlinepar++;
 7755: 	} /* end k*/
 7756:       } /*end j */
 7757:     } /* end i */
 7758:   } /* end itimes */
 7759: 
 7760: } /* end of prwizard */
 7761: /******************* Gompertz Likelihood ******************************/
 7762: double gompertz(double x[])
 7763: { 
 7764:   double A,B,L=0.0,sump=0.,num=0.;
 7765:   int i,n=0; /* n is the size of the sample */
 7766: 
 7767:   for (i=1;i<=imx ; i++) {
 7768:     sump=sump+weight[i];
 7769:     /*    sump=sump+1;*/
 7770:     num=num+1;
 7771:   }
 7772:  
 7773:  
 7774:   /* for (i=0; i<=imx; i++) 
 7775:      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]);*/
 7776: 
 7777:   for (i=1;i<=imx ; i++)
 7778:     {
 7779:       if (cens[i] == 1 && wav[i]>1)
 7780: 	A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
 7781:       
 7782:       if (cens[i] == 0 && wav[i]>1)
 7783: 	A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
 7784: 	     +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
 7785:       
 7786:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 7787:       if (wav[i] > 1 ) { /* ??? */
 7788: 	L=L+A*weight[i];
 7789: 	/* 	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]);*/
 7790:       }
 7791:     }
 7792: 
 7793:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 7794:  
 7795:   return -2*L*num/sump;
 7796: }
 7797: 
 7798: #ifdef GSL
 7799: /******************* Gompertz_f Likelihood ******************************/
 7800: double gompertz_f(const gsl_vector *v, void *params)
 7801: { 
 7802:   double A,B,LL=0.0,sump=0.,num=0.;
 7803:   double *x= (double *) v->data;
 7804:   int i,n=0; /* n is the size of the sample */
 7805: 
 7806:   for (i=0;i<=imx-1 ; i++) {
 7807:     sump=sump+weight[i];
 7808:     /*    sump=sump+1;*/
 7809:     num=num+1;
 7810:   }
 7811:  
 7812:  
 7813:   /* for (i=0; i<=imx; i++) 
 7814:      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]);*/
 7815:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
 7816:   for (i=1;i<=imx ; i++)
 7817:     {
 7818:       if (cens[i] == 1 && wav[i]>1)
 7819: 	A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
 7820:       
 7821:       if (cens[i] == 0 && wav[i]>1)
 7822: 	A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
 7823: 	     +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
 7824:       
 7825:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 7826:       if (wav[i] > 1 ) { /* ??? */
 7827: 	LL=LL+A*weight[i];
 7828: 	/* 	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]);*/
 7829:       }
 7830:     }
 7831: 
 7832:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 7833:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
 7834:  
 7835:   return -2*LL*num/sump;
 7836: }
 7837: #endif
 7838: 
 7839: /******************* Printing html file ***********/
 7840: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
 7841: 		  int lastpass, int stepm, int weightopt, char model[],\
 7842: 		  int imx,  double p[],double **matcov,double agemortsup){
 7843:   int i,k;
 7844: 
 7845:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
 7846:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
 7847:   for (i=1;i<=2;i++) 
 7848:     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]));
 7849:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
 7850:   fprintf(fichtm,"</ul>");
 7851: 
 7852: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
 7853: 
 7854:  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>");
 7855: 
 7856:  for (k=agegomp;k<(agemortsup-2);k++) 
 7857:    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]);
 7858: 
 7859:  
 7860:   fflush(fichtm);
 7861: }
 7862: 
 7863: /******************* Gnuplot file **************/
 7864: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 7865: 
 7866:   char dirfileres[132],optfileres[132];
 7867: 
 7868:   int ng;
 7869: 
 7870: 
 7871:   /*#ifdef windows */
 7872:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 7873:     /*#endif */
 7874: 
 7875: 
 7876:   strcpy(dirfileres,optionfilefiname);
 7877:   strcpy(optfileres,"vpl");
 7878:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
 7879:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
 7880:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
 7881:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
 7882:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
 7883: 
 7884: } 
 7885: 
 7886: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
 7887: {
 7888: 
 7889:   /*-------- data file ----------*/
 7890:   FILE *fic;
 7891:   char dummy[]="                         ";
 7892:   int i=0, j=0, n=0, iv=0, v;
 7893:   int lstra;
 7894:   int linei, month, year,iout;
 7895:   char line[MAXLINE], linetmp[MAXLINE];
 7896:   char stra[MAXLINE], strb[MAXLINE];
 7897:   char *stratrunc;
 7898: 
 7899:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
 7900:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
 7901: 
 7902:   for(v=1; v <=ncovcol;v++){
 7903:     DummyV[v]=0;
 7904:     FixedV[v]=0;
 7905:   }
 7906:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
 7907:     DummyV[v]=1;
 7908:     FixedV[v]=0;
 7909:   }
 7910:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
 7911:     DummyV[v]=0;
 7912:     FixedV[v]=1;
 7913:   }
 7914:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
 7915:     DummyV[v]=1;
 7916:     FixedV[v]=1;
 7917:   }
 7918:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
 7919:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
 7920:     fprintf(ficlog,"Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
 7921:   }
 7922: 
 7923:   if((fic=fopen(datafile,"r"))==NULL)    {
 7924:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
 7925:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
 7926:   }
 7927: 
 7928:   i=1;
 7929:   linei=0;
 7930:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
 7931:     linei=linei+1;
 7932:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
 7933:       if(line[j] == '\t')
 7934: 	line[j] = ' ';
 7935:     }
 7936:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
 7937:       ;
 7938:     };
 7939:     line[j+1]=0;  /* Trims blanks at end of line */
 7940:     if(line[0]=='#'){
 7941:       fprintf(ficlog,"Comment line\n%s\n",line);
 7942:       printf("Comment line\n%s\n",line);
 7943:       continue;
 7944:     }
 7945:     trimbb(linetmp,line); /* Trims multiple blanks in line */
 7946:     strcpy(line, linetmp);
 7947:     
 7948:     /* Loops on waves */
 7949:     for (j=maxwav;j>=1;j--){
 7950:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
 7951: 	cutv(stra, strb, line, ' '); 
 7952: 	if(strb[0]=='.') { /* Missing value */
 7953: 	  lval=-1;
 7954: 	  cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
 7955: 	  cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
 7956: 	  if(isalpha(strb[1])) { /* .m or .d Really Missing value */
 7957: 	    printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value out of %d measured at wave %d. If missing, you should remove this individual or impute a value.  Exiting.\n", strb, linei,i,line,iv, nqtv, j);
 7958: 	    fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value out of %d measured at wave %d. If missing, you should remove this individual or impute a value.  Exiting.\n", strb, linei,i,line,iv, nqtv, j);fflush(ficlog);
 7959: 	    return 1;
 7960: 	  }
 7961: 	}else{
 7962: 	  errno=0;
 7963: 	  /* what_kind_of_number(strb); */
 7964: 	  dval=strtod(strb,&endptr); 
 7965: 	  /* if( strb[0]=='\0' || (*endptr != '\0')){ */
 7966: 	  /* if(strb != endptr && *endptr == '\0') */
 7967: 	  /*    dval=dlval; */
 7968: 	  /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
 7969: 	  if( strb[0]=='\0' || (*endptr != '\0')){
 7970: 	    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);
 7971: 	    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);
 7972: 	    return 1;
 7973: 	  }
 7974: 	  cotqvar[j][iv][i]=dval; 
 7975: 	  cotvar[j][ntv+iv][i]=dval; 
 7976: 	}
 7977: 	strcpy(line,stra);
 7978:       }/* end loop ntqv */
 7979:       
 7980:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
 7981: 	cutv(stra, strb, line, ' '); 
 7982: 	if(strb[0]=='.') { /* Missing value */
 7983: 	  lval=-1;
 7984: 	}else{
 7985: 	  errno=0;
 7986: 	  lval=strtol(strb,&endptr,10); 
 7987: 	  /*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
 7988: 	  if( strb[0]=='\0' || (*endptr != '\0')){
 7989: 	    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);
 7990: 	    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);
 7991: 	    return 1;
 7992: 	  }
 7993: 	}
 7994: 	if(lval <-1 || lval >1){
 7995: 	  printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 7996:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 7997:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 7998:  For example, for multinomial values like 1, 2 and 3,\n			\
 7999:  build V1=0 V2=0 for the reference value (1),\n				\
 8000:         V1=1 V2=0 for (2) \n						\
 8001:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 8002:  output of IMaCh is often meaningless.\n				\
 8003:  Exiting.\n",lval,linei, i,line,j);
 8004: 	  fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 8005:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 8006:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 8007:  For example, for multinomial values like 1, 2 and 3,\n			\
 8008:  build V1=0 V2=0 for the reference value (1),\n				\
 8009:         V1=1 V2=0 for (2) \n						\
 8010:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 8011:  output of IMaCh is often meaningless.\n				\
 8012:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
 8013: 	  return 1;
 8014: 	}
 8015: 	cotvar[j][iv][i]=(double)(lval);
 8016: 	strcpy(line,stra);
 8017:       }/* end loop ntv */
 8018:       
 8019:       /* Statuses  at wave */
 8020:       cutv(stra, strb, line, ' '); 
 8021:       if(strb[0]=='.') { /* Missing value */
 8022: 	lval=-1;
 8023:       }else{
 8024: 	errno=0;
 8025: 	lval=strtol(strb,&endptr,10); 
 8026: 	/*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
 8027: 	if( strb[0]=='\0' || (*endptr != '\0')){
 8028: 	  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);
 8029: 	  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);
 8030: 	  return 1;
 8031: 	}
 8032:       }
 8033:       
 8034:       s[j][i]=lval;
 8035:       
 8036:       /* Date of Interview */
 8037:       strcpy(line,stra);
 8038:       cutv(stra, strb,line,' ');
 8039:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 8040:       }
 8041:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 8042: 	month=99;
 8043: 	year=9999;
 8044:       }else{
 8045: 	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);
 8046: 	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);
 8047: 	return 1;
 8048:       }
 8049:       anint[j][i]= (double) year; 
 8050:       mint[j][i]= (double)month; 
 8051:       strcpy(line,stra);
 8052:     } /* End loop on waves */
 8053:     
 8054:     /* Date of death */
 8055:     cutv(stra, strb,line,' '); 
 8056:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 8057:     }
 8058:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 8059:       month=99;
 8060:       year=9999;
 8061:     }else{
 8062:       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);
 8063:       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);
 8064:       return 1;
 8065:     }
 8066:     andc[i]=(double) year; 
 8067:     moisdc[i]=(double) month; 
 8068:     strcpy(line,stra);
 8069:     
 8070:     /* Date of birth */
 8071:     cutv(stra, strb,line,' '); 
 8072:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 8073:     }
 8074:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
 8075:       month=99;
 8076:       year=9999;
 8077:     }else{
 8078:       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);
 8079:       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);
 8080:       return 1;
 8081:     }
 8082:     if (year==9999) {
 8083:       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);
 8084:       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);
 8085:       return 1;
 8086:       
 8087:     }
 8088:     annais[i]=(double)(year);
 8089:     moisnais[i]=(double)(month); 
 8090:     strcpy(line,stra);
 8091:     
 8092:     /* Sample weight */
 8093:     cutv(stra, strb,line,' '); 
 8094:     errno=0;
 8095:     dval=strtod(strb,&endptr); 
 8096:     if( strb[0]=='\0' || (*endptr != '\0')){
 8097:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
 8098:       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);
 8099:       fflush(ficlog);
 8100:       return 1;
 8101:     }
 8102:     weight[i]=dval; 
 8103:     strcpy(line,stra);
 8104:     
 8105:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
 8106:       cutv(stra, strb, line, ' '); 
 8107:       if(strb[0]=='.') { /* Missing value */
 8108: 	lval=-1;
 8109:       }else{
 8110: 	errno=0;
 8111: 	/* what_kind_of_number(strb); */
 8112: 	dval=strtod(strb,&endptr);
 8113: 	/* if(strb != endptr && *endptr == '\0') */
 8114: 	/*   dval=dlval; */
 8115: 	/* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
 8116: 	if( strb[0]=='\0' || (*endptr != '\0')){
 8117: 	  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);
 8118: 	  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);
 8119: 	  return 1;
 8120: 	}
 8121: 	coqvar[iv][i]=dval; 
 8122: 	covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
 8123:       }
 8124:       strcpy(line,stra);
 8125:     }/* end loop nqv */
 8126:     
 8127:     /* Covariate values */
 8128:     for (j=ncovcol;j>=1;j--){
 8129:       cutv(stra, strb,line,' '); 
 8130:       if(strb[0]=='.') { /* Missing covariate value */
 8131: 	lval=-1;
 8132:       }else{
 8133: 	errno=0;
 8134: 	lval=strtol(strb,&endptr,10); 
 8135: 	if( strb[0]=='\0' || (*endptr != '\0')){
 8136: 	  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);
 8137: 	  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);
 8138: 	  return 1;
 8139: 	}
 8140:       }
 8141:       if(lval <-1 || lval >1){
 8142: 	printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 8143:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 8144:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 8145:  For example, for multinomial values like 1, 2 and 3,\n			\
 8146:  build V1=0 V2=0 for the reference value (1),\n				\
 8147:         V1=1 V2=0 for (2) \n						\
 8148:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 8149:  output of IMaCh is often meaningless.\n				\
 8150:  Exiting.\n",lval,linei, i,line,j);
 8151: 	fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 8152:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 8153:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 8154:  For example, for multinomial values like 1, 2 and 3,\n			\
 8155:  build V1=0 V2=0 for the reference value (1),\n				\
 8156:         V1=1 V2=0 for (2) \n						\
 8157:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 8158:  output of IMaCh is often meaningless.\n				\
 8159:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
 8160: 	return 1;
 8161:       }
 8162:       covar[j][i]=(double)(lval);
 8163:       strcpy(line,stra);
 8164:     }  
 8165:     lstra=strlen(stra);
 8166:     
 8167:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
 8168:       stratrunc = &(stra[lstra-9]);
 8169:       num[i]=atol(stratrunc);
 8170:     }
 8171:     else
 8172:       num[i]=atol(stra);
 8173:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
 8174:       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;}*/
 8175:     
 8176:     i=i+1;
 8177:   } /* End loop reading  data */
 8178:   
 8179:   *imax=i-1; /* Number of individuals */
 8180:   fclose(fic);
 8181:   
 8182:   return (0);
 8183:   /* endread: */
 8184:   printf("Exiting readdata: ");
 8185:   fclose(fic);
 8186:   return (1);
 8187: }
 8188: 
 8189: void removefirstspace(char **stri){/*, char stro[]) {*/
 8190:   char *p1 = *stri, *p2 = *stri;
 8191:   while (*p2 == ' ')
 8192:     p2++; 
 8193:   /* while ((*p1++ = *p2++) !=0) */
 8194:   /*   ; */
 8195:   /* do */
 8196:   /*   while (*p2 == ' ') */
 8197:   /*     p2++; */
 8198:   /* while (*p1++ == *p2++); */
 8199:   *stri=p2; 
 8200: }
 8201: 
 8202: int decoderesult ( char resultline[], int nres)
 8203: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
 8204: {
 8205:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
 8206:   char resultsav[MAXLINE];
 8207:   int resultmodel[MAXLINE];
 8208:   int modelresult[MAXLINE];
 8209:   char stra[80], strb[80], strc[80], strd[80],stre[80];
 8210: 
 8211:   removefirstspace(&resultline);
 8212:   printf("decoderesult:%s\n",resultline);
 8213: 
 8214:   if (strstr(resultline,"v") !=0){
 8215:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
 8216:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
 8217:     return 1;
 8218:   }
 8219:   trimbb(resultsav, resultline);
 8220:   if (strlen(resultsav) >1){
 8221:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
 8222:   }
 8223:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
 8224:     printf("ERROR: the number of variable in the resultline, %d, differs from the number of variable used in the model line, %d.\n",j, cptcovs);
 8225:     fprintf(ficlog,"ERROR: the number of variable in the resultline, %d, differs from the number of variable used in the model line, %d.\n",j, cptcovs);
 8226:   }
 8227:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
 8228:     if(nbocc(resultsav,'=') >1){
 8229:        cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' 
 8230: 				      resultsav= V4=1 V5=25.1 V3=0 strb=V3=0 stra= V4=1 V5=25.1 */
 8231:        cutl(strc,strd,strb,'=');  /* strb:V4=1 strc=1 strd=V4 */
 8232:     }else
 8233:       cutl(strc,strd,resultsav,'=');
 8234:     Tvalsel[k]=atof(strc); /* 1 */
 8235:     
 8236:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
 8237:     Tvarsel[k]=atoi(strc);
 8238:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
 8239:     /* cptcovsel++;     */
 8240:     if (nbocc(stra,'=') >0)
 8241:       strcpy(resultsav,stra); /* and analyzes it */
 8242:   }
 8243:   /* Checking for missing or useless values in comparison of current model needs */
 8244:   for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 8245:     if(Typevar[k1]==0){ /* Single covariate in model */
 8246:       match=0;
 8247:       for(k2=1; k2 <=j;k2++){/* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
 8248: 	if(Tvar[k1]==Tvarsel[k2]) {/* Tvar[1]=5 == Tvarsel[2]=5   */
 8249: 	  modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
 8250: 	  match=1;
 8251: 	  break;
 8252: 	}
 8253:       }
 8254:       if(match == 0){
 8255: 	printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
 8256:       }
 8257:     }
 8258:   }
 8259:   /* Checking for missing or useless values in comparison of current model needs */
 8260:   for(k2=1; k2 <=j;k2++){ /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
 8261:     match=0;
 8262:     for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 8263:       if(Typevar[k1]==0){ /* Single */
 8264: 	if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
 8265: 	  resultmodel[k1]=k2;  /* resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
 8266: 	  ++match;
 8267: 	}
 8268:       }
 8269:     }
 8270:     if(match == 0){
 8271:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
 8272:     }else if(match > 1){
 8273:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
 8274:     }
 8275:   }
 8276:       
 8277:   /* We need to deduce which combination number is chosen and save quantitative values */
 8278:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 8279:   /* result line V4=1 V5=25.1 V3=0  V2=8 V1=1 */
 8280:   /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
 8281:   /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
 8282:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
 8283:   /*    1 0 0 0 */
 8284:   /*    2 1 0 0 */
 8285:   /*    3 0 1 0 */ 
 8286:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 */
 8287:   /*    5 0 0 1 */
 8288:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 */
 8289:   /*    7 0 1 1 */
 8290:   /*    8 1 1 1 */
 8291:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
 8292:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
 8293:   /* V5*age V5 known which value for nres?  */
 8294:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
 8295:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* model line */
 8296:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
 8297:       k3= resultmodel[k1]; /* resultmodel[2(V4)] = 1=k3 */
 8298:       k2=(int)Tvarsel[k3]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
 8299:       k+=Tvalsel[k3]*pow(2,k4);  /*  Tvalsel[1]=1  */
 8300:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres][1]=1(V4=1)  Tresult[nres][2]=0(V3=0) */
 8301:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
 8302:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
 8303:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
 8304:       k4++;;
 8305:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
 8306:       k3q= resultmodel[k1]; /* resultmodel[2] = 1=k3 */
 8307:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
 8308:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
 8309:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
 8310:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
 8311:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
 8312:       k4q++;;
 8313:     }
 8314:   }
 8315:   
 8316:   TKresult[nres]=++k; /* Combination for the nresult and the model */
 8317:   return (0);
 8318: }
 8319: 
 8320: int decodemodel( char model[], int lastobs)
 8321:  /**< This routine decodes the model and returns:
 8322: 	* Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
 8323: 	* - nagesqr = 1 if age*age in the model, otherwise 0.
 8324: 	* - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
 8325: 	* - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
 8326: 	* - cptcovage number of covariates with age*products =2
 8327: 	* - cptcovs number of simple covariates
 8328: 	* - 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
 8329: 	*     which is a new column after the 9 (ncovcol) variables. 
 8330: 	* - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
 8331: 	* - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
 8332: 	*    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
 8333: 	* - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
 8334: 	*/
 8335: {
 8336:   int i, j, k, ks, v;
 8337:   int  j1, k1, k2, k3, k4;
 8338:   char modelsav[80];
 8339:   char stra[80], strb[80], strc[80], strd[80],stre[80];
 8340:   char *strpt;
 8341: 
 8342:   /*removespace(model);*/
 8343:   if (strlen(model) >1){ /* If there is at least 1 covariate */
 8344:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
 8345:     if (strstr(model,"AGE") !=0){
 8346:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
 8347:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
 8348:       return 1;
 8349:     }
 8350:     if (strstr(model,"v") !=0){
 8351:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
 8352:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
 8353:       return 1;
 8354:     }
 8355:     strcpy(modelsav,model); 
 8356:     if ((strpt=strstr(model,"age*age")) !=0){
 8357:       printf(" strpt=%s, model=%s\n",strpt, model);
 8358:       if(strpt != model){
 8359: 	printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
 8360:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
 8361:  corresponding column of parameters.\n",model);
 8362: 	fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
 8363:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
 8364:  corresponding column of parameters.\n",model); fflush(ficlog);
 8365: 	return 1;
 8366:       }
 8367:       nagesqr=1;
 8368:       if (strstr(model,"+age*age") !=0)
 8369: 	substrchaine(modelsav, model, "+age*age");
 8370:       else if (strstr(model,"age*age+") !=0)
 8371: 	substrchaine(modelsav, model, "age*age+");
 8372:       else 
 8373: 	substrchaine(modelsav, model, "age*age");
 8374:     }else
 8375:       nagesqr=0;
 8376:     if (strlen(modelsav) >1){
 8377:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
 8378:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
 8379:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
 8380:       cptcovt= j+1; /* Number of total covariates in the model, not including
 8381: 		     * cst, age and age*age 
 8382: 		     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
 8383:       /* including age products which are counted in cptcovage.
 8384:        * but the covariates which are products must be treated 
 8385:        * separately: ncovn=4- 2=2 (V1+V3). */
 8386:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
 8387:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
 8388:       
 8389:       
 8390:       /*   Design
 8391:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
 8392:        *  <          ncovcol=8                >
 8393:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
 8394:        *   k=  1    2      3       4     5       6      7        8
 8395:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
 8396:        *  covar[k,i], value of kth covariate if not including age for individual i:
 8397:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
 8398:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
 8399:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
 8400:        *  Tage[++cptcovage]=k
 8401:        *       if products, new covar are created after ncovcol with k1
 8402:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
 8403:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
 8404:        *  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
 8405:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
 8406:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
 8407:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
 8408:        *  <          ncovcol=8                >
 8409:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
 8410:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
 8411:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
 8412:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 8413:        * p Tprod[1]@2={                         6, 5}
 8414:        *p Tvard[1][1]@4= {7, 8, 5, 6}
 8415:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
 8416:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 8417:        *How to reorganize?
 8418:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
 8419:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 8420:        *       {2,   1,     4,      8,    5,      6,     3,       7}
 8421:        * Struct []
 8422:        */
 8423:       
 8424:       /* This loop fills the array Tvar from the string 'model'.*/
 8425:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
 8426:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
 8427:       /* 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
 8428:       /* 	k=3 V4 Tvar[k=3]= 4 (from V4) */
 8429:       /* 	k=2 V1 Tvar[k=2]= 1 (from V1) */
 8430:       /* 	k=1 Tvar[1]=2 (from V2) */
 8431:       /* 	k=5 Tvar[5] */
 8432:       /* for (k=1; k<=cptcovn;k++) { */
 8433:       /* 	cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 8434:       /* 	} */
 8435:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
 8436:       /*
 8437:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
 8438:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
 8439:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
 8440:       }
 8441:       cptcovage=0;
 8442:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
 8443: 	cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
 8444: 					 modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
 8445: 	if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
 8446: 	/*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
 8447: 	/*scanf("%d",i);*/
 8448: 	if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
 8449: 	  cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
 8450: 	  if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
 8451: 	    /* covar is not filled and then is empty */
 8452: 	    cptcovprod--;
 8453: 	    cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
 8454: 	    Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
 8455: 	    Typevar[k]=1;  /* 1 for age product */
 8456: 	    cptcovage++; /* Sums the number of covariates which include age as a product */
 8457: 	    Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
 8458: 	    /*printf("stre=%s ", stre);*/
 8459: 	  } else if (strcmp(strd,"age")==0) { /* or age*Vn */
 8460: 	    cptcovprod--;
 8461: 	    cutl(stre,strb,strc,'V');
 8462: 	    Tvar[k]=atoi(stre);
 8463: 	    Typevar[k]=1;  /* 1 for age product */
 8464: 	    cptcovage++;
 8465: 	    Tage[cptcovage]=k;
 8466: 	  } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
 8467: 	    /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
 8468: 	    cptcovn++;
 8469: 	    cptcovprodnoage++;k1++;
 8470: 	    cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
 8471: 	    Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
 8472: 						because this model-covariate is a construction we invent a new column
 8473: 						which is after existing variables ncovcol+nqv+ntv+nqtv + k1
 8474: 						If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
 8475: 						Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
 8476: 	    Typevar[k]=2;  /* 2 for double fixed dummy covariates */
 8477: 	    cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
 8478: 	    Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
 8479: 	    Tposprod[k]=k1; /* Tpsprod[3]=1, Tposprod[2]=5 */
 8480: 	    Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
 8481: 	    Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
 8482: 	    k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
 8483: 	    /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
 8484: 	    /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
 8485:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
 8486: 	    /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
 8487: 	    for (i=1; i<=lastobs;i++){
 8488: 	      /* Computes the new covariate which is a product of
 8489: 		 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
 8490: 	      covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
 8491: 	    }
 8492: 	  } /* End age is not in the model */
 8493: 	} /* End if model includes a product */
 8494: 	else { /* no more sum */
 8495: 	  /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
 8496: 	  /*  scanf("%d",i);*/
 8497: 	  cutl(strd,strc,strb,'V');
 8498: 	  ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
 8499: 	  cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
 8500: 	  Tvar[k]=atoi(strd);
 8501: 	  Typevar[k]=0;  /* 0 for simple covariates */
 8502: 	}
 8503: 	strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
 8504: 				/*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
 8505: 				  scanf("%d",i);*/
 8506:       } /* end of loop + on total covariates */
 8507:     } /* end if strlen(modelsave == 0) age*age might exist */
 8508:   } /* end if strlen(model == 0) */
 8509:   
 8510:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
 8511:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
 8512:   
 8513:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
 8514:      printf("cptcovprod=%d ", cptcovprod);
 8515:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
 8516:      scanf("%d ",i);*/
 8517: 
 8518: 
 8519: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
 8520:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
 8521: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
 8522:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
 8523:    k =           1    2   3     4       5       6      7      8        9
 8524:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
 8525:    Typevar[k]=   0    0   0     2       1       0      2      1        1
 8526:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
 8527:    Dummy[k]      1    0   0     0       3       1      1      2        3
 8528: 	  Tmodelind[combination of covar]=k;
 8529: */  
 8530: /* Dispatching between quantitative and time varying covariates */
 8531:   /* If Tvar[k] >ncovcol it is a product */
 8532:   /* Tvar[k] is the value n of Vn with n varying for 1 to nvcol, or p  Vp=Vn*Vm for product */
 8533: 	/* Computing effective variables, ie used by the model, that is from the cptcovt variables */
 8534:   printf("Model=%s\n\
 8535: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
 8536: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
 8537: Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product\n",model);
 8538:   fprintf(ficlog,"Model=%s\n\
 8539: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
 8540: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
 8541: Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product\n",model);
 8542:   for(k=1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
 8543:   for(k=1, ncovf=0, nsd=0, nsq=0, ncovv=0, ncova=0, ncoveff=0, nqfveff=0, ntveff=0, nqtveff=0;k<=cptcovt; k++){ /* or cptocvt */
 8544:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
 8545:       Fixed[k]= 0;
 8546:       Dummy[k]= 0;
 8547:       ncoveff++;
 8548:       ncovf++;
 8549:       nsd++;
 8550:       modell[k].maintype= FTYPE;
 8551:       TvarsD[nsd]=Tvar[k];
 8552:       TvarsDind[nsd]=k;
 8553:       TvarF[ncovf]=Tvar[k];
 8554:       TvarFind[ncovf]=k;
 8555:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 8556:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 8557:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
 8558:       Fixed[k]= 0;
 8559:       Dummy[k]= 0;
 8560:       ncoveff++;
 8561:       ncovf++;
 8562:       modell[k].maintype= FTYPE;
 8563:       TvarF[ncovf]=Tvar[k];
 8564:       TvarFind[ncovf]=k;
 8565:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 8566:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 8567:     }else if( Tvar[k] <=ncovcol+nqv && Typevar[k]==0){/* Remind that product Vn*Vm are added in k Only simple fixed quantitative variable */
 8568:       Fixed[k]= 0;
 8569:       Dummy[k]= 1;
 8570:       nqfveff++;
 8571:       modell[k].maintype= FTYPE;
 8572:       modell[k].subtype= FQ;
 8573:       nsq++;
 8574:       TvarsQ[nsq]=Tvar[k];
 8575:       TvarsQind[nsq]=k;
 8576:       ncovf++;
 8577:       TvarF[ncovf]=Tvar[k];
 8578:       TvarFind[ncovf]=k;
 8579:       TvarFQ[nqfveff]=Tvar[k]-ncovcol; /* TvarFQ[1]=V2-1=1st in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
 8580:       TvarFQind[nqfveff]=k; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
 8581:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
 8582:       Fixed[k]= 1;
 8583:       Dummy[k]= 0;
 8584:       ntveff++; /* Only simple time varying dummy variable */
 8585:       modell[k].maintype= VTYPE;
 8586:       modell[k].subtype= VD;
 8587:       nsd++;
 8588:       TvarsD[nsd]=Tvar[k];
 8589:       TvarsDind[nsd]=k;
 8590:       ncovv++; /* Only simple time varying variables */
 8591:       TvarV[ncovv]=Tvar[k];
 8592:       TvarVind[ncovv]=k; /* TvarVind[2]=2  TvarVind[3]=3 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Any time varying singele */
 8593:       TvarVD[ntveff]=Tvar[k]; /* TvarVD[1]=V4  TvarVD[2]=V3 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying dummy variable */
 8594:       TvarVDind[ntveff]=k; /* TvarVDind[1]=2 TvarVDind[2]=3 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying dummy variable */
 8595:       printf("Quasi Tmodelind[%d]=%d,Tvar[Tmodelind[%d]]=V%d, ncovcol=%d, nqv=%d,Tvar[k]- ncovcol-nqv=%d\n",ntveff,k,ntveff,Tvar[k], ncovcol, nqv,Tvar[k]- ncovcol-nqv);
 8596:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
 8597:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
 8598:       Fixed[k]= 1;
 8599:       Dummy[k]= 1;
 8600:       nqtveff++;
 8601:       modell[k].maintype= VTYPE;
 8602:       modell[k].subtype= VQ;
 8603:       ncovv++; /* Only simple time varying variables */
 8604:       nsq++;
 8605:       TvarsQ[nsq]=Tvar[k];
 8606:       TvarsQind[nsq]=k;
 8607:       TvarV[ncovv]=Tvar[k];
 8608:       TvarVind[ncovv]=k; /* TvarVind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Any time varying singele */
 8609:       TvarVQ[nqtveff]=Tvar[k]; /* TvarVQ[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying quantitative variable */
 8610:       TvarVQind[nqtveff]=k; /* TvarVQind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying quantitative variable */
 8611:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
 8612:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
 8613:       printf("Quasi TmodelQind[%d]=%d,Tvar[TmodelQind[%d]]=V%d, ncovcol=%d, nqv=%d, ntv=%d,Tvar[k]- ncovcol-nqv-ntv=%d\n",nqtveff,k,nqtveff,Tvar[k], ncovcol, nqv, ntv, Tvar[k]- ncovcol-nqv-ntv);
 8614:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
 8615:     }else if (Typevar[k] == 1) {  /* product with age */
 8616:       ncova++;
 8617:       TvarA[ncova]=Tvar[k];
 8618:       TvarAind[ncova]=k;
 8619:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
 8620:       	Fixed[k]= 2;
 8621:       	Dummy[k]= 2;
 8622:       	modell[k].maintype= ATYPE;
 8623:       	modell[k].subtype= APFD;
 8624:       	/* ncoveff++; */
 8625:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
 8626:       	Fixed[k]= 2;
 8627:       	Dummy[k]= 3;
 8628:       	modell[k].maintype= ATYPE;
 8629:       	modell[k].subtype= APFQ;		/*	Product age * fixed quantitative */
 8630:       	/* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
 8631:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
 8632:       	Fixed[k]= 3;
 8633:       	Dummy[k]= 2;
 8634:       	modell[k].maintype= ATYPE;
 8635:       	modell[k].subtype= APVD;		/*	Product age * varying dummy */
 8636:       	/* ntveff++; /\* Only simple time varying dummy variable *\/ */
 8637:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
 8638:       	Fixed[k]= 3;
 8639:       	Dummy[k]= 3;
 8640:       	modell[k].maintype= ATYPE;
 8641:       	modell[k].subtype= APVQ;		/*	Product age * varying quantitative */
 8642:       	/* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
 8643:       }
 8644:     }else if (Typevar[k] == 2) {  /* product without age */
 8645:       k1=Tposprod[k];
 8646:       if(Tvard[k1][1] <=ncovcol){
 8647:     	if(Tvard[k1][2] <=ncovcol){
 8648:     	  Fixed[k]= 1;
 8649:     	  Dummy[k]= 0;
 8650:     	  modell[k].maintype= FTYPE;
 8651:     	  modell[k].subtype= FPDD;		/*	Product fixed dummy * fixed dummy */
 8652:     	  ncovf++; /* Fixed variables without age */
 8653:     	  TvarF[ncovf]=Tvar[k];
 8654:     	  TvarFind[ncovf]=k;
 8655:     	}else if(Tvard[k1][2] <=ncovcol+nqv){
 8656:     	  Fixed[k]= 0;  /* or 2 ?*/
 8657:     	  Dummy[k]= 1;
 8658:     	  modell[k].maintype= FTYPE;
 8659:     	  modell[k].subtype= FPDQ;		/*	Product fixed dummy * fixed quantitative */
 8660:     	  ncovf++; /* Varying variables without age */
 8661:     	  TvarF[ncovf]=Tvar[k];
 8662:     	  TvarFind[ncovf]=k;
 8663:     	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
 8664:     	  Fixed[k]= 1;
 8665:     	  Dummy[k]= 0;
 8666:     	  modell[k].maintype= VTYPE;
 8667:     	  modell[k].subtype= VPDD;		/*	Product fixed dummy * varying dummy */
 8668:     	  ncovv++; /* Varying variables without age */
 8669:     	  TvarV[ncovv]=Tvar[k];
 8670:     	  TvarVind[ncovv]=k;
 8671:     	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
 8672:     	  Fixed[k]= 1;
 8673:     	  Dummy[k]= 1;
 8674:     	  modell[k].maintype= VTYPE;
 8675:     	  modell[k].subtype= VPDQ;		/*	Product fixed dummy * varying quantitative */
 8676:     	  ncovv++; /* Varying variables without age */
 8677:     	  TvarV[ncovv]=Tvar[k];
 8678:     	  TvarVind[ncovv]=k;
 8679:     	}
 8680:       }else if(Tvard[k1][1] <=ncovcol+nqv){
 8681:     	if(Tvard[k1][2] <=ncovcol){
 8682:     	  Fixed[k]= 0;  /* or 2 ?*/
 8683:     	  Dummy[k]= 1;
 8684:     	  modell[k].maintype= FTYPE;
 8685:     	  modell[k].subtype= FPDQ;		/*	Product fixed quantitative * fixed dummy */
 8686:     	  ncovf++; /* Fixed variables without age */
 8687:     	  TvarF[ncovf]=Tvar[k];
 8688:     	  TvarFind[ncovf]=k;
 8689:     	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
 8690:     	  Fixed[k]= 1;
 8691:     	  Dummy[k]= 1;
 8692:     	  modell[k].maintype= VTYPE;
 8693:     	  modell[k].subtype= VPDQ;		/*	Product fixed quantitative * varying dummy */
 8694:     	  ncovv++; /* Varying variables without age */
 8695:     	  TvarV[ncovv]=Tvar[k];
 8696:     	  TvarVind[ncovv]=k;
 8697:     	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
 8698:     	  Fixed[k]= 1;
 8699:     	  Dummy[k]= 1;
 8700:     	  modell[k].maintype= VTYPE;
 8701:     	  modell[k].subtype= VPQQ;		/*	Product fixed quantitative * varying quantitative */
 8702:     	  ncovv++; /* Varying variables without age */
 8703:     	  TvarV[ncovv]=Tvar[k];
 8704:     	  TvarVind[ncovv]=k;
 8705:     	  ncovv++; /* Varying variables without age */
 8706:     	  TvarV[ncovv]=Tvar[k];
 8707:     	  TvarVind[ncovv]=k;
 8708:     	}
 8709:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
 8710:     	if(Tvard[k1][2] <=ncovcol){
 8711:     	  Fixed[k]= 1;
 8712:     	  Dummy[k]= 1;
 8713:     	  modell[k].maintype= VTYPE;
 8714:     	  modell[k].subtype= VPDD;		/*	Product time varying dummy * fixed dummy */
 8715:     	  ncovv++; /* Varying variables without age */
 8716:     	  TvarV[ncovv]=Tvar[k];
 8717:     	  TvarVind[ncovv]=k;
 8718:     	}else if(Tvard[k1][2] <=ncovcol+nqv){
 8719:     	  Fixed[k]= 1;
 8720:     	  Dummy[k]= 1;
 8721:     	  modell[k].maintype= VTYPE;
 8722:     	  modell[k].subtype= VPDQ;		/*	Product time varying dummy * fixed quantitative */
 8723:     	  ncovv++; /* Varying variables without age */
 8724:     	  TvarV[ncovv]=Tvar[k];
 8725:     	  TvarVind[ncovv]=k;
 8726:     	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
 8727:     	  Fixed[k]= 1;
 8728:     	  Dummy[k]= 0;
 8729:     	  modell[k].maintype= VTYPE;
 8730:     	  modell[k].subtype= VPDD;		/*	Product time varying dummy * time varying dummy */
 8731:     	  ncovv++; /* Varying variables without age */
 8732:     	  TvarV[ncovv]=Tvar[k];
 8733:     	  TvarVind[ncovv]=k;
 8734:     	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
 8735:     	  Fixed[k]= 1;
 8736:     	  Dummy[k]= 1;
 8737:     	  modell[k].maintype= VTYPE;
 8738:     	  modell[k].subtype= VPDQ;		/*	Product time varying dummy * time varying quantitative */
 8739:     	  ncovv++; /* Varying variables without age */
 8740:     	  TvarV[ncovv]=Tvar[k];
 8741:     	  TvarVind[ncovv]=k;
 8742:     	}
 8743:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
 8744:     	if(Tvard[k1][2] <=ncovcol){
 8745:     	  Fixed[k]= 1;
 8746:     	  Dummy[k]= 1;
 8747:     	  modell[k].maintype= VTYPE;
 8748:     	  modell[k].subtype= VPDQ;		/*	Product time varying quantitative * fixed dummy */
 8749:     	  ncovv++; /* Varying variables without age */
 8750:     	  TvarV[ncovv]=Tvar[k];
 8751:     	  TvarVind[ncovv]=k;
 8752:     	}else if(Tvard[k1][2] <=ncovcol+nqv){
 8753:     	  Fixed[k]= 1;
 8754:     	  Dummy[k]= 1;
 8755:     	  modell[k].maintype= VTYPE;
 8756:     	  modell[k].subtype= VPQQ;		/*	Product time varying quantitative * fixed quantitative */
 8757:     	  ncovv++; /* Varying variables without age */
 8758:     	  TvarV[ncovv]=Tvar[k];
 8759:     	  TvarVind[ncovv]=k;
 8760:     	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
 8761:     	  Fixed[k]= 1;
 8762:     	  Dummy[k]= 1;
 8763:     	  modell[k].maintype= VTYPE;
 8764:     	  modell[k].subtype= VPDQ;		/*	Product time varying quantitative * time varying dummy */
 8765:     	  ncovv++; /* Varying variables without age */
 8766:     	  TvarV[ncovv]=Tvar[k];
 8767:     	  TvarVind[ncovv]=k;
 8768:     	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
 8769:     	  Fixed[k]= 1;
 8770:     	  Dummy[k]= 1;
 8771:     	  modell[k].maintype= VTYPE;
 8772:     	  modell[k].subtype= VPQQ;		/*	Product time varying quantitative * time varying quantitative */
 8773:     	  ncovv++; /* Varying variables without age */
 8774:     	  TvarV[ncovv]=Tvar[k];
 8775:     	  TvarVind[ncovv]=k;
 8776:     	}
 8777:       }else{
 8778:     	printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
 8779:     	fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
 8780:       } /*end k1*/
 8781:     }else{
 8782:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
 8783:       fprintf(ficlog,"Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
 8784:     }
 8785:     printf("Decodemodel, k=%d, Tvar[%d]=V%d,Typevar=%d, Fixed=%d, Dummy=%d\n",k, k,Tvar[k],Typevar[k],Fixed[k],Dummy[k]);
 8786:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
 8787:     fprintf(ficlog,"Decodemodel, k=%d, Tvar[%d]=V%d,Typevar=%d, Fixed=%d, Dummy=%d\n",k, k,Tvar[k],Typevar[k],Fixed[k],Dummy[k]);
 8788:   }
 8789:   /* Searching for doublons in the model */
 8790:   for(k1=1; k1<= cptcovt;k1++){
 8791:     for(k2=1; k2 <k1;k2++){
 8792:       if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){
 8793: 	if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
 8794: 	  if(Tvar[k1]==Tvar[k2]){
 8795: 	    printf("Error duplication in the model=%s at positions (+) %d and %d, Tvar[%d]=V%d, Tvar[%d]=V%d, Typevar=%d, Fixed=%d, Dummy=%d\n", model, k1,k2, k1, Tvar[k1], k2, Tvar[k2],Typevar[k1],Fixed[Tvar[k1]],Dummy[Tvar[k1]]);
 8796: 	    fprintf(ficlog,"Error duplication in the model=%s at positions (+) %d and %d, Tvar[%d]=V%d, Tvar[%d]=V%d, Typevar=%d, Fixed=%d, Dummy=%d\n", model, k1,k2, k1, Tvar[k1], k2, Tvar[k2],Typevar[k1],Fixed[Tvar[k1]],Dummy[Tvar[k1]]); fflush(ficlog);
 8797: 	    return(1);
 8798: 	  }
 8799: 	}else if (Typevar[k1] ==2){
 8800: 	  k3=Tposprod[k1];
 8801: 	  k4=Tposprod[k2];
 8802: 	  if( ((Tvard[k3][1]== Tvard[k4][1])&&(Tvard[k3][2]== Tvard[k4][2])) || ((Tvard[k3][1]== Tvard[k4][2])&&(Tvard[k3][2]== Tvard[k4][1])) ){
 8803: 	    printf("Error duplication in the model=%s at positions (+) %d and %d, V%d*V%d, Typevar=%d, Fixed=%d, Dummy=%d\n",model, k1,k2, Tvard[k3][1], Tvard[k3][2],Typevar[k1],Fixed[Tvar[k1]],Dummy[Tvar[k1]]);
 8804: 	    fprintf(ficlog,"Error duplication in the model=%s at positions (+) %d and %d, V%d*V%d, Typevar=%d, Fixed=%d, Dummy=%d\n",model, k1,k2, Tvard[k3][1], Tvard[k3][2],Typevar[k1],Fixed[Tvar[k1]],Dummy[Tvar[k1]]); fflush(ficlog);
 8805: 	    return(1);
 8806: 	  }
 8807: 	}
 8808:       }
 8809:     }
 8810:   }
 8811:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
 8812:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
 8813:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
 8814:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
 8815:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
 8816:   /*endread:*/
 8817:   printf("Exiting decodemodel: ");
 8818:   return (1);
 8819: }
 8820: 
 8821: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
 8822: {
 8823:   int i, m;
 8824:   int firstone=0;
 8825:   
 8826:   for (i=1; i<=imx; i++) {
 8827:     for(m=2; (m<= maxwav); m++) {
 8828:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
 8829: 	anint[m][i]=9999;
 8830: 	if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
 8831: 	  s[m][i]=-1;
 8832:       }
 8833:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
 8834: 	*nberr = *nberr + 1;
 8835: 	if(firstone == 0){
 8836: 	  firstone=1;
 8837: 	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);
 8838: 	}
 8839: 	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);
 8840: 	s[m][i]=-1;
 8841:       }
 8842:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
 8843: 	(*nberr)++;
 8844: 	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]); 
 8845: 	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]); 
 8846: 	s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
 8847:       }
 8848:     }
 8849:   }
 8850: 
 8851:   for (i=1; i<=imx; i++)  {
 8852:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
 8853:     for(m=firstpass; (m<= lastpass); m++){
 8854:       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 */
 8855: 	if (s[m][i] >= nlstate+1) {
 8856: 	  if(agedc[i]>0){
 8857: 	    if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
 8858: 	      agev[m][i]=agedc[i];
 8859: 	      /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
 8860: 	    }else {
 8861: 	      if ((int)andc[i]!=9999){
 8862: 		nbwarn++;
 8863: 		printf("Warning negative age at death: %ld line:%d\n",num[i],i);
 8864: 		fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
 8865: 		agev[m][i]=-1;
 8866: 	      }
 8867: 	    }
 8868: 	  } /* agedc > 0 */
 8869: 	} /* end if */
 8870: 	else if(s[m][i] !=9){ /* Standard case, age in fractional
 8871: 				 years but with the precision of a month */
 8872: 	  agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
 8873: 	  if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
 8874: 	    agev[m][i]=1;
 8875: 	  else if(agev[m][i] < *agemin){ 
 8876: 	    *agemin=agev[m][i];
 8877: 	    printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
 8878: 	  }
 8879: 	  else if(agev[m][i] >*agemax){
 8880: 	    *agemax=agev[m][i];
 8881: 	    /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
 8882: 	  }
 8883: 	  /*agev[m][i]=anint[m][i]-annais[i];*/
 8884: 	  /*	 agev[m][i] = age[i]+2*m;*/
 8885: 	} /* en if 9*/
 8886: 	else { /* =9 */
 8887: 	  /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
 8888: 	  agev[m][i]=1;
 8889: 	  s[m][i]=-1;
 8890: 	}
 8891:       }
 8892:       else if(s[m][i]==0) /*= 0 Unknown */
 8893: 	agev[m][i]=1;
 8894:       else{
 8895: 	printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
 8896: 	fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
 8897: 	agev[m][i]=0;
 8898:       }
 8899:     } /* End for lastpass */
 8900:   }
 8901:     
 8902:   for (i=1; i<=imx; i++)  {
 8903:     for(m=firstpass; (m<=lastpass); m++){
 8904:       if (s[m][i] > (nlstate+ndeath)) {
 8905: 	(*nberr)++;
 8906: 	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);	
 8907: 	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);	
 8908: 	return 1;
 8909:       }
 8910:     }
 8911:   }
 8912: 
 8913:   /*for (i=1; i<=imx; i++){
 8914:   for (m=firstpass; (m<lastpass); m++){
 8915:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
 8916: }
 8917: 
 8918: }*/
 8919: 
 8920: 
 8921:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
 8922:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
 8923: 
 8924:   return (0);
 8925:  /* endread:*/
 8926:     printf("Exiting calandcheckages: ");
 8927:     return (1);
 8928: }
 8929: 
 8930: #if defined(_MSC_VER)
 8931: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 8932: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 8933: //#include "stdafx.h"
 8934: //#include <stdio.h>
 8935: //#include <tchar.h>
 8936: //#include <windows.h>
 8937: //#include <iostream>
 8938: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
 8939: 
 8940: LPFN_ISWOW64PROCESS fnIsWow64Process;
 8941: 
 8942: BOOL IsWow64()
 8943: {
 8944: 	BOOL bIsWow64 = FALSE;
 8945: 
 8946: 	//typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
 8947: 	//  (HANDLE, PBOOL);
 8948: 
 8949: 	//LPFN_ISWOW64PROCESS fnIsWow64Process;
 8950: 
 8951: 	HMODULE module = GetModuleHandle(_T("kernel32"));
 8952: 	const char funcName[] = "IsWow64Process";
 8953: 	fnIsWow64Process = (LPFN_ISWOW64PROCESS)
 8954: 		GetProcAddress(module, funcName);
 8955: 
 8956: 	if (NULL != fnIsWow64Process)
 8957: 	{
 8958: 		if (!fnIsWow64Process(GetCurrentProcess(),
 8959: 			&bIsWow64))
 8960: 			//throw std::exception("Unknown error");
 8961: 			printf("Unknown error\n");
 8962: 	}
 8963: 	return bIsWow64 != FALSE;
 8964: }
 8965: #endif
 8966: 
 8967: void syscompilerinfo(int logged)
 8968:  {
 8969:    /* #include "syscompilerinfo.h"*/
 8970:    /* command line Intel compiler 32bit windows, XP compatible:*/
 8971:    /* /GS /W3 /Gy
 8972:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
 8973:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
 8974:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
 8975:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
 8976:    */ 
 8977:    /* 64 bits */
 8978:    /*
 8979:      /GS /W3 /Gy
 8980:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
 8981:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
 8982:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
 8983:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
 8984:    /* Optimization are useless and O3 is slower than O2 */
 8985:    /*
 8986:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
 8987:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
 8988:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
 8989:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
 8990:    */
 8991:    /* Link is */ /* /OUT:"visual studio
 8992:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
 8993:       /PDB:"visual studio
 8994:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
 8995:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
 8996:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
 8997:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
 8998:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
 8999:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
 9000:       uiAccess='false'"
 9001:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
 9002:       /NOLOGO /TLBID:1
 9003:    */
 9004: #if defined __INTEL_COMPILER
 9005: #if defined(__GNUC__)
 9006: 	struct utsname sysInfo;  /* For Intel on Linux and OS/X */
 9007: #endif
 9008: #elif defined(__GNUC__) 
 9009: #ifndef  __APPLE__
 9010: #include <gnu/libc-version.h>  /* Only on gnu */
 9011: #endif
 9012:    struct utsname sysInfo;
 9013:    int cross = CROSS;
 9014:    if (cross){
 9015: 	   printf("Cross-");
 9016: 	   if(logged) fprintf(ficlog, "Cross-");
 9017:    }
 9018: #endif
 9019: 
 9020: #include <stdint.h>
 9021: 
 9022:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
 9023: #if defined(__clang__)
 9024:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");	/* Clang/LLVM. ---------------------------------------------- */
 9025: #endif
 9026: #if defined(__ICC) || defined(__INTEL_COMPILER)
 9027:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
 9028: #endif
 9029: #if defined(__GNUC__) || defined(__GNUG__)
 9030:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
 9031: #endif
 9032: #if defined(__HP_cc) || defined(__HP_aCC)
 9033:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
 9034: #endif
 9035: #if defined(__IBMC__) || defined(__IBMCPP__)
 9036:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
 9037: #endif
 9038: #if defined(_MSC_VER)
 9039:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
 9040: #endif
 9041: #if defined(__PGI)
 9042:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
 9043: #endif
 9044: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
 9045:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
 9046: #endif
 9047:    printf(" for "); if (logged) fprintf(ficlog, " for ");
 9048:    
 9049: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
 9050: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
 9051:     // Windows (x64 and x86)
 9052:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
 9053: #elif __unix__ // all unices, not all compilers
 9054:     // Unix
 9055:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
 9056: #elif __linux__
 9057:     // linux
 9058:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
 9059: #elif __APPLE__
 9060:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
 9061:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
 9062: #endif
 9063: 
 9064: /*  __MINGW32__	  */
 9065: /*  __CYGWIN__	 */
 9066: /* __MINGW64__  */
 9067: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
 9068: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
 9069: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
 9070: /* _WIN64  // Defined for applications for Win64. */
 9071: /* _M_X64 // Defined for compilations that target x64 processors. */
 9072: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
 9073: 
 9074: #if UINTPTR_MAX == 0xffffffff
 9075:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
 9076: #elif UINTPTR_MAX == 0xffffffffffffffff
 9077:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
 9078: #else
 9079:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
 9080: #endif
 9081: 
 9082: #if defined(__GNUC__)
 9083: # if defined(__GNUC_PATCHLEVEL__)
 9084: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 9085:                             + __GNUC_MINOR__ * 100 \
 9086:                             + __GNUC_PATCHLEVEL__)
 9087: # else
 9088: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 9089:                             + __GNUC_MINOR__ * 100)
 9090: # endif
 9091:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
 9092:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
 9093: 
 9094:    if (uname(&sysInfo) != -1) {
 9095:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 9096: 	 if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 9097:    }
 9098:    else
 9099:       perror("uname() error");
 9100:    //#ifndef __INTEL_COMPILER 
 9101: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
 9102:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
 9103:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
 9104: #endif
 9105: #endif
 9106: 
 9107:    //   void main()
 9108:    //   {
 9109: #if defined(_MSC_VER)
 9110:    if (IsWow64()){
 9111: 	   printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 9112: 	   if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 9113:    }
 9114:    else{
 9115: 	   printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 9116: 	   if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 9117:    }
 9118:    //	   printf("\nPress Enter to continue...");
 9119:    //	   getchar();
 9120:    //   }
 9121: 
 9122: #endif
 9123:    
 9124: 
 9125: }
 9126: 
 9127: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
 9128:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 9129:   int i, j, k, i1, k4=0, nres=0 ;
 9130:   /* double ftolpl = 1.e-10; */
 9131:   double age, agebase, agelim;
 9132:   double tot;
 9133: 
 9134:   strcpy(filerespl,"PL_");
 9135:   strcat(filerespl,fileresu);
 9136:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
 9137:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
 9138:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
 9139:   }
 9140:   printf("\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
 9141:   fprintf(ficlog,"\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
 9142:   pstamp(ficrespl);
 9143:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
 9144:   fprintf(ficrespl,"#Age ");
 9145:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
 9146:   fprintf(ficrespl,"\n");
 9147:   
 9148:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
 9149: 
 9150:   agebase=ageminpar;
 9151:   agelim=agemaxpar;
 9152: 
 9153:   /* i1=pow(2,ncoveff); */
 9154:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
 9155:   if (cptcovn < 1){i1=1;}
 9156: 
 9157:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
 9158:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 9159:       if(TKresult[nres]!= k)
 9160: 	continue;
 9161: 
 9162:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 9163:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
 9164:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 9165:       /* k=k+1; */
 9166:       /* to clean */
 9167:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
 9168:       fprintf(ficrespl,"#******");
 9169:       printf("#******");
 9170:       fprintf(ficlog,"#******");
 9171:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
 9172: 	fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
 9173: 	printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9174: 	fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9175:       }
 9176:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 9177: 	printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 9178: 	fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 9179: 	fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 9180:       }
 9181:       fprintf(ficrespl,"******\n");
 9182:       printf("******\n");
 9183:       fprintf(ficlog,"******\n");
 9184:       if(invalidvarcomb[k]){
 9185: 	printf("\nCombination (%d) ignored because no case \n",k); 
 9186: 	fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
 9187: 	fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
 9188: 	continue;
 9189:       }
 9190: 
 9191:       fprintf(ficrespl,"#Age ");
 9192:       for(j=1;j<=cptcoveff;j++) {
 9193: 	fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9194:       }
 9195:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
 9196:       fprintf(ficrespl,"Total Years_to_converge\n");
 9197:     
 9198:       for (age=agebase; age<=agelim; age++){
 9199: 	/* for (age=agebase; age<=agebase; age++){ */
 9200: 	prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
 9201: 	fprintf(ficrespl,"%.0f ",age );
 9202: 	for(j=1;j<=cptcoveff;j++)
 9203: 	  fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9204: 	tot=0.;
 9205: 	for(i=1; i<=nlstate;i++){
 9206: 	  tot +=  prlim[i][i];
 9207: 	  fprintf(ficrespl," %.5f", prlim[i][i]);
 9208: 	}
 9209: 	fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
 9210:       } /* Age */
 9211:       /* was end of cptcod */
 9212:     } /* cptcov */
 9213:   } /* nres */
 9214:   return 0;
 9215: }
 9216: 
 9217: 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){
 9218: 	/*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
 9219: 	
 9220: 	/* Computes the back prevalence limit  for any combination	of covariate values 
 9221:    * at any age between ageminpar and agemaxpar
 9222: 	 */
 9223:   int i, j, k, i1, nres=0 ;
 9224:   /* double ftolpl = 1.e-10; */
 9225:   double age, agebase, agelim;
 9226:   double tot;
 9227:   /* double ***mobaverage; */
 9228:   /* double	 **dnewm, **doldm, **dsavm;  /\* for use *\/ */
 9229: 
 9230:   strcpy(fileresplb,"PLB_");
 9231:   strcat(fileresplb,fileresu);
 9232:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
 9233:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
 9234:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
 9235:   }
 9236:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
 9237:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
 9238:   pstamp(ficresplb);
 9239:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
 9240:   fprintf(ficresplb,"#Age ");
 9241:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
 9242:   fprintf(ficresplb,"\n");
 9243:   
 9244:   
 9245:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
 9246:   
 9247:   agebase=ageminpar;
 9248:   agelim=agemaxpar;
 9249:   
 9250:   
 9251:   i1=pow(2,cptcoveff);
 9252:   if (cptcovn < 1){i1=1;}
 9253:   
 9254:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 9255:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
 9256:       if(TKresult[nres]!= k)
 9257: 	continue;
 9258:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
 9259:       fprintf(ficresplb,"#******");
 9260:       printf("#******");
 9261:       fprintf(ficlog,"#******");
 9262:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
 9263: 	fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9264: 	printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9265: 	fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9266:       }
 9267:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
 9268: 	printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
 9269: 	fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
 9270: 	fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
 9271:       }
 9272:       fprintf(ficresplb,"******\n");
 9273:       printf("******\n");
 9274:       fprintf(ficlog,"******\n");
 9275:       if(invalidvarcomb[k]){
 9276: 	printf("\nCombination (%d) ignored because no cases \n",k); 
 9277: 	fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
 9278: 	fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
 9279: 	continue;
 9280:       }
 9281:     
 9282:       fprintf(ficresplb,"#Age ");
 9283:       for(j=1;j<=cptcoveff;j++) {
 9284: 	fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9285:       }
 9286:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
 9287:       fprintf(ficresplb,"Total Years_to_converge\n");
 9288:     
 9289:     
 9290:       for (age=agebase; age<=agelim; age++){
 9291: 	/* for (age=agebase; age<=agebase; age++){ */
 9292: 	if(mobilavproj > 0){
 9293: 	  /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
 9294: 	  /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
 9295: 	  bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
 9296: 	}else if (mobilavproj == 0){
 9297: 	  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);
 9298: 	  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);
 9299: 	  exit(1);
 9300: 	}else{
 9301: 	  /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
 9302: 	  bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
 9303: 	}
 9304: 	fprintf(ficresplb,"%.0f ",age );
 9305: 	for(j=1;j<=cptcoveff;j++)
 9306: 	  fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9307: 	tot=0.;
 9308: 	for(i=1; i<=nlstate;i++){
 9309: 	  tot +=  bprlim[i][i];
 9310: 	  fprintf(ficresplb," %.5f", bprlim[i][i]);
 9311: 	}
 9312: 	fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
 9313:       } /* Age */
 9314:       /* was end of cptcod */
 9315:     } /* end of any combination */
 9316:   } /* end of nres */  
 9317:   /* hBijx(p, bage, fage); */
 9318:   /* fclose(ficrespijb); */
 9319:   
 9320:   return 0;
 9321: }
 9322:  
 9323: int hPijx(double *p, int bage, int fage){
 9324:     /*------------- h Pij x at various ages ------------*/
 9325: 
 9326:   int stepsize;
 9327:   int agelim;
 9328:   int hstepm;
 9329:   int nhstepm;
 9330:   int h, i, i1, j, k, k4, nres=0;
 9331: 
 9332:   double agedeb;
 9333:   double ***p3mat;
 9334: 
 9335:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
 9336:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
 9337:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
 9338:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
 9339:     }
 9340:     printf("Computing pij: result on file '%s' \n", filerespij);
 9341:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
 9342:   
 9343:     stepsize=(int) (stepm+YEARM-1)/YEARM;
 9344:     /*if (stepm<=24) stepsize=2;*/
 9345: 
 9346:     agelim=AGESUP;
 9347:     hstepm=stepsize*YEARM; /* Every year of age */
 9348:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
 9349: 		
 9350:     /* hstepm=1;   aff par mois*/
 9351:     pstamp(ficrespij);
 9352:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
 9353:     i1= pow(2,cptcoveff);
 9354: 		/* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 9355: 		/*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
 9356: 		/*  	k=k+1;  */
 9357:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
 9358:     for(k=1; k<=i1;k++){
 9359:       if(TKresult[nres]!= k)
 9360: 	continue;
 9361:       fprintf(ficrespij,"\n#****** ");
 9362:       for(j=1;j<=cptcoveff;j++) 
 9363: 	fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9364:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
 9365: 	printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 9366: 	fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
 9367:       }
 9368:       fprintf(ficrespij,"******\n");
 9369:       
 9370:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
 9371: 	nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 9372: 	nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 9373: 	
 9374: 	/*	  nhstepm=nhstepm*YEARM; aff par mois*/
 9375: 	
 9376: 	p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 9377: 	oldm=oldms;savm=savms;
 9378: 	hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
 9379: 	fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
 9380: 	for(i=1; i<=nlstate;i++)
 9381: 	  for(j=1; j<=nlstate+ndeath;j++)
 9382: 	    fprintf(ficrespij," %1d-%1d",i,j);
 9383: 	fprintf(ficrespij,"\n");
 9384: 	for (h=0; h<=nhstepm; h++){
 9385: 	  /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
 9386: 	  fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
 9387: 	  for(i=1; i<=nlstate;i++)
 9388: 	    for(j=1; j<=nlstate+ndeath;j++)
 9389: 	      fprintf(ficrespij," %.5f", p3mat[i][j][h]);
 9390: 	  fprintf(ficrespij,"\n");
 9391: 	}
 9392: 	free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 9393: 	fprintf(ficrespij,"\n");
 9394:       }
 9395:       /*}*/
 9396:     }
 9397:     return 0;
 9398: }
 9399:  
 9400:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
 9401:     /*------------- h Bij x at various ages ------------*/
 9402: 
 9403:   int stepsize;
 9404:   /* int agelim; */
 9405: 	int ageminl;
 9406:   int hstepm;
 9407:   int nhstepm;
 9408:   int h, i, i1, j, k, nres;
 9409: 	
 9410:   double agedeb;
 9411:   double ***p3mat;
 9412: 	
 9413:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
 9414:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
 9415:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
 9416:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
 9417:   }
 9418:   printf("Computing pij back: result on file '%s' \n", filerespijb);
 9419:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
 9420:   
 9421:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 9422:   /*if (stepm<=24) stepsize=2;*/
 9423:   
 9424:   /* agelim=AGESUP; */
 9425:   ageminl=30;
 9426:   hstepm=stepsize*YEARM; /* Every year of age */
 9427:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
 9428:   
 9429:   /* hstepm=1;   aff par mois*/
 9430:   pstamp(ficrespijb);
 9431:   fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
 9432:   i1= pow(2,cptcoveff);
 9433:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 9434:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
 9435:   /*  	k=k+1;  */
 9436:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 9437:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
 9438:       if(TKresult[nres]!= k)
 9439: 	continue;
 9440:       fprintf(ficrespijb,"\n#****** ");
 9441:       for(j=1;j<=cptcoveff;j++)
 9442: 	fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 9443:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
 9444: 	fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
 9445:       }
 9446:       fprintf(ficrespijb,"******\n");
 9447:       if(invalidvarcomb[k]){
 9448: 	fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
 9449: 	continue;
 9450:       }
 9451:       
 9452:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
 9453:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
 9454: 	/* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
 9455: 	nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
 9456: 	nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
 9457: 	
 9458: 	/*	  nhstepm=nhstepm*YEARM; aff par mois*/
 9459: 	
 9460: 	p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 9461: 	/* oldm=oldms;savm=savms; */
 9462: 	/* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
 9463: 	hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
 9464: 	/* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
 9465: 	fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
 9466: 	for(i=1; i<=nlstate;i++)
 9467: 	  for(j=1; j<=nlstate+ndeath;j++)
 9468: 	    fprintf(ficrespijb," %1d-%1d",i,j);
 9469: 	fprintf(ficrespijb,"\n");
 9470: 	for (h=0; h<=nhstepm; h++){
 9471: 	  /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
 9472: 	  fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
 9473: 	  /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
 9474: 	  for(i=1; i<=nlstate;i++)
 9475: 	    for(j=1; j<=nlstate+ndeath;j++)
 9476: 	      fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
 9477: 	  fprintf(ficrespijb,"\n");
 9478: 	}
 9479: 	free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 9480: 	fprintf(ficrespijb,"\n");
 9481:       } /* end age deb */
 9482:     } /* end combination */
 9483:   } /* end nres */
 9484:   return 0;
 9485:  } /*  hBijx */
 9486: 
 9487: 
 9488: /***********************************************/
 9489: /**************** Main Program *****************/
 9490: /***********************************************/
 9491: 
 9492: int main(int argc, char *argv[])
 9493: {
 9494: #ifdef GSL
 9495:   const gsl_multimin_fminimizer_type *T;
 9496:   size_t iteri = 0, it;
 9497:   int rval = GSL_CONTINUE;
 9498:   int status = GSL_SUCCESS;
 9499:   double ssval;
 9500: #endif
 9501:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
 9502:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
 9503:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
 9504:   int jj, ll, li, lj, lk;
 9505:   int numlinepar=0; /* Current linenumber of parameter file */
 9506:   int num_filled;
 9507:   int itimes;
 9508:   int NDIM=2;
 9509:   int vpopbased=0;
 9510:   int nres=0;
 9511: 
 9512:   char ca[32], cb[32];
 9513:   /*  FILE *fichtm; *//* Html File */
 9514:   /* FILE *ficgp;*/ /*Gnuplot File */
 9515:   struct stat info;
 9516:   double agedeb=0.;
 9517: 
 9518:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
 9519:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
 9520: 
 9521:   double fret;
 9522:   double dum=0.; /* Dummy variable */
 9523:   double ***p3mat;
 9524:   /* double ***mobaverage; */
 9525: 
 9526:   char line[MAXLINE];
 9527:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
 9528: 
 9529:   char  modeltemp[MAXLINE];
 9530:   char resultline[MAXLINE];
 9531:   
 9532:   char pathr[MAXLINE], pathimach[MAXLINE]; 
 9533:   char *tok, *val; /* pathtot */
 9534:   int firstobs=1, lastobs=10;
 9535:   int c,  h , cpt, c2;
 9536:   int jl=0;
 9537:   int i1, j1, jk, stepsize=0;
 9538:   int count=0;
 9539: 
 9540:   int *tab; 
 9541:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
 9542:   int backcast=0;
 9543:   int mobilav=0,popforecast=0;
 9544:   int hstepm=0, nhstepm=0;
 9545:   int agemortsup;
 9546:   float  sumlpop=0.;
 9547:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
 9548:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
 9549: 
 9550:   double bage=0, fage=110., age, agelim=0., agebase=0.;
 9551:   double ftolpl=FTOL;
 9552:   double **prlim;
 9553:   double **bprlim;
 9554:   double ***param; /* Matrix of parameters */
 9555:   double  *p;
 9556:   double **matcov; /* Matrix of covariance */
 9557:   double **hess; /* Hessian matrix */
 9558:   double ***delti3; /* Scale */
 9559:   double *delti; /* Scale */
 9560:   double ***eij, ***vareij;
 9561:   double **varpl; /* Variances of prevalence limits by age */
 9562:   double *epj, vepp;
 9563: 
 9564:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
 9565:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
 9566: 
 9567:   double **ximort;
 9568:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
 9569:   int *dcwave;
 9570: 
 9571:   char z[1]="c";
 9572: 
 9573:   /*char  *strt;*/
 9574:   char strtend[80];
 9575: 
 9576: 
 9577: /*   setlocale (LC_ALL, ""); */
 9578: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
 9579: /*   textdomain (PACKAGE); */
 9580: /*   setlocale (LC_CTYPE, ""); */
 9581: /*   setlocale (LC_MESSAGES, ""); */
 9582: 
 9583:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
 9584:   rstart_time = time(NULL);  
 9585:   /*  (void) gettimeofday(&start_time,&tzp);*/
 9586:   start_time = *localtime(&rstart_time);
 9587:   curr_time=start_time;
 9588:   /*tml = *localtime(&start_time.tm_sec);*/
 9589:   /* strcpy(strstart,asctime(&tml)); */
 9590:   strcpy(strstart,asctime(&start_time));
 9591: 
 9592: /*  printf("Localtime (at start)=%s",strstart); */
 9593: /*  tp.tm_sec = tp.tm_sec +86400; */
 9594: /*  tm = *localtime(&start_time.tm_sec); */
 9595: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
 9596: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
 9597: /*   tmg.tm_hour=tmg.tm_hour + 1; */
 9598: /*   tp.tm_sec = mktime(&tmg); */
 9599: /*   strt=asctime(&tmg); */
 9600: /*   printf("Time(after) =%s",strstart);  */
 9601: /*  (void) time (&time_value);
 9602: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
 9603: *  tm = *localtime(&time_value);
 9604: *  strstart=asctime(&tm);
 9605: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
 9606: */
 9607: 
 9608:   nberr=0; /* Number of errors and warnings */
 9609:   nbwarn=0;
 9610: #ifdef WIN32
 9611:   _getcwd(pathcd, size);
 9612: #else
 9613:   getcwd(pathcd, size);
 9614: #endif
 9615:   syscompilerinfo(0);
 9616:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
 9617:   if(argc <=1){
 9618:     printf("\nEnter the parameter file name: ");
 9619:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
 9620:       printf("ERROR Empty parameter file name\n");
 9621:       goto end;
 9622:     }
 9623:     i=strlen(pathr);
 9624:     if(pathr[i-1]=='\n')
 9625:       pathr[i-1]='\0';
 9626:     i=strlen(pathr);
 9627:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
 9628:       pathr[i-1]='\0';
 9629:     }
 9630:     i=strlen(pathr);
 9631:     if( i==0 ){
 9632:       printf("ERROR Empty parameter file name\n");
 9633:       goto end;
 9634:     }
 9635:     for (tok = pathr; tok != NULL; ){
 9636:       printf("Pathr |%s|\n",pathr);
 9637:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
 9638:       printf("val= |%s| pathr=%s\n",val,pathr);
 9639:       strcpy (pathtot, val);
 9640:       if(pathr[0] == '\0') break; /* Dirty */
 9641:     }
 9642:   }
 9643:   else{
 9644:     strcpy(pathtot,argv[1]);
 9645:   }
 9646:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
 9647:   /*cygwin_split_path(pathtot,path,optionfile);
 9648:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
 9649:   /* cutv(path,optionfile,pathtot,'\\');*/
 9650: 
 9651:   /* Split argv[0], imach program to get pathimach */
 9652:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
 9653:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 9654:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 9655:  /*   strcpy(pathimach,argv[0]); */
 9656:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
 9657:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
 9658:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
 9659: #ifdef WIN32
 9660:   _chdir(path); /* Can be a relative path */
 9661:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
 9662: #else
 9663:   chdir(path); /* Can be a relative path */
 9664:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
 9665: #endif
 9666:   printf("Current directory %s!\n",pathcd);
 9667:   strcpy(command,"mkdir ");
 9668:   strcat(command,optionfilefiname);
 9669:   if((outcmd=system(command)) != 0){
 9670:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
 9671:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
 9672:     /* fclose(ficlog); */
 9673: /*     exit(1); */
 9674:   }
 9675: /*   if((imk=mkdir(optionfilefiname))<0){ */
 9676: /*     perror("mkdir"); */
 9677: /*   } */
 9678: 
 9679:   /*-------- arguments in the command line --------*/
 9680: 
 9681:   /* Main Log file */
 9682:   strcat(filelog, optionfilefiname);
 9683:   strcat(filelog,".log");    /* */
 9684:   if((ficlog=fopen(filelog,"w"))==NULL)    {
 9685:     printf("Problem with logfile %s\n",filelog);
 9686:     goto end;
 9687:   }
 9688:   fprintf(ficlog,"Log filename:%s\n",filelog);
 9689:   fprintf(ficlog,"Version %s %s",version,fullversion);
 9690:   fprintf(ficlog,"\nEnter the parameter file name: \n");
 9691:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
 9692:  path=%s \n\
 9693:  optionfile=%s\n\
 9694:  optionfilext=%s\n\
 9695:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
 9696: 
 9697:   syscompilerinfo(1);
 9698: 
 9699:   printf("Local time (at start):%s",strstart);
 9700:   fprintf(ficlog,"Local time (at start): %s",strstart);
 9701:   fflush(ficlog);
 9702: /*   (void) gettimeofday(&curr_time,&tzp); */
 9703: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
 9704: 
 9705:   /* */
 9706:   strcpy(fileres,"r");
 9707:   strcat(fileres, optionfilefiname);
 9708:   strcat(fileresu, optionfilefiname); /* Without r in front */
 9709:   strcat(fileres,".txt");    /* Other files have txt extension */
 9710:   strcat(fileresu,".txt");    /* Other files have txt extension */
 9711: 
 9712:   /* Main ---------arguments file --------*/
 9713: 
 9714:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
 9715:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 9716:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 9717:     fflush(ficlog);
 9718:     /* goto end; */
 9719:     exit(70); 
 9720:   }
 9721: 
 9722: 
 9723: 
 9724:   strcpy(filereso,"o");
 9725:   strcat(filereso,fileresu);
 9726:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
 9727:     printf("Problem with Output resultfile: %s\n", filereso);
 9728:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
 9729:     fflush(ficlog);
 9730:     goto end;
 9731:   }
 9732: 
 9733:   /* Reads comments: lines beginning with '#' */
 9734:   numlinepar=0;
 9735: 
 9736:     /* First parameter line */
 9737:   while(fgets(line, MAXLINE, ficpar)) {
 9738:     /* If line starts with a # it is a comment */
 9739:     if (line[0] == '#') {
 9740:       numlinepar++;
 9741:       fputs(line,stdout);
 9742:       fputs(line,ficparo);
 9743:       fputs(line,ficlog);
 9744:       continue;
 9745:     }else
 9746:       break;
 9747:   }
 9748:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
 9749: 			title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
 9750:     if (num_filled != 5) {
 9751:       printf("Should be 5 parameters\n");
 9752:     }
 9753:     numlinepar++;
 9754:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
 9755:   }
 9756:   /* Second parameter line */
 9757:   while(fgets(line, MAXLINE, ficpar)) {
 9758:     /* If line starts with a # it is a comment */
 9759:     if (line[0] == '#') {
 9760:       numlinepar++;
 9761:       fputs(line,stdout);
 9762:       fputs(line,ficparo);
 9763:       fputs(line,ficlog);
 9764:       continue;
 9765:     }else
 9766:       break;
 9767:   }
 9768:   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", \
 9769: 			&ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
 9770:     if (num_filled != 11) {
 9771:       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");
 9772:       printf("but line=%s\n",line);
 9773:     }
 9774:     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);
 9775:   }
 9776:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
 9777:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
 9778:   /* Third parameter line */
 9779:   while(fgets(line, MAXLINE, ficpar)) {
 9780:     /* If line starts with a # it is a comment */
 9781:     if (line[0] == '#') {
 9782:       numlinepar++;
 9783:       fputs(line,stdout);
 9784:       fputs(line,ficparo);
 9785:       fputs(line,ficlog);
 9786:       continue;
 9787:     }else
 9788:       break;
 9789:   }
 9790:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
 9791:     if (num_filled == 0)
 9792:             model[0]='\0';
 9793:     else if (num_filled != 1){
 9794:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
 9795:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
 9796:       model[0]='\0';
 9797:       goto end;
 9798:     }
 9799:     else{
 9800:       if (model[0]=='+'){
 9801: 	for(i=1; i<=strlen(model);i++)
 9802: 	  modeltemp[i-1]=model[i];
 9803: 	strcpy(model,modeltemp); 
 9804:       }
 9805:     }
 9806:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
 9807:     printf("model=1+age+%s\n",model);fflush(stdout);
 9808:   }
 9809:   /* 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); */
 9810:   /* numlinepar=numlinepar+3; /\* In general *\/ */
 9811:   /* 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); */
 9812:   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);
 9813:   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);
 9814:   fflush(ficlog);
 9815:   /* if(model[0]=='#'|| model[0]== '\0'){ */
 9816:   if(model[0]=='#'){
 9817:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
 9818:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
 9819:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");		\
 9820:     if(mle != -1){
 9821:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
 9822:       exit(1);
 9823:     }
 9824:   }
 9825:   while((c=getc(ficpar))=='#' && c!= EOF){
 9826:     ungetc(c,ficpar);
 9827:     fgets(line, MAXLINE, ficpar);
 9828:     numlinepar++;
 9829:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
 9830:       z[0]=line[1];
 9831:     }
 9832:     /* printf("****line [1] = %c \n",line[1]); */
 9833:     fputs(line, stdout);
 9834:     //puts(line);
 9835:     fputs(line,ficparo);
 9836:     fputs(line,ficlog);
 9837:   }
 9838:   ungetc(c,ficpar);
 9839: 
 9840:    
 9841:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
 9842:   coqvar=matrix(1,nqv,1,n);  /**< Fixed quantitative covariate */
 9843:   cotvar=ma3x(1,maxwav,1,ntv+nqtv,1,n);  /**< Time varying covariate (dummy and quantitative)*/
 9844:   cotqvar=ma3x(1,maxwav,1,nqtv,1,n);  /**< Time varying quantitative covariate */
 9845:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
 9846:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
 9847:      v1+v2*age+v2*v3 makes cptcovn = 3
 9848:   */
 9849:   if (strlen(model)>1) 
 9850:     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*/
 9851:   else
 9852:     ncovmodel=2; /* Constant and age */
 9853:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
 9854:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
 9855:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
 9856:     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);
 9857:     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);
 9858:     fflush(stdout);
 9859:     fclose (ficlog);
 9860:     goto end;
 9861:   }
 9862:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 9863:   delti=delti3[1][1];
 9864:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
 9865:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
 9866:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 9867:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 9868:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 9869:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 9870:     fclose (ficparo);
 9871:     fclose (ficlog);
 9872:     goto end;
 9873:     exit(0);
 9874:   }  else if(mle==-5) { /* Main Wizard */
 9875:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 9876:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 9877:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 9878:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 9879:     matcov=matrix(1,npar,1,npar);
 9880:     hess=matrix(1,npar,1,npar);
 9881:   }  else{ /* Begin of mle != -1 or -5 */
 9882:     /* Read guessed parameters */
 9883:     /* Reads comments: lines beginning with '#' */
 9884:     while((c=getc(ficpar))=='#' && c!= EOF){
 9885:       ungetc(c,ficpar);
 9886:       fgets(line, MAXLINE, ficpar);
 9887:       numlinepar++;
 9888:       fputs(line,stdout);
 9889:       fputs(line,ficparo);
 9890:       fputs(line,ficlog);
 9891:     }
 9892:     ungetc(c,ficpar);
 9893:     
 9894:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 9895:     for(i=1; i <=nlstate; i++){
 9896:       j=0;
 9897:       for(jj=1; jj <=nlstate+ndeath; jj++){
 9898: 	if(jj==i) continue;
 9899: 	j++;
 9900: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 9901: 	if ((i1 != i) || (j1 != jj)){
 9902: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
 9903: It might be a problem of design; if ncovcol and the model are correct\n \
 9904: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
 9905: 	  exit(1);
 9906: 	}
 9907: 	fprintf(ficparo,"%1d%1d",i1,j1);
 9908: 	if(mle==1)
 9909: 	  printf("%1d%1d",i,jj);
 9910: 	fprintf(ficlog,"%1d%1d",i,jj);
 9911: 	for(k=1; k<=ncovmodel;k++){
 9912: 	  fscanf(ficpar," %lf",&param[i][j][k]);
 9913: 	  if(mle==1){
 9914: 	    printf(" %lf",param[i][j][k]);
 9915: 	    fprintf(ficlog," %lf",param[i][j][k]);
 9916: 	  }
 9917: 	  else
 9918: 	    fprintf(ficlog," %lf",param[i][j][k]);
 9919: 	  fprintf(ficparo," %lf",param[i][j][k]);
 9920: 	}
 9921: 	fscanf(ficpar,"\n");
 9922: 	numlinepar++;
 9923: 	if(mle==1)
 9924: 	  printf("\n");
 9925: 	fprintf(ficlog,"\n");
 9926: 	fprintf(ficparo,"\n");
 9927:       }
 9928:     }  
 9929:     fflush(ficlog);
 9930:     
 9931:     /* Reads scales values */
 9932:     p=param[1][1];
 9933:     
 9934:     /* Reads comments: lines beginning with '#' */
 9935:     while((c=getc(ficpar))=='#' && c!= EOF){
 9936:       ungetc(c,ficpar);
 9937:       fgets(line, MAXLINE, ficpar);
 9938:       numlinepar++;
 9939:       fputs(line,stdout);
 9940:       fputs(line,ficparo);
 9941:       fputs(line,ficlog);
 9942:     }
 9943:     ungetc(c,ficpar);
 9944: 
 9945:     for(i=1; i <=nlstate; i++){
 9946:       for(j=1; j <=nlstate+ndeath-1; j++){
 9947: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 9948: 	if ( (i1-i) * (j1-j) != 0){
 9949: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
 9950: 	  exit(1);
 9951: 	}
 9952: 	printf("%1d%1d",i,j);
 9953: 	fprintf(ficparo,"%1d%1d",i1,j1);
 9954: 	fprintf(ficlog,"%1d%1d",i1,j1);
 9955: 	for(k=1; k<=ncovmodel;k++){
 9956: 	  fscanf(ficpar,"%le",&delti3[i][j][k]);
 9957: 	  printf(" %le",delti3[i][j][k]);
 9958: 	  fprintf(ficparo," %le",delti3[i][j][k]);
 9959: 	  fprintf(ficlog," %le",delti3[i][j][k]);
 9960: 	}
 9961: 	fscanf(ficpar,"\n");
 9962: 	numlinepar++;
 9963: 	printf("\n");
 9964: 	fprintf(ficparo,"\n");
 9965: 	fprintf(ficlog,"\n");
 9966:       }
 9967:     }
 9968:     fflush(ficlog);
 9969:     
 9970:     /* Reads covariance matrix */
 9971:     delti=delti3[1][1];
 9972: 		
 9973: 		
 9974:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
 9975: 		
 9976:     /* Reads comments: lines beginning with '#' */
 9977:     while((c=getc(ficpar))=='#' && c!= EOF){
 9978:       ungetc(c,ficpar);
 9979:       fgets(line, MAXLINE, ficpar);
 9980:       numlinepar++;
 9981:       fputs(line,stdout);
 9982:       fputs(line,ficparo);
 9983:       fputs(line,ficlog);
 9984:     }
 9985:     ungetc(c,ficpar);
 9986: 		
 9987:     matcov=matrix(1,npar,1,npar);
 9988:     hess=matrix(1,npar,1,npar);
 9989:     for(i=1; i <=npar; i++)
 9990:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
 9991: 		
 9992:     /* Scans npar lines */
 9993:     for(i=1; i <=npar; i++){
 9994:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
 9995:       if(count != 3){
 9996: 	printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
 9997: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
 9998: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
 9999: 	fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
10000: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
10001: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
10002: 	exit(1);
10003:       }else{
10004: 	if(mle==1)
10005: 	  printf("%1d%1d%d",i1,j1,jk);
10006:       }
10007:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
10008:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
10009:       for(j=1; j <=i; j++){
10010: 	fscanf(ficpar," %le",&matcov[i][j]);
10011: 	if(mle==1){
10012: 	  printf(" %.5le",matcov[i][j]);
10013: 	}
10014: 	fprintf(ficlog," %.5le",matcov[i][j]);
10015: 	fprintf(ficparo," %.5le",matcov[i][j]);
10016:       }
10017:       fscanf(ficpar,"\n");
10018:       numlinepar++;
10019:       if(mle==1)
10020: 				printf("\n");
10021:       fprintf(ficlog,"\n");
10022:       fprintf(ficparo,"\n");
10023:     }
10024:     /* End of read covariance matrix npar lines */
10025:     for(i=1; i <=npar; i++)
10026:       for(j=i+1;j<=npar;j++)
10027: 	matcov[i][j]=matcov[j][i];
10028:     
10029:     if(mle==1)
10030:       printf("\n");
10031:     fprintf(ficlog,"\n");
10032:     
10033:     fflush(ficlog);
10034:     
10035:     /*-------- Rewriting parameter file ----------*/
10036:     strcpy(rfileres,"r");    /* "Rparameterfile */
10037:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
10038:     strcat(rfileres,".");    /* */
10039:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
10040:     if((ficres =fopen(rfileres,"w"))==NULL) {
10041:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
10042:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
10043:     }
10044:     fprintf(ficres,"#%s\n",version);
10045:   }    /* End of mle != -3 */
10046:   
10047:   /*  Main data
10048:    */
10049:   n= lastobs;
10050:   num=lvector(1,n);
10051:   moisnais=vector(1,n);
10052:   annais=vector(1,n);
10053:   moisdc=vector(1,n);
10054:   andc=vector(1,n);
10055:   weight=vector(1,n);
10056:   agedc=vector(1,n);
10057:   cod=ivector(1,n);
10058:   for(i=1;i<=n;i++){
10059:     num[i]=0;
10060:     moisnais[i]=0;
10061:     annais[i]=0;
10062:     moisdc[i]=0;
10063:     andc[i]=0;
10064:     agedc[i]=0;
10065:     cod[i]=0;
10066:     weight[i]=1.0; /* Equal weights, 1 by default */
10067:   }
10068:   mint=matrix(1,maxwav,1,n);
10069:   anint=matrix(1,maxwav,1,n);
10070:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
10071:   tab=ivector(1,NCOVMAX);
10072:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
10073:   ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
10074: 
10075:   /* Reads data from file datafile */
10076:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
10077:     goto end;
10078: 
10079:   /* Calculation of the number of parameters from char model */
10080:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
10081: 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
10082: 	k=3 V4 Tvar[k=3]= 4 (from V4)
10083: 	k=2 V1 Tvar[k=2]= 1 (from V1)
10084: 	k=1 Tvar[1]=2 (from V2)
10085:   */
10086:   
10087:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
10088:   TvarsDind=ivector(1,NCOVMAX); /*  */
10089:   TvarsD=ivector(1,NCOVMAX); /*  */
10090:   TvarsQind=ivector(1,NCOVMAX); /*  */
10091:   TvarsQ=ivector(1,NCOVMAX); /*  */
10092:   TvarF=ivector(1,NCOVMAX); /*  */
10093:   TvarFind=ivector(1,NCOVMAX); /*  */
10094:   TvarV=ivector(1,NCOVMAX); /*  */
10095:   TvarVind=ivector(1,NCOVMAX); /*  */
10096:   TvarA=ivector(1,NCOVMAX); /*  */
10097:   TvarAind=ivector(1,NCOVMAX); /*  */
10098:   TvarFD=ivector(1,NCOVMAX); /*  */
10099:   TvarFDind=ivector(1,NCOVMAX); /*  */
10100:   TvarFQ=ivector(1,NCOVMAX); /*  */
10101:   TvarFQind=ivector(1,NCOVMAX); /*  */
10102:   TvarVD=ivector(1,NCOVMAX); /*  */
10103:   TvarVDind=ivector(1,NCOVMAX); /*  */
10104:   TvarVQ=ivector(1,NCOVMAX); /*  */
10105:   TvarVQind=ivector(1,NCOVMAX); /*  */
10106: 
10107:   Tvalsel=vector(1,NCOVMAX); /*  */
10108:   Tvarsel=ivector(1,NCOVMAX); /*  */
10109:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
10110:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
10111:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
10112:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
10113:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
10114:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
10115:   */
10116:   /* For model-covariate k tells which data-covariate to use but
10117:     because this model-covariate is a construction we invent a new column
10118:     ncovcol + k1
10119:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
10120:     Tvar[3=V1*V4]=4+1 etc */
10121:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
10122:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
10123:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
10124:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
10125:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
10126:   */
10127:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
10128:   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
10129: 			    * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
10130: 			    * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
10131:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
10132: 			 4 covariates (3 plus signs)
10133: 			 Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
10134: 		      */  
10135:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
10136: 				* individual dummy, fixed or varying:
10137: 				* Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
10138: 				* 3, 1, 0, 0, 0, 0, 0, 0},
10139: 				* model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
10140: 				* V1 df, V2 qf, V3 & V4 dv, V5 qv
10141: 				* Tmodelind[1]@9={9,0,3,2,}*/
10142:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
10143:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
10144: 				* individual quantitative, fixed or varying:
10145: 				* Tmodelqind[1]=1,Tvaraff[1]@9={4,
10146: 				* 3, 1, 0, 0, 0, 0, 0, 0},
10147: 				* model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
10148: /* Main decodemodel */
10149: 
10150: 
10151:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
10152:     goto end;
10153: 
10154:   if((double)(lastobs-imx)/(double)imx > 1.10){
10155:     nbwarn++;
10156:     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); 
10157:     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); 
10158:   }
10159:     /*  if(mle==1){*/
10160:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
10161:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
10162:   }
10163: 
10164:     /*-calculation of age at interview from date of interview and age at death -*/
10165:   agev=matrix(1,maxwav,1,imx);
10166: 
10167:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
10168:     goto end;
10169: 
10170: 
10171:   agegomp=(int)agemin;
10172:   free_vector(moisnais,1,n);
10173:   free_vector(annais,1,n);
10174:   /* free_matrix(mint,1,maxwav,1,n);
10175:      free_matrix(anint,1,maxwav,1,n);*/
10176:   /* free_vector(moisdc,1,n); */
10177:   /* free_vector(andc,1,n); */
10178:   /* */
10179:   
10180:   wav=ivector(1,imx);
10181:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
10182:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
10183:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
10184:   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.*/
10185:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
10186:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
10187:    
10188:   /* Concatenates waves */
10189:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
10190:      Death is a valid wave (if date is known).
10191:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
10192:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
10193:      and mw[mi+1][i]. dh depends on stepm.
10194:   */
10195: 
10196:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
10197:   /* */
10198:  
10199:   free_vector(moisdc,1,n);
10200:   free_vector(andc,1,n);
10201: 
10202:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
10203:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
10204:   ncodemax[1]=1;
10205:   Ndum =ivector(-1,NCOVMAX);  
10206:   cptcoveff=0;
10207:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
10208:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
10209:   }
10210:   
10211:   ncovcombmax=pow(2,cptcoveff);
10212:   invalidvarcomb=ivector(1, ncovcombmax); 
10213:   for(i=1;i<ncovcombmax;i++)
10214:     invalidvarcomb[i]=0;
10215:   
10216:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
10217:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
10218:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
10219:   
10220:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
10221:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
10222:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
10223:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
10224:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
10225:    * (currently 0 or 1) in the data.
10226:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
10227:    * corresponding modality (h,j).
10228:    */
10229: 
10230:   h=0;
10231:   /*if (cptcovn > 0) */
10232:   m=pow(2,cptcoveff);
10233:  
10234: 	  /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
10235: 	   * For k=4 covariates, h goes from 1 to m=2**k
10236: 	   * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
10237:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
10238: 	   *     h\k   1     2     3     4
10239: 	   *______________________________  
10240: 	   *     1 i=1 1 i=1 1 i=1 1 i=1 1
10241: 	   *     2     2     1     1     1
10242: 	   *     3 i=2 1     2     1     1
10243: 	   *     4     2     2     1     1
10244: 	   *     5 i=3 1 i=2 1     2     1
10245: 	   *     6     2     1     2     1
10246: 	   *     7 i=4 1     2     2     1
10247: 	   *     8     2     2     2     1
10248: 	   *     9 i=5 1 i=3 1 i=2 1     2
10249: 	   *    10     2     1     1     2
10250: 	   *    11 i=6 1     2     1     2
10251: 	   *    12     2     2     1     2
10252: 	   *    13 i=7 1 i=4 1     2     2    
10253: 	   *    14     2     1     2     2
10254: 	   *    15 i=8 1     2     2     2
10255: 	   *    16     2     2     2     2
10256: 	   */
10257:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
10258:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
10259:      * and the value of each covariate?
10260:      * V1=1, V2=1, V3=2, V4=1 ?
10261:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
10262:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
10263:      * In order to get the real value in the data, we use nbcode
10264:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
10265:      * We are keeping this crazy system in order to be able (in the future?) 
10266:      * to have more than 2 values (0 or 1) for a covariate.
10267:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
10268:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
10269:      *              bbbbbbbb
10270:      *              76543210     
10271:      *   h-1        00000101 (6-1=5)
10272:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
10273:      *           &
10274:      *     1        00000001 (1)
10275:      *              00000000        = 1 & ((h-1) >> (k-1))
10276:      *          +1= 00000001 =1 
10277:      *
10278:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
10279:      *          h'      1101 =2^3+2^2+0x2^1+2^0
10280:      *    >>k'            11
10281:      *          &   00000001
10282:      *            = 00000001
10283:      *      +1    = 00000010=2    =  codtabm(14,3)   
10284:      * Reverse h=6 and m=16?
10285:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
10286:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
10287:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
10288:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
10289:      * V3=decodtabm(14,3,2**4)=2
10290:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
10291:      *(h-1) >> (j-1)    0011 =13 >> 2
10292:      *          &1 000000001
10293:      *           = 000000001
10294:      *         +1= 000000010 =2
10295:      *                  2211
10296:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
10297:      *                  V3=2
10298: 		 * codtabm and decodtabm are identical
10299:      */
10300: 
10301: 
10302:  free_ivector(Ndum,-1,NCOVMAX);
10303: 
10304: 
10305:     
10306:   /* Initialisation of ----------- gnuplot -------------*/
10307:   strcpy(optionfilegnuplot,optionfilefiname);
10308:   if(mle==-3)
10309:     strcat(optionfilegnuplot,"-MORT_");
10310:   strcat(optionfilegnuplot,".gp");
10311: 
10312:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
10313:     printf("Problem with file %s",optionfilegnuplot);
10314:   }
10315:   else{
10316:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
10317:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
10318:     //fprintf(ficgp,"set missing 'NaNq'\n");
10319:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
10320:   }
10321:   /*  fclose(ficgp);*/
10322: 
10323: 
10324:   /* Initialisation of --------- index.htm --------*/
10325: 
10326:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
10327:   if(mle==-3)
10328:     strcat(optionfilehtm,"-MORT_");
10329:   strcat(optionfilehtm,".htm");
10330:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
10331:     printf("Problem with %s \n",optionfilehtm);
10332:     exit(0);
10333:   }
10334: 
10335:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
10336:   strcat(optionfilehtmcov,"-cov.htm");
10337:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
10338:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
10339:   }
10340:   else{
10341:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
10342: <hr size=\"2\" color=\"#EC5E5E\"> \n\
10343: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
10344: 	  optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
10345:   }
10346: 
10347:   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>  \
10348: <hr size=\"2\" color=\"#EC5E5E\"> \n\
10349: <font size=\"2\">IMaCh-%s <br> %s</font> \
10350: <hr size=\"2\" color=\"#EC5E5E\"> \n\
10351: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
10352: \n\
10353: <hr  size=\"2\" color=\"#EC5E5E\">\
10354:  <ul><li><h4>Parameter files</h4>\n\
10355:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
10356:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
10357:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
10358:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
10359:  - Date and time at start: %s</ul>\n",\
10360: 	  optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
10361: 	  optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
10362: 	  fileres,fileres,\
10363: 	  filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
10364:   fflush(fichtm);
10365: 
10366:   strcpy(pathr,path);
10367:   strcat(pathr,optionfilefiname);
10368: #ifdef WIN32
10369:   _chdir(optionfilefiname); /* Move to directory named optionfile */
10370: #else
10371:   chdir(optionfilefiname); /* Move to directory named optionfile */
10372: #endif
10373: 	  
10374:   
10375:   /* Calculates basic frequencies. Computes observed prevalence at single age 
10376: 		 and for any valid combination of covariates
10377:      and prints on file fileres'p'. */
10378:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
10379: 	      firstpass, lastpass,  stepm,  weightopt, model);
10380: 
10381:   fprintf(fichtm,"\n");
10382:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
10383: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
10384: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
10385: 	  imx,agemin,agemax,jmin,jmax,jmean);
10386:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
10387: 	oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
10388: 	newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
10389: 	savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
10390: 	oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
10391: 
10392:   /* For Powell, parameters are in a vector p[] starting at p[1]
10393:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
10394:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
10395: 
10396:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
10397:   /* For mortality only */
10398:   if (mle==-3){
10399:     ximort=matrix(1,NDIM,1,NDIM); 
10400: 		for(i=1;i<=NDIM;i++)
10401: 			for(j=1;j<=NDIM;j++)
10402: 				ximort[i][j]=0.;
10403:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
10404:     cens=ivector(1,n);
10405:     ageexmed=vector(1,n);
10406:     agecens=vector(1,n);
10407:     dcwave=ivector(1,n);
10408: 		
10409:     for (i=1; i<=imx; i++){
10410:       dcwave[i]=-1;
10411:       for (m=firstpass; m<=lastpass; m++)
10412: 	if (s[m][i]>nlstate) {
10413: 	  dcwave[i]=m;
10414: 	  /*	printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
10415: 	  break;
10416: 	}
10417:     }
10418:     
10419:     for (i=1; i<=imx; i++) {
10420:       if (wav[i]>0){
10421: 	ageexmed[i]=agev[mw[1][i]][i];
10422: 	j=wav[i];
10423: 	agecens[i]=1.; 
10424: 	
10425: 	if (ageexmed[i]> 1 && wav[i] > 0){
10426: 	  agecens[i]=agev[mw[j][i]][i];
10427: 	  cens[i]= 1;
10428: 	}else if (ageexmed[i]< 1) 
10429: 	  cens[i]= -1;
10430: 	if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
10431: 	  cens[i]=0 ;
10432:       }
10433:       else cens[i]=-1;
10434:     }
10435:     
10436:     for (i=1;i<=NDIM;i++) {
10437:       for (j=1;j<=NDIM;j++)
10438: 	ximort[i][j]=(i == j ? 1.0 : 0.0);
10439:     }
10440:     
10441:     /*p[1]=0.0268; p[NDIM]=0.083;*/
10442:     /*printf("%lf %lf", p[1], p[2]);*/
10443:     
10444:     
10445: #ifdef GSL
10446:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
10447: #else
10448:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
10449: #endif
10450:     strcpy(filerespow,"POW-MORT_"); 
10451:     strcat(filerespow,fileresu);
10452:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
10453:       printf("Problem with resultfile: %s\n", filerespow);
10454:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
10455:     }
10456: #ifdef GSL
10457:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
10458: #else
10459:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
10460: #endif
10461:     /*  for (i=1;i<=nlstate;i++)
10462: 	for(j=1;j<=nlstate+ndeath;j++)
10463: 	if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
10464:     */
10465:     fprintf(ficrespow,"\n");
10466: #ifdef GSL
10467:     /* gsl starts here */ 
10468:     T = gsl_multimin_fminimizer_nmsimplex;
10469:     gsl_multimin_fminimizer *sfm = NULL;
10470:     gsl_vector *ss, *x;
10471:     gsl_multimin_function minex_func;
10472: 
10473:     /* Initial vertex size vector */
10474:     ss = gsl_vector_alloc (NDIM);
10475:     
10476:     if (ss == NULL){
10477:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
10478:     }
10479:     /* Set all step sizes to 1 */
10480:     gsl_vector_set_all (ss, 0.001);
10481: 
10482:     /* Starting point */
10483:     
10484:     x = gsl_vector_alloc (NDIM);
10485:     
10486:     if (x == NULL){
10487:       gsl_vector_free(ss);
10488:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
10489:     }
10490:   
10491:     /* Initialize method and iterate */
10492:     /*     p[1]=0.0268; p[NDIM]=0.083; */
10493:     /*     gsl_vector_set(x, 0, 0.0268); */
10494:     /*     gsl_vector_set(x, 1, 0.083); */
10495:     gsl_vector_set(x, 0, p[1]);
10496:     gsl_vector_set(x, 1, p[2]);
10497: 
10498:     minex_func.f = &gompertz_f;
10499:     minex_func.n = NDIM;
10500:     minex_func.params = (void *)&p; /* ??? */
10501:     
10502:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
10503:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
10504:     
10505:     printf("Iterations beginning .....\n\n");
10506:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
10507: 
10508:     iteri=0;
10509:     while (rval == GSL_CONTINUE){
10510:       iteri++;
10511:       status = gsl_multimin_fminimizer_iterate(sfm);
10512:       
10513:       if (status) printf("error: %s\n", gsl_strerror (status));
10514:       fflush(0);
10515:       
10516:       if (status) 
10517:         break;
10518:       
10519:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
10520:       ssval = gsl_multimin_fminimizer_size (sfm);
10521:       
10522:       if (rval == GSL_SUCCESS)
10523:         printf ("converged to a local maximum at\n");
10524:       
10525:       printf("%5d ", iteri);
10526:       for (it = 0; it < NDIM; it++){
10527: 	printf ("%10.5f ", gsl_vector_get (sfm->x, it));
10528:       }
10529:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
10530:     }
10531:     
10532:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
10533:     
10534:     gsl_vector_free(x); /* initial values */
10535:     gsl_vector_free(ss); /* inital step size */
10536:     for (it=0; it<NDIM; it++){
10537:       p[it+1]=gsl_vector_get(sfm->x,it);
10538:       fprintf(ficrespow," %.12lf", p[it]);
10539:     }
10540:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
10541: #endif
10542: #ifdef POWELL
10543:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
10544: #endif  
10545:     fclose(ficrespow);
10546:     
10547:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
10548: 
10549:     for(i=1; i <=NDIM; i++)
10550:       for(j=i+1;j<=NDIM;j++)
10551: 				matcov[i][j]=matcov[j][i];
10552:     
10553:     printf("\nCovariance matrix\n ");
10554:     fprintf(ficlog,"\nCovariance matrix\n ");
10555:     for(i=1; i <=NDIM; i++) {
10556:       for(j=1;j<=NDIM;j++){ 
10557: 				printf("%f ",matcov[i][j]);
10558: 				fprintf(ficlog,"%f ",matcov[i][j]);
10559:       }
10560:       printf("\n ");  fprintf(ficlog,"\n ");
10561:     }
10562:     
10563:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
10564:     for (i=1;i<=NDIM;i++) {
10565:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
10566:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
10567:     }
10568:     lsurv=vector(1,AGESUP);
10569:     lpop=vector(1,AGESUP);
10570:     tpop=vector(1,AGESUP);
10571:     lsurv[agegomp]=100000;
10572:     
10573:     for (k=agegomp;k<=AGESUP;k++) {
10574:       agemortsup=k;
10575:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
10576:     }
10577:     
10578:     for (k=agegomp;k<agemortsup;k++)
10579:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
10580:     
10581:     for (k=agegomp;k<agemortsup;k++){
10582:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
10583:       sumlpop=sumlpop+lpop[k];
10584:     }
10585:     
10586:     tpop[agegomp]=sumlpop;
10587:     for (k=agegomp;k<(agemortsup-3);k++){
10588:       /*  tpop[k+1]=2;*/
10589:       tpop[k+1]=tpop[k]-lpop[k];
10590:     }
10591:     
10592:     
10593:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
10594:     for (k=agegomp;k<(agemortsup-2);k++) 
10595:       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]);
10596:     
10597:     
10598:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
10599: 		ageminpar=50;
10600: 		agemaxpar=100;
10601:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
10602:       	printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
10603: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
10604: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
10605:       	fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
10606: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
10607: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
10608:     }else{
10609: 			printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
10610: 			fprintf(ficlog,"Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
10611:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
10612: 		}
10613:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
10614: 		     stepm, weightopt,\
10615: 		     model,imx,p,matcov,agemortsup);
10616:     
10617:     free_vector(lsurv,1,AGESUP);
10618:     free_vector(lpop,1,AGESUP);
10619:     free_vector(tpop,1,AGESUP);
10620:     free_matrix(ximort,1,NDIM,1,NDIM);
10621:     free_ivector(cens,1,n);
10622:     free_vector(agecens,1,n);
10623:     free_ivector(dcwave,1,n);
10624: #ifdef GSL
10625: #endif
10626:   } /* Endof if mle==-3 mortality only */
10627:   /* Standard  */
10628:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
10629:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
10630:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
10631:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
10632:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
10633:     for (k=1; k<=npar;k++)
10634:       printf(" %d %8.5f",k,p[k]);
10635:     printf("\n");
10636:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
10637:       /* mlikeli uses func not funcone */
10638:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
10639:     }
10640:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
10641:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
10642:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
10643:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
10644:     }
10645:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
10646:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
10647:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
10648:     for (k=1; k<=npar;k++)
10649:       printf(" %d %8.5f",k,p[k]);
10650:     printf("\n");
10651:     
10652:     /*--------- results files --------------*/
10653:     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);
10654:     
10655:     
10656:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
10657:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
10658:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
10659:     for(i=1,jk=1; i <=nlstate; i++){
10660:       for(k=1; k <=(nlstate+ndeath); k++){
10661: 	if (k != i) {
10662: 	  printf("%d%d ",i,k);
10663: 	  fprintf(ficlog,"%d%d ",i,k);
10664: 	  fprintf(ficres,"%1d%1d ",i,k);
10665: 	  for(j=1; j <=ncovmodel; j++){
10666: 	    printf("%12.7f ",p[jk]);
10667: 	    fprintf(ficlog,"%12.7f ",p[jk]);
10668: 	    fprintf(ficres,"%12.7f ",p[jk]);
10669: 	    jk++; 
10670: 	  }
10671: 	  printf("\n");
10672: 	  fprintf(ficlog,"\n");
10673: 	  fprintf(ficres,"\n");
10674: 	}
10675:       }
10676:     }
10677:     if(mle != 0){
10678:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
10679:       ftolhess=ftol; /* Usually correct */
10680:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
10681:       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");
10682:       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");
10683:       for(i=1,jk=1; i <=nlstate; i++){
10684: 	for(k=1; k <=(nlstate+ndeath); k++){
10685: 	  if (k != i) {
10686: 	    printf("%d%d ",i,k);
10687: 	    fprintf(ficlog,"%d%d ",i,k);
10688: 	    for(j=1; j <=ncovmodel; j++){
10689: 	      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]));
10690: 	      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]));
10691: 	      jk++; 
10692: 	    }
10693: 	    printf("\n");
10694: 	    fprintf(ficlog,"\n");
10695: 	  }
10696: 	}
10697:       }
10698:     } /* end of hesscov and Wald tests */
10699:     
10700:     /*  */
10701:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
10702:     printf("# Scales (for hessian or gradient estimation)\n");
10703:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
10704:     for(i=1,jk=1; i <=nlstate; i++){
10705:       for(j=1; j <=nlstate+ndeath; j++){
10706: 	if (j!=i) {
10707: 	  fprintf(ficres,"%1d%1d",i,j);
10708: 	  printf("%1d%1d",i,j);
10709: 	  fprintf(ficlog,"%1d%1d",i,j);
10710: 	  for(k=1; k<=ncovmodel;k++){
10711: 	    printf(" %.5e",delti[jk]);
10712: 	    fprintf(ficlog," %.5e",delti[jk]);
10713: 	    fprintf(ficres," %.5e",delti[jk]);
10714: 	    jk++;
10715: 	  }
10716: 	  printf("\n");
10717: 	  fprintf(ficlog,"\n");
10718: 	  fprintf(ficres,"\n");
10719: 	}
10720:       }
10721:     }
10722:     
10723:     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");
10724:     if(mle >= 1) /* To big for the screen */
10725:       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");
10726:     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");
10727:     /* # 121 Var(a12)\n\ */
10728:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
10729:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
10730:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
10731:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
10732:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
10733:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
10734:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
10735:     
10736:     
10737:     /* Just to have a covariance matrix which will be more understandable
10738:        even is we still don't want to manage dictionary of variables
10739:     */
10740:     for(itimes=1;itimes<=2;itimes++){
10741:       jj=0;
10742:       for(i=1; i <=nlstate; i++){
10743: 	for(j=1; j <=nlstate+ndeath; j++){
10744: 	  if(j==i) continue;
10745: 	  for(k=1; k<=ncovmodel;k++){
10746: 	    jj++;
10747: 	    ca[0]= k+'a'-1;ca[1]='\0';
10748: 	    if(itimes==1){
10749: 	      if(mle>=1)
10750: 		printf("#%1d%1d%d",i,j,k);
10751: 	      fprintf(ficlog,"#%1d%1d%d",i,j,k);
10752: 	      fprintf(ficres,"#%1d%1d%d",i,j,k);
10753: 	    }else{
10754: 	      if(mle>=1)
10755: 		printf("%1d%1d%d",i,j,k);
10756: 	      fprintf(ficlog,"%1d%1d%d",i,j,k);
10757: 	      fprintf(ficres,"%1d%1d%d",i,j,k);
10758: 	    }
10759: 	    ll=0;
10760: 	    for(li=1;li <=nlstate; li++){
10761: 	      for(lj=1;lj <=nlstate+ndeath; lj++){
10762: 		if(lj==li) continue;
10763: 		for(lk=1;lk<=ncovmodel;lk++){
10764: 		  ll++;
10765: 		  if(ll<=jj){
10766: 		    cb[0]= lk +'a'-1;cb[1]='\0';
10767: 		    if(ll<jj){
10768: 		      if(itimes==1){
10769: 			if(mle>=1)
10770: 			  printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
10771: 			fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
10772: 			fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
10773: 		      }else{
10774: 			if(mle>=1)
10775: 			  printf(" %.5e",matcov[jj][ll]); 
10776: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
10777: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
10778: 		      }
10779: 		    }else{
10780: 		      if(itimes==1){
10781: 			if(mle>=1)
10782: 			  printf(" Var(%s%1d%1d)",ca,i,j);
10783: 			fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
10784: 			fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
10785: 		      }else{
10786: 			if(mle>=1)
10787: 			  printf(" %.7e",matcov[jj][ll]); 
10788: 			fprintf(ficlog," %.7e",matcov[jj][ll]); 
10789: 			fprintf(ficres," %.7e",matcov[jj][ll]); 
10790: 		      }
10791: 		    }
10792: 		  }
10793: 		} /* end lk */
10794: 	      } /* end lj */
10795: 	    } /* end li */
10796: 	    if(mle>=1)
10797: 	      printf("\n");
10798: 	    fprintf(ficlog,"\n");
10799: 	    fprintf(ficres,"\n");
10800: 	    numlinepar++;
10801: 	  } /* end k*/
10802: 	} /*end j */
10803:       } /* end i */
10804:     } /* end itimes */
10805:     
10806:     fflush(ficlog);
10807:     fflush(ficres);
10808:     while(fgets(line, MAXLINE, ficpar)) {
10809:       /* If line starts with a # it is a comment */
10810:       if (line[0] == '#') {
10811: 	numlinepar++;
10812: 	fputs(line,stdout);
10813: 	fputs(line,ficparo);
10814: 	fputs(line,ficlog);
10815: 	continue;
10816:       }else
10817: 	break;
10818:     }
10819:     
10820:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
10821:     /*   ungetc(c,ficpar); */
10822:     /*   fgets(line, MAXLINE, ficpar); */
10823:     /*   fputs(line,stdout); */
10824:     /*   fputs(line,ficparo); */
10825:     /* } */
10826:     /* ungetc(c,ficpar); */
10827:     
10828:     estepm=0;
10829:     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){
10830:       
10831:       if (num_filled != 6) {
10832: 	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);
10833: 	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);
10834: 	goto end;
10835:       }
10836:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
10837:     }
10838:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
10839:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
10840:     
10841:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
10842:     if (estepm==0 || estepm < stepm) estepm=stepm;
10843:     if (fage <= 2) {
10844:       bage = ageminpar;
10845:       fage = agemaxpar;
10846:     }
10847:     
10848:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
10849:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
10850:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
10851: 		
10852:     /* Other stuffs, more or less useful */    
10853:     while((c=getc(ficpar))=='#' && c!= EOF){
10854:       ungetc(c,ficpar);
10855:       fgets(line, MAXLINE, ficpar);
10856:       fputs(line,stdout);
10857:       fputs(line,ficparo);
10858:     }
10859:     ungetc(c,ficpar);
10860:     
10861:     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);
10862:     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);
10863:     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);
10864:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
10865:     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);
10866:     
10867:     while((c=getc(ficpar))=='#' && c!= EOF){
10868:       ungetc(c,ficpar);
10869:       fgets(line, MAXLINE, ficpar);
10870:       fputs(line,stdout);
10871:       fputs(line,ficparo);
10872:     }
10873:     ungetc(c,ficpar);
10874:     
10875:     
10876:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
10877:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
10878:     
10879:     fscanf(ficpar,"pop_based=%d\n",&popbased);
10880:     fprintf(ficlog,"pop_based=%d\n",popbased);
10881:     fprintf(ficparo,"pop_based=%d\n",popbased);   
10882:     fprintf(ficres,"pop_based=%d\n",popbased);   
10883:     
10884:     while((c=getc(ficpar))=='#' && c!= EOF){
10885:       ungetc(c,ficpar);
10886:       fgets(line, MAXLINE, ficpar);
10887:       fputs(line,stdout);
10888:       fputs(line,ficres);
10889:       fputs(line,ficparo);
10890:     }
10891:     ungetc(c,ficpar);
10892:     
10893:     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);
10894:     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);
10895:     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);
10896:     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);
10897:     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);
10898:     /* day and month of proj2 are not used but only year anproj2.*/
10899:     
10900:     while((c=getc(ficpar))=='#' && c!= EOF){
10901:       ungetc(c,ficpar);
10902:       fgets(line, MAXLINE, ficpar);
10903:       fputs(line,stdout);
10904:       fputs(line,ficparo);
10905:       fputs(line,ficres);
10906:     }
10907:     ungetc(c,ficpar);
10908:     
10909:     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);
10910:     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);
10911:     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);
10912:     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);
10913:     /* day and month of proj2 are not used but only year anproj2.*/
10914:     
10915:     /* Results */
10916:     nresult=0;
10917:     while(fgets(line, MAXLINE, ficpar)) {
10918:       /* If line starts with a # it is a comment */
10919:       if (line[0] == '#') {
10920: 	numlinepar++;
10921: 	fputs(line,stdout);
10922: 	fputs(line,ficparo);
10923: 	fputs(line,ficlog);
10924: 	fputs(line,ficres);
10925: 	continue;
10926:       }else
10927: 	break;
10928:     }
10929:     if (!feof(ficpar))
10930:     while((num_filled=sscanf(line,"result:%[^\n]\n",resultline)) !=EOF){
10931:       if (num_filled == 0){
10932: 	resultline[0]='\0';
10933:       break;
10934:       } else if (num_filled != 1){
10935: 	printf("ERROR %d: result line should be at minimum 'result=' %s\n",num_filled, line);
10936:       }
10937:       nresult++; /* Sum of resultlines */
10938:       printf("Result %d: result=%s\n",nresult, resultline);
10939:       if(nresult > MAXRESULTLINES){
10940: 	printf("ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
10941: 	fprintf(ficlog,"ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
10942: 	goto end;
10943:       }
10944:       decoderesult(resultline, nresult); /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
10945:       fprintf(ficparo,"result: %s\n",resultline);
10946:       fprintf(ficres,"result: %s\n",resultline);
10947:       fprintf(ficlog,"result: %s\n",resultline);
10948:       while(fgets(line, MAXLINE, ficpar)) {
10949: 	/* If line starts with a # it is a comment */
10950: 	if (line[0] == '#') {
10951: 	  numlinepar++;
10952: 	  fputs(line,stdout);
10953: 	  fputs(line,ficparo);
10954: 	  fputs(line,ficres);
10955: 	  fputs(line,ficlog);
10956: 	  continue;
10957: 	}else
10958: 	  break;
10959:       }
10960:       if (feof(ficpar))
10961: 	break;
10962:       else{ /* Processess output results for this combination of covariate values */
10963:       }				   
10964:     } /* end while */
10965: 
10966: 
10967:     
10968:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
10969:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
10970:     
10971:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
10972:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
10973:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
10974: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
10975: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
10976:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
10977: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
10978: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
10979:     }else{
10980:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
10981:     }
10982:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
10983: 		 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
10984: 		 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
10985: 		
10986:     /*------------ free_vector  -------------*/
10987:     /*  chdir(path); */
10988: 		
10989:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
10990:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
10991:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
10992:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
10993:     free_lvector(num,1,n);
10994:     free_vector(agedc,1,n);
10995:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
10996:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
10997:     fclose(ficparo);
10998:     fclose(ficres);
10999: 		
11000: 		
11001:     /* Other results (useful)*/
11002: 		
11003: 		
11004:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
11005:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
11006:     prlim=matrix(1,nlstate,1,nlstate);
11007:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
11008:     fclose(ficrespl);
11009: 
11010:     /*------------- h Pij x at various ages ------------*/
11011:     /*#include "hpijx.h"*/
11012:     hPijx(p, bage, fage);
11013:     fclose(ficrespij);
11014:     
11015:     /* ncovcombmax=  pow(2,cptcoveff); */
11016:     /*-------------- Variance of one-step probabilities---*/
11017:     k=1;
11018:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
11019:     
11020:     /* Prevalence for each covariates in probs[age][status][cov] */
11021:     probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
11022:     for(i=1;i<=AGESUP;i++)
11023:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
11024: 	for(k=1;k<=ncovcombmax;k++)
11025: 	  probs[i][j][k]=0.;
11026:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
11027:     if (mobilav!=0 ||mobilavproj !=0 ) {
11028:       mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
11029:       for(i=1;i<=AGESUP;i++)
11030: 	for(j=1;j<=nlstate;j++)
11031: 	  for(k=1;k<=ncovcombmax;k++)
11032: 	    mobaverages[i][j][k]=0.;
11033:       mobaverage=mobaverages;
11034:       if (mobilav!=0) {
11035: 	printf("Movingaveraging observed prevalence\n");
11036: 	if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
11037: 	  fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
11038: 	  printf(" Error in movingaverage mobilav=%d\n",mobilav);
11039: 	}
11040:       }
11041:       /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
11042:       /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
11043:       else if (mobilavproj !=0) {
11044: 	printf("Movingaveraging projected observed prevalence\n");
11045: 	if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
11046: 	  fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
11047: 	  printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
11048: 	}
11049:       }
11050:     }/* end if moving average */
11051:     
11052:     /*---------- Forecasting ------------------*/
11053:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
11054:     if(prevfcast==1){
11055:       /*    if(stepm ==1){*/
11056:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
11057:     }
11058:     if(backcast==1){
11059:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath); 	
11060:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath); 	
11061:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
11062: 
11063:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
11064: 
11065:       bprlim=matrix(1,nlstate,1,nlstate);
11066:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
11067:       fclose(ficresplb);
11068: 
11069:       hBijx(p, bage, fage, mobaverage);
11070:       fclose(ficrespijb);
11071:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
11072: 
11073:       /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
11074: 	 bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
11075:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
11076:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
11077:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
11078:     }
11079:     
11080:  
11081:     /* ------ Other prevalence ratios------------ */
11082: 
11083:     free_ivector(wav,1,imx);
11084:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
11085:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
11086:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
11087: 		
11088: 		
11089:     /*---------- Health expectancies, no variances ------------*/
11090: 		
11091:     strcpy(filerese,"E_");
11092:     strcat(filerese,fileresu);
11093:     if((ficreseij=fopen(filerese,"w"))==NULL) {
11094:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
11095:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
11096:     }
11097:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
11098:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
11099: 
11100:     pstamp(ficreseij);
11101:  		
11102:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
11103:     if (cptcovn < 1){i1=1;}
11104:     
11105:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
11106:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
11107:       if(TKresult[nres]!= k)
11108: 	continue;
11109:       fprintf(ficreseij,"\n#****** ");
11110:       printf("\n#****** ");
11111:       for(j=1;j<=cptcoveff;j++) {
11112: 	fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11113: 	printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11114:       }
11115:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
11116: 	printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11117: 	fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11118:       }
11119:       fprintf(ficreseij,"******\n");
11120:       printf("******\n");
11121:       
11122:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
11123:       oldm=oldms;savm=savms;
11124:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
11125:       
11126:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
11127:     }
11128:     fclose(ficreseij);
11129:     printf("done evsij\n");fflush(stdout);
11130:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
11131: 		
11132:     /*---------- State-specific expectancies and variances ------------*/
11133: 		
11134: 		
11135:     strcpy(filerest,"T_");
11136:     strcat(filerest,fileresu);
11137:     if((ficrest=fopen(filerest,"w"))==NULL) {
11138:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
11139:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
11140:     }
11141:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
11142:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
11143: 		
11144: 
11145:     strcpy(fileresstde,"STDE_");
11146:     strcat(fileresstde,fileresu);
11147:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
11148:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
11149:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
11150:     }
11151:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
11152:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
11153: 
11154:     strcpy(filerescve,"CVE_");
11155:     strcat(filerescve,fileresu);
11156:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
11157:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
11158:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
11159:     }
11160:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
11161:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
11162: 
11163:     strcpy(fileresv,"V_");
11164:     strcat(fileresv,fileresu);
11165:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
11166:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
11167:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
11168:     }
11169:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
11170:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
11171: 
11172:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
11173:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
11174:           
11175:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
11176:     if (cptcovn < 1){i1=1;}
11177:     
11178:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
11179:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
11180:       if(TKresult[nres]!= k)
11181: 	continue;
11182:       printf("\n#****** Result for:");
11183:       fprintf(ficrest,"\n#****** Result for:");
11184:       fprintf(ficlog,"\n#****** Result for:");
11185:       for(j=1;j<=cptcoveff;j++){ 
11186: 	printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11187: 	fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11188: 	fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11189:       }
11190:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
11191: 	printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11192: 	fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11193: 	fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11194:       }	
11195:       fprintf(ficrest,"******\n");
11196:       fprintf(ficlog,"******\n");
11197:       printf("******\n");
11198:       
11199:       fprintf(ficresstdeij,"\n#****** ");
11200:       fprintf(ficrescveij,"\n#****** ");
11201:       for(j=1;j<=cptcoveff;j++) {
11202: 	fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11203: 	fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11204:       }
11205:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
11206: 	fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11207: 	fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11208:       }	
11209:       fprintf(ficresstdeij,"******\n");
11210:       fprintf(ficrescveij,"******\n");
11211:       
11212:       fprintf(ficresvij,"\n#****** ");
11213:       /* pstamp(ficresvij); */
11214:       for(j=1;j<=cptcoveff;j++) 
11215: 	fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11216:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
11217: 	fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11218:       }	
11219:       fprintf(ficresvij,"******\n");
11220:       
11221:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
11222:       oldm=oldms;savm=savms;
11223:       printf(" cvevsij ");
11224:       fprintf(ficlog, " cvevsij ");
11225:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
11226:       printf(" end cvevsij \n ");
11227:       fprintf(ficlog, " end cvevsij \n ");
11228:       
11229:       /*
11230:        */
11231:       /* goto endfree; */
11232:       
11233:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
11234:       pstamp(ficrest);
11235:       
11236:       
11237:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
11238: 	oldm=oldms;savm=savms; /* ZZ Segmentation fault */
11239: 	cptcod= 0; /* To be deleted */
11240: 	printf("varevsij vpopbased=%d \n",vpopbased);
11241: 	fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
11242: 	varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart, nres); /* cptcod not initialized Intel */
11243: 	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 ");
11244: 	if(vpopbased==1)
11245: 	  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);
11246: 	else
11247: 	  fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
11248: 	fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
11249: 	for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
11250: 	fprintf(ficrest,"\n");
11251: 	/* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
11252: 	epj=vector(1,nlstate+1);
11253: 	printf("Computing age specific period (stable) prevalences in each health state \n");
11254: 	fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
11255: 	for(age=bage; age <=fage ;age++){
11256: 	  prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
11257: 	  if (vpopbased==1) {
11258: 	    if(mobilav ==0){
11259: 	      for(i=1; i<=nlstate;i++)
11260: 		prlim[i][i]=probs[(int)age][i][k];
11261: 	    }else{ /* mobilav */ 
11262: 	      for(i=1; i<=nlstate;i++)
11263: 		prlim[i][i]=mobaverage[(int)age][i][k];
11264: 	    }
11265: 	  }
11266: 	  
11267: 	  fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
11268: 	  /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
11269: 	  /* printf(" age %4.0f ",age); */
11270: 	  for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
11271: 	    for(i=1, epj[j]=0.;i <=nlstate;i++) {
11272: 	      epj[j] += prlim[i][i]*eij[i][j][(int)age];
11273: 	      /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
11274: 	      /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
11275: 	    }
11276: 	    epj[nlstate+1] +=epj[j];
11277: 	  }
11278: 	  /* printf(" age %4.0f \n",age); */
11279: 	  
11280: 	  for(i=1, vepp=0.;i <=nlstate;i++)
11281: 	    for(j=1;j <=nlstate;j++)
11282: 	      vepp += vareij[i][j][(int)age];
11283: 	  fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
11284: 	  for(j=1;j <=nlstate;j++){
11285: 	    fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
11286: 	  }
11287: 	  fprintf(ficrest,"\n");
11288: 	}
11289:       } /* End vpopbased */
11290:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
11291:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
11292:       free_vector(epj,1,nlstate+1);
11293:       printf("done selection\n");fflush(stdout);
11294:       fprintf(ficlog,"done selection\n");fflush(ficlog);
11295:       
11296:       /*}*/
11297:     } /* End k selection */
11298: 
11299:     printf("done State-specific expectancies\n");fflush(stdout);
11300:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
11301: 
11302:     /*------- Variance of period (stable) prevalence------*/   
11303:     
11304:     strcpy(fileresvpl,"VPL_");
11305:     strcat(fileresvpl,fileresu);
11306:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
11307:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
11308:       exit(0);
11309:     }
11310:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
11311:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
11312:     
11313:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
11314:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
11315:     
11316:     i1=pow(2,cptcoveff);
11317:     if (cptcovn < 1){i1=1;}
11318: 
11319:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
11320:     for(k=1; k<=i1;k++){
11321:       if(TKresult[nres]!= k)
11322: 	continue;
11323:       fprintf(ficresvpl,"\n#****** ");
11324:       printf("\n#****** ");
11325:       fprintf(ficlog,"\n#****** ");
11326:       for(j=1;j<=cptcoveff;j++) {
11327: 	fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11328: 	fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11329: 	printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
11330:       }
11331:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
11332: 	printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11333: 	fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11334: 	fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
11335:       }	
11336:       fprintf(ficresvpl,"******\n");
11337:       printf("******\n");
11338:       fprintf(ficlog,"******\n");
11339:       
11340:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
11341:       oldm=oldms;savm=savms;
11342:       varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart, nres);
11343:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
11344:       /*}*/
11345:     }
11346:     
11347:     fclose(ficresvpl);
11348:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
11349:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
11350:     
11351:     free_vector(weight,1,n);
11352:     free_imatrix(Tvard,1,NCOVMAX,1,2);
11353:     free_imatrix(s,1,maxwav+1,1,n);
11354:     free_matrix(anint,1,maxwav,1,n); 
11355:     free_matrix(mint,1,maxwav,1,n);
11356:     free_ivector(cod,1,n);
11357:     free_ivector(tab,1,NCOVMAX);
11358:     fclose(ficresstdeij);
11359:     fclose(ficrescveij);
11360:     fclose(ficresvij);
11361:     fclose(ficrest);
11362:     fclose(ficpar);
11363:     
11364:     
11365:     /*---------- End : free ----------------*/
11366:     if (mobilav!=0 ||mobilavproj !=0)
11367:       free_ma3x(mobaverages,1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
11368:     free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
11369:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
11370:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
11371:   }  /* mle==-3 arrives here for freeing */
11372:   /* endfree:*/
11373:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
11374:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
11375:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
11376:   free_ma3x(cotqvar,1,maxwav,1,nqtv,1,n);
11377:   free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,1,n);
11378:   free_matrix(coqvar,1,maxwav,1,n);
11379:   free_matrix(covar,0,NCOVMAX,1,n);
11380:   free_matrix(matcov,1,npar,1,npar);
11381:   free_matrix(hess,1,npar,1,npar);
11382:   /*free_vector(delti,1,npar);*/
11383:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
11384:   free_matrix(agev,1,maxwav,1,imx);
11385:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
11386:   
11387:   free_ivector(ncodemax,1,NCOVMAX);
11388:   free_ivector(ncodemaxwundef,1,NCOVMAX);
11389:   free_ivector(Dummy,-1,NCOVMAX);
11390:   free_ivector(Fixed,-1,NCOVMAX);
11391:   free_ivector(DummyV,1,NCOVMAX);
11392:   free_ivector(FixedV,1,NCOVMAX);
11393:   free_ivector(Typevar,-1,NCOVMAX);
11394:   free_ivector(Tvar,1,NCOVMAX);
11395:   free_ivector(TvarsQ,1,NCOVMAX);
11396:   free_ivector(TvarsQind,1,NCOVMAX);
11397:   free_ivector(TvarsD,1,NCOVMAX);
11398:   free_ivector(TvarsDind,1,NCOVMAX);
11399:   free_ivector(TvarFD,1,NCOVMAX);
11400:   free_ivector(TvarFDind,1,NCOVMAX);
11401:   free_ivector(TvarF,1,NCOVMAX);
11402:   free_ivector(TvarFind,1,NCOVMAX);
11403:   free_ivector(TvarV,1,NCOVMAX);
11404:   free_ivector(TvarVind,1,NCOVMAX);
11405:   free_ivector(TvarA,1,NCOVMAX);
11406:   free_ivector(TvarAind,1,NCOVMAX);
11407:   free_ivector(TvarFQ,1,NCOVMAX);
11408:   free_ivector(TvarFQind,1,NCOVMAX);
11409:   free_ivector(TvarVD,1,NCOVMAX);
11410:   free_ivector(TvarVDind,1,NCOVMAX);
11411:   free_ivector(TvarVQ,1,NCOVMAX);
11412:   free_ivector(TvarVQind,1,NCOVMAX);
11413:   free_ivector(Tvarsel,1,NCOVMAX);
11414:   free_vector(Tvalsel,1,NCOVMAX);
11415:   free_ivector(Tposprod,1,NCOVMAX);
11416:   free_ivector(Tprod,1,NCOVMAX);
11417:   free_ivector(Tvaraff,1,NCOVMAX);
11418:   free_ivector(invalidvarcomb,1,ncovcombmax);
11419:   free_ivector(Tage,1,NCOVMAX);
11420:   free_ivector(Tmodelind,1,NCOVMAX);
11421:   free_ivector(TmodelInvind,1,NCOVMAX);
11422:   free_ivector(TmodelInvQind,1,NCOVMAX);
11423:   
11424:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
11425:   /* free_imatrix(codtab,1,100,1,10); */
11426:   fflush(fichtm);
11427:   fflush(ficgp);
11428:   
11429:   
11430:   if((nberr >0) || (nbwarn>0)){
11431:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
11432:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d. Please look at the log file for details.\n",nberr,nbwarn);
11433:   }else{
11434:     printf("End of Imach\n");
11435:     fprintf(ficlog,"End of Imach\n");
11436:   }
11437:   printf("See log file on %s\n",filelog);
11438:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
11439:   /*(void) gettimeofday(&end_time,&tzp);*/
11440:   rend_time = time(NULL);  
11441:   end_time = *localtime(&rend_time);
11442:   /* tml = *localtime(&end_time.tm_sec); */
11443:   strcpy(strtend,asctime(&end_time));
11444:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
11445:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
11446:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
11447:   
11448:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
11449:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
11450:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
11451:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
11452: /*   if(fileappend(fichtm,optionfilehtm)){ */
11453:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
11454:   fclose(fichtm);
11455:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
11456:   fclose(fichtmcov);
11457:   fclose(ficgp);
11458:   fclose(ficlog);
11459:   /*------ End -----------*/
11460:   
11461:   
11462:   printf("Before Current directory %s!\n",pathcd);
11463: #ifdef WIN32
11464:   if (_chdir(pathcd) != 0)
11465:     printf("Can't move to directory %s!\n",path);
11466:   if(_getcwd(pathcd,MAXLINE) > 0)
11467: #else
11468:     if(chdir(pathcd) != 0)
11469:       printf("Can't move to directory %s!\n", path);
11470:   if (getcwd(pathcd, MAXLINE) > 0)
11471: #endif 
11472:     printf("Current directory %s!\n",pathcd);
11473:   /*strcat(plotcmd,CHARSEPARATOR);*/
11474:   sprintf(plotcmd,"gnuplot");
11475: #ifdef _WIN32
11476:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
11477: #endif
11478:   if(!stat(plotcmd,&info)){
11479:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
11480:     if(!stat(getenv("GNUPLOTBIN"),&info)){
11481:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
11482:     }else
11483:       strcpy(pplotcmd,plotcmd);
11484: #ifdef __unix
11485:     strcpy(plotcmd,GNUPLOTPROGRAM);
11486:     if(!stat(plotcmd,&info)){
11487:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
11488:     }else
11489:       strcpy(pplotcmd,plotcmd);
11490: #endif
11491:   }else
11492:     strcpy(pplotcmd,plotcmd);
11493:   
11494:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
11495:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
11496:   
11497:   if((outcmd=system(plotcmd)) != 0){
11498:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
11499:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
11500:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
11501:     if((outcmd=system(plotcmd)) != 0)
11502:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
11503:   }
11504:   printf(" Successful, please wait...");
11505:   while (z[0] != 'q') {
11506:     /* chdir(path); */
11507:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
11508:     scanf("%s",z);
11509: /*     if (z[0] == 'c') system("./imach"); */
11510:     if (z[0] == 'e') {
11511: #ifdef __APPLE__
11512:       sprintf(pplotcmd, "open %s", optionfilehtm);
11513: #elif __linux
11514:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
11515: #else
11516:       sprintf(pplotcmd, "%s", optionfilehtm);
11517: #endif
11518:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
11519:       system(pplotcmd);
11520:     }
11521:     else if (z[0] == 'g') system(plotcmd);
11522:     else if (z[0] == 'q') exit(0);
11523:   }
11524: end:
11525:   while (z[0] != 'q') {
11526:     printf("\nType  q for exiting: "); fflush(stdout);
11527:     scanf("%s",z);
11528:   }
11529: }

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