File:  [Local Repository] / imach / src / imach.c
Revision 1.233: download - view: text, annotated - select for diffs
Tue Aug 23 07:40:50 2016 UTC (7 years, 8 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
Summary: not working

    1: /* $Id: imach.c,v 1.233 2016/08/23 07:40:50 brouard Exp $
    2:   $State: Exp $
    3:   $Log: imach.c,v $
    4:   Revision 1.233  2016/08/23 07:40:50  brouard
    5:   Summary: not working
    6: 
    7:   Revision 1.232  2016/08/22 14:20:21  brouard
    8:   Summary: not working
    9: 
   10:   Revision 1.231  2016/08/22 07:17:15  brouard
   11:   Summary: not working
   12: 
   13:   Revision 1.230  2016/08/22 06:55:53  brouard
   14:   Summary: Not working
   15: 
   16:   Revision 1.229  2016/07/23 09:45:53  brouard
   17:   Summary: Completing for func too
   18: 
   19:   Revision 1.228  2016/07/22 17:45:30  brouard
   20:   Summary: Fixing some arrays, still debugging
   21: 
   22:   Revision 1.226  2016/07/12 18:42:34  brouard
   23:   Summary: temp
   24: 
   25:   Revision 1.225  2016/07/12 08:40:03  brouard
   26:   Summary: saving but not running
   27: 
   28:   Revision 1.224  2016/07/01 13:16:01  brouard
   29:   Summary: Fixes
   30: 
   31:   Revision 1.223  2016/02/19 09:23:35  brouard
   32:   Summary: temporary
   33: 
   34:   Revision 1.222  2016/02/17 08:14:50  brouard
   35:   Summary: Probably last 0.98 stable version 0.98r6
   36: 
   37:   Revision 1.221  2016/02/15 23:35:36  brouard
   38:   Summary: minor bug
   39: 
   40:   Revision 1.219  2016/02/15 00:48:12  brouard
   41:   *** empty log message ***
   42: 
   43:   Revision 1.218  2016/02/12 11:29:23  brouard
   44:   Summary: 0.99 Back projections
   45: 
   46:   Revision 1.217  2015/12/23 17:18:31  brouard
   47:   Summary: Experimental backcast
   48: 
   49:   Revision 1.216  2015/12/18 17:32:11  brouard
   50:   Summary: 0.98r4 Warning and status=-2
   51: 
   52:   Version 0.98r4 is now:
   53:    - displaying an error when status is -1, date of interview unknown and date of death known;
   54:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
   55:   Older changes concerning s=-2, dating from 2005 have been supersed.
   56: 
   57:   Revision 1.215  2015/12/16 08:52:24  brouard
   58:   Summary: 0.98r4 working
   59: 
   60:   Revision 1.214  2015/12/16 06:57:54  brouard
   61:   Summary: temporary not working
   62: 
   63:   Revision 1.213  2015/12/11 18:22:17  brouard
   64:   Summary: 0.98r4
   65: 
   66:   Revision 1.212  2015/11/21 12:47:24  brouard
   67:   Summary: minor typo
   68: 
   69:   Revision 1.211  2015/11/21 12:41:11  brouard
   70:   Summary: 0.98r3 with some graph of projected cross-sectional
   71: 
   72:   Author: Nicolas Brouard
   73: 
   74:   Revision 1.210  2015/11/18 17:41:20  brouard
   75:   Summary: Start working on projected prevalences
   76: 
   77:   Revision 1.209  2015/11/17 22:12:03  brouard
   78:   Summary: Adding ftolpl parameter
   79:   Author: N Brouard
   80: 
   81:   We had difficulties to get smoothed confidence intervals. It was due
   82:   to the period prevalence which wasn't computed accurately. The inner
   83:   parameter ftolpl is now an outer parameter of the .imach parameter
   84:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
   85:   computation are long.
   86: 
   87:   Revision 1.208  2015/11/17 14:31:57  brouard
   88:   Summary: temporary
   89: 
   90:   Revision 1.207  2015/10/27 17:36:57  brouard
   91:   *** empty log message ***
   92: 
   93:   Revision 1.206  2015/10/24 07:14:11  brouard
   94:   *** empty log message ***
   95: 
   96:   Revision 1.205  2015/10/23 15:50:53  brouard
   97:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
   98: 
   99:   Revision 1.204  2015/10/01 16:20:26  brouard
  100:   Summary: Some new graphs of contribution to likelihood
  101: 
  102:   Revision 1.203  2015/09/30 17:45:14  brouard
  103:   Summary: looking at better estimation of the hessian
  104: 
  105:   Also a better criteria for convergence to the period prevalence And
  106:   therefore adding the number of years needed to converge. (The
  107:   prevalence in any alive state shold sum to one
  108: 
  109:   Revision 1.202  2015/09/22 19:45:16  brouard
  110:   Summary: Adding some overall graph on contribution to likelihood. Might change
  111: 
  112:   Revision 1.201  2015/09/15 17:34:58  brouard
  113:   Summary: 0.98r0
  114: 
  115:   - Some new graphs like suvival functions
  116:   - Some bugs fixed like model=1+age+V2.
  117: 
  118:   Revision 1.200  2015/09/09 16:53:55  brouard
  119:   Summary: Big bug thanks to Flavia
  120: 
  121:   Even model=1+age+V2. did not work anymore
  122: 
  123:   Revision 1.199  2015/09/07 14:09:23  brouard
  124:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
  125: 
  126:   Revision 1.198  2015/09/03 07:14:39  brouard
  127:   Summary: 0.98q5 Flavia
  128: 
  129:   Revision 1.197  2015/09/01 18:24:39  brouard
  130:   *** empty log message ***
  131: 
  132:   Revision 1.196  2015/08/18 23:17:52  brouard
  133:   Summary: 0.98q5
  134: 
  135:   Revision 1.195  2015/08/18 16:28:39  brouard
  136:   Summary: Adding a hack for testing purpose
  137: 
  138:   After reading the title, ftol and model lines, if the comment line has
  139:   a q, starting with #q, the answer at the end of the run is quit. It
  140:   permits to run test files in batch with ctest. The former workaround was
  141:   $ echo q | imach foo.imach
  142: 
  143:   Revision 1.194  2015/08/18 13:32:00  brouard
  144:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
  145: 
  146:   Revision 1.193  2015/08/04 07:17:42  brouard
  147:   Summary: 0.98q4
  148: 
  149:   Revision 1.192  2015/07/16 16:49:02  brouard
  150:   Summary: Fixing some outputs
  151: 
  152:   Revision 1.191  2015/07/14 10:00:33  brouard
  153:   Summary: Some fixes
  154: 
  155:   Revision 1.190  2015/05/05 08:51:13  brouard
  156:   Summary: Adding digits in output parameters (7 digits instead of 6)
  157: 
  158:   Fix 1+age+.
  159: 
  160:   Revision 1.189  2015/04/30 14:45:16  brouard
  161:   Summary: 0.98q2
  162: 
  163:   Revision 1.188  2015/04/30 08:27:53  brouard
  164:   *** empty log message ***
  165: 
  166:   Revision 1.187  2015/04/29 09:11:15  brouard
  167:   *** empty log message ***
  168: 
  169:   Revision 1.186  2015/04/23 12:01:52  brouard
  170:   Summary: V1*age is working now, version 0.98q1
  171: 
  172:   Some codes had been disabled in order to simplify and Vn*age was
  173:   working in the optimization phase, ie, giving correct MLE parameters,
  174:   but, as usual, outputs were not correct and program core dumped.
  175: 
  176:   Revision 1.185  2015/03/11 13:26:42  brouard
  177:   Summary: Inclusion of compile and links command line for Intel Compiler
  178: 
  179:   Revision 1.184  2015/03/11 11:52:39  brouard
  180:   Summary: Back from Windows 8. Intel Compiler
  181: 
  182:   Revision 1.183  2015/03/10 20:34:32  brouard
  183:   Summary: 0.98q0, trying with directest, mnbrak fixed
  184: 
  185:   We use directest instead of original Powell test; probably no
  186:   incidence on the results, but better justifications;
  187:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
  188:   wrong results.
  189: 
  190:   Revision 1.182  2015/02/12 08:19:57  brouard
  191:   Summary: Trying to keep directest which seems simpler and more general
  192:   Author: Nicolas Brouard
  193: 
  194:   Revision 1.181  2015/02/11 23:22:24  brouard
  195:   Summary: Comments on Powell added
  196: 
  197:   Author:
  198: 
  199:   Revision 1.180  2015/02/11 17:33:45  brouard
  200:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
  201: 
  202:   Revision 1.179  2015/01/04 09:57:06  brouard
  203:   Summary: back to OS/X
  204: 
  205:   Revision 1.178  2015/01/04 09:35:48  brouard
  206:   *** empty log message ***
  207: 
  208:   Revision 1.177  2015/01/03 18:40:56  brouard
  209:   Summary: Still testing ilc32 on OSX
  210: 
  211:   Revision 1.176  2015/01/03 16:45:04  brouard
  212:   *** empty log message ***
  213: 
  214:   Revision 1.175  2015/01/03 16:33:42  brouard
  215:   *** empty log message ***
  216: 
  217:   Revision 1.174  2015/01/03 16:15:49  brouard
  218:   Summary: Still in cross-compilation
  219: 
  220:   Revision 1.173  2015/01/03 12:06:26  brouard
  221:   Summary: trying to detect cross-compilation
  222: 
  223:   Revision 1.172  2014/12/27 12:07:47  brouard
  224:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
  225: 
  226:   Revision 1.171  2014/12/23 13:26:59  brouard
  227:   Summary: Back from Visual C
  228: 
  229:   Still problem with utsname.h on Windows
  230: 
  231:   Revision 1.170  2014/12/23 11:17:12  brouard
  232:   Summary: Cleaning some \%% back to %%
  233: 
  234:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
  235: 
  236:   Revision 1.169  2014/12/22 23:08:31  brouard
  237:   Summary: 0.98p
  238: 
  239:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
  240: 
  241:   Revision 1.168  2014/12/22 15:17:42  brouard
  242:   Summary: update
  243: 
  244:   Revision 1.167  2014/12/22 13:50:56  brouard
  245:   Summary: Testing uname and compiler version and if compiled 32 or 64
  246: 
  247:   Testing on Linux 64
  248: 
  249:   Revision 1.166  2014/12/22 11:40:47  brouard
  250:   *** empty log message ***
  251: 
  252:   Revision 1.165  2014/12/16 11:20:36  brouard
  253:   Summary: After compiling on Visual C
  254: 
  255:   * imach.c (Module): Merging 1.61 to 1.162
  256: 
  257:   Revision 1.164  2014/12/16 10:52:11  brouard
  258:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
  259: 
  260:   * imach.c (Module): Merging 1.61 to 1.162
  261: 
  262:   Revision 1.163  2014/12/16 10:30:11  brouard
  263:   * imach.c (Module): Merging 1.61 to 1.162
  264: 
  265:   Revision 1.162  2014/09/25 11:43:39  brouard
  266:   Summary: temporary backup 0.99!
  267: 
  268:   Revision 1.1  2014/09/16 11:06:58  brouard
  269:   Summary: With some code (wrong) for nlopt
  270: 
  271:   Author:
  272: 
  273:   Revision 1.161  2014/09/15 20:41:41  brouard
  274:   Summary: Problem with macro SQR on Intel compiler
  275: 
  276:   Revision 1.160  2014/09/02 09:24:05  brouard
  277:   *** empty log message ***
  278: 
  279:   Revision 1.159  2014/09/01 10:34:10  brouard
  280:   Summary: WIN32
  281:   Author: Brouard
  282: 
  283:   Revision 1.158  2014/08/27 17:11:51  brouard
  284:   *** empty log message ***
  285: 
  286:   Revision 1.157  2014/08/27 16:26:55  brouard
  287:   Summary: Preparing windows Visual studio version
  288:   Author: Brouard
  289: 
  290:   In order to compile on Visual studio, time.h is now correct and time_t
  291:   and tm struct should be used. difftime should be used but sometimes I
  292:   just make the differences in raw time format (time(&now).
  293:   Trying to suppress #ifdef LINUX
  294:   Add xdg-open for __linux in order to open default browser.
  295: 
  296:   Revision 1.156  2014/08/25 20:10:10  brouard
  297:   *** empty log message ***
  298: 
  299:   Revision 1.155  2014/08/25 18:32:34  brouard
  300:   Summary: New compile, minor changes
  301:   Author: Brouard
  302: 
  303:   Revision 1.154  2014/06/20 17:32:08  brouard
  304:   Summary: Outputs now all graphs of convergence to period prevalence
  305: 
  306:   Revision 1.153  2014/06/20 16:45:46  brouard
  307:   Summary: If 3 live state, convergence to period prevalence on same graph
  308:   Author: Brouard
  309: 
  310:   Revision 1.152  2014/06/18 17:54:09  brouard
  311:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
  312: 
  313:   Revision 1.151  2014/06/18 16:43:30  brouard
  314:   *** empty log message ***
  315: 
  316:   Revision 1.150  2014/06/18 16:42:35  brouard
  317:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
  318:   Author: brouard
  319: 
  320:   Revision 1.149  2014/06/18 15:51:14  brouard
  321:   Summary: Some fixes in parameter files errors
  322:   Author: Nicolas Brouard
  323: 
  324:   Revision 1.148  2014/06/17 17:38:48  brouard
  325:   Summary: Nothing new
  326:   Author: Brouard
  327: 
  328:   Just a new packaging for OS/X version 0.98nS
  329: 
  330:   Revision 1.147  2014/06/16 10:33:11  brouard
  331:   *** empty log message ***
  332: 
  333:   Revision 1.146  2014/06/16 10:20:28  brouard
  334:   Summary: Merge
  335:   Author: Brouard
  336: 
  337:   Merge, before building revised version.
  338: 
  339:   Revision 1.145  2014/06/10 21:23:15  brouard
  340:   Summary: Debugging with valgrind
  341:   Author: Nicolas Brouard
  342: 
  343:   Lot of changes in order to output the results with some covariates
  344:   After the Edimburgh REVES conference 2014, it seems mandatory to
  345:   improve the code.
  346:   No more memory valgrind error but a lot has to be done in order to
  347:   continue the work of splitting the code into subroutines.
  348:   Also, decodemodel has been improved. Tricode is still not
  349:   optimal. nbcode should be improved. Documentation has been added in
  350:   the source code.
  351: 
  352:   Revision 1.143  2014/01/26 09:45:38  brouard
  353:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
  354: 
  355:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  356:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
  357: 
  358:   Revision 1.142  2014/01/26 03:57:36  brouard
  359:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
  360: 
  361:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  362: 
  363:   Revision 1.141  2014/01/26 02:42:01  brouard
  364:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  365: 
  366:   Revision 1.140  2011/09/02 10:37:54  brouard
  367:   Summary: times.h is ok with mingw32 now.
  368: 
  369:   Revision 1.139  2010/06/14 07:50:17  brouard
  370:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
  371:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
  372: 
  373:   Revision 1.138  2010/04/30 18:19:40  brouard
  374:   *** empty log message ***
  375: 
  376:   Revision 1.137  2010/04/29 18:11:38  brouard
  377:   (Module): Checking covariates for more complex models
  378:   than V1+V2. A lot of change to be done. Unstable.
  379: 
  380:   Revision 1.136  2010/04/26 20:30:53  brouard
  381:   (Module): merging some libgsl code. Fixing computation
  382:   of likelione (using inter/intrapolation if mle = 0) in order to
  383:   get same likelihood as if mle=1.
  384:   Some cleaning of code and comments added.
  385: 
  386:   Revision 1.135  2009/10/29 15:33:14  brouard
  387:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  388: 
  389:   Revision 1.134  2009/10/29 13:18:53  brouard
  390:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  391: 
  392:   Revision 1.133  2009/07/06 10:21:25  brouard
  393:   just nforces
  394: 
  395:   Revision 1.132  2009/07/06 08:22:05  brouard
  396:   Many tings
  397: 
  398:   Revision 1.131  2009/06/20 16:22:47  brouard
  399:   Some dimensions resccaled
  400: 
  401:   Revision 1.130  2009/05/26 06:44:34  brouard
  402:   (Module): Max Covariate is now set to 20 instead of 8. A
  403:   lot of cleaning with variables initialized to 0. Trying to make
  404:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
  405: 
  406:   Revision 1.129  2007/08/31 13:49:27  lievre
  407:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
  408: 
  409:   Revision 1.128  2006/06/30 13:02:05  brouard
  410:   (Module): Clarifications on computing e.j
  411: 
  412:   Revision 1.127  2006/04/28 18:11:50  brouard
  413:   (Module): Yes the sum of survivors was wrong since
  414:   imach-114 because nhstepm was no more computed in the age
  415:   loop. Now we define nhstepma in the age loop.
  416:   (Module): In order to speed up (in case of numerous covariates) we
  417:   compute health expectancies (without variances) in a first step
  418:   and then all the health expectancies with variances or standard
  419:   deviation (needs data from the Hessian matrices) which slows the
  420:   computation.
  421:   In the future we should be able to stop the program is only health
  422:   expectancies and graph are needed without standard deviations.
  423: 
  424:   Revision 1.126  2006/04/28 17:23:28  brouard
  425:   (Module): Yes the sum of survivors was wrong since
  426:   imach-114 because nhstepm was no more computed in the age
  427:   loop. Now we define nhstepma in the age loop.
  428:   Version 0.98h
  429: 
  430:   Revision 1.125  2006/04/04 15:20:31  lievre
  431:   Errors in calculation of health expectancies. Age was not initialized.
  432:   Forecasting file added.
  433: 
  434:   Revision 1.124  2006/03/22 17:13:53  lievre
  435:   Parameters are printed with %lf instead of %f (more numbers after the comma).
  436:   The log-likelihood is printed in the log file
  437: 
  438:   Revision 1.123  2006/03/20 10:52:43  brouard
  439:   * imach.c (Module): <title> changed, corresponds to .htm file
  440:   name. <head> headers where missing.
  441: 
  442:   * imach.c (Module): Weights can have a decimal point as for
  443:   English (a comma might work with a correct LC_NUMERIC environment,
  444:   otherwise the weight is truncated).
  445:   Modification of warning when the covariates values are not 0 or
  446:   1.
  447:   Version 0.98g
  448: 
  449:   Revision 1.122  2006/03/20 09:45:41  brouard
  450:   (Module): Weights can have a decimal point as for
  451:   English (a comma might work with a correct LC_NUMERIC environment,
  452:   otherwise the weight is truncated).
  453:   Modification of warning when the covariates values are not 0 or
  454:   1.
  455:   Version 0.98g
  456: 
  457:   Revision 1.121  2006/03/16 17:45:01  lievre
  458:   * imach.c (Module): Comments concerning covariates added
  459: 
  460:   * imach.c (Module): refinements in the computation of lli if
  461:   status=-2 in order to have more reliable computation if stepm is
  462:   not 1 month. Version 0.98f
  463: 
  464:   Revision 1.120  2006/03/16 15:10:38  lievre
  465:   (Module): refinements in the computation of lli if
  466:   status=-2 in order to have more reliable computation if stepm is
  467:   not 1 month. Version 0.98f
  468: 
  469:   Revision 1.119  2006/03/15 17:42:26  brouard
  470:   (Module): Bug if status = -2, the loglikelihood was
  471:   computed as likelihood omitting the logarithm. Version O.98e
  472: 
  473:   Revision 1.118  2006/03/14 18:20:07  brouard
  474:   (Module): varevsij Comments added explaining the second
  475:   table of variances if popbased=1 .
  476:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  477:   (Module): Function pstamp added
  478:   (Module): Version 0.98d
  479: 
  480:   Revision 1.117  2006/03/14 17:16:22  brouard
  481:   (Module): varevsij Comments added explaining the second
  482:   table of variances if popbased=1 .
  483:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  484:   (Module): Function pstamp added
  485:   (Module): Version 0.98d
  486: 
  487:   Revision 1.116  2006/03/06 10:29:27  brouard
  488:   (Module): Variance-covariance wrong links and
  489:   varian-covariance of ej. is needed (Saito).
  490: 
  491:   Revision 1.115  2006/02/27 12:17:45  brouard
  492:   (Module): One freematrix added in mlikeli! 0.98c
  493: 
  494:   Revision 1.114  2006/02/26 12:57:58  brouard
  495:   (Module): Some improvements in processing parameter
  496:   filename with strsep.
  497: 
  498:   Revision 1.113  2006/02/24 14:20:24  brouard
  499:   (Module): Memory leaks checks with valgrind and:
  500:   datafile was not closed, some imatrix were not freed and on matrix
  501:   allocation too.
  502: 
  503:   Revision 1.112  2006/01/30 09:55:26  brouard
  504:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
  505: 
  506:   Revision 1.111  2006/01/25 20:38:18  brouard
  507:   (Module): Lots of cleaning and bugs added (Gompertz)
  508:   (Module): Comments can be added in data file. Missing date values
  509:   can be a simple dot '.'.
  510: 
  511:   Revision 1.110  2006/01/25 00:51:50  brouard
  512:   (Module): Lots of cleaning and bugs added (Gompertz)
  513: 
  514:   Revision 1.109  2006/01/24 19:37:15  brouard
  515:   (Module): Comments (lines starting with a #) are allowed in data.
  516: 
  517:   Revision 1.108  2006/01/19 18:05:42  lievre
  518:   Gnuplot problem appeared...
  519:   To be fixed
  520: 
  521:   Revision 1.107  2006/01/19 16:20:37  brouard
  522:   Test existence of gnuplot in imach path
  523: 
  524:   Revision 1.106  2006/01/19 13:24:36  brouard
  525:   Some cleaning and links added in html output
  526: 
  527:   Revision 1.105  2006/01/05 20:23:19  lievre
  528:   *** empty log message ***
  529: 
  530:   Revision 1.104  2005/09/30 16:11:43  lievre
  531:   (Module): sump fixed, loop imx fixed, and simplifications.
  532:   (Module): If the status is missing at the last wave but we know
  533:   that the person is alive, then we can code his/her status as -2
  534:   (instead of missing=-1 in earlier versions) and his/her
  535:   contributions to the likelihood is 1 - Prob of dying from last
  536:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
  537:   the healthy state at last known wave). Version is 0.98
  538: 
  539:   Revision 1.103  2005/09/30 15:54:49  lievre
  540:   (Module): sump fixed, loop imx fixed, and simplifications.
  541: 
  542:   Revision 1.102  2004/09/15 17:31:30  brouard
  543:   Add the possibility to read data file including tab characters.
  544: 
  545:   Revision 1.101  2004/09/15 10:38:38  brouard
  546:   Fix on curr_time
  547: 
  548:   Revision 1.100  2004/07/12 18:29:06  brouard
  549:   Add version for Mac OS X. Just define UNIX in Makefile
  550: 
  551:   Revision 1.99  2004/06/05 08:57:40  brouard
  552:   *** empty log message ***
  553: 
  554:   Revision 1.98  2004/05/16 15:05:56  brouard
  555:   New version 0.97 . First attempt to estimate force of mortality
  556:   directly from the data i.e. without the need of knowing the health
  557:   state at each age, but using a Gompertz model: log u =a + b*age .
  558:   This is the basic analysis of mortality and should be done before any
  559:   other analysis, in order to test if the mortality estimated from the
  560:   cross-longitudinal survey is different from the mortality estimated
  561:   from other sources like vital statistic data.
  562: 
  563:   The same imach parameter file can be used but the option for mle should be -3.
  564: 
  565:   Agnès, who wrote this part of the code, tried to keep most of the
  566:   former routines in order to include the new code within the former code.
  567: 
  568:   The output is very simple: only an estimate of the intercept and of
  569:   the slope with 95% confident intervals.
  570: 
  571:   Current limitations:
  572:   A) Even if you enter covariates, i.e. with the
  573:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
  574:   B) There is no computation of Life Expectancy nor Life Table.
  575: 
  576:   Revision 1.97  2004/02/20 13:25:42  lievre
  577:   Version 0.96d. Population forecasting command line is (temporarily)
  578:   suppressed.
  579: 
  580:   Revision 1.96  2003/07/15 15:38:55  brouard
  581:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
  582:   rewritten within the same printf. Workaround: many printfs.
  583: 
  584:   Revision 1.95  2003/07/08 07:54:34  brouard
  585:   * imach.c (Repository):
  586:   (Repository): Using imachwizard code to output a more meaningful covariance
  587:   matrix (cov(a12,c31) instead of numbers.
  588: 
  589:   Revision 1.94  2003/06/27 13:00:02  brouard
  590:   Just cleaning
  591: 
  592:   Revision 1.93  2003/06/25 16:33:55  brouard
  593:   (Module): On windows (cygwin) function asctime_r doesn't
  594:   exist so I changed back to asctime which exists.
  595:   (Module): Version 0.96b
  596: 
  597:   Revision 1.92  2003/06/25 16:30:45  brouard
  598:   (Module): On windows (cygwin) function asctime_r doesn't
  599:   exist so I changed back to asctime which exists.
  600: 
  601:   Revision 1.91  2003/06/25 15:30:29  brouard
  602:   * imach.c (Repository): Duplicated warning errors corrected.
  603:   (Repository): Elapsed time after each iteration is now output. It
  604:   helps to forecast when convergence will be reached. Elapsed time
  605:   is stamped in powell.  We created a new html file for the graphs
  606:   concerning matrix of covariance. It has extension -cov.htm.
  607: 
  608:   Revision 1.90  2003/06/24 12:34:15  brouard
  609:   (Module): Some bugs corrected for windows. Also, when
  610:   mle=-1 a template is output in file "or"mypar.txt with the design
  611:   of the covariance matrix to be input.
  612: 
  613:   Revision 1.89  2003/06/24 12:30:52  brouard
  614:   (Module): Some bugs corrected for windows. Also, when
  615:   mle=-1 a template is output in file "or"mypar.txt with the design
  616:   of the covariance matrix to be input.
  617: 
  618:   Revision 1.88  2003/06/23 17:54:56  brouard
  619:   * 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.
  620: 
  621:   Revision 1.87  2003/06/18 12:26:01  brouard
  622:   Version 0.96
  623: 
  624:   Revision 1.86  2003/06/17 20:04:08  brouard
  625:   (Module): Change position of html and gnuplot routines and added
  626:   routine fileappend.
  627: 
  628:   Revision 1.85  2003/06/17 13:12:43  brouard
  629:   * imach.c (Repository): Check when date of death was earlier that
  630:   current date of interview. It may happen when the death was just
  631:   prior to the death. In this case, dh was negative and likelihood
  632:   was wrong (infinity). We still send an "Error" but patch by
  633:   assuming that the date of death was just one stepm after the
  634:   interview.
  635:   (Repository): Because some people have very long ID (first column)
  636:   we changed int to long in num[] and we added a new lvector for
  637:   memory allocation. But we also truncated to 8 characters (left
  638:   truncation)
  639:   (Repository): No more line truncation errors.
  640: 
  641:   Revision 1.84  2003/06/13 21:44:43  brouard
  642:   * imach.c (Repository): Replace "freqsummary" at a correct
  643:   place. It differs from routine "prevalence" which may be called
  644:   many times. Probs is memory consuming and must be used with
  645:   parcimony.
  646:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
  647: 
  648:   Revision 1.83  2003/06/10 13:39:11  lievre
  649:   *** empty log message ***
  650: 
  651:   Revision 1.82  2003/06/05 15:57:20  brouard
  652:   Add log in  imach.c and  fullversion number is now printed.
  653: 
  654: */
  655: /*
  656:    Interpolated Markov Chain
  657: 
  658:   Short summary of the programme:
  659:   
  660:   This program computes Healthy Life Expectancies or State-specific
  661:   (if states aren't health statuses) Expectancies from
  662:   cross-longitudinal data. Cross-longitudinal data consist in: 
  663: 
  664:   -1- a first survey ("cross") where individuals from different ages
  665:   are interviewed on their health status or degree of disability (in
  666:   the case of a health survey which is our main interest)
  667: 
  668:   -2- at least a second wave of interviews ("longitudinal") which
  669:   measure each change (if any) in individual health status.  Health
  670:   expectancies are computed from the time spent in each health state
  671:   according to a model. More health states you consider, more time is
  672:   necessary to reach the Maximum Likelihood of the parameters involved
  673:   in the model.  The simplest model is the multinomial logistic model
  674:   where pij is the probability to be observed in state j at the second
  675:   wave conditional to be observed in state i at the first
  676:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
  677:   etc , where 'age' is age and 'sex' is a covariate. If you want to
  678:   have a more complex model than "constant and age", you should modify
  679:   the program where the markup *Covariates have to be included here
  680:   again* invites you to do it.  More covariates you add, slower the
  681:   convergence.
  682: 
  683:   The advantage of this computer programme, compared to a simple
  684:   multinomial logistic model, is clear when the delay between waves is not
  685:   identical for each individual. Also, if a individual missed an
  686:   intermediate interview, the information is lost, but taken into
  687:   account using an interpolation or extrapolation.  
  688: 
  689:   hPijx is the probability to be observed in state i at age x+h
  690:   conditional to the observed state i at age x. The delay 'h' can be
  691:   split into an exact number (nh*stepm) of unobserved intermediate
  692:   states. This elementary transition (by month, quarter,
  693:   semester or year) is modelled as a multinomial logistic.  The hPx
  694:   matrix is simply the matrix product of nh*stepm elementary matrices
  695:   and the contribution of each individual to the likelihood is simply
  696:   hPijx.
  697: 
  698:   Also this programme outputs the covariance matrix of the parameters but also
  699:   of the life expectancies. It also computes the period (stable) prevalence.
  700: 
  701: Back prevalence and projections:
  702: 
  703:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
  704:    double agemaxpar, double ftolpl, int *ncvyearp, double
  705:    dateprev1,double dateprev2, int firstpass, int lastpass, int
  706:    mobilavproj)
  707: 
  708:     Computes the back prevalence limit for any combination of
  709:     covariate values k at any age between ageminpar and agemaxpar and
  710:     returns it in **bprlim. In the loops,
  711: 
  712:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
  713:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
  714: 
  715:    - hBijx Back Probability to be in state i at age x-h being in j at x
  716:    Computes for any combination of covariates k and any age between bage and fage 
  717:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
  718:  			oldm=oldms;savm=savms;
  719: 
  720:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
  721:      Computes the transition matrix starting at age 'age' over
  722:      'nhstepm*hstepm*stepm' months (i.e. until
  723:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
  724:      nhstepm*hstepm matrices. 
  725: 
  726:      Returns p3mat[i][j][h] after calling
  727:      p3mat[i][j][h]=matprod2(newm,
  728:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
  729:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
  730:      oldm);
  731: 
  732: Important routines
  733: 
  734: - func (or funcone), computes logit (pij) distinguishing
  735:   o fixed variables (single or product dummies or quantitative);
  736:   o varying variables by:
  737:    (1) wave (single, product dummies, quantitative), 
  738:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
  739:        % fixed dummy (treated) or quantitative (not done because time-consuming);
  740:        % varying dummy (not done) or quantitative (not done);
  741: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
  742:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
  743: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
  744:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
  745:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
  746: 
  747: 
  748:   
  749:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
  750:            Institut national d'études démographiques, Paris.
  751:   This software have been partly granted by Euro-REVES, a concerted action
  752:   from the European Union.
  753:   It is copyrighted identically to a GNU software product, ie programme and
  754:   software can be distributed freely for non commercial use. Latest version
  755:   can be accessed at http://euroreves.ined.fr/imach .
  756: 
  757:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
  758:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
  759:   
  760:   **********************************************************************/
  761: /*
  762:   main
  763:   read parameterfile
  764:   read datafile
  765:   concatwav
  766:   freqsummary
  767:   if (mle >= 1)
  768:     mlikeli
  769:   print results files
  770:   if mle==1 
  771:      computes hessian
  772:   read end of parameter file: agemin, agemax, bage, fage, estepm
  773:       begin-prev-date,...
  774:   open gnuplot file
  775:   open html file
  776:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
  777:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
  778:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
  779:     freexexit2 possible for memory heap.
  780: 
  781:   h Pij x                         | pij_nom  ficrestpij
  782:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
  783:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
  784:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
  785: 
  786:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
  787:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
  788:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
  789:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
  790:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
  791: 
  792:   forecasting if prevfcast==1 prevforecast call prevalence()
  793:   health expectancies
  794:   Variance-covariance of DFLE
  795:   prevalence()
  796:    movingaverage()
  797:   varevsij() 
  798:   if popbased==1 varevsij(,popbased)
  799:   total life expectancies
  800:   Variance of period (stable) prevalence
  801:  end
  802: */
  803: 
  804: /* #define DEBUG */
  805: /* #define DEBUGBRENT */
  806: /* #define DEBUGLINMIN */
  807: /* #define DEBUGHESS */
  808: #define DEBUGHESSIJ
  809: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
  810: #define POWELL /* Instead of NLOPT */
  811: #define POWELLNOF3INFF1TEST /* Skip test */
  812: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
  813: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
  814: 
  815: #include <math.h>
  816: #include <stdio.h>
  817: #include <stdlib.h>
  818: #include <string.h>
  819: #include <ctype.h>
  820: 
  821: #ifdef _WIN32
  822: #include <io.h>
  823: #include <windows.h>
  824: #include <tchar.h>
  825: #else
  826: #include <unistd.h>
  827: #endif
  828: 
  829: #include <limits.h>
  830: #include <sys/types.h>
  831: 
  832: #if defined(__GNUC__)
  833: #include <sys/utsname.h> /* Doesn't work on Windows */
  834: #endif
  835: 
  836: #include <sys/stat.h>
  837: #include <errno.h>
  838: /* extern int errno; */
  839: 
  840: /* #ifdef LINUX */
  841: /* #include <time.h> */
  842: /* #include "timeval.h" */
  843: /* #else */
  844: /* #include <sys/time.h> */
  845: /* #endif */
  846: 
  847: #include <time.h>
  848: 
  849: #ifdef GSL
  850: #include <gsl/gsl_errno.h>
  851: #include <gsl/gsl_multimin.h>
  852: #endif
  853: 
  854: 
  855: #ifdef NLOPT
  856: #include <nlopt.h>
  857: typedef struct {
  858:   double (* function)(double [] );
  859: } myfunc_data ;
  860: #endif
  861: 
  862: /* #include <libintl.h> */
  863: /* #define _(String) gettext (String) */
  864: 
  865: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
  866: 
  867: #define GNUPLOTPROGRAM "gnuplot"
  868: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
  869: #define FILENAMELENGTH 132
  870: 
  871: #define	GLOCK_ERROR_NOPATH		-1	/* empty path */
  872: #define	GLOCK_ERROR_GETCWD		-2	/* cannot get cwd */
  873: 
  874: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
  875: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
  876: 
  877: #define NINTERVMAX 8
  878: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
  879: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
  880: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
  881: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
  882: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
  883: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
  884: #define MAXN 20000
  885: #define YEARM 12. /**< Number of months per year */
  886: /* #define AGESUP 130 */
  887: #define AGESUP 150
  888: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
  889: #define AGEBASE 40
  890: #define AGEOVERFLOW 1.e20
  891: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
  892: #ifdef _WIN32
  893: #define DIRSEPARATOR '\\'
  894: #define CHARSEPARATOR "\\"
  895: #define ODIRSEPARATOR '/'
  896: #else
  897: #define DIRSEPARATOR '/'
  898: #define CHARSEPARATOR "/"
  899: #define ODIRSEPARATOR '\\'
  900: #endif
  901: 
  902: /* $Id: imach.c,v 1.233 2016/08/23 07:40:50 brouard Exp $ */
  903: /* $State: Exp $ */
  904: #include "version.h"
  905: char version[]=__IMACH_VERSION__;
  906: 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";
  907: char fullversion[]="$Revision: 1.233 $ $Date: 2016/08/23 07:40:50 $"; 
  908: char strstart[80];
  909: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
  910: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
  911: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
  912: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
  913: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
  914: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
  915: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
  916: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
  917: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
  918: int cptcovprodnoage=0; /**< Number of covariate products without age */   
  919: int cptcoveff=0; /* Total number of covariates to vary for printing results */
  920: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
  921: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
  922: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
  923: 
  924: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
  925: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
  926: int ntveff=0; /**< ntveff number of effective time varying variables */
  927: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
  928: int cptcov=0; /* Working variable */
  929: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
  930: int npar=NPARMAX;
  931: int nlstate=2; /* Number of live states */
  932: int ndeath=1; /* Number of dead states */
  933: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
  934: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
  935: int popbased=0;
  936: 
  937: int *wav; /* Number of waves for this individuual 0 is possible */
  938: int maxwav=0; /* Maxim number of waves */
  939: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
  940: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
  941: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
  942: 		   to the likelihood and the sum of weights (done by funcone)*/
  943: int mle=1, weightopt=0;
  944: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
  945: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
  946: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
  947: 	   * wave mi and wave mi+1 is not an exact multiple of stepm. */
  948: int countcallfunc=0;  /* Count the number of calls to func */
  949: int selected(int kvar); /* Is covariate kvar selected for printing results */
  950: 
  951: double jmean=1; /* Mean space between 2 waves */
  952: double **matprod2(); /* test */
  953: double **oldm, **newm, **savm; /* Working pointers to matrices */
  954: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
  955: double	 **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
  956: 
  957: /*FILE *fic ; */ /* Used in readdata only */
  958: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
  959: FILE *ficlog, *ficrespow;
  960: int globpr=0; /* Global variable for printing or not */
  961: double fretone; /* Only one call to likelihood */
  962: long ipmx=0; /* Number of contributions */
  963: double sw; /* Sum of weights */
  964: char filerespow[FILENAMELENGTH];
  965: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
  966: FILE *ficresilk;
  967: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
  968: FILE *ficresprobmorprev;
  969: FILE *fichtm, *fichtmcov; /* Html File */
  970: FILE *ficreseij;
  971: char filerese[FILENAMELENGTH];
  972: FILE *ficresstdeij;
  973: char fileresstde[FILENAMELENGTH];
  974: FILE *ficrescveij;
  975: char filerescve[FILENAMELENGTH];
  976: FILE  *ficresvij;
  977: char fileresv[FILENAMELENGTH];
  978: FILE  *ficresvpl;
  979: char fileresvpl[FILENAMELENGTH];
  980: char title[MAXLINE];
  981: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
  982: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
  983: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
  984: char command[FILENAMELENGTH];
  985: int  outcmd=0;
  986: 
  987: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
  988: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
  989: char filelog[FILENAMELENGTH]; /* Log file */
  990: char filerest[FILENAMELENGTH];
  991: char fileregp[FILENAMELENGTH];
  992: char popfile[FILENAMELENGTH];
  993: 
  994: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
  995: 
  996: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
  997: /* struct timezone tzp; */
  998: /* extern int gettimeofday(); */
  999: struct tm tml, *gmtime(), *localtime();
 1000: 
 1001: extern time_t time();
 1002: 
 1003: struct tm start_time, end_time, curr_time, last_time, forecast_time;
 1004: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
 1005: struct tm tm;
 1006: 
 1007: char strcurr[80], strfor[80];
 1008: 
 1009: char *endptr;
 1010: long lval;
 1011: double dval;
 1012: 
 1013: #define NR_END 1
 1014: #define FREE_ARG char*
 1015: #define FTOL 1.0e-10
 1016: 
 1017: #define NRANSI 
 1018: #define ITMAX 200 
 1019: 
 1020: #define TOL 2.0e-4 
 1021: 
 1022: #define CGOLD 0.3819660 
 1023: #define ZEPS 1.0e-10 
 1024: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
 1025: 
 1026: #define GOLD 1.618034 
 1027: #define GLIMIT 100.0 
 1028: #define TINY 1.0e-20 
 1029: 
 1030: static double maxarg1,maxarg2;
 1031: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
 1032: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
 1033:   
 1034: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
 1035: #define rint(a) floor(a+0.5)
 1036: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
 1037: #define mytinydouble 1.0e-16
 1038: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
 1039: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
 1040: /* static double dsqrarg; */
 1041: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
 1042: static double sqrarg;
 1043: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
 1044: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
 1045: int agegomp= AGEGOMP;
 1046: 
 1047: int imx; 
 1048: int stepm=1;
 1049: /* Stepm, step in month: minimum step interpolation*/
 1050: 
 1051: int estepm;
 1052: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
 1053: 
 1054: int m,nb;
 1055: long *num;
 1056: int firstpass=0, lastpass=4,*cod, *cens;
 1057: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
 1058: 		   covariate for which somebody answered excluding 
 1059: 		   undefined. Usually 2: 0 and 1. */
 1060: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
 1061: 			     covariate for which somebody answered including 
 1062: 			     undefined. Usually 3: -1, 0 and 1. */
 1063: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
 1064: double **pmmij, ***probs; /* Global pointer */
 1065: double ***mobaverage, ***mobaverages; /* New global variable */
 1066: double *ageexmed,*agecens;
 1067: double dateintmean=0;
 1068: 
 1069: double *weight;
 1070: int **s; /* Status */
 1071: double *agedc;
 1072: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
 1073: 		  * covar=matrix(0,NCOVMAX,1,n); 
 1074: 		  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
 1075: double **coqvar; /* Fixed quantitative covariate iqv */
 1076: double ***cotvar; /* Time varying covariate itv */
 1077: double ***cotqvar; /* Time varying quantitative covariate itqv */
 1078: double  idx; 
 1079: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
 1080: 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 */
 1081: 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 */
 1082: 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 */
 1083: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1084: 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 */
 1085: int *TvarAind; /**< TvarindA[1]=5, TvarAind[2]=8  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1086: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1087: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1088: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
 1089: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
 1090: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
 1091: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
 1092: 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 */
 1093: 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 */
 1094: 
 1095: int *Tvarsel; /**< Selected covariates for output */
 1096: double *Tvalsel; /**< Selected modality value of covariate for output */
 1097: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
 1098: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
 1099: 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 */ 
 1100: int *Tage;
 1101: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
 1102: 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*/
 1103: 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*/ 
 1104: 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  */
 1105: int *Ndum; /** Freq of modality (tricode */
 1106: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
 1107: int **Tvard;
 1108: int *Tprod;/**< Gives the k position of the k1 product */
 1109: int *Tposprod; /**< Gives the k1 product from the k position */
 1110: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
 1111:    if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
 1112:    Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
 1113: */
 1114: int cptcovprod, *Tvaraff, *invalidvarcomb;
 1115: double *lsurv, *lpop, *tpop;
 1116: 
 1117: #define FD 1; /* Fixed dummy covariate */
 1118: #define FQ 2; /* Fixed quantitative covariate */
 1119: #define FP 3; /* Fixed product covariate */
 1120: #define FPDD 7; /* Fixed product dummy*dummy covariate */
 1121: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
 1122: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
 1123: #define VD 10; /* Varying dummy covariate */
 1124: #define VQ 11; /* Varying quantitative covariate */
 1125: #define VP 12; /* Varying product covariate */
 1126: #define VPDD 13; /* Varying product dummy*dummy covariate */
 1127: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
 1128: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
 1129: #define APFD 16; /* Age product * fixed dummy covariate */
 1130: #define APFQ 17; /* Age product * fixed quantitative covariate */
 1131: #define APVD 18; /* Age product * varying dummy covariate */
 1132: #define APVQ 19; /* Age product * varying quantitative covariate */
 1133: 
 1134: #define FTYPE 1; /* Fixed covariate */
 1135: #define VTYPE 2; /* Varying covariate (loop in wave) */
 1136: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
 1137: 
 1138: struct kmodel{
 1139: 	int maintype; /* main type */
 1140: 	int subtype; /* subtype */
 1141: };
 1142: struct kmodel modell[NCOVMAX];
 1143: 
 1144: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
 1145: double ftolhess; /**< Tolerance for computing hessian */
 1146: 
 1147: /**************** split *************************/
 1148: static	int split( char *path, char *dirc, char *name, char *ext, char *finame )
 1149: {
 1150:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
 1151:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
 1152:   */ 
 1153:   char	*ss;				/* pointer */
 1154:   int	l1=0, l2=0;				/* length counters */
 1155: 
 1156:   l1 = strlen(path );			/* length of path */
 1157:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
 1158:   ss= strrchr( path, DIRSEPARATOR );		/* find last / */
 1159:   if ( ss == NULL ) {			/* no directory, so determine current directory */
 1160:     strcpy( name, path );		/* we got the fullname name because no directory */
 1161:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
 1162:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
 1163:     /* get current working directory */
 1164:     /*    extern  char* getcwd ( char *buf , int len);*/
 1165: #ifdef WIN32
 1166:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
 1167: #else
 1168: 	if (getcwd(dirc, FILENAME_MAX) == NULL) {
 1169: #endif
 1170:       return( GLOCK_ERROR_GETCWD );
 1171:     }
 1172:     /* got dirc from getcwd*/
 1173:     printf(" DIRC = %s \n",dirc);
 1174:   } else {				/* strip directory from path */
 1175:     ss++;				/* after this, the filename */
 1176:     l2 = strlen( ss );			/* length of filename */
 1177:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
 1178:     strcpy( name, ss );		/* save file name */
 1179:     strncpy( dirc, path, l1 - l2 );	/* now the directory */
 1180:     dirc[l1-l2] = '\0';			/* add zero */
 1181:     printf(" DIRC2 = %s \n",dirc);
 1182:   }
 1183:   /* We add a separator at the end of dirc if not exists */
 1184:   l1 = strlen( dirc );			/* length of directory */
 1185:   if( dirc[l1-1] != DIRSEPARATOR ){
 1186:     dirc[l1] =  DIRSEPARATOR;
 1187:     dirc[l1+1] = 0; 
 1188:     printf(" DIRC3 = %s \n",dirc);
 1189:   }
 1190:   ss = strrchr( name, '.' );		/* find last / */
 1191:   if (ss >0){
 1192:     ss++;
 1193:     strcpy(ext,ss);			/* save extension */
 1194:     l1= strlen( name);
 1195:     l2= strlen(ss)+1;
 1196:     strncpy( finame, name, l1-l2);
 1197:     finame[l1-l2]= 0;
 1198:   }
 1199: 
 1200:   return( 0 );				/* we're done */
 1201: }
 1202: 
 1203: 
 1204: /******************************************/
 1205: 
 1206: void replace_back_to_slash(char *s, char*t)
 1207: {
 1208:   int i;
 1209:   int lg=0;
 1210:   i=0;
 1211:   lg=strlen(t);
 1212:   for(i=0; i<= lg; i++) {
 1213:     (s[i] = t[i]);
 1214:     if (t[i]== '\\') s[i]='/';
 1215:   }
 1216: }
 1217: 
 1218: char *trimbb(char *out, char *in)
 1219: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
 1220:   char *s;
 1221:   s=out;
 1222:   while (*in != '\0'){
 1223:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
 1224:       in++;
 1225:     }
 1226:     *out++ = *in++;
 1227:   }
 1228:   *out='\0';
 1229:   return s;
 1230: }
 1231: 
 1232: /* char *substrchaine(char *out, char *in, char *chain) */
 1233: /* { */
 1234: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
 1235: /*   char *s, *t; */
 1236: /*   t=in;s=out; */
 1237: /*   while ((*in != *chain) && (*in != '\0')){ */
 1238: /*     *out++ = *in++; */
 1239: /*   } */
 1240: 
 1241: /*   /\* *in matches *chain *\/ */
 1242: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
 1243: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1244: /*   } */
 1245: /*   in--; chain--; */
 1246: /*   while ( (*in != '\0')){ */
 1247: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1248: /*     *out++ = *in++; */
 1249: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1250: /*   } */
 1251: /*   *out='\0'; */
 1252: /*   out=s; */
 1253: /*   return out; */
 1254: /* } */
 1255: char *substrchaine(char *out, char *in, char *chain)
 1256: {
 1257:   /* Substract chain 'chain' from 'in', return and output 'out' */
 1258:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
 1259: 
 1260:   char *strloc;
 1261: 
 1262:   strcpy (out, in); 
 1263:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
 1264:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
 1265:   if(strloc != NULL){ 
 1266:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
 1267:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
 1268:     /* strcpy (strloc, strloc +strlen(chain));*/
 1269:   }
 1270:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
 1271:   return out;
 1272: }
 1273: 
 1274: 
 1275: char *cutl(char *blocc, char *alocc, char *in, char occ)
 1276: {
 1277:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
 1278:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
 1279:      gives blocc="abcdef" and alocc="ghi2j".
 1280:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
 1281:   */
 1282:   char *s, *t;
 1283:   t=in;s=in;
 1284:   while ((*in != occ) && (*in != '\0')){
 1285:     *alocc++ = *in++;
 1286:   }
 1287:   if( *in == occ){
 1288:     *(alocc)='\0';
 1289:     s=++in;
 1290:   }
 1291:  
 1292:   if (s == t) {/* occ not found */
 1293:     *(alocc-(in-s))='\0';
 1294:     in=s;
 1295:   }
 1296:   while ( *in != '\0'){
 1297:     *blocc++ = *in++;
 1298:   }
 1299: 
 1300:   *blocc='\0';
 1301:   return t;
 1302: }
 1303: char *cutv(char *blocc, char *alocc, char *in, char occ)
 1304: {
 1305:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
 1306:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
 1307:      gives blocc="abcdef2ghi" and alocc="j".
 1308:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
 1309:   */
 1310:   char *s, *t;
 1311:   t=in;s=in;
 1312:   while (*in != '\0'){
 1313:     while( *in == occ){
 1314:       *blocc++ = *in++;
 1315:       s=in;
 1316:     }
 1317:     *blocc++ = *in++;
 1318:   }
 1319:   if (s == t) /* occ not found */
 1320:     *(blocc-(in-s))='\0';
 1321:   else
 1322:     *(blocc-(in-s)-1)='\0';
 1323:   in=s;
 1324:   while ( *in != '\0'){
 1325:     *alocc++ = *in++;
 1326:   }
 1327: 
 1328:   *alocc='\0';
 1329:   return s;
 1330: }
 1331: 
 1332: int nbocc(char *s, char occ)
 1333: {
 1334:   int i,j=0;
 1335:   int lg=20;
 1336:   i=0;
 1337:   lg=strlen(s);
 1338:   for(i=0; i<= lg; i++) {
 1339:   if  (s[i] == occ ) j++;
 1340:   }
 1341:   return j;
 1342: }
 1343: 
 1344: /* void cutv(char *u,char *v, char*t, char occ) */
 1345: /* { */
 1346: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
 1347: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
 1348: /*      gives u="abcdef2ghi" and v="j" *\/ */
 1349: /*   int i,lg,j,p=0; */
 1350: /*   i=0; */
 1351: /*   lg=strlen(t); */
 1352: /*   for(j=0; j<=lg-1; j++) { */
 1353: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
 1354: /*   } */
 1355: 
 1356: /*   for(j=0; j<p; j++) { */
 1357: /*     (u[j] = t[j]); */
 1358: /*   } */
 1359: /*      u[p]='\0'; */
 1360: 
 1361: /*    for(j=0; j<= lg; j++) { */
 1362: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
 1363: /*   } */
 1364: /* } */
 1365: 
 1366: #ifdef _WIN32
 1367: char * strsep(char **pp, const char *delim)
 1368: {
 1369:   char *p, *q;
 1370:          
 1371:   if ((p = *pp) == NULL)
 1372:     return 0;
 1373:   if ((q = strpbrk (p, delim)) != NULL)
 1374:   {
 1375:     *pp = q + 1;
 1376:     *q = '\0';
 1377:   }
 1378:   else
 1379:     *pp = 0;
 1380:   return p;
 1381: }
 1382: #endif
 1383: 
 1384: /********************** nrerror ********************/
 1385: 
 1386: void nrerror(char error_text[])
 1387: {
 1388:   fprintf(stderr,"ERREUR ...\n");
 1389:   fprintf(stderr,"%s\n",error_text);
 1390:   exit(EXIT_FAILURE);
 1391: }
 1392: /*********************** vector *******************/
 1393: double *vector(int nl, int nh)
 1394: {
 1395:   double *v;
 1396:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
 1397:   if (!v) nrerror("allocation failure in vector");
 1398:   return v-nl+NR_END;
 1399: }
 1400: 
 1401: /************************ free vector ******************/
 1402: void free_vector(double*v, int nl, int nh)
 1403: {
 1404:   free((FREE_ARG)(v+nl-NR_END));
 1405: }
 1406: 
 1407: /************************ivector *******************************/
 1408: int *ivector(long nl,long nh)
 1409: {
 1410:   int *v;
 1411:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
 1412:   if (!v) nrerror("allocation failure in ivector");
 1413:   return v-nl+NR_END;
 1414: }
 1415: 
 1416: /******************free ivector **************************/
 1417: void free_ivector(int *v, long nl, long nh)
 1418: {
 1419:   free((FREE_ARG)(v+nl-NR_END));
 1420: }
 1421: 
 1422: /************************lvector *******************************/
 1423: long *lvector(long nl,long nh)
 1424: {
 1425:   long *v;
 1426:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
 1427:   if (!v) nrerror("allocation failure in ivector");
 1428:   return v-nl+NR_END;
 1429: }
 1430: 
 1431: /******************free lvector **************************/
 1432: void free_lvector(long *v, long nl, long nh)
 1433: {
 1434:   free((FREE_ARG)(v+nl-NR_END));
 1435: }
 1436: 
 1437: /******************* imatrix *******************************/
 1438: int **imatrix(long nrl, long nrh, long ncl, long nch) 
 1439:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
 1440: { 
 1441:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
 1442:   int **m; 
 1443:   
 1444:   /* allocate pointers to rows */ 
 1445:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
 1446:   if (!m) nrerror("allocation failure 1 in matrix()"); 
 1447:   m += NR_END; 
 1448:   m -= nrl; 
 1449:   
 1450:   
 1451:   /* allocate rows and set pointers to them */ 
 1452:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
 1453:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
 1454:   m[nrl] += NR_END; 
 1455:   m[nrl] -= ncl; 
 1456:   
 1457:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
 1458:   
 1459:   /* return pointer to array of pointers to rows */ 
 1460:   return m; 
 1461: } 
 1462: 
 1463: /****************** free_imatrix *************************/
 1464: void free_imatrix(m,nrl,nrh,ncl,nch)
 1465:       int **m;
 1466:       long nch,ncl,nrh,nrl; 
 1467:      /* free an int matrix allocated by imatrix() */ 
 1468: { 
 1469:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
 1470:   free((FREE_ARG) (m+nrl-NR_END)); 
 1471: } 
 1472: 
 1473: /******************* matrix *******************************/
 1474: double **matrix(long nrl, long nrh, long ncl, long nch)
 1475: {
 1476:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
 1477:   double **m;
 1478: 
 1479:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1480:   if (!m) nrerror("allocation failure 1 in matrix()");
 1481:   m += NR_END;
 1482:   m -= nrl;
 1483: 
 1484:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1485:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1486:   m[nrl] += NR_END;
 1487:   m[nrl] -= ncl;
 1488: 
 1489:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1490:   return m;
 1491:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
 1492: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
 1493: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
 1494:    */
 1495: }
 1496: 
 1497: /*************************free matrix ************************/
 1498: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
 1499: {
 1500:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1501:   free((FREE_ARG)(m+nrl-NR_END));
 1502: }
 1503: 
 1504: /******************* ma3x *******************************/
 1505: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
 1506: {
 1507:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
 1508:   double ***m;
 1509: 
 1510:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1511:   if (!m) nrerror("allocation failure 1 in matrix()");
 1512:   m += NR_END;
 1513:   m -= nrl;
 1514: 
 1515:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1516:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1517:   m[nrl] += NR_END;
 1518:   m[nrl] -= ncl;
 1519: 
 1520:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1521: 
 1522:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
 1523:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
 1524:   m[nrl][ncl] += NR_END;
 1525:   m[nrl][ncl] -= nll;
 1526:   for (j=ncl+1; j<=nch; j++) 
 1527:     m[nrl][j]=m[nrl][j-1]+nlay;
 1528:   
 1529:   for (i=nrl+1; i<=nrh; i++) {
 1530:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
 1531:     for (j=ncl+1; j<=nch; j++) 
 1532:       m[i][j]=m[i][j-1]+nlay;
 1533:   }
 1534:   return m; 
 1535:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
 1536:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
 1537:   */
 1538: }
 1539: 
 1540: /*************************free ma3x ************************/
 1541: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
 1542: {
 1543:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
 1544:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1545:   free((FREE_ARG)(m+nrl-NR_END));
 1546: }
 1547: 
 1548: /*************** function subdirf ***********/
 1549: char *subdirf(char fileres[])
 1550: {
 1551:   /* Caution optionfilefiname is hidden */
 1552:   strcpy(tmpout,optionfilefiname);
 1553:   strcat(tmpout,"/"); /* Add to the right */
 1554:   strcat(tmpout,fileres);
 1555:   return tmpout;
 1556: }
 1557: 
 1558: /*************** function subdirf2 ***********/
 1559: char *subdirf2(char fileres[], char *preop)
 1560: {
 1561:   
 1562:   /* Caution optionfilefiname is hidden */
 1563:   strcpy(tmpout,optionfilefiname);
 1564:   strcat(tmpout,"/");
 1565:   strcat(tmpout,preop);
 1566:   strcat(tmpout,fileres);
 1567:   return tmpout;
 1568: }
 1569: 
 1570: /*************** function subdirf3 ***********/
 1571: char *subdirf3(char fileres[], char *preop, char *preop2)
 1572: {
 1573:   
 1574:   /* Caution optionfilefiname is hidden */
 1575:   strcpy(tmpout,optionfilefiname);
 1576:   strcat(tmpout,"/");
 1577:   strcat(tmpout,preop);
 1578:   strcat(tmpout,preop2);
 1579:   strcat(tmpout,fileres);
 1580:   return tmpout;
 1581: }
 1582:  
 1583: /*************** function subdirfext ***********/
 1584: char *subdirfext(char fileres[], char *preop, char *postop)
 1585: {
 1586:   
 1587:   strcpy(tmpout,preop);
 1588:   strcat(tmpout,fileres);
 1589:   strcat(tmpout,postop);
 1590:   return tmpout;
 1591: }
 1592: 
 1593: /*************** function subdirfext3 ***********/
 1594: char *subdirfext3(char fileres[], char *preop, char *postop)
 1595: {
 1596:   
 1597:   /* Caution optionfilefiname is hidden */
 1598:   strcpy(tmpout,optionfilefiname);
 1599:   strcat(tmpout,"/");
 1600:   strcat(tmpout,preop);
 1601:   strcat(tmpout,fileres);
 1602:   strcat(tmpout,postop);
 1603:   return tmpout;
 1604: }
 1605:  
 1606: char *asc_diff_time(long time_sec, char ascdiff[])
 1607: {
 1608:   long sec_left, days, hours, minutes;
 1609:   days = (time_sec) / (60*60*24);
 1610:   sec_left = (time_sec) % (60*60*24);
 1611:   hours = (sec_left) / (60*60) ;
 1612:   sec_left = (sec_left) %(60*60);
 1613:   minutes = (sec_left) /60;
 1614:   sec_left = (sec_left) % (60);
 1615:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
 1616:   return ascdiff;
 1617: }
 1618: 
 1619: /***************** f1dim *************************/
 1620: extern int ncom; 
 1621: extern double *pcom,*xicom;
 1622: extern double (*nrfunc)(double []); 
 1623:  
 1624: double f1dim(double x) 
 1625: { 
 1626:   int j; 
 1627:   double f;
 1628:   double *xt; 
 1629:  
 1630:   xt=vector(1,ncom); 
 1631:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
 1632:   f=(*nrfunc)(xt); 
 1633:   free_vector(xt,1,ncom); 
 1634:   return f; 
 1635: } 
 1636: 
 1637: /*****************brent *************************/
 1638: double brent(double ax, double bx, double cx, double (*f)(double), double tol, 	double *xmin) 
 1639: {
 1640:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
 1641:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
 1642:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
 1643:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
 1644:    * returned function value. 
 1645:   */
 1646:   int iter; 
 1647:   double a,b,d,etemp;
 1648:   double fu=0,fv,fw,fx;
 1649:   double ftemp=0.;
 1650:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
 1651:   double e=0.0; 
 1652:  
 1653:   a=(ax < cx ? ax : cx); 
 1654:   b=(ax > cx ? ax : cx); 
 1655:   x=w=v=bx; 
 1656:   fw=fv=fx=(*f)(x); 
 1657:   for (iter=1;iter<=ITMAX;iter++) { 
 1658:     xm=0.5*(a+b); 
 1659:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
 1660:     /*		if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
 1661:     printf(".");fflush(stdout);
 1662:     fprintf(ficlog,".");fflush(ficlog);
 1663: #ifdef DEBUGBRENT
 1664:     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);
 1665:     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);
 1666:     /*		if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
 1667: #endif
 1668:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
 1669:       *xmin=x; 
 1670:       return fx; 
 1671:     } 
 1672:     ftemp=fu;
 1673:     if (fabs(e) > tol1) { 
 1674:       r=(x-w)*(fx-fv); 
 1675:       q=(x-v)*(fx-fw); 
 1676:       p=(x-v)*q-(x-w)*r; 
 1677:       q=2.0*(q-r); 
 1678:       if (q > 0.0) p = -p; 
 1679:       q=fabs(q); 
 1680:       etemp=e; 
 1681:       e=d; 
 1682:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
 1683: 				d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1684:       else { 
 1685: 				d=p/q; 
 1686: 				u=x+d; 
 1687: 				if (u-a < tol2 || b-u < tol2) 
 1688: 					d=SIGN(tol1,xm-x); 
 1689:       } 
 1690:     } else { 
 1691:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1692:     } 
 1693:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
 1694:     fu=(*f)(u); 
 1695:     if (fu <= fx) { 
 1696:       if (u >= x) a=x; else b=x; 
 1697:       SHFT(v,w,x,u) 
 1698:       SHFT(fv,fw,fx,fu) 
 1699:     } else { 
 1700:       if (u < x) a=u; else b=u; 
 1701:       if (fu <= fw || w == x) { 
 1702: 				v=w; 
 1703: 				w=u; 
 1704: 				fv=fw; 
 1705: 				fw=fu; 
 1706:       } else if (fu <= fv || v == x || v == w) { 
 1707: 				v=u; 
 1708: 				fv=fu; 
 1709:       } 
 1710:     } 
 1711:   } 
 1712:   nrerror("Too many iterations in brent"); 
 1713:   *xmin=x; 
 1714:   return fx; 
 1715: } 
 1716: 
 1717: /****************** mnbrak ***********************/
 1718: 
 1719: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
 1720: 	    double (*func)(double)) 
 1721: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
 1722: the downhill direction (defined by the function as evaluated at the initial points) and returns
 1723: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
 1724: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
 1725:    */
 1726:   double ulim,u,r,q, dum;
 1727:   double fu; 
 1728: 
 1729:   double scale=10.;
 1730:   int iterscale=0;
 1731: 
 1732:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
 1733:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
 1734: 
 1735: 
 1736:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
 1737:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
 1738:   /*   *bx = *ax - (*ax - *bx)/scale; */
 1739:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
 1740:   /* } */
 1741: 
 1742:   if (*fb > *fa) { 
 1743:     SHFT(dum,*ax,*bx,dum) 
 1744:     SHFT(dum,*fb,*fa,dum) 
 1745:   } 
 1746:   *cx=(*bx)+GOLD*(*bx-*ax); 
 1747:   *fc=(*func)(*cx); 
 1748: #ifdef DEBUG
 1749:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
 1750:   fprintf(ficlog,"mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
 1751: #endif
 1752:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc. If fc=inf it exits and if flat fb=fc it exits too.*/
 1753:     r=(*bx-*ax)*(*fb-*fc); 
 1754:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
 1755:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
 1756:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
 1757:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
 1758:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
 1759:       fu=(*func)(u); 
 1760: #ifdef DEBUG
 1761:       /* f(x)=A(x-u)**2+f(u) */
 1762:       double A, fparabu; 
 1763:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 1764:       fparabu= *fa - A*(*ax-u)*(*ax-u);
 1765:       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);
 1766:       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);
 1767:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
 1768:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
 1769:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
 1770:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
 1771: #endif 
 1772: #ifdef MNBRAKORIGINAL
 1773: #else
 1774: /*       if (fu > *fc) { */
 1775: /* #ifdef DEBUG */
 1776: /*       printf("mnbrak4  fu > fc \n"); */
 1777: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
 1778: /* #endif */
 1779: /* 	/\* 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 *\\/  *\/ */
 1780: /* 	/\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
 1781: /* 	dum=u; /\* Shifting c and u *\/ */
 1782: /* 	u = *cx; */
 1783: /* 	*cx = dum; */
 1784: /* 	dum = fu; */
 1785: /* 	fu = *fc; */
 1786: /* 	*fc =dum; */
 1787: /*       } else { /\* end *\/ */
 1788: /* #ifdef DEBUG */
 1789: /*       printf("mnbrak3  fu < fc \n"); */
 1790: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
 1791: /* #endif */
 1792: /* 	dum=u; /\* Shifting c and u *\/ */
 1793: /* 	u = *cx; */
 1794: /* 	*cx = dum; */
 1795: /* 	dum = fu; */
 1796: /* 	fu = *fc; */
 1797: /* 	*fc =dum; */
 1798: /*       } */
 1799: #ifdef DEBUGMNBRAK
 1800: 		 double A, fparabu; 
 1801:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 1802:      fparabu= *fa - A*(*ax-u)*(*ax-u);
 1803:      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);
 1804:      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);
 1805: #endif
 1806:       dum=u; /* Shifting c and u */
 1807:       u = *cx;
 1808:       *cx = dum;
 1809:       dum = fu;
 1810:       fu = *fc;
 1811:       *fc =dum;
 1812: #endif
 1813:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
 1814: #ifdef DEBUG
 1815:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
 1816:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
 1817: #endif
 1818:       fu=(*func)(u); 
 1819:       if (fu < *fc) { 
 1820: #ifdef DEBUG
 1821: 				printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
 1822: 			  fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
 1823: #endif
 1824: 			  SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
 1825: 				SHFT(*fb,*fc,fu,(*func)(u)) 
 1826: #ifdef DEBUG
 1827: 					printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
 1828: #endif
 1829:       } 
 1830:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
 1831: #ifdef DEBUG
 1832:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
 1833:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
 1834: #endif
 1835:       u=ulim; 
 1836:       fu=(*func)(u); 
 1837:     } else { /* u could be left to b (if r > q parabola has a maximum) */
 1838: #ifdef DEBUG
 1839:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
 1840:       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);
 1841: #endif
 1842:       u=(*cx)+GOLD*(*cx-*bx); 
 1843:       fu=(*func)(u); 
 1844: #ifdef DEBUG
 1845:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
 1846:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
 1847: #endif
 1848:     } /* end tests */
 1849:     SHFT(*ax,*bx,*cx,u) 
 1850:     SHFT(*fa,*fb,*fc,fu) 
 1851: #ifdef DEBUG
 1852:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
 1853:       fprintf(ficlog, "\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
 1854: #endif
 1855:   } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
 1856: } 
 1857: 
 1858: /*************** linmin ************************/
 1859: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
 1860: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
 1861: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
 1862: the value of func at the returned location p . This is actually all accomplished by calling the
 1863: routines mnbrak and brent .*/
 1864: int ncom; 
 1865: double *pcom,*xicom;
 1866: double (*nrfunc)(double []); 
 1867:  
 1868: #ifdef LINMINORIGINAL
 1869: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
 1870: #else
 1871: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
 1872: #endif
 1873: { 
 1874:   double brent(double ax, double bx, double cx, 
 1875: 	       double (*f)(double), double tol, double *xmin); 
 1876:   double f1dim(double x); 
 1877:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
 1878: 	      double *fc, double (*func)(double)); 
 1879:   int j; 
 1880:   double xx,xmin,bx,ax; 
 1881:   double fx,fb,fa;
 1882: 
 1883: #ifdef LINMINORIGINAL
 1884: #else
 1885:   double scale=10., axs, xxs; /* Scale added for infinity */
 1886: #endif
 1887:   
 1888:   ncom=n; 
 1889:   pcom=vector(1,n); 
 1890:   xicom=vector(1,n); 
 1891:   nrfunc=func; 
 1892:   for (j=1;j<=n;j++) { 
 1893:     pcom[j]=p[j]; 
 1894:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
 1895:   } 
 1896: 
 1897: #ifdef LINMINORIGINAL
 1898:   xx=1.;
 1899: #else
 1900:   axs=0.0;
 1901:   xxs=1.;
 1902:   do{
 1903:     xx= xxs;
 1904: #endif
 1905:     ax=0.;
 1906:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
 1907:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
 1908:     /* 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))   */
 1909:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
 1910:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
 1911:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
 1912:     /* 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]]*/
 1913: #ifdef LINMINORIGINAL
 1914: #else
 1915:     if (fx != fx){
 1916: 			xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
 1917: 			printf("|");
 1918: 			fprintf(ficlog,"|");
 1919: #ifdef DEBUGLINMIN
 1920: 			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);
 1921: #endif
 1922:     }
 1923:   }while(fx != fx && xxs > 1.e-5);
 1924: #endif
 1925:   
 1926: #ifdef DEBUGLINMIN
 1927:   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);
 1928:   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);
 1929: #endif
 1930: #ifdef LINMINORIGINAL
 1931: #else
 1932: 	if(fb == fx){ /* Flat function in the direction */
 1933: 		xmin=xx;
 1934:     *flat=1;
 1935: 	}else{
 1936:     *flat=0;
 1937: #endif
 1938: 		/*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
 1939:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
 1940:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
 1941:   /* fmin = f(p[j] + xmin * xi[j]) */
 1942:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
 1943:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
 1944: #ifdef DEBUG
 1945:   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);
 1946:   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);
 1947: #endif
 1948: #ifdef LINMINORIGINAL
 1949: #else
 1950: 			}
 1951: #endif
 1952: #ifdef DEBUGLINMIN
 1953:   printf("linmin end ");
 1954:   fprintf(ficlog,"linmin end ");
 1955: #endif
 1956:   for (j=1;j<=n;j++) { 
 1957: #ifdef LINMINORIGINAL
 1958:     xi[j] *= xmin; 
 1959: #else
 1960: #ifdef DEBUGLINMIN
 1961:     if(xxs <1.0)
 1962:       printf(" before xi[%d]=%12.8f", j,xi[j]);
 1963: #endif
 1964:     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) */
 1965: #ifdef DEBUGLINMIN
 1966:     if(xxs <1.0)
 1967:       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 );
 1968: #endif
 1969: #endif
 1970:     p[j] += xi[j]; /* Parameters values are updated accordingly */
 1971:   } 
 1972: #ifdef DEBUGLINMIN
 1973:   printf("\n");
 1974:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
 1975:   fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
 1976:   for (j=1;j<=n;j++) { 
 1977:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
 1978:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
 1979:     if(j % ncovmodel == 0){
 1980:       printf("\n");
 1981:       fprintf(ficlog,"\n");
 1982:     }
 1983:   }
 1984: #else
 1985: #endif
 1986:   free_vector(xicom,1,n); 
 1987:   free_vector(pcom,1,n); 
 1988: } 
 1989: 
 1990: 
 1991: /*************** powell ************************/
 1992: /*
 1993: Minimization of a function func of n variables. Input consists of an initial starting point
 1994: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
 1995: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
 1996: such that failure to decrease by more than this amount on one iteration signals doneness. On
 1997: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
 1998: function value at p , and iter is the number of iterations taken. The routine linmin is used.
 1999:  */
 2000: #ifdef LINMINORIGINAL
 2001: #else
 2002: 	int *flatdir; /* Function is vanishing in that direction */
 2003: 	int flat=0, flatd=0; /* Function is vanishing in that direction */
 2004: #endif
 2005: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
 2006: 	    double (*func)(double [])) 
 2007: { 
 2008: #ifdef LINMINORIGINAL
 2009:  void linmin(double p[], double xi[], int n, double *fret, 
 2010: 	      double (*func)(double [])); 
 2011: #else 
 2012:  void linmin(double p[], double xi[], int n, double *fret, 
 2013: 						 double (*func)(double []),int *flat); 
 2014: #endif
 2015:   int i,ibig,j; 
 2016:   double del,t,*pt,*ptt,*xit;
 2017:   double directest;
 2018:   double fp,fptt;
 2019:   double *xits;
 2020:   int niterf, itmp;
 2021: #ifdef LINMINORIGINAL
 2022: #else
 2023: 
 2024:   flatdir=ivector(1,n); 
 2025:   for (j=1;j<=n;j++) flatdir[j]=0; 
 2026: #endif
 2027: 
 2028:   pt=vector(1,n); 
 2029:   ptt=vector(1,n); 
 2030:   xit=vector(1,n); 
 2031:   xits=vector(1,n); 
 2032:   *fret=(*func)(p); 
 2033:   for (j=1;j<=n;j++) pt[j]=p[j]; 
 2034:   rcurr_time = time(NULL);  
 2035:   for (*iter=1;;++(*iter)) { 
 2036:     fp=(*fret); /* From former iteration or initial value */
 2037:     ibig=0; 
 2038:     del=0.0; 
 2039:     rlast_time=rcurr_time;
 2040:     /* (void) gettimeofday(&curr_time,&tzp); */
 2041:     rcurr_time = time(NULL);  
 2042:     curr_time = *localtime(&rcurr_time);
 2043:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
 2044:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
 2045: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
 2046:     for (i=1;i<=n;i++) {
 2047:       printf(" %d %.12f",i, p[i]);
 2048:       fprintf(ficlog," %d %.12lf",i, p[i]);
 2049:       fprintf(ficrespow," %.12lf", p[i]);
 2050:     }
 2051:     printf("\n");
 2052:     fprintf(ficlog,"\n");
 2053:     fprintf(ficrespow,"\n");fflush(ficrespow);
 2054:     if(*iter <=3){
 2055:       tml = *localtime(&rcurr_time);
 2056:       strcpy(strcurr,asctime(&tml));
 2057:       rforecast_time=rcurr_time; 
 2058:       itmp = strlen(strcurr);
 2059:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
 2060: 				strcurr[itmp-1]='\0';
 2061:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 2062:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 2063:       for(niterf=10;niterf<=30;niterf+=10){
 2064: 				rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
 2065: 				forecast_time = *localtime(&rforecast_time);
 2066: 				strcpy(strfor,asctime(&forecast_time));
 2067: 				itmp = strlen(strfor);
 2068: 				if(strfor[itmp-1]=='\n')
 2069: 					strfor[itmp-1]='\0';
 2070: 				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);
 2071: 				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);
 2072:       }
 2073:     }
 2074:     for (i=1;i<=n;i++) { /* For each direction i */
 2075:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
 2076:       fptt=(*fret); 
 2077: #ifdef DEBUG
 2078:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 2079:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 2080: #endif
 2081:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
 2082:       fprintf(ficlog,"%d",i);fflush(ficlog);
 2083: #ifdef LINMINORIGINAL
 2084:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
 2085: #else
 2086:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
 2087: 			flatdir[i]=flat; /* Function is vanishing in that direction i */
 2088: #endif
 2089: 			/* Outputs are fret(new point p) p is updated and xit rescaled */
 2090:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
 2091: 				/* because that direction will be replaced unless the gain del is small */
 2092: 				/* in comparison with the 'probable' gain, mu^2, with the last average direction. */
 2093: 				/* Unless the n directions are conjugate some gain in the determinant may be obtained */
 2094: 				/* with the new direction. */
 2095: 				del=fabs(fptt-(*fret)); 
 2096: 				ibig=i; 
 2097:       } 
 2098: #ifdef DEBUG
 2099:       printf("%d %.12e",i,(*fret));
 2100:       fprintf(ficlog,"%d %.12e",i,(*fret));
 2101:       for (j=1;j<=n;j++) {
 2102: 				xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
 2103: 				printf(" x(%d)=%.12e",j,xit[j]);
 2104: 				fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
 2105:       }
 2106:       for(j=1;j<=n;j++) {
 2107: 				printf(" p(%d)=%.12e",j,p[j]);
 2108: 				fprintf(ficlog," p(%d)=%.12e",j,p[j]);
 2109:       }
 2110:       printf("\n");
 2111:       fprintf(ficlog,"\n");
 2112: #endif
 2113:     } /* end loop on each direction i */
 2114:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
 2115:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
 2116:     /* New value of last point Pn is not computed, P(n-1) */
 2117:       for(j=1;j<=n;j++) {
 2118: 				if(flatdir[j] >0){
 2119: 					printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
 2120: 					fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
 2121: 				}
 2122: 				/* printf("\n"); */
 2123: 				/* fprintf(ficlog,"\n"); */
 2124: 			}
 2125:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
 2126:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
 2127:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
 2128:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
 2129:       /* decreased of more than 3.84  */
 2130:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
 2131:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
 2132:       /* By adding 10 parameters more the gain should be 18.31 */
 2133: 			
 2134:       /* Starting the program with initial values given by a former maximization will simply change */
 2135:       /* the scales of the directions and the directions, because the are reset to canonical directions */
 2136:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
 2137:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
 2138: #ifdef DEBUG
 2139:       int k[2],l;
 2140:       k[0]=1;
 2141:       k[1]=-1;
 2142:       printf("Max: %.12e",(*func)(p));
 2143:       fprintf(ficlog,"Max: %.12e",(*func)(p));
 2144:       for (j=1;j<=n;j++) {
 2145: 	printf(" %.12e",p[j]);
 2146: 	fprintf(ficlog," %.12e",p[j]);
 2147:       }
 2148:       printf("\n");
 2149:       fprintf(ficlog,"\n");
 2150:       for(l=0;l<=1;l++) {
 2151: 	for (j=1;j<=n;j++) {
 2152: 	  ptt[j]=p[j]+(p[j]-pt[j])*k[l];
 2153: 	  printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 2154: 	  fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 2155: 	}
 2156: 	printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 2157: 	fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 2158:       }
 2159: #endif
 2160: 
 2161: #ifdef LINMINORIGINAL
 2162: #else
 2163:       free_ivector(flatdir,1,n); 
 2164: #endif
 2165:       free_vector(xit,1,n); 
 2166:       free_vector(xits,1,n); 
 2167:       free_vector(ptt,1,n); 
 2168:       free_vector(pt,1,n); 
 2169:       return; 
 2170:     } /* enough precision */ 
 2171:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
 2172:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
 2173:       ptt[j]=2.0*p[j]-pt[j]; 
 2174:       xit[j]=p[j]-pt[j]; 
 2175:       pt[j]=p[j]; 
 2176:     } 
 2177:     fptt=(*func)(ptt); /* f_3 */
 2178: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
 2179: 		if (*iter <=4) {
 2180: #else
 2181: #endif
 2182: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
 2183: #else
 2184:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
 2185: #endif
 2186:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
 2187:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
 2188:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
 2189:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
 2190:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
 2191:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
 2192:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
 2193:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
 2194:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
 2195:       /*  Even if f3 <f1, directest can be negative and t >0 */
 2196:       /* mu² and del² are equal when f3=f1 */
 2197: 			/* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
 2198: 			/* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
 2199: 			/* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
 2200: 			/* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
 2201: #ifdef NRCORIGINAL
 2202:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
 2203: #else
 2204:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
 2205:       t= t- del*SQR(fp-fptt);
 2206: #endif
 2207:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
 2208: #ifdef DEBUG
 2209:       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);
 2210:       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);
 2211:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 2212: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 2213:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 2214: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 2215:       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);
 2216:       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);
 2217: #endif
 2218: #ifdef POWELLORIGINAL
 2219:       if (t < 0.0) { /* Then we use it for new direction */
 2220: #else
 2221:       if (directest*t < 0.0) { /* Contradiction between both tests */
 2222: 				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);
 2223:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 2224:         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);
 2225:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 2226:       } 
 2227:       if (directest < 0.0) { /* Then we use it for new direction */
 2228: #endif
 2229: #ifdef DEBUGLINMIN
 2230: 				printf("Before linmin in direction P%d-P0\n",n);
 2231: 				for (j=1;j<=n;j++) {
 2232: 					printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2233: 					fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2234: 					if(j % ncovmodel == 0){
 2235: 						printf("\n");
 2236: 						fprintf(ficlog,"\n");
 2237: 					}
 2238: 				}
 2239: #endif
 2240: #ifdef LINMINORIGINAL
 2241:  				linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
 2242: #else
 2243: 				linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
 2244: 				flatdir[i]=flat; /* Function is vanishing in that direction i */
 2245: #endif
 2246: 
 2247: #ifdef DEBUGLINMIN
 2248: 				for (j=1;j<=n;j++) { 
 2249: 					printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2250: 					fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2251: 					if(j % ncovmodel == 0){
 2252: 						printf("\n");
 2253: 						fprintf(ficlog,"\n");
 2254: 					}
 2255: 				}
 2256: #endif
 2257: 				for (j=1;j<=n;j++) { 
 2258: 					xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
 2259: 					xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
 2260: 				}
 2261: #ifdef LINMINORIGINAL
 2262: #else
 2263: 				for (j=1, flatd=0;j<=n;j++) {
 2264: 					if(flatdir[j]>0)
 2265: 						flatd++;
 2266: 				}
 2267: 				if(flatd >0){
 2268: 					printf("%d flat directions\n",flatd);
 2269: 					fprintf(ficlog,"%d flat directions\n",flatd);
 2270: 					for (j=1;j<=n;j++) { 
 2271: 						if(flatdir[j]>0){
 2272: 							printf("%d ",j);
 2273: 							fprintf(ficlog,"%d ",j);
 2274: 						}
 2275: 					}
 2276: 					printf("\n");
 2277: 					fprintf(ficlog,"\n");
 2278: 				}
 2279: #endif
 2280: 				printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 2281: 				fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 2282: 				
 2283: #ifdef DEBUG
 2284: 				printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 2285: 				fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 2286: 				for(j=1;j<=n;j++){
 2287: 					printf(" %lf",xit[j]);
 2288: 					fprintf(ficlog," %lf",xit[j]);
 2289: 				}
 2290: 				printf("\n");
 2291: 				fprintf(ficlog,"\n");
 2292: #endif
 2293:       } /* end of t or directest negative */
 2294: #ifdef POWELLNOF3INFF1TEST
 2295: #else
 2296:     } /* end if (fptt < fp)  */
 2297: #endif
 2298: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
 2299: 		} /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
 2300: #else
 2301: #endif
 2302:   } /* loop iteration */ 
 2303: } 
 2304: 
 2305: /**** Prevalence limit (stable or period prevalence)  ****************/
 2306: 
 2307: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
 2308: {
 2309:   /* Computes the prevalence limit in each live state at age x and for covariate ij by left multiplying the unit
 2310:      matrix by transitions matrix until convergence is reached with precision ftolpl */
 2311:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
 2312:   /* Wx is row vector: population in state 1, population in state 2, population dead */
 2313:   /* or prevalence in state 1, prevalence in state 2, 0 */
 2314:   /* newm is the matrix after multiplications, its rows are identical at a factor */
 2315:   /* Initial matrix pimij */
 2316:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
 2317:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
 2318:   /*  0,                   0                  , 1} */
 2319:   /*
 2320:    * and after some iteration: */
 2321:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
 2322:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
 2323:   /*  0,                   0                  , 1} */
 2324:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
 2325:   /* {0.51571254859325999, 0.4842874514067399, */
 2326:   /*  0.51326036147820708, 0.48673963852179264} */
 2327:   /* If we start from prlim again, prlim tends to a constant matrix */
 2328: 
 2329:   int i, ii,j,k;
 2330:   double *min, *max, *meandiff, maxmax,sumnew=0.;
 2331:   /* double **matprod2(); */ /* test */
 2332:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
 2333:   double **newm;
 2334:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
 2335:   int ncvloop=0;
 2336:   
 2337:   min=vector(1,nlstate);
 2338:   max=vector(1,nlstate);
 2339:   meandiff=vector(1,nlstate);
 2340: 
 2341: 	/* Starting with matrix unity */
 2342:   for (ii=1;ii<=nlstate+ndeath;ii++)
 2343:     for (j=1;j<=nlstate+ndeath;j++){
 2344:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2345:     }
 2346:   
 2347:   cov[1]=1.;
 2348:   
 2349:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2350:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
 2351:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
 2352:     ncvloop++;
 2353:     newm=savm;
 2354:     /* Covariates have to be included here again */
 2355:     cov[2]=agefin;
 2356:     if(nagesqr==1)
 2357:       cov[3]= agefin*agefin;;
 2358:     for (k=1; k<=cptcovn;k++) {
 2359:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 2360: 			/* Here comes the value of the covariate 'ij' */
 2361:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 2362:       /* 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])]); */
 2363:     }
 2364:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2365:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
 2366:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
 2367:     for (k=1; k<=cptcovprod;k++) /* Useless */
 2368:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 2369:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
 2370:     
 2371:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 2372:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 2373:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 2374:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2375:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 2376: 		/* age and covariate values of ij are in 'cov' */
 2377:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
 2378:     
 2379:     savm=oldm;
 2380:     oldm=newm;
 2381: 
 2382:     for(j=1; j<=nlstate; j++){
 2383:       max[j]=0.;
 2384:       min[j]=1.;
 2385:     }
 2386:     for(i=1;i<=nlstate;i++){
 2387:       sumnew=0;
 2388:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
 2389:       for(j=1; j<=nlstate; j++){ 
 2390: 	prlim[i][j]= newm[i][j]/(1-sumnew);
 2391: 	max[j]=FMAX(max[j],prlim[i][j]);
 2392: 	min[j]=FMIN(min[j],prlim[i][j]);
 2393:       }
 2394:     }
 2395: 
 2396:     maxmax=0.;
 2397:     for(j=1; j<=nlstate; j++){
 2398:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
 2399:       maxmax=FMAX(maxmax,meandiff[j]);
 2400:       /* 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); */
 2401:     } /* j loop */
 2402:     *ncvyear= (int)age- (int)agefin;
 2403:     /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
 2404:     if(maxmax < ftolpl){
 2405:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
 2406:       free_vector(min,1,nlstate);
 2407:       free_vector(max,1,nlstate);
 2408:       free_vector(meandiff,1,nlstate);
 2409:       return prlim;
 2410:     }
 2411:   } /* age loop */
 2412:     /* After some age loop it doesn't converge */
 2413:   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\
 2414: 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);
 2415:   /* 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); */
 2416:   free_vector(min,1,nlstate);
 2417:   free_vector(max,1,nlstate);
 2418:   free_vector(meandiff,1,nlstate);
 2419:   
 2420:   return prlim; /* should not reach here */
 2421: }
 2422: 
 2423: 
 2424:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
 2425: 
 2426:  /* 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) */
 2427:  /* 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) */
 2428:  double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij)
 2429: {
 2430:   /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
 2431:      matrix by transitions matrix until convergence is reached with precision ftolpl */
 2432:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
 2433:   /* Wx is row vector: population in state 1, population in state 2, population dead */
 2434:   /* or prevalence in state 1, prevalence in state 2, 0 */
 2435:   /* newm is the matrix after multiplications, its rows are identical at a factor */
 2436:   /* Initial matrix pimij */
 2437:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
 2438:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
 2439:   /*  0,                   0                  , 1} */
 2440:   /*
 2441:    * and after some iteration: */
 2442:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
 2443:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
 2444:   /*  0,                   0                  , 1} */
 2445:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
 2446:   /* {0.51571254859325999, 0.4842874514067399, */
 2447:   /*  0.51326036147820708, 0.48673963852179264} */
 2448:   /* If we start from prlim again, prlim tends to a constant matrix */
 2449: 
 2450:   int i, ii,j,k;
 2451:   double *min, *max, *meandiff, maxmax,sumnew=0.;
 2452:   /* double **matprod2(); */ /* test */
 2453:   double **out, cov[NCOVMAX+1], **bmij();
 2454:   double **newm;
 2455:   double	 **dnewm, **doldm, **dsavm;  /* for use */
 2456:   double	 **oldm, **savm;  /* for use */
 2457: 
 2458:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
 2459:   int ncvloop=0;
 2460:   
 2461:   min=vector(1,nlstate);
 2462:   max=vector(1,nlstate);
 2463:   meandiff=vector(1,nlstate);
 2464: 
 2465: 	dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
 2466: 	oldm=oldms; savm=savms;
 2467: 
 2468: 	/* Starting with matrix unity */
 2469: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2470: 		for (j=1;j<=nlstate+ndeath;j++){
 2471:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2472:     }
 2473:   
 2474:   cov[1]=1.;
 2475:   
 2476:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2477:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
 2478:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
 2479:   for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
 2480:     ncvloop++;
 2481:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
 2482: 		/* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
 2483:     /* Covariates have to be included here again */
 2484:     cov[2]=agefin;
 2485:     if(nagesqr==1)
 2486:       cov[3]= agefin*agefin;;
 2487:     for (k=1; k<=cptcovn;k++) {
 2488:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 2489:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 2490:       /* 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])]); */
 2491:     }
 2492:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2493:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
 2494:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
 2495:     for (k=1; k<=cptcovprod;k++) /* Useless */
 2496:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 2497:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
 2498:     
 2499:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 2500:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 2501:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 2502:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2503:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 2504: 		/* ij should be linked to the correct index of cov */
 2505: 		/* age and covariate values ij are in 'cov', but we need to pass
 2506: 		 * ij for the observed prevalence at age and status and covariate
 2507: 		 * number:  prevacurrent[(int)agefin][ii][ij]
 2508: 		 */
 2509:     /* 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 *\/ */
 2510:     /* 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 *\/ */
 2511:     out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij)); /* Bug Valgrind */
 2512:     savm=oldm;
 2513:     oldm=newm;
 2514:     for(j=1; j<=nlstate; j++){
 2515:       max[j]=0.;
 2516:       min[j]=1.;
 2517:     }
 2518:     for(j=1; j<=nlstate; j++){ 
 2519:       for(i=1;i<=nlstate;i++){
 2520: 				/* bprlim[i][j]= newm[i][j]/(1-sumnew); */
 2521: 				bprlim[i][j]= newm[i][j];
 2522: 				max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
 2523: 				min[i]=FMIN(min[i],bprlim[i][j]);
 2524:       }
 2525:     }
 2526: 		
 2527:     maxmax=0.;
 2528:     for(i=1; i<=nlstate; i++){
 2529:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
 2530:       maxmax=FMAX(maxmax,meandiff[i]);
 2531:       /* 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); */
 2532:     } /* j loop */
 2533:     *ncvyear= -( (int)age- (int)agefin);
 2534:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
 2535:     if(maxmax < ftolpl){
 2536:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
 2537:       free_vector(min,1,nlstate);
 2538:       free_vector(max,1,nlstate);
 2539:       free_vector(meandiff,1,nlstate);
 2540:       return bprlim;
 2541:     }
 2542:   } /* age loop */
 2543:     /* After some age loop it doesn't converge */
 2544:   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\
 2545: 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);
 2546:   /* 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); */
 2547:   free_vector(min,1,nlstate);
 2548:   free_vector(max,1,nlstate);
 2549:   free_vector(meandiff,1,nlstate);
 2550:   
 2551:   return bprlim; /* should not reach here */
 2552: }
 2553: 
 2554: /*************** transition probabilities ***************/ 
 2555: 
 2556: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 2557: {
 2558:   /* According to parameters values stored in x and the covariate's values stored in cov,
 2559:      computes the probability to be observed in state j being in state i by appying the
 2560:      model to the ncovmodel covariates (including constant and age).
 2561:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 2562:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 2563:      ncth covariate in the global vector x is given by the formula:
 2564:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 2565:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 2566:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 2567:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 2568:      Outputs ps[i][j] the probability to be observed in j being in j according to
 2569:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 2570:   */
 2571:   double s1, lnpijopii;
 2572:   /*double t34;*/
 2573:   int i,j, nc, ii, jj;
 2574: 
 2575:   for(i=1; i<= nlstate; i++){
 2576:     for(j=1; j<i;j++){
 2577:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2578: 	/*lnpijopii += param[i][j][nc]*cov[nc];*/
 2579: 	lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 2580: 	/* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2581:       }
 2582:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2583:       /* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2584:     }
 2585:     for(j=i+1; j<=nlstate+ndeath;j++){
 2586:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2587: 	/*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 2588: 	lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 2589: 	/* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 2590:       }
 2591:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2592:     }
 2593:   }
 2594:   
 2595:   for(i=1; i<= nlstate; i++){
 2596:     s1=0;
 2597:     for(j=1; j<i; j++){
 2598:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2599:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2600:     }
 2601:     for(j=i+1; j<=nlstate+ndeath; j++){
 2602:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2603:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2604:     }
 2605:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 2606:     ps[i][i]=1./(s1+1.);
 2607:     /* Computing other pijs */
 2608:     for(j=1; j<i; j++)
 2609:       ps[i][j]= exp(ps[i][j])*ps[i][i];
 2610:     for(j=i+1; j<=nlstate+ndeath; j++)
 2611:       ps[i][j]= exp(ps[i][j])*ps[i][i];
 2612:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 2613:   } /* end i */
 2614:   
 2615:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 2616:     for(jj=1; jj<= nlstate+ndeath; jj++){
 2617:       ps[ii][jj]=0;
 2618:       ps[ii][ii]=1;
 2619:     }
 2620:   }
 2621:   
 2622:   
 2623:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 2624:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 2625:   /* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 2626:   /*   } */
 2627:   /*   printf("\n "); */
 2628:   /* } */
 2629:   /* printf("\n ");printf("%lf ",cov[2]);*/
 2630:   /*
 2631:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
 2632: 		goto end;*/
 2633:   return ps;
 2634: }
 2635: 
 2636: /*************** backward transition probabilities ***************/ 
 2637: 
 2638:  /* 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 ) */
 2639: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
 2640:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
 2641: {
 2642:   /* Computes the backward probability at age agefin and covariate ij
 2643:    * and returns in **ps as well as **bmij.
 2644:    */
 2645:   int i, ii, j,k;
 2646:   
 2647:   double **out, **pmij();
 2648:   double sumnew=0.;
 2649:   double agefin;
 2650:   
 2651:   double **dnewm, **dsavm, **doldm;
 2652:   double **bbmij;
 2653:   
 2654:   doldm=ddoldms; /* global pointers */
 2655:   dnewm=ddnewms;
 2656:   dsavm=ddsavms;
 2657:   
 2658:   agefin=cov[2];
 2659:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
 2660:      the observed prevalence (with this covariate ij) */
 2661:   dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
 2662:   /* We do have the matrix Px in savm  and we need pij */
 2663:   for (j=1;j<=nlstate+ndeath;j++){
 2664:     sumnew=0.; /* w1 p11 + w2 p21 only on live states */
 2665:     for (ii=1;ii<=nlstate;ii++){
 2666:       sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
 2667:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
 2668:     for (ii=1;ii<=nlstate+ndeath;ii++){
 2669:       if(sumnew >= 1.e-10){
 2670: 	/* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
 2671: 	/* 	doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
 2672: 	/* }else if(agefin >= agemaxpar+stepm/YEARM){ */
 2673: 	/* 	doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
 2674: 	/* }else */
 2675: 	doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
 2676:       }else{
 2677: 	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);
 2678:       }
 2679:     } /*End ii */
 2680:   } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
 2681:   /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
 2682:   bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
 2683:   /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
 2684:   /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
 2685:   /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
 2686:   /* left Product of this matrix by diag matrix of prevalences (savm) */
 2687:   for (j=1;j<=nlstate+ndeath;j++){
 2688:     for (ii=1;ii<=nlstate+ndeath;ii++){
 2689:       dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
 2690:     }
 2691:   } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
 2692:   ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
 2693:   /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
 2694:   /* end bmij */
 2695:   return ps; 
 2696: }
 2697: /*************** transition probabilities ***************/ 
 2698: 
 2699: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 2700: {
 2701:   /* According to parameters values stored in x and the covariate's values stored in cov,
 2702:      computes the probability to be observed in state j being in state i by appying the
 2703:      model to the ncovmodel covariates (including constant and age).
 2704:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 2705:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 2706:      ncth covariate in the global vector x is given by the formula:
 2707:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 2708:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 2709:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 2710:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 2711:      Outputs ps[i][j] the probability to be observed in j being in j according to
 2712:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 2713:   */
 2714:   double s1, lnpijopii;
 2715:   /*double t34;*/
 2716:   int i,j, nc, ii, jj;
 2717: 
 2718: 	for(i=1; i<= nlstate; i++){
 2719: 		for(j=1; j<i;j++){
 2720: 			for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2721: 				/*lnpijopii += param[i][j][nc]*cov[nc];*/
 2722: 				lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 2723: 				/* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2724: 			}
 2725: 			ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2726: 			/* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 2727: 		}
 2728: 		for(j=i+1; j<=nlstate+ndeath;j++){
 2729: 			for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 2730: 				/*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 2731: 				lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 2732: 				/* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 2733: 			}
 2734: 			ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 2735: 		}
 2736: 	}
 2737: 	
 2738: 	for(i=1; i<= nlstate; i++){
 2739: 		s1=0;
 2740: 		for(j=1; j<i; j++){
 2741: 			s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2742: 			/*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2743: 		}
 2744: 		for(j=i+1; j<=nlstate+ndeath; j++){
 2745: 			s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 2746: 			/*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 2747: 		}
 2748: 		/* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 2749: 		ps[i][i]=1./(s1+1.);
 2750: 		/* Computing other pijs */
 2751: 		for(j=1; j<i; j++)
 2752: 			ps[i][j]= exp(ps[i][j])*ps[i][i];
 2753: 		for(j=i+1; j<=nlstate+ndeath; j++)
 2754: 			ps[i][j]= exp(ps[i][j])*ps[i][i];
 2755: 		/* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 2756: 	} /* end i */
 2757: 	
 2758: 	for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 2759: 		for(jj=1; jj<= nlstate+ndeath; jj++){
 2760: 			ps[ii][jj]=0;
 2761: 			ps[ii][ii]=1;
 2762: 		}
 2763: 	}
 2764: 	/* Added for backcast */ /* Transposed matrix too */
 2765: 	for(jj=1; jj<= nlstate+ndeath; jj++){
 2766: 		s1=0.;
 2767: 		for(ii=1; ii<= nlstate+ndeath; ii++){
 2768: 			s1+=ps[ii][jj];
 2769: 		}
 2770: 		for(ii=1; ii<= nlstate; ii++){
 2771: 			ps[ii][jj]=ps[ii][jj]/s1;
 2772: 		}
 2773: 	}
 2774: 	/* Transposition */
 2775: 	for(jj=1; jj<= nlstate+ndeath; jj++){
 2776: 		for(ii=jj; ii<= nlstate+ndeath; ii++){
 2777: 			s1=ps[ii][jj];
 2778: 			ps[ii][jj]=ps[jj][ii];
 2779: 			ps[jj][ii]=s1;
 2780: 		}
 2781: 	}
 2782: 	/* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 2783: 	/*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 2784: 	/* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 2785: 	/*   } */
 2786: 	/*   printf("\n "); */
 2787: 	/* } */
 2788: 	/* printf("\n ");printf("%lf ",cov[2]);*/
 2789: 	/*
 2790: 		for(i=1; i<= npar; i++) printf("%f ",x[i]);
 2791: 		goto end;*/
 2792: 	return ps;
 2793: }
 2794: 
 2795: 
 2796: /**************** Product of 2 matrices ******************/
 2797: 
 2798: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
 2799: {
 2800:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
 2801:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
 2802:   /* in, b, out are matrice of pointers which should have been initialized 
 2803:      before: only the contents of out is modified. The function returns
 2804:      a pointer to pointers identical to out */
 2805:   int i, j, k;
 2806:   for(i=nrl; i<= nrh; i++)
 2807:     for(k=ncolol; k<=ncoloh; k++){
 2808:       out[i][k]=0.;
 2809:       for(j=ncl; j<=nch; j++)
 2810:   	out[i][k] +=in[i][j]*b[j][k];
 2811:     }
 2812:   return out;
 2813: }
 2814: 
 2815: 
 2816: /************* Higher Matrix Product ***************/
 2817: 
 2818: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
 2819: {
 2820:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
 2821:      'nhstepm*hstepm*stepm' months (i.e. until
 2822:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
 2823:      nhstepm*hstepm matrices. 
 2824:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
 2825:      (typically every 2 years instead of every month which is too big 
 2826:      for the memory).
 2827:      Model is determined by parameters x and covariates have to be 
 2828:      included manually here. 
 2829: 
 2830:      */
 2831: 
 2832:   int i, j, d, h, k;
 2833:   double **out, cov[NCOVMAX+1];
 2834:   double **newm;
 2835:   double agexact;
 2836:   double agebegin, ageend;
 2837: 
 2838:   /* Hstepm could be zero and should return the unit matrix */
 2839:   for (i=1;i<=nlstate+ndeath;i++)
 2840:     for (j=1;j<=nlstate+ndeath;j++){
 2841:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 2842:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 2843:     }
 2844:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2845:   for(h=1; h <=nhstepm; h++){
 2846:     for(d=1; d <=hstepm; d++){
 2847:       newm=savm;
 2848:       /* Covariates have to be included here again */
 2849:       cov[1]=1.;
 2850:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
 2851:       cov[2]=agexact;
 2852:       if(nagesqr==1)
 2853: 	cov[3]= agexact*agexact;
 2854:       for (k=1; k<=cptcovn;k++) 
 2855: 	cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 2856:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 2857:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
 2858: 	/* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2859: 	cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 2860:       /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
 2861:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
 2862: 	cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
 2863:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 2864:       
 2865:       
 2866:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 2867:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 2868: 			/* right multiplication of oldm by the current matrix */
 2869:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
 2870: 		   pmij(pmmij,cov,ncovmodel,x,nlstate));
 2871:       /* if((int)age == 70){ */
 2872:       /* 	printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
 2873:       /* 	for(i=1; i<=nlstate+ndeath; i++) { */
 2874:       /* 	  printf("%d pmmij ",i); */
 2875:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 2876:       /* 	    printf("%f ",pmmij[i][j]); */
 2877:       /* 	  } */
 2878:       /* 	  printf(" oldm "); */
 2879:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 2880:       /* 	    printf("%f ",oldm[i][j]); */
 2881:       /* 	  } */
 2882:       /* 	  printf("\n"); */
 2883:       /* 	} */
 2884:       /* } */
 2885:       savm=oldm;
 2886:       oldm=newm;
 2887:     }
 2888:     for(i=1; i<=nlstate+ndeath; i++)
 2889:       for(j=1;j<=nlstate+ndeath;j++) {
 2890: 				po[i][j][h]=newm[i][j];
 2891: 				/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 2892:       }
 2893:     /*printf("h=%d ",h);*/
 2894:   } /* end h */
 2895: 	/*     printf("\n H=%d \n",h); */
 2896:   return po;
 2897: }
 2898: 
 2899: /************* Higher Back Matrix Product ***************/
 2900: /* 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 ) */
 2901: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
 2902: {
 2903:   /* Computes the transition matrix starting at age 'age' over
 2904:      'nhstepm*hstepm*stepm' months (i.e. until
 2905:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
 2906:      nhstepm*hstepm matrices.
 2907:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
 2908:      (typically every 2 years instead of every month which is too big
 2909:      for the memory).
 2910:      Model is determined by parameters x and covariates have to be
 2911:      included manually here.
 2912: 
 2913:   */
 2914: 
 2915:   int i, j, d, h, k;
 2916:   double **out, cov[NCOVMAX+1];
 2917:   double **newm;
 2918:   double agexact;
 2919:   double agebegin, ageend;
 2920:   double **oldm, **savm;
 2921: 
 2922:   oldm=oldms;savm=savms;
 2923:   /* Hstepm could be zero and should return the unit matrix */
 2924:   for (i=1;i<=nlstate+ndeath;i++)
 2925:     for (j=1;j<=nlstate+ndeath;j++){
 2926:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 2927:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 2928:     }
 2929:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 2930:   for(h=1; h <=nhstepm; h++){
 2931:     for(d=1; d <=hstepm; d++){
 2932:       newm=savm;
 2933:       /* Covariates have to be included here again */
 2934:       cov[1]=1.;
 2935:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
 2936:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
 2937:       cov[2]=agexact;
 2938:       if(nagesqr==1)
 2939: 	cov[3]= agexact*agexact;
 2940:       for (k=1; k<=cptcovn;k++)
 2941: 	cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
 2942:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 2943:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
 2944: 	/* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2945: 	cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 2946:       /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
 2947:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
 2948: 	cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
 2949:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 2950: 			
 2951: 			
 2952:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 2953:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 2954:       /* Careful transposed matrix */
 2955:       /* age is in cov[2] */
 2956:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
 2957:       /* 						 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
 2958:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
 2959: 		   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
 2960:       /* if((int)age == 70){ */
 2961:       /* 	printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
 2962:       /* 	for(i=1; i<=nlstate+ndeath; i++) { */
 2963:       /* 	  printf("%d pmmij ",i); */
 2964:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 2965:       /* 	    printf("%f ",pmmij[i][j]); */
 2966:       /* 	  } */
 2967:       /* 	  printf(" oldm "); */
 2968:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 2969:       /* 	    printf("%f ",oldm[i][j]); */
 2970:       /* 	  } */
 2971:       /* 	  printf("\n"); */
 2972:       /* 	} */
 2973:       /* } */
 2974:       savm=oldm;
 2975:       oldm=newm;
 2976:     }
 2977:     for(i=1; i<=nlstate+ndeath; i++)
 2978:       for(j=1;j<=nlstate+ndeath;j++) {
 2979: 	po[i][j][h]=newm[i][j];
 2980: 	/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 2981:       }
 2982:     /*printf("h=%d ",h);*/
 2983:   } /* end h */
 2984:   /*     printf("\n H=%d \n",h); */
 2985:   return po;
 2986: }
 2987: 
 2988: 
 2989: #ifdef NLOPT
 2990:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
 2991:   double fret;
 2992:   double *xt;
 2993:   int j;
 2994:   myfunc_data *d2 = (myfunc_data *) pd;
 2995: /* xt = (p1-1); */
 2996:   xt=vector(1,n); 
 2997:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
 2998: 
 2999:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
 3000:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
 3001:   printf("Function = %.12lf ",fret);
 3002:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
 3003:   printf("\n");
 3004:  free_vector(xt,1,n);
 3005:   return fret;
 3006: }
 3007: #endif
 3008: 
 3009: /*************** log-likelihood *************/
 3010: double func( double *x)
 3011: {
 3012:   int i, ii, j, k, mi, d, kk;
 3013:   int ioffset=0;
 3014:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 3015:   double **out;
 3016:   double lli; /* Individual log likelihood */
 3017:   int s1, s2;
 3018:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
 3019:   double bbh, survp;
 3020:   long ipmx;
 3021:   double agexact;
 3022:   /*extern weight */
 3023:   /* We are differentiating ll according to initial status */
 3024:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 3025:   /*for(i=1;i<imx;i++) 
 3026:     printf(" %d\n",s[4][i]);
 3027:   */
 3028: 
 3029:   ++countcallfunc;
 3030: 
 3031:   cov[1]=1.;
 3032: 
 3033:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 3034:   ioffset=0;
 3035:   if(mle==1){
 3036:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3037:       /* Computes the values of the ncovmodel covariates of the model
 3038: 	 depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
 3039: 	 Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
 3040: 	 to be observed in j being in i according to the model.
 3041:       */
 3042:       ioffset=2+nagesqr+cptcovage;
 3043:    /* Fixed */
 3044: 			for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
 3045: 				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)*/
 3046: 			}
 3047:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
 3048: 	 is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
 3049: 	 has been calculated etc */
 3050:       /* For an individual i, wav[i] gives the number of effective waves */
 3051:       /* We compute the contribution to Likelihood of each effective transition
 3052: 	 mw[mi][i] is real wave of the mi th effectve wave */
 3053:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
 3054: 	 s2=s[mw[mi+1][i]][i];
 3055: 	 And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
 3056: 	 But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
 3057: 	 meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
 3058:       */
 3059:       for(mi=1; mi<= wav[i]-1; mi++){
 3060: 				for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
 3061: 					cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i];
 3062: 				}
 3063: 				for (ii=1;ii<=nlstate+ndeath;ii++)
 3064: 					for (j=1;j<=nlstate+ndeath;j++){
 3065: 						oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3066: 						savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3067: 					}
 3068: 				for(d=0; d<dh[mi][i]; d++){
 3069: 					newm=savm;
 3070: 					agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3071: 					cov[2]=agexact;
 3072: 					if(nagesqr==1)
 3073: 						cov[3]= agexact*agexact;  /* Should be changed here */
 3074: 					for (kk=1; kk<=cptcovage;kk++) {
 3075: 						cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
 3076: 					}
 3077: 					out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3078: 											 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3079: 					savm=oldm;
 3080: 					oldm=newm;
 3081: 				} /* end mult */
 3082: 				
 3083: 				/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 3084: 				/* But now since version 0.9 we anticipate for bias at large stepm.
 3085: 				 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 3086: 				 * (in months) between two waves is not a multiple of stepm, we rounded to 
 3087: 				 * the nearest (and in case of equal distance, to the lowest) interval but now
 3088: 				 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 3089: 				 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
 3090: 				 * probability in order to take into account the bias as a fraction of the way
 3091: 				 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
 3092: 				 * -stepm/2 to stepm/2 .
 3093: 				 * For stepm=1 the results are the same as for previous versions of Imach.
 3094: 				 * For stepm > 1 the results are less biased than in previous versions. 
 3095: 				 */
 3096: 				s1=s[mw[mi][i]][i];
 3097: 				s2=s[mw[mi+1][i]][i];
 3098: 				bbh=(double)bh[mi][i]/(double)stepm; 
 3099: 				/* bias bh is positive if real duration
 3100: 				 * is higher than the multiple of stepm and negative otherwise.
 3101: 				 */
 3102: 				/* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
 3103: 				if( s2 > nlstate){ 
 3104: 					/* i.e. if s2 is a death state and if the date of death is known 
 3105: 						 then the contribution to the likelihood is the probability to 
 3106: 						 die between last step unit time and current  step unit time, 
 3107: 						 which is also equal to probability to die before dh 
 3108: 						 minus probability to die before dh-stepm . 
 3109: 						 In version up to 0.92 likelihood was computed
 3110: 						 as if date of death was unknown. Death was treated as any other
 3111: 						 health state: the date of the interview describes the actual state
 3112: 						 and not the date of a change in health state. The former idea was
 3113: 						 to consider that at each interview the state was recorded
 3114: 						 (healthy, disable or death) and IMaCh was corrected; but when we
 3115: 						 introduced the exact date of death then we should have modified
 3116: 						 the contribution of an exact death to the likelihood. This new
 3117: 						 contribution is smaller and very dependent of the step unit
 3118: 						 stepm. It is no more the probability to die between last interview
 3119: 						 and month of death but the probability to survive from last
 3120: 						 interview up to one month before death multiplied by the
 3121: 						 probability to die within a month. Thanks to Chris
 3122: 						 Jackson for correcting this bug.  Former versions increased
 3123: 						 mortality artificially. The bad side is that we add another loop
 3124: 						 which slows down the processing. The difference can be up to 10%
 3125: 						 lower mortality.
 3126: 					*/
 3127: 					/* If, at the beginning of the maximization mostly, the
 3128: 						 cumulative probability or probability to be dead is
 3129: 						 constant (ie = 1) over time d, the difference is equal to
 3130: 						 0.  out[s1][3] = savm[s1][3]: probability, being at state
 3131: 						 s1 at precedent wave, to be dead a month before current
 3132: 						 wave is equal to probability, being at state s1 at
 3133: 						 precedent wave, to be dead at mont of the current
 3134: 						 wave. Then the observed probability (that this person died)
 3135: 						 is null according to current estimated parameter. In fact,
 3136: 						 it should be very low but not zero otherwise the log go to
 3137: 						 infinity.
 3138: 					*/
 3139: /* #ifdef INFINITYORIGINAL */
 3140: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 3141: /* #else */
 3142: /* 	  if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
 3143: /* 	    lli=log(mytinydouble); */
 3144: /* 	  else */
 3145: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 3146: /* #endif */
 3147: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 3148: 	  
 3149: 	} else if  ( s2==-1 ) { /* alive */
 3150: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 3151: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 3152: 	  /*survp += out[s1][j]; */
 3153: 	  lli= log(survp);
 3154: 	}
 3155: 	else if  (s2==-4) { 
 3156: 	  for (j=3,survp=0. ; j<=nlstate; j++)  
 3157: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 3158: 	  lli= log(survp); 
 3159: 	} 
 3160: 	else if  (s2==-5) { 
 3161: 	  for (j=1,survp=0. ; j<=2; j++)  
 3162: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 3163: 	  lli= log(survp); 
 3164: 	} 
 3165: 	else{
 3166: 	  lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 3167: 	  /*  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 */
 3168: 	} 
 3169: 	/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 3170: 	/*if(lli ==000.0)*/
 3171: 	/*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); */
 3172: 	ipmx +=1;
 3173: 	sw += weight[i];
 3174: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3175: 	/* if (lli < log(mytinydouble)){ */
 3176: 	/*   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); */
 3177: 	/*   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]); */
 3178: 	/* } */
 3179:       } /* end of wave */
 3180:     } /* end of individual */
 3181:   }  else if(mle==2){
 3182:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3183:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 3184:       for(mi=1; mi<= wav[i]-1; mi++){
 3185: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 3186: 	  for (j=1;j<=nlstate+ndeath;j++){
 3187: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3188: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3189: 	  }
 3190: 	for(d=0; d<=dh[mi][i]; d++){
 3191: 	  newm=savm;
 3192: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3193: 	  cov[2]=agexact;
 3194: 	  if(nagesqr==1)
 3195: 	    cov[3]= agexact*agexact;
 3196: 	  for (kk=1; kk<=cptcovage;kk++) {
 3197: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3198: 	  }
 3199: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3200: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3201: 	  savm=oldm;
 3202: 	  oldm=newm;
 3203: 	} /* end mult */
 3204:       
 3205: 	s1=s[mw[mi][i]][i];
 3206: 	s2=s[mw[mi+1][i]][i];
 3207: 	bbh=(double)bh[mi][i]/(double)stepm; 
 3208: 	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 */
 3209: 	ipmx +=1;
 3210: 	sw += weight[i];
 3211: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3212:       } /* end of wave */
 3213:     } /* end of individual */
 3214:   }  else if(mle==3){  /* exponential inter-extrapolation */
 3215:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3216:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 3217:       for(mi=1; mi<= wav[i]-1; mi++){
 3218: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 3219: 	  for (j=1;j<=nlstate+ndeath;j++){
 3220: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3221: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3222: 	  }
 3223: 	for(d=0; d<dh[mi][i]; d++){
 3224: 	  newm=savm;
 3225: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3226: 	  cov[2]=agexact;
 3227: 	  if(nagesqr==1)
 3228: 	    cov[3]= agexact*agexact;
 3229: 	  for (kk=1; kk<=cptcovage;kk++) {
 3230: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3231: 	  }
 3232: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3233: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3234: 	  savm=oldm;
 3235: 	  oldm=newm;
 3236: 	} /* end mult */
 3237:       
 3238: 	s1=s[mw[mi][i]][i];
 3239: 	s2=s[mw[mi+1][i]][i];
 3240: 	bbh=(double)bh[mi][i]/(double)stepm; 
 3241: 	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 */
 3242: 	ipmx +=1;
 3243: 	sw += weight[i];
 3244: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3245:       } /* end of wave */
 3246:     } /* end of individual */
 3247:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
 3248:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3249:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 3250:       for(mi=1; mi<= wav[i]-1; mi++){
 3251: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 3252: 	  for (j=1;j<=nlstate+ndeath;j++){
 3253: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3254: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3255: 	  }
 3256: 	for(d=0; d<dh[mi][i]; d++){
 3257: 	  newm=savm;
 3258: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3259: 	  cov[2]=agexact;
 3260: 	  if(nagesqr==1)
 3261: 	    cov[3]= agexact*agexact;
 3262: 	  for (kk=1; kk<=cptcovage;kk++) {
 3263: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3264: 	  }
 3265: 	
 3266: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3267: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3268: 	  savm=oldm;
 3269: 	  oldm=newm;
 3270: 	} /* end mult */
 3271:       
 3272: 	s1=s[mw[mi][i]][i];
 3273: 	s2=s[mw[mi+1][i]][i];
 3274: 	if( s2 > nlstate){ 
 3275: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 3276: 	} else if  ( s2==-1 ) { /* alive */
 3277: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 3278: 	    survp += out[s1][j];
 3279: 	  lli= log(survp);
 3280: 	}else{
 3281: 	  lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 3282: 	}
 3283: 	ipmx +=1;
 3284: 	sw += weight[i];
 3285: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3286: /* 	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]); */
 3287:       } /* end of wave */
 3288:     } /* end of individual */
 3289:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
 3290:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3291:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 3292:       for(mi=1; mi<= wav[i]-1; mi++){
 3293: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 3294: 	  for (j=1;j<=nlstate+ndeath;j++){
 3295: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3296: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3297: 	  }
 3298: 	for(d=0; d<dh[mi][i]; d++){
 3299: 	  newm=savm;
 3300: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3301: 	  cov[2]=agexact;
 3302: 	  if(nagesqr==1)
 3303: 	    cov[3]= agexact*agexact;
 3304: 	  for (kk=1; kk<=cptcovage;kk++) {
 3305: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3306: 	  }
 3307: 	
 3308: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3309: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3310: 	  savm=oldm;
 3311: 	  oldm=newm;
 3312: 	} /* end mult */
 3313:       
 3314: 	s1=s[mw[mi][i]][i];
 3315: 	s2=s[mw[mi+1][i]][i];
 3316: 	lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 3317: 	ipmx +=1;
 3318: 	sw += weight[i];
 3319: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3320: 	/*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]);*/
 3321:       } /* end of wave */
 3322:     } /* end of individual */
 3323:   } /* End of if */
 3324:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 3325:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 3326:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 3327:   return -l;
 3328: }
 3329: 
 3330: /*************** log-likelihood *************/
 3331: double funcone( double *x)
 3332: {
 3333:   /* Same as func but slower because of a lot of printf and if */
 3334:   int i, ii, j, k, mi, d, kk;
 3335:   int ioffset=0;
 3336:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 3337:   double **out;
 3338:   double lli; /* Individual log likelihood */
 3339:   double llt;
 3340:   int s1, s2;
 3341:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
 3342: 
 3343:   double bbh, survp;
 3344:   double agexact;
 3345:   double agebegin, ageend;
 3346:   /*extern weight */
 3347:   /* We are differentiating ll according to initial status */
 3348:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 3349:   /*for(i=1;i<imx;i++) 
 3350:     printf(" %d\n",s[4][i]);
 3351:   */
 3352:   cov[1]=1.;
 3353: 
 3354:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 3355:   ioffset=0;
 3356:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 3357:     ioffset=2+nagesqr+cptcovage;
 3358:     /* Fixed */
 3359:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
 3360:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
 3361:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
 3362:       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)*/
 3363: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
 3364: /*    cov[2+6]=covar[Tvar[6]][i];  */
 3365: /*    cov[2+6]=covar[2][i]; V2  */
 3366: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
 3367: /*    cov[2+7]=covar[Tvar[7]][i];  */
 3368: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
 3369: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
 3370: /*    cov[2+9]=covar[Tvar[9]][i];  */
 3371: /*    cov[2+9]=covar[1][i]; V1  */
 3372:     }
 3373:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
 3374:     /*   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?)*\/ */
 3375:     /* } */
 3376:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
 3377:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
 3378:     /* } */
 3379:     
 3380: 
 3381:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
 3382:     /* Wave varying (but not age varying) */
 3383:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
 3384: 				cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i];
 3385: 			}
 3386:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
 3387: 				/* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
 3388: 				/* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
 3389: 				/* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
 3390: 				/* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
 3391: 				/* 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]); */
 3392:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
 3393: 			/* 	iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
 3394: 			/* 	/\* 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]); *\/ */
 3395: 			/* 	cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
 3396:       /* } */
 3397:       for (ii=1;ii<=nlstate+ndeath;ii++)
 3398: 				for (j=1;j<=nlstate+ndeath;j++){
 3399: 					oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3400: 					savm[ii][j]=(ii==j ? 1.0 : 0.0);
 3401: 				}
 3402:       
 3403:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
 3404:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
 3405:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
 3406: 				/*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 3407: 					and mw[mi+1][i]. dh depends on stepm.*/
 3408: 				newm=savm;
 3409: 				agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 3410: 				cov[2]=agexact;
 3411: 				if(nagesqr==1)
 3412: 					cov[3]= agexact*agexact;
 3413: 				for (kk=1; kk<=cptcovage;kk++) {
 3414: 					cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 3415: 				}
 3416: 				/* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
 3417: 				/* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 3418: 				out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 3419: 										 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 3420: 				/* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
 3421: 				/* 	     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
 3422: 				savm=oldm;
 3423: 				oldm=newm;
 3424:       } /* end mult */
 3425:       
 3426:       s1=s[mw[mi][i]][i];
 3427:       s2=s[mw[mi+1][i]][i];
 3428:       /* if(s2==-1){ */
 3429:       /* 	printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
 3430:       /* 	/\* exit(1); *\/ */
 3431:       /* } */
 3432:       bbh=(double)bh[mi][i]/(double)stepm; 
 3433:       /* bias is positive if real duration
 3434:        * is higher than the multiple of stepm and negative otherwise.
 3435:        */
 3436:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
 3437: 				lli=log(out[s1][s2] - savm[s1][s2]);
 3438:       } else if  ( s2==-1 ) { /* alive */
 3439: 				for (j=1,survp=0. ; j<=nlstate; j++) 
 3440: 					survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 3441: 				lli= log(survp);
 3442:       }else if (mle==1){
 3443: 				lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 3444:       } else if(mle==2){
 3445: 				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 */
 3446:       } else if(mle==3){  /* exponential inter-extrapolation */
 3447: 				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 */
 3448:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
 3449: 				lli=log(out[s1][s2]); /* Original formula */
 3450:       } else{  /* mle=0 back to 1 */
 3451: 				lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 3452: 				/*lli=log(out[s1][s2]); */ /* Original formula */
 3453:       } /* End of if */
 3454:       ipmx +=1;
 3455:       sw += weight[i];
 3456:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 3457:       /*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]); */
 3458:       if(globpr){
 3459: 				fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
 3460:  %11.6f %11.6f %11.6f ", \
 3461: 								num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
 3462: 								2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
 3463: 				for(k=1,llt=0.,l=0.; k<=nlstate; k++){
 3464: 					llt +=ll[k]*gipmx/gsw;
 3465: 					fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
 3466: 				}
 3467: 				fprintf(ficresilk," %10.6f\n", -llt);
 3468:       }
 3469: 	} /* end of wave */
 3470: } /* end of individual */
 3471: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 3472: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 3473: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 3474: if(globpr==0){ /* First time we count the contributions and weights */
 3475: 	gipmx=ipmx;
 3476: 	gsw=sw;
 3477: }
 3478: return -l;
 3479: }
 3480: 
 3481: 
 3482: /*************** function likelione ***********/
 3483: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
 3484: {
 3485:   /* This routine should help understanding what is done with 
 3486:      the selection of individuals/waves and
 3487:      to check the exact contribution to the likelihood.
 3488:      Plotting could be done.
 3489:    */
 3490:   int k;
 3491: 
 3492:   if(*globpri !=0){ /* Just counts and sums, no printings */
 3493:     strcpy(fileresilk,"ILK_"); 
 3494:     strcat(fileresilk,fileresu);
 3495:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
 3496:       printf("Problem with resultfile: %s\n", fileresilk);
 3497:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
 3498:     }
 3499:     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");
 3500:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
 3501:     /* 	i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
 3502:     for(k=1; k<=nlstate; k++) 
 3503:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
 3504:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
 3505:   }
 3506: 
 3507:   *fretone=(*funcone)(p);
 3508:   if(*globpri !=0){
 3509:     fclose(ficresilk);
 3510:     if (mle ==0)
 3511:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
 3512:     else if(mle >=1)
 3513:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
 3514:     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));
 3515:     
 3516:       
 3517:     for (k=1; k<= nlstate ; k++) {
 3518:       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> \
 3519: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
 3520:     }
 3521:     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> \
 3522: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
 3523:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
 3524: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
 3525:     fflush(fichtm);
 3526:   }
 3527:   return;
 3528: }
 3529: 
 3530: 
 3531: /*********** Maximum Likelihood Estimation ***************/
 3532: 
 3533: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
 3534: {
 3535:   int i,j, iter=0;
 3536:   double **xi;
 3537:   double fret;
 3538:   double fretone; /* Only one call to likelihood */
 3539:   /*  char filerespow[FILENAMELENGTH];*/
 3540: 
 3541: #ifdef NLOPT
 3542:   int creturn;
 3543:   nlopt_opt opt;
 3544:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
 3545:   double *lb;
 3546:   double minf; /* the minimum objective value, upon return */
 3547:   double * p1; /* Shifted parameters from 0 instead of 1 */
 3548:   myfunc_data dinst, *d = &dinst;
 3549: #endif
 3550: 
 3551: 
 3552:   xi=matrix(1,npar,1,npar);
 3553:   for (i=1;i<=npar;i++)
 3554:     for (j=1;j<=npar;j++)
 3555:       xi[i][j]=(i==j ? 1.0 : 0.0);
 3556:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
 3557:   strcpy(filerespow,"POW_"); 
 3558:   strcat(filerespow,fileres);
 3559:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
 3560:     printf("Problem with resultfile: %s\n", filerespow);
 3561:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 3562:   }
 3563:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
 3564:   for (i=1;i<=nlstate;i++)
 3565:     for(j=1;j<=nlstate+ndeath;j++)
 3566:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 3567:   fprintf(ficrespow,"\n");
 3568: #ifdef POWELL
 3569:   powell(p,xi,npar,ftol,&iter,&fret,func);
 3570: #endif
 3571: 
 3572: #ifdef NLOPT
 3573: #ifdef NEWUOA
 3574:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
 3575: #else
 3576:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
 3577: #endif
 3578:   lb=vector(0,npar-1);
 3579:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
 3580:   nlopt_set_lower_bounds(opt, lb);
 3581:   nlopt_set_initial_step1(opt, 0.1);
 3582:   
 3583:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
 3584:   d->function = func;
 3585:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
 3586:   nlopt_set_min_objective(opt, myfunc, d);
 3587:   nlopt_set_xtol_rel(opt, ftol);
 3588:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
 3589:     printf("nlopt failed! %d\n",creturn); 
 3590:   }
 3591:   else {
 3592:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
 3593:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
 3594:     iter=1; /* not equal */
 3595:   }
 3596:   nlopt_destroy(opt);
 3597: #endif
 3598:   free_matrix(xi,1,npar,1,npar);
 3599:   fclose(ficrespow);
 3600:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 3601:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 3602:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 3603: 
 3604: }
 3605: 
 3606: /**** Computes Hessian and covariance matrix ***/
 3607: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
 3608: {
 3609:   double  **a,**y,*x,pd;
 3610:   /* double **hess; */
 3611:   int i, j;
 3612:   int *indx;
 3613: 
 3614:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
 3615:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
 3616:   void lubksb(double **a, int npar, int *indx, double b[]) ;
 3617:   void ludcmp(double **a, int npar, int *indx, double *d) ;
 3618:   double gompertz(double p[]);
 3619:   /* hess=matrix(1,npar,1,npar); */
 3620: 
 3621:   printf("\nCalculation of the hessian matrix. Wait...\n");
 3622:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
 3623:   for (i=1;i<=npar;i++){
 3624:     printf("%d-",i);fflush(stdout);
 3625:     fprintf(ficlog,"%d-",i);fflush(ficlog);
 3626:    
 3627:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
 3628:     
 3629:     /*  printf(" %f ",p[i]);
 3630: 	printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
 3631:   }
 3632:   
 3633:   for (i=1;i<=npar;i++) {
 3634:     for (j=1;j<=npar;j++)  {
 3635:       if (j>i) { 
 3636: 	printf(".%d-%d",i,j);fflush(stdout);
 3637: 	fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
 3638: 	hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
 3639: 	
 3640: 	hess[j][i]=hess[i][j];    
 3641: 	/*printf(" %lf ",hess[i][j]);*/
 3642:       }
 3643:     }
 3644:   }
 3645:   printf("\n");
 3646:   fprintf(ficlog,"\n");
 3647: 
 3648:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
 3649:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
 3650:   
 3651:   a=matrix(1,npar,1,npar);
 3652:   y=matrix(1,npar,1,npar);
 3653:   x=vector(1,npar);
 3654:   indx=ivector(1,npar);
 3655:   for (i=1;i<=npar;i++)
 3656:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
 3657:   ludcmp(a,npar,indx,&pd);
 3658: 
 3659:   for (j=1;j<=npar;j++) {
 3660:     for (i=1;i<=npar;i++) x[i]=0;
 3661:     x[j]=1;
 3662:     lubksb(a,npar,indx,x);
 3663:     for (i=1;i<=npar;i++){ 
 3664:       matcov[i][j]=x[i];
 3665:     }
 3666:   }
 3667: 
 3668:   printf("\n#Hessian matrix#\n");
 3669:   fprintf(ficlog,"\n#Hessian matrix#\n");
 3670:   for (i=1;i<=npar;i++) { 
 3671:     for (j=1;j<=npar;j++) { 
 3672:       printf("%.6e ",hess[i][j]);
 3673:       fprintf(ficlog,"%.6e ",hess[i][j]);
 3674:     }
 3675:     printf("\n");
 3676:     fprintf(ficlog,"\n");
 3677:   }
 3678: 
 3679:   /* printf("\n#Covariance matrix#\n"); */
 3680:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
 3681:   /* for (i=1;i<=npar;i++) {  */
 3682:   /*   for (j=1;j<=npar;j++) {  */
 3683:   /*     printf("%.6e ",matcov[i][j]); */
 3684:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
 3685:   /*   } */
 3686:   /*   printf("\n"); */
 3687:   /*   fprintf(ficlog,"\n"); */
 3688:   /* } */
 3689: 
 3690:   /* Recompute Inverse */
 3691:   /* for (i=1;i<=npar;i++) */
 3692:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
 3693:   /* ludcmp(a,npar,indx,&pd); */
 3694: 
 3695:   /*  printf("\n#Hessian matrix recomputed#\n"); */
 3696: 
 3697:   /* for (j=1;j<=npar;j++) { */
 3698:   /*   for (i=1;i<=npar;i++) x[i]=0; */
 3699:   /*   x[j]=1; */
 3700:   /*   lubksb(a,npar,indx,x); */
 3701:   /*   for (i=1;i<=npar;i++){  */
 3702:   /*     y[i][j]=x[i]; */
 3703:   /*     printf("%.3e ",y[i][j]); */
 3704:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
 3705:   /*   } */
 3706:   /*   printf("\n"); */
 3707:   /*   fprintf(ficlog,"\n"); */
 3708:   /* } */
 3709: 
 3710:   /* Verifying the inverse matrix */
 3711: #ifdef DEBUGHESS
 3712:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
 3713: 
 3714:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
 3715:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
 3716: 
 3717:   for (j=1;j<=npar;j++) {
 3718:     for (i=1;i<=npar;i++){ 
 3719:       printf("%.2f ",y[i][j]);
 3720:       fprintf(ficlog,"%.2f ",y[i][j]);
 3721:     }
 3722:     printf("\n");
 3723:     fprintf(ficlog,"\n");
 3724:   }
 3725: #endif
 3726: 
 3727:   free_matrix(a,1,npar,1,npar);
 3728:   free_matrix(y,1,npar,1,npar);
 3729:   free_vector(x,1,npar);
 3730:   free_ivector(indx,1,npar);
 3731:   /* free_matrix(hess,1,npar,1,npar); */
 3732: 
 3733: 
 3734: }
 3735: 
 3736: /*************** hessian matrix ****************/
 3737: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
 3738: { /* Around values of x, computes the function func and returns the scales delti and hessian */
 3739:   int i;
 3740:   int l=1, lmax=20;
 3741:   double k1,k2, res, fx;
 3742:   double p2[MAXPARM+1]; /* identical to x */
 3743:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 3744:   int k=0,kmax=10;
 3745:   double l1;
 3746: 
 3747:   fx=func(x);
 3748:   for (i=1;i<=npar;i++) p2[i]=x[i];
 3749:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
 3750:     l1=pow(10,l);
 3751:     delts=delt;
 3752:     for(k=1 ; k <kmax; k=k+1){
 3753:       delt = delta*(l1*k);
 3754:       p2[theta]=x[theta] +delt;
 3755:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
 3756:       p2[theta]=x[theta]-delt;
 3757:       k2=func(p2)-fx;
 3758:       /*res= (k1-2.0*fx+k2)/delt/delt; */
 3759:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
 3760:       
 3761: #ifdef DEBUGHESSII
 3762:       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);
 3763:       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);
 3764: #endif
 3765:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
 3766:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 3767: 	k=kmax;
 3768:       }
 3769:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
 3770: 	k=kmax; l=lmax*10;
 3771:       }
 3772:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
 3773: 	delts=delt;
 3774:       }
 3775:     } /* End loop k */
 3776:   }
 3777:   delti[theta]=delts;
 3778:   return res; 
 3779:   
 3780: }
 3781: 
 3782: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
 3783: {
 3784:   int i;
 3785:   int l=1, lmax=20;
 3786:   double k1,k2,k3,k4,res,fx;
 3787:   double p2[MAXPARM+1];
 3788:   int k, kmax=1;
 3789:   double v1, v2, cv12, lc1, lc2;
 3790: 
 3791:   int firstime=0;
 3792:   
 3793:   fx=func(x);
 3794:   for (k=1; k<=kmax; k=k+10) {
 3795:     for (i=1;i<=npar;i++) p2[i]=x[i];
 3796:     p2[thetai]=x[thetai]+delti[thetai]*k;
 3797:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
 3798:     k1=func(p2)-fx;
 3799:   
 3800:     p2[thetai]=x[thetai]+delti[thetai]*k;
 3801:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
 3802:     k2=func(p2)-fx;
 3803:   
 3804:     p2[thetai]=x[thetai]-delti[thetai]*k;
 3805:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
 3806:     k3=func(p2)-fx;
 3807:   
 3808:     p2[thetai]=x[thetai]-delti[thetai]*k;
 3809:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
 3810:     k4=func(p2)-fx;
 3811:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
 3812:     if(k1*k2*k3*k4 <0.){
 3813:       firstime=1;
 3814:       kmax=kmax+10;
 3815:     }
 3816:     if(kmax >=10 || firstime ==1){
 3817:       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);
 3818:       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);
 3819:       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);
 3820:       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);
 3821:     }
 3822: #ifdef DEBUGHESSIJ
 3823:     v1=hess[thetai][thetai];
 3824:     v2=hess[thetaj][thetaj];
 3825:     cv12=res;
 3826:     /* Computing eigen value of Hessian matrix */
 3827:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3828:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3829:     if ((lc2 <0) || (lc1 <0) ){
 3830:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
 3831:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
 3832:       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);
 3833:       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);
 3834:     }
 3835: #endif
 3836:   }
 3837:   return res;
 3838: }
 3839: 
 3840:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
 3841: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
 3842: /* { */
 3843: /*   int i; */
 3844: /*   int l=1, lmax=20; */
 3845: /*   double k1,k2,k3,k4,res,fx; */
 3846: /*   double p2[MAXPARM+1]; */
 3847: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
 3848: /*   int k=0,kmax=10; */
 3849: /*   double l1; */
 3850:   
 3851: /*   fx=func(x); */
 3852: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
 3853: /*     l1=pow(10,l); */
 3854: /*     delts=delt; */
 3855: /*     for(k=1 ; k <kmax; k=k+1){ */
 3856: /*       delt = delti*(l1*k); */
 3857: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
 3858: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
 3859: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
 3860: /*       k1=func(p2)-fx; */
 3861:       
 3862: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
 3863: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
 3864: /*       k2=func(p2)-fx; */
 3865:       
 3866: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
 3867: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
 3868: /*       k3=func(p2)-fx; */
 3869:       
 3870: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
 3871: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
 3872: /*       k4=func(p2)-fx; */
 3873: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
 3874: /* #ifdef DEBUGHESSIJ */
 3875: /*       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); */
 3876: /*       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); */
 3877: /* #endif */
 3878: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
 3879: /* 	k=kmax; */
 3880: /*       } */
 3881: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
 3882: /* 	k=kmax; l=lmax*10; */
 3883: /*       } */
 3884: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
 3885: /* 	delts=delt; */
 3886: /*       } */
 3887: /*     } /\* End loop k *\/ */
 3888: /*   } */
 3889: /*   delti[theta]=delts; */
 3890: /*   return res;  */
 3891: /* } */
 3892: 
 3893: 
 3894: /************** Inverse of matrix **************/
 3895: void ludcmp(double **a, int n, int *indx, double *d) 
 3896: { 
 3897:   int i,imax,j,k; 
 3898:   double big,dum,sum,temp; 
 3899:   double *vv; 
 3900:  
 3901:   vv=vector(1,n); 
 3902:   *d=1.0; 
 3903:   for (i=1;i<=n;i++) { 
 3904:     big=0.0; 
 3905:     for (j=1;j<=n;j++) 
 3906:       if ((temp=fabs(a[i][j])) > big) big=temp; 
 3907:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
 3908:     vv[i]=1.0/big; 
 3909:   } 
 3910:   for (j=1;j<=n;j++) { 
 3911:     for (i=1;i<j;i++) { 
 3912:       sum=a[i][j]; 
 3913:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
 3914:       a[i][j]=sum; 
 3915:     } 
 3916:     big=0.0; 
 3917:     for (i=j;i<=n;i++) { 
 3918:       sum=a[i][j]; 
 3919:       for (k=1;k<j;k++) 
 3920: 	sum -= a[i][k]*a[k][j]; 
 3921:       a[i][j]=sum; 
 3922:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
 3923: 	big=dum; 
 3924: 	imax=i; 
 3925:       } 
 3926:     } 
 3927:     if (j != imax) { 
 3928:       for (k=1;k<=n;k++) { 
 3929: 	dum=a[imax][k]; 
 3930: 	a[imax][k]=a[j][k]; 
 3931: 	a[j][k]=dum; 
 3932:       } 
 3933:       *d = -(*d); 
 3934:       vv[imax]=vv[j]; 
 3935:     } 
 3936:     indx[j]=imax; 
 3937:     if (a[j][j] == 0.0) a[j][j]=TINY; 
 3938:     if (j != n) { 
 3939:       dum=1.0/(a[j][j]); 
 3940:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
 3941:     } 
 3942:   } 
 3943:   free_vector(vv,1,n);  /* Doesn't work */
 3944: ;
 3945: } 
 3946: 
 3947: void lubksb(double **a, int n, int *indx, double b[]) 
 3948: { 
 3949:   int i,ii=0,ip,j; 
 3950:   double sum; 
 3951:  
 3952:   for (i=1;i<=n;i++) { 
 3953:     ip=indx[i]; 
 3954:     sum=b[ip]; 
 3955:     b[ip]=b[i]; 
 3956:     if (ii) 
 3957:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
 3958:     else if (sum) ii=i; 
 3959:     b[i]=sum; 
 3960:   } 
 3961:   for (i=n;i>=1;i--) { 
 3962:     sum=b[i]; 
 3963:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
 3964:     b[i]=sum/a[i][i]; 
 3965:   } 
 3966: } 
 3967: 
 3968: void pstamp(FILE *fichier)
 3969: {
 3970:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
 3971: }
 3972: 
 3973: /************ Frequencies ********************/
 3974: void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
 3975: 		  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[],	\
 3976: 		  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
 3977: {  /* Some frequencies */
 3978:   
 3979:   int i, m, jk, j1, bool, z1,j, k, iv;
 3980:   int iind=0, iage=0;
 3981:   int mi; /* Effective wave */
 3982:   int first;
 3983:   double ***freq; /* Frequencies */
 3984:   double *meanq;
 3985:   double **meanqt;
 3986:   double *pp, **prop, *posprop, *pospropt;
 3987:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
 3988:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
 3989:   double agebegin, ageend;
 3990:     
 3991:   pp=vector(1,nlstate);
 3992:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
 3993:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
 3994:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
 3995:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
 3996:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
 3997:   meanqt=matrix(1,lastpass,1,nqtveff);
 3998:   strcpy(fileresp,"P_");
 3999:   strcat(fileresp,fileresu);
 4000:   /*strcat(fileresphtm,fileresu);*/
 4001:   if((ficresp=fopen(fileresp,"w"))==NULL) {
 4002:     printf("Problem with prevalence resultfile: %s\n", fileresp);
 4003:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
 4004:     exit(0);
 4005:   }
 4006: 
 4007:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
 4008:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
 4009:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
 4010:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
 4011:     fflush(ficlog);
 4012:     exit(70); 
 4013:   }
 4014:   else{
 4015:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 4016: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 4017: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
 4018: 	    fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 4019:   }
 4020:   fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies and prevalence by age at begin of transition</h4>\n",fileresphtm, fileresphtm);
 4021:     
 4022:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
 4023:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
 4024:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
 4025:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
 4026:     fflush(ficlog);
 4027:     exit(70); 
 4028:   }
 4029:   else{
 4030:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 4031: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 4032: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
 4033: 	    fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 4034:   }
 4035:   fprintf(ficresphtmfr,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies of all effective transitions by age at begin of transition </h4>Unknown status is -1<br/>\n",fileresphtmfr, fileresphtmfr);
 4036: 
 4037:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
 4038:   j1=0;
 4039:   
 4040:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
 4041:   j=cptcoveff;  /* Only dummy covariates of the model */
 4042:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 4043: 
 4044:   first=1;
 4045: 
 4046:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
 4047:      reference=low_education V1=0,V2=0
 4048:      med_educ                V1=1 V2=0, 
 4049:      high_educ               V1=0 V2=1
 4050:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
 4051:   */
 4052: 
 4053:   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 */
 4054:     posproptt=0.;
 4055:     /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
 4056:       scanf("%d", i);*/
 4057:     for (i=-5; i<=nlstate+ndeath; i++)  
 4058:       for (jk=-5; jk<=nlstate+ndeath; jk++)  
 4059: 				for(m=iagemin; m <= iagemax+3; m++)
 4060: 					freq[i][jk][m]=0;
 4061: 		
 4062:     for (i=1; i<=nlstate; i++)  {
 4063:       for(m=iagemin; m <= iagemax+3; m++)
 4064: 				prop[i][m]=0;
 4065:       posprop[i]=0;
 4066:       pospropt[i]=0;
 4067:     }
 4068:     /* for (z1=1; z1<= nqfveff; z1++) {   */
 4069:     /*   meanq[z1]+=0.; */
 4070:     /*   for(m=1;m<=lastpass;m++){ */
 4071:     /* 	meanqt[m][z1]=0.; */
 4072:     /*   } */
 4073:     /* } */
 4074: 		
 4075:     dateintsum=0;
 4076:     k2cpt=0;
 4077:     /* For that combination of covariate j1, we count and print the frequencies in one pass */
 4078:     for (iind=1; iind<=imx; iind++) { /* For each individual iind */
 4079:       bool=1;
 4080:       if(anyvaryingduminmodel==0){ /* If All fixed covariates */
 4081: 				if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
 4082: 	  /* for (z1=1; z1<= nqfveff; z1++) {   */
 4083: 	  /*   meanq[z1]+=coqvar[Tvar[z1]][iind];  /\* Computes mean of quantitative with selected filter *\/ */
 4084: 	  /* } */
 4085: 					for (z1=1; z1<=cptcoveff; z1++) {  
 4086: 						/* if(Tvaraff[z1] ==-20){ */
 4087: 						/* 	 /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
 4088: 						/* }else  if(Tvaraff[z1] ==-10){ */
 4089: 						/* 	 /\* sumnew+=coqvar[z1][iind]; *\/ */
 4090: 						/* }else  */
 4091: 						if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
 4092: 							/* Tests if this individual iind responded to j1 (V4=1 V3=0) */
 4093: 							bool=0;
 4094: 							/* 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", 
 4095: 								 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
 4096: 								 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
 4097: 							/* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
 4098: 						} /* Onlyf fixed */
 4099: 					} /* end z1 */
 4100: 				} /* cptcovn > 0 */
 4101:       } /* end any */
 4102:       if (bool==1){ /* We selected an individual iind satisfying combination j1 or all fixed */
 4103: 				/* for(m=firstpass; m<=lastpass; m++){ */
 4104: 				for(mi=1; mi<wav[iind];mi++){ /* For that wave */
 4105: 					m=mw[mi][iind];
 4106: 					if(anyvaryingduminmodel==1){ /* Some are varying covariates */
 4107: 						for (z1=1; z1<=cptcoveff; z1++) {
 4108: 							if( Fixed[Tmodelind[z1]]==1){
 4109: 								iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
 4110: 								if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
 4111: 									bool=0;
 4112: 							}else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
 4113: 								if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
 4114: 									bool=0;
 4115: 								}
 4116: 							}
 4117: 						}
 4118: 					}/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
 4119: 					/* bool =0 we keep that guy which corresponds to the combination of dummy values */
 4120: 					if(bool==1){
 4121: 						/* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
 4122: 							 and mw[mi+1][iind]. dh depends on stepm. */
 4123: 						agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
 4124: 						ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
 4125: 						if(m >=firstpass && m <=lastpass){
 4126: 							k2=anint[m][iind]+(mint[m][iind]/12.);
 4127: 							/*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
 4128: 							if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
 4129: 							if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
 4130: 							if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
 4131: 								prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
 4132: 							if (m<lastpass) {
 4133: 								/* if(s[m][iind]==4 && s[m+1][iind]==4) */
 4134: 								/*   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]); */
 4135: 								if(s[m][iind]==-1)
 4136: 									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.));
 4137: 								freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
 4138: 								/* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
 4139: 								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 */
 4140: 							}
 4141: 						} /* end if between passes */  
 4142: 						if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99)) {
 4143: 							dateintsum=dateintsum+k2;
 4144: 							k2cpt++;
 4145: 							/* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
 4146: 						}
 4147: 					} /* end bool 2 */
 4148: 				} /* end m */
 4149:       } /* end bool */
 4150:     } /* end iind = 1 to imx */
 4151:     /* prop[s][age] is feeded for any initial and valid live state as well as
 4152:        freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
 4153: 		
 4154: 		
 4155:     /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 4156:     pstamp(ficresp);
 4157:     /* if  (ncoveff>0) { */
 4158:     if  (cptcoveff>0) {
 4159:       fprintf(ficresp, "\n#********** Variable "); 
 4160:       fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
 4161:       fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
 4162:       for (z1=1; z1<=cptcoveff; z1++){
 4163: 				fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 4164: 				fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 4165: 				fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 4166:       }
 4167:       fprintf(ficresp, "**********\n#");
 4168:       fprintf(ficresphtm, "**********</h3>\n");
 4169:       fprintf(ficresphtmfr, "**********</h3>\n");
 4170:       fprintf(ficlog, "\n#********** Variable "); 
 4171:       for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 4172:       fprintf(ficlog, "**********\n");
 4173:     }
 4174:     fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
 4175:     for(i=1; i<=nlstate;i++) {
 4176:       fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
 4177:       fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
 4178:     }
 4179:     fprintf(ficresp, "\n");
 4180:     fprintf(ficresphtm, "\n");
 4181: 		
 4182:     /* Header of frequency table by age */
 4183:     fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
 4184:     fprintf(ficresphtmfr,"<th>Age</th> ");
 4185:     for(jk=-1; jk <=nlstate+ndeath; jk++){
 4186:       for(m=-1; m <=nlstate+ndeath; m++){
 4187: 				if(jk!=0 && m!=0)
 4188: 					fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
 4189:       }
 4190:     }
 4191:     fprintf(ficresphtmfr, "\n");
 4192: 		
 4193:     /* For each age */
 4194:     for(iage=iagemin; iage <= iagemax+3; iage++){
 4195:       fprintf(ficresphtm,"<tr>");
 4196:       if(iage==iagemax+1){
 4197: 				fprintf(ficlog,"1");
 4198: 				fprintf(ficresphtmfr,"<tr><th>0</th> ");
 4199:       }else if(iage==iagemax+2){
 4200: 				fprintf(ficlog,"0");
 4201: 				fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
 4202:       }else if(iage==iagemax+3){
 4203: 				fprintf(ficlog,"Total");
 4204: 				fprintf(ficresphtmfr,"<tr><th>Total</th> ");
 4205:       }else{
 4206: 				if(first==1){
 4207: 					first=0;
 4208: 					printf("See log file for details...\n");
 4209: 				}
 4210: 				fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
 4211: 				fprintf(ficlog,"Age %d", iage);
 4212:       }
 4213:       for(jk=1; jk <=nlstate ; jk++){
 4214: 				for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
 4215: 					pp[jk] += freq[jk][m][iage]; 
 4216:       }
 4217:       for(jk=1; jk <=nlstate ; jk++){
 4218: 				for(m=-1, pos=0; m <=0 ; m++)
 4219: 					pos += freq[jk][m][iage];
 4220: 				if(pp[jk]>=1.e-10){
 4221: 					if(first==1){
 4222: 						printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 4223: 					}
 4224: 					fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 4225: 				}else{
 4226: 					if(first==1)
 4227: 						printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 4228: 					fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 4229: 				}
 4230:       }
 4231: 			
 4232:       for(jk=1; jk <=nlstate ; jk++){ 
 4233: 				/* posprop[jk]=0; */
 4234: 				for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
 4235: 					pp[jk] += freq[jk][m][iage];
 4236:       }	/* pp[jk] is the total number of transitions starting from state jk and any ending status until this age */
 4237: 			
 4238:       for(jk=1,pos=0, pospropta=0.; jk <=nlstate ; jk++){
 4239: 				pos += pp[jk]; /* pos is the total number of transitions until this age */
 4240: 				posprop[jk] += prop[jk][iage]; /* prop is the number of transitions from a live state
 4241: 																					from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
 4242: 				pospropta += prop[jk][iage]; /* prop is the number of transitions from a live state
 4243: 																				from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
 4244:       }
 4245:       for(jk=1; jk <=nlstate ; jk++){
 4246: 				if(pos>=1.e-5){
 4247: 					if(first==1)
 4248: 						printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 4249: 					fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 4250: 				}else{
 4251: 					if(first==1)
 4252: 						printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 4253: 					fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 4254: 				}
 4255: 				if( iage <= iagemax){
 4256: 					if(pos>=1.e-5){
 4257: 						fprintf(ficresp," %d %.5f %.0f %.0f",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
 4258: 						fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
 4259: 						/*probs[iage][jk][j1]= pp[jk]/pos;*/
 4260: 						/*printf("\niage=%d jk=%d j1=%d %.5f %.0f %.0f %f",iage,jk,j1,pp[jk]/pos, pp[jk],pos,probs[iage][jk][j1]);*/
 4261: 					}
 4262: 					else{
 4263: 						fprintf(ficresp," %d NaNq %.0f %.0f",iage,prop[jk][iage],pospropta);
 4264: 						fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[jk][iage],pospropta);
 4265: 					}
 4266: 				}
 4267: 				pospropt[jk] +=posprop[jk];
 4268:       } /* end loop jk */
 4269:       /* pospropt=0.; */
 4270:       for(jk=-1; jk <=nlstate+ndeath; jk++){
 4271: 				for(m=-1; m <=nlstate+ndeath; m++){
 4272: 					if(freq[jk][m][iage] !=0 ) { /* minimizing output */
 4273: 						if(first==1){
 4274: 							printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]);
 4275: 						}
 4276: 						fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iage]);
 4277: 					}
 4278: 					if(jk!=0 && m!=0)
 4279: 						fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][iage]);
 4280: 				}
 4281:       } /* end loop jk */
 4282:       posproptt=0.; 
 4283:       for(jk=1; jk <=nlstate; jk++){
 4284: 				posproptt += pospropt[jk];
 4285:       }
 4286:       fprintf(ficresphtmfr,"</tr>\n ");
 4287:       if(iage <= iagemax){
 4288: 				fprintf(ficresp,"\n");
 4289: 				fprintf(ficresphtm,"</tr>\n");
 4290:       }
 4291:       if(first==1)
 4292: 				printf("Others in log...\n");
 4293:       fprintf(ficlog,"\n");
 4294:     } /* end loop age iage */
 4295:     fprintf(ficresphtm,"<tr><th>Tot</th>");
 4296:     for(jk=1; jk <=nlstate ; jk++){
 4297:       if(posproptt < 1.e-5){
 4298: 				fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[jk],posproptt);	
 4299:       }else{
 4300: 				fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[jk]/posproptt,pospropt[jk],posproptt);	
 4301:       }
 4302:     }
 4303:     fprintf(ficresphtm,"</tr>\n");
 4304:     fprintf(ficresphtm,"</table>\n");
 4305:     fprintf(ficresphtmfr,"</table>\n");
 4306:     if(posproptt < 1.e-5){
 4307:       fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
 4308:       fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
 4309:       fprintf(ficres,"\n  This combination (%d) is not valid and no result will be produced\n\n",j1);
 4310:       invalidvarcomb[j1]=1;
 4311:     }else{
 4312:       fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
 4313:       invalidvarcomb[j1]=0;
 4314:     }
 4315:     fprintf(ficresphtmfr,"</table>\n");
 4316:   } /* end selected combination of covariate j1 */
 4317:   dateintmean=dateintsum/k2cpt; 
 4318: 	
 4319:   fclose(ficresp);
 4320:   fclose(ficresphtm);
 4321:   fclose(ficresphtmfr);
 4322:   free_vector(meanq,1,nqfveff);
 4323:   free_matrix(meanqt,1,lastpass,1,nqtveff);
 4324:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);
 4325:   free_vector(pospropt,1,nlstate);
 4326:   free_vector(posprop,1,nlstate);
 4327:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);
 4328:   free_vector(pp,1,nlstate);
 4329:   /* End of freqsummary */
 4330: }
 4331: 
 4332: /************ Prevalence ********************/
 4333: 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)
 4334: {  
 4335:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 4336:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 4337:      We still use firstpass and lastpass as another selection.
 4338:   */
 4339:  
 4340:   int i, m, jk, j1, bool, z1,j, iv;
 4341:   int mi; /* Effective wave */
 4342:   int iage;
 4343:   double agebegin, ageend;
 4344: 
 4345:   double **prop;
 4346:   double posprop; 
 4347:   double  y2; /* in fractional years */
 4348:   int iagemin, iagemax;
 4349:   int first; /** to stop verbosity which is redirected to log file */
 4350: 
 4351:   iagemin= (int) agemin;
 4352:   iagemax= (int) agemax;
 4353:   /*pp=vector(1,nlstate);*/
 4354:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
 4355:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
 4356:   j1=0;
 4357:   
 4358:   /*j=cptcoveff;*/
 4359:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 4360:   
 4361:   first=1;
 4362:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
 4363:     for (i=1; i<=nlstate; i++)  
 4364:       for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)
 4365: 	prop[i][iage]=0.0;
 4366:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
 4367:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
 4368:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
 4369:     
 4370:     for (i=1; i<=imx; i++) { /* Each individual */
 4371:       bool=1;
 4372:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
 4373:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
 4374: 	m=mw[mi][i];
 4375: 	/* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
 4376: 	/* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
 4377: 	for (z1=1; z1<=cptcoveff; z1++){
 4378: 	  if( Fixed[Tmodelind[z1]]==1){
 4379: 	    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
 4380: 	    if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
 4381: 	      bool=0;
 4382: 	  }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
 4383: 	    if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
 4384: 	      bool=0;
 4385: 	    }
 4386: 	}
 4387: 	if(bool==1){ /* Otherwise we skip that wave/person */
 4388: 	  agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
 4389: 	  /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
 4390: 	  if(m >=firstpass && m <=lastpass){
 4391: 	    y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
 4392: 	    if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
 4393: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 4394: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 4395: 	      if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){
 4396: 		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); 
 4397: 		exit(1);
 4398: 	      }
 4399: 	      if (s[m][i]>0 && s[m][i]<=nlstate) { 
 4400: 		/*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]]);*/
 4401: 		prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
 4402: 		prop[s[m][i]][iagemax+3] += weight[i]; 
 4403: 	      } /* end valid statuses */ 
 4404: 	    } /* end selection of dates */
 4405: 	  } /* end selection of waves */
 4406: 	} /* end bool */
 4407:       } /* end wave */
 4408:     } /* end individual */
 4409:     for(i=iagemin; i <= iagemax+3; i++){  
 4410:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
 4411: 	posprop += prop[jk][i]; 
 4412:       } 
 4413:       
 4414:       for(jk=1; jk <=nlstate ; jk++){	    
 4415: 	if( i <=  iagemax){ 
 4416: 	  if(posprop>=1.e-5){ 
 4417: 	    probs[i][jk][j1]= prop[jk][i]/posprop;
 4418: 	  } else{
 4419: 	    if(first==1){
 4420: 	      first=0;
 4421: 	      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]);
 4422: 	    }
 4423: 	  }
 4424: 	} 
 4425:       }/* end jk */ 
 4426:     }/* end i */ 
 4427:      /*} *//* end i1 */
 4428:   } /* end j1 */
 4429:   
 4430:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
 4431:   /*free_vector(pp,1,nlstate);*/
 4432:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);
 4433: }  /* End of prevalence */
 4434: 
 4435: /************* Waves Concatenation ***************/
 4436: 
 4437: 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)
 4438: {
 4439:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 4440:      Death is a valid wave (if date is known).
 4441:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
 4442:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 4443:      and mw[mi+1][i]. dh depends on stepm.
 4444:   */
 4445: 
 4446:   int i=0, mi=0, m=0, mli=0;
 4447:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
 4448:      double sum=0., jmean=0.;*/
 4449:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
 4450:   int j, k=0,jk, ju, jl;
 4451:   double sum=0.;
 4452:   first=0;
 4453:   firstwo=0;
 4454:   firsthree=0;
 4455:   firstfour=0;
 4456:   jmin=100000;
 4457:   jmax=-1;
 4458:   jmean=0.;
 4459: 
 4460: /* Treating live states */
 4461:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
 4462:     mi=0;  /* First valid wave */
 4463:     mli=0; /* Last valid wave */
 4464:     m=firstpass;
 4465:     while(s[m][i] <= nlstate){  /* a live state */
 4466:       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 */
 4467: 	mli=m-1;/* mw[++mi][i]=m-1; */
 4468:       }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 */
 4469: 	mw[++mi][i]=m;
 4470: 	mli=m;
 4471:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
 4472:       if(m < lastpass){ /* m < lastpass, standard case */
 4473: 	m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
 4474:       }
 4475:       else{ /* m >= lastpass, eventual special issue with warning */
 4476: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
 4477: 	break;
 4478: #else
 4479: 	if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
 4480: 	  if(firsthree == 0){
 4481: 	    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);
 4482: 	    firsthree=1;
 4483: 	  }
 4484: 	  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);
 4485: 	  mw[++mi][i]=m;
 4486: 	  mli=m;
 4487: 	}
 4488: 	if(s[m][i]==-2){ /* Vital status is really unknown */
 4489: 	  nbwarn++;
 4490: 	  if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
 4491: 	    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);
 4492: 	    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);
 4493: 	  }
 4494: 	  break;
 4495: 	}
 4496: 	break;
 4497: #endif
 4498:       }/* End m >= lastpass */
 4499:     }/* end while */
 4500: 
 4501:     /* mi is the last effective wave, m is lastpass, mw[j][i] gives the # of j-th effective wave for individual i */
 4502:     /* After last pass */
 4503: /* Treating death states */
 4504:     if (s[m][i] > nlstate){  /* In a death state */
 4505:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
 4506:       /* } */
 4507:       mi++;	/* Death is another wave */
 4508:       /* if(mi==0)  never been interviewed correctly before death */
 4509:       /* Only death is a correct wave */
 4510:       mw[mi][i]=m;
 4511:     }
 4512: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
 4513:     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 */
 4514:       /* m++; */
 4515:       /* mi++; */
 4516:       /* s[m][i]=nlstate+1;  /\* We are setting the status to the last of non live state *\/ */
 4517:       /* mw[mi][i]=m; */
 4518:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
 4519: 	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 */
 4520: 	  nbwarn++;
 4521: 	  if(firstfiv==0){
 4522: 	    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 );
 4523: 	    firstfiv=1;
 4524: 	  }else{
 4525: 	    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 );
 4526: 	  }
 4527: 	}else{ /* Death occured afer last wave potential bias */
 4528: 	  nberr++;
 4529: 	  if(firstwo==0){
 4530: 	    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 );
 4531: 	    firstwo=1;
 4532: 	  }
 4533: 	  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 );
 4534: 	}
 4535:       }else{ /* end date of interview is known */
 4536: 	/* death is known but not confirmed by death status at any wave */
 4537: 	if(firstfour==0){
 4538: 	  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 );
 4539: 	  firstfour=1;
 4540: 	}
 4541: 	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 );
 4542:       }
 4543:     } /* end if date of death is known */
 4544: #endif
 4545:     wav[i]=mi; /* mi should be the last effective wave (or mli) */
 4546:     /* wav[i]=mw[mi][i]; */
 4547:     if(mi==0){
 4548:       nbwarn++;
 4549:       if(first==0){
 4550: 	printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
 4551: 	first=1;
 4552:       }
 4553:       if(first==1){
 4554: 	fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
 4555:       }
 4556:     } /* end mi==0 */
 4557:   } /* End individuals */
 4558:   /* wav and mw are no more changed */
 4559: 	
 4560:   
 4561:   for(i=1; i<=imx; i++){
 4562:     for(mi=1; mi<wav[i];mi++){
 4563:       if (stepm <=0)
 4564: 	dh[mi][i]=1;
 4565:       else{
 4566: 	if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
 4567: 	  if (agedc[i] < 2*AGESUP) {
 4568: 	    j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
 4569: 	    if(j==0) j=1;  /* Survives at least one month after exam */
 4570: 	    else if(j<0){
 4571: 	      nberr++;
 4572: 	      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]);
 4573: 	      j=1; /* Temporary Dangerous patch */
 4574: 	      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);
 4575: 	      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]);
 4576: 	      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);
 4577: 	    }
 4578: 	    k=k+1;
 4579: 	    if (j >= jmax){
 4580: 	      jmax=j;
 4581: 	      ijmax=i;
 4582: 	    }
 4583: 	    if (j <= jmin){
 4584: 	      jmin=j;
 4585: 	      ijmin=i;
 4586: 	    }
 4587: 	    sum=sum+j;
 4588: 	    /*if (j<0) printf("j=%d num=%d \n",j,i);*/
 4589: 	    /*	  printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
 4590: 	  }
 4591: 	}
 4592: 	else{
 4593: 	  j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 4594: /* 	  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]); */
 4595: 					
 4596: 	  k=k+1;
 4597: 	  if (j >= jmax) {
 4598: 	    jmax=j;
 4599: 	    ijmax=i;
 4600: 	  }
 4601: 	  else if (j <= jmin){
 4602: 	    jmin=j;
 4603: 	    ijmin=i;
 4604: 	  }
 4605: 	  /*	    if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
 4606: 	  /*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]);*/
 4607: 	  if(j<0){
 4608: 	    nberr++;
 4609: 	    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]);
 4610: 	    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]);
 4611: 	  }
 4612: 	  sum=sum+j;
 4613: 	}
 4614: 	jk= j/stepm;
 4615: 	jl= j -jk*stepm;
 4616: 	ju= j -(jk+1)*stepm;
 4617: 	if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
 4618: 	  if(jl==0){
 4619: 	    dh[mi][i]=jk;
 4620: 	    bh[mi][i]=0;
 4621: 	  }else{ /* We want a negative bias in order to only have interpolation ie
 4622: 		  * to avoid the price of an extra matrix product in likelihood */
 4623: 	    dh[mi][i]=jk+1;
 4624: 	    bh[mi][i]=ju;
 4625: 	  }
 4626: 	}else{
 4627: 	  if(jl <= -ju){
 4628: 	    dh[mi][i]=jk;
 4629: 	    bh[mi][i]=jl;	/* bias is positive if real duration
 4630: 				 * is higher than the multiple of stepm and negative otherwise.
 4631: 				 */
 4632: 	  }
 4633: 	  else{
 4634: 	    dh[mi][i]=jk+1;
 4635: 	    bh[mi][i]=ju;
 4636: 	  }
 4637: 	  if(dh[mi][i]==0){
 4638: 	    dh[mi][i]=1; /* At least one step */
 4639: 	    bh[mi][i]=ju; /* At least one step */
 4640: 	    /*  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);*/
 4641: 	  }
 4642: 	} /* end if mle */
 4643:       }
 4644:     } /* end wave */
 4645:   }
 4646:   jmean=sum/k;
 4647:   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);
 4648:   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);
 4649: }
 4650: 
 4651: /*********** Tricode ****************************/
 4652:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
 4653: {
 4654:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
 4655:   /*	  Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
 4656:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
 4657:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
 4658:    * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
 4659:   */
 4660: 
 4661:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
 4662:   int modmaxcovj=0; /* Modality max of covariates j */
 4663:   int cptcode=0; /* Modality max of covariates j */
 4664:   int modmincovj=0; /* Modality min of covariates j */
 4665: 
 4666: 
 4667:   /* cptcoveff=0;  */
 4668: 	/* *cptcov=0; */
 4669:  
 4670:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
 4671: 
 4672:   /* Loop on covariates without age and products and no quantitative variable */
 4673:   /* for (j=1; j<=(cptcovs); j++) { /\* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only *\/ */
 4674:   for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
 4675:     for (j=-1; (j < maxncov); j++) Ndum[j]=0;
 4676:     if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
 4677:       switch(Fixed[k]) {
 4678:       case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
 4679: 				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*/
 4680: 					ij=(int)(covar[Tvar[k]][i]);
 4681: 					/* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
 4682: 					 * If product of Vn*Vm, still boolean *:
 4683: 					 * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
 4684: 					 * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
 4685: 					/* Finds for covariate j, n=Tvar[j] of Vn . ij is the
 4686: 						 modality of the nth covariate of individual i. */
 4687: 					if (ij > modmaxcovj)
 4688: 						modmaxcovj=ij; 
 4689: 					else if (ij < modmincovj) 
 4690: 						modmincovj=ij; 
 4691: 					if ((ij < -1) && (ij > NCOVMAX)){
 4692: 						printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
 4693: 						exit(1);
 4694: 					}else
 4695: 						Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
 4696: 					/*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
 4697: 					/*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
 4698: 					/* getting the maximum value of the modality of the covariate
 4699: 						 (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
 4700: 						 female ies 1, then modmaxcovj=1.
 4701: 					*/
 4702: 				} /* end for loop on individuals i */
 4703: 				printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
 4704: 				fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
 4705: 				cptcode=modmaxcovj;
 4706: 				/* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
 4707: 				/*for (i=0; i<=cptcode; i++) {*/
 4708: 				for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
 4709: 					printf("Frequencies of covariates %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
 4710: 					fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
 4711: 					if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
 4712: 						if( j != -1){
 4713: 							ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
 4714: 																 covariate for which somebody answered excluding 
 4715: 																 undefined. Usually 2: 0 and 1. */
 4716: 						}
 4717: 						ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
 4718: 																		covariate for which somebody answered including 
 4719: 																		undefined. Usually 3: -1, 0 and 1. */
 4720: 					}	/* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
 4721: 						 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
 4722: 				} /* Ndum[-1] number of undefined modalities */
 4723: 			
 4724: 				/* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
 4725: 				/* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
 4726: 				/* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
 4727: 				/* modmincovj=3; modmaxcovj = 7; */
 4728: 				/* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
 4729: 				/* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
 4730: 			  /*		 defining two dummy variables: variables V1_1 and V1_2.*/
 4731:  	      /* nbcode[Tvar[j]][ij]=k; */
 4732: 	      /* nbcode[Tvar[j]][1]=0; */
 4733: 	      /* nbcode[Tvar[j]][2]=1; */
 4734: 	      /* nbcode[Tvar[j]][3]=2; */
 4735: 	      /* To be continued (not working yet). */
 4736: 	      ij=0; /* ij is similar to i but can jump over null modalities */
 4737: 				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*/
 4738:       	  if (Ndum[i] == 0) { /* If nobody responded to this modality k */
 4739: 	          break;
 4740: 	        }
 4741: 					ij++;
 4742: 					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*/
 4743: 					cptcode = ij; /* New max modality for covar j */
 4744: 				} /* end of loop on modality i=-1 to 1 or more */
 4745: 				break;
 4746:       case 1: /* Testing on varying covariate, could be simple and
 4747: 	       * should look at waves or product of fixed *
 4748: 	       * varying. No time to test -1, assuming 0 and 1 only */
 4749: 				ij=0;
 4750: 				for(i=0; i<=1;i++){
 4751: 					nbcode[Tvar[k]][++ij]=i;
 4752: 				}
 4753: 				break;
 4754:       default:
 4755: 				break;
 4756:       } /* end switch */
 4757:     } /* end dummy test */
 4758:     
 4759:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
 4760:     /* 	/\*recode from 0 *\/ */
 4761:     /* 				     k is a modality. If we have model=V1+V1*sex  */
 4762:     /* 				     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
 4763:     /* 				  But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
 4764:     /* 	} */
 4765:     /* 	/\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
 4766:     /* 	if (ij > ncodemax[j]) { */
 4767:     /* 	  printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
 4768:     /* 	  fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
 4769:     /* 	  break; */
 4770:     /* 	} */
 4771:     /*   }  /\* end of loop on modality k *\/ */
 4772:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
 4773:   
 4774:   for (k=-1; k< maxncov; k++) Ndum[k]=0; 
 4775:   /* Look at fixed dummy (single or product) covariates to check empty modalities */
 4776:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
 4777:     /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
 4778:     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 */ 
 4779:     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 */
 4780:     /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
 4781:   } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
 4782:   
 4783:   ij=0;
 4784:   /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
 4785:   for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
 4786:     /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
 4787:     /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
 4788:     if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
 4789:       /* If product not in single variable we don't print results */
 4790:       /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
 4791:       ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
 4792:       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*/
 4793:       Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
 4794:       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 */
 4795:       if(Fixed[k]!=0)
 4796:         anyvaryingduminmodel=1;
 4797: 			/* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
 4798: 			/*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
 4799: 			/* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
 4800: 			/*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
 4801: 			/* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
 4802: 			/*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
 4803:     } 
 4804:   } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
 4805:   /* ij--; */
 4806:   /* cptcoveff=ij; /\*Number of total covariates*\/ */
 4807:   *cptcov=ij; /*Number of total real effective covariates: effective
 4808: 							 * because they can be excluded from the model and real
 4809: 							 * if in the model but excluded because missing values, but how to get k from ij?*/
 4810:   for(j=ij+1; j<= cptcovt; j++){
 4811:     Tvaraff[j]=0;
 4812:     Tmodelind[j]=0;
 4813:   }
 4814:   for(j=ntveff+1; j<= cptcovt; j++){
 4815:     TmodelInvind[j]=0;
 4816:   }
 4817:   /* To be sorted */
 4818:   ;
 4819: }
 4820: 
 4821: 
 4822: /*********** Health Expectancies ****************/
 4823: 
 4824: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
 4825: 
 4826: {
 4827:   /* Health expectancies, no variances */
 4828:   int i, j, nhstepm, hstepm, h, nstepm;
 4829:   int nhstepma, nstepma; /* Decreasing with age */
 4830:   double age, agelim, hf;
 4831:   double ***p3mat;
 4832:   double eip;
 4833: 
 4834:   pstamp(ficreseij);
 4835:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
 4836:   fprintf(ficreseij,"# Age");
 4837:   for(i=1; i<=nlstate;i++){
 4838:     for(j=1; j<=nlstate;j++){
 4839:       fprintf(ficreseij," e%1d%1d ",i,j);
 4840:     }
 4841:     fprintf(ficreseij," e%1d. ",i);
 4842:   }
 4843:   fprintf(ficreseij,"\n");
 4844: 
 4845:   
 4846:   if(estepm < stepm){
 4847:     printf ("Problem %d lower than %d\n",estepm, stepm);
 4848:   }
 4849:   else  hstepm=estepm;   
 4850:   /* We compute the life expectancy from trapezoids spaced every estepm months
 4851:    * This is mainly to measure the difference between two models: for example
 4852:    * if stepm=24 months pijx are given only every 2 years and by summing them
 4853:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 4854:    * progression in between and thus overestimating or underestimating according
 4855:    * to the curvature of the survival function. If, for the same date, we 
 4856:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 4857:    * to compare the new estimate of Life expectancy with the same linear 
 4858:    * hypothesis. A more precise result, taking into account a more precise
 4859:    * curvature will be obtained if estepm is as small as stepm. */
 4860: 
 4861:   /* For example we decided to compute the life expectancy with the smallest unit */
 4862:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 4863:      nhstepm is the number of hstepm from age to agelim 
 4864:      nstepm is the number of stepm from age to agelin. 
 4865:      Look at hpijx to understand the reason of that which relies in memory size
 4866:      and note for a fixed period like estepm months */
 4867:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 4868:      survival function given by stepm (the optimization length). Unfortunately it
 4869:      means that if the survival funtion is printed only each two years of age and if
 4870:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 4871:      results. So we changed our mind and took the option of the best precision.
 4872:   */
 4873:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 4874: 
 4875:   agelim=AGESUP;
 4876:   /* If stepm=6 months */
 4877:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
 4878:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 4879:     
 4880: /* nhstepm age range expressed in number of stepm */
 4881:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 4882:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 4883:   /* if (stepm >= YEARM) hstepm=1;*/
 4884:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 4885:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4886: 
 4887:   for (age=bage; age<=fage; age ++){ 
 4888:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 4889:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 4890:     /* if (stepm >= YEARM) hstepm=1;*/
 4891:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 4892: 
 4893:     /* If stepm=6 months */
 4894:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 4895:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 4896:     
 4897:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 4898:     
 4899:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 4900:     
 4901:     printf("%d|",(int)age);fflush(stdout);
 4902:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 4903:     
 4904:     /* Computing expectancies */
 4905:     for(i=1; i<=nlstate;i++)
 4906:       for(j=1; j<=nlstate;j++)
 4907: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 4908: 	  eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
 4909: 	  
 4910: 	  /* 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]);*/
 4911: 
 4912: 	}
 4913: 
 4914:     fprintf(ficreseij,"%3.0f",age );
 4915:     for(i=1; i<=nlstate;i++){
 4916:       eip=0;
 4917:       for(j=1; j<=nlstate;j++){
 4918: 	eip +=eij[i][j][(int)age];
 4919: 	fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
 4920:       }
 4921:       fprintf(ficreseij,"%9.4f", eip );
 4922:     }
 4923:     fprintf(ficreseij,"\n");
 4924:     
 4925:   }
 4926:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4927:   printf("\n");
 4928:   fprintf(ficlog,"\n");
 4929:   
 4930: }
 4931: 
 4932: 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[] )
 4933: 
 4934: {
 4935:   /* Covariances of health expectancies eij and of total life expectancies according
 4936:      to initial status i, ei. .
 4937:   */
 4938:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
 4939:   int nhstepma, nstepma; /* Decreasing with age */
 4940:   double age, agelim, hf;
 4941:   double ***p3matp, ***p3matm, ***varhe;
 4942:   double **dnewm,**doldm;
 4943:   double *xp, *xm;
 4944:   double **gp, **gm;
 4945:   double ***gradg, ***trgradg;
 4946:   int theta;
 4947: 
 4948:   double eip, vip;
 4949: 
 4950:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
 4951:   xp=vector(1,npar);
 4952:   xm=vector(1,npar);
 4953:   dnewm=matrix(1,nlstate*nlstate,1,npar);
 4954:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
 4955:   
 4956:   pstamp(ficresstdeij);
 4957:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
 4958:   fprintf(ficresstdeij,"# Age");
 4959:   for(i=1; i<=nlstate;i++){
 4960:     for(j=1; j<=nlstate;j++)
 4961:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
 4962:     fprintf(ficresstdeij," e%1d. ",i);
 4963:   }
 4964:   fprintf(ficresstdeij,"\n");
 4965: 
 4966:   pstamp(ficrescveij);
 4967:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
 4968:   fprintf(ficrescveij,"# Age");
 4969:   for(i=1; i<=nlstate;i++)
 4970:     for(j=1; j<=nlstate;j++){
 4971:       cptj= (j-1)*nlstate+i;
 4972:       for(i2=1; i2<=nlstate;i2++)
 4973: 	for(j2=1; j2<=nlstate;j2++){
 4974: 	  cptj2= (j2-1)*nlstate+i2;
 4975: 	  if(cptj2 <= cptj)
 4976: 	    fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
 4977: 	}
 4978:     }
 4979:   fprintf(ficrescveij,"\n");
 4980:   
 4981:   if(estepm < stepm){
 4982:     printf ("Problem %d lower than %d\n",estepm, stepm);
 4983:   }
 4984:   else  hstepm=estepm;   
 4985:   /* We compute the life expectancy from trapezoids spaced every estepm months
 4986:    * This is mainly to measure the difference between two models: for example
 4987:    * if stepm=24 months pijx are given only every 2 years and by summing them
 4988:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 4989:    * progression in between and thus overestimating or underestimating according
 4990:    * to the curvature of the survival function. If, for the same date, we 
 4991:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 4992:    * to compare the new estimate of Life expectancy with the same linear 
 4993:    * hypothesis. A more precise result, taking into account a more precise
 4994:    * curvature will be obtained if estepm is as small as stepm. */
 4995: 
 4996:   /* For example we decided to compute the life expectancy with the smallest unit */
 4997:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 4998:      nhstepm is the number of hstepm from age to agelim 
 4999:      nstepm is the number of stepm from age to agelin. 
 5000:      Look at hpijx to understand the reason of that which relies in memory size
 5001:      and note for a fixed period like estepm months */
 5002:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 5003:      survival function given by stepm (the optimization length). Unfortunately it
 5004:      means that if the survival funtion is printed only each two years of age and if
 5005:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 5006:      results. So we changed our mind and took the option of the best precision.
 5007:   */
 5008:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 5009: 
 5010:   /* If stepm=6 months */
 5011:   /* nhstepm age range expressed in number of stepm */
 5012:   agelim=AGESUP;
 5013:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
 5014:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 5015:   /* if (stepm >= YEARM) hstepm=1;*/
 5016:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 5017:   
 5018:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5019:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5020:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
 5021:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
 5022:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
 5023:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
 5024: 
 5025:   for (age=bage; age<=fage; age ++){ 
 5026:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 5027:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 5028:     /* if (stepm >= YEARM) hstepm=1;*/
 5029:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 5030: 		
 5031:     /* If stepm=6 months */
 5032:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 5033:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 5034:     
 5035:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 5036: 		
 5037:     /* Computing  Variances of health expectancies */
 5038:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
 5039:        decrease memory allocation */
 5040:     for(theta=1; theta <=npar; theta++){
 5041:       for(i=1; i<=npar; i++){ 
 5042: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 5043: 	xm[i] = x[i] - (i==theta ?delti[theta]:0);
 5044:       }
 5045:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
 5046:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
 5047: 			
 5048:       for(j=1; j<= nlstate; j++){
 5049: 	for(i=1; i<=nlstate; i++){
 5050: 	  for(h=0; h<=nhstepm-1; h++){
 5051: 	    gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
 5052: 	    gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
 5053: 	  }
 5054: 	}
 5055:       }
 5056: 			
 5057:       for(ij=1; ij<= nlstate*nlstate; ij++)
 5058: 	for(h=0; h<=nhstepm-1; h++){
 5059: 	  gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
 5060: 	}
 5061:     }/* End theta */
 5062:     
 5063:     
 5064:     for(h=0; h<=nhstepm-1; h++)
 5065:       for(j=1; j<=nlstate*nlstate;j++)
 5066: 	for(theta=1; theta <=npar; theta++)
 5067: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 5068:     
 5069: 		
 5070:     for(ij=1;ij<=nlstate*nlstate;ij++)
 5071:       for(ji=1;ji<=nlstate*nlstate;ji++)
 5072: 	varhe[ij][ji][(int)age] =0.;
 5073: 		
 5074:     printf("%d|",(int)age);fflush(stdout);
 5075:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 5076:     for(h=0;h<=nhstepm-1;h++){
 5077:       for(k=0;k<=nhstepm-1;k++){
 5078: 	matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
 5079: 	matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
 5080: 	for(ij=1;ij<=nlstate*nlstate;ij++)
 5081: 	  for(ji=1;ji<=nlstate*nlstate;ji++)
 5082: 	    varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
 5083:       }
 5084:     }
 5085: 		
 5086:     /* Computing expectancies */
 5087:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 5088:     for(i=1; i<=nlstate;i++)
 5089:       for(j=1; j<=nlstate;j++)
 5090: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 5091: 	  eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
 5092: 					
 5093: 	  /* 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]);*/
 5094: 					
 5095: 	}
 5096: 		
 5097:     fprintf(ficresstdeij,"%3.0f",age );
 5098:     for(i=1; i<=nlstate;i++){
 5099:       eip=0.;
 5100:       vip=0.;
 5101:       for(j=1; j<=nlstate;j++){
 5102: 	eip += eij[i][j][(int)age];
 5103: 	for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
 5104: 	  vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
 5105: 	fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
 5106:       }
 5107:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
 5108:     }
 5109:     fprintf(ficresstdeij,"\n");
 5110: 		
 5111:     fprintf(ficrescveij,"%3.0f",age );
 5112:     for(i=1; i<=nlstate;i++)
 5113:       for(j=1; j<=nlstate;j++){
 5114: 	cptj= (j-1)*nlstate+i;
 5115: 	for(i2=1; i2<=nlstate;i2++)
 5116: 	  for(j2=1; j2<=nlstate;j2++){
 5117: 	    cptj2= (j2-1)*nlstate+i2;
 5118: 	    if(cptj2 <= cptj)
 5119: 	      fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
 5120: 	  }
 5121:       }
 5122:     fprintf(ficrescveij,"\n");
 5123: 		
 5124:   }
 5125:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
 5126:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
 5127:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
 5128:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
 5129:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5130:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5131:   printf("\n");
 5132:   fprintf(ficlog,"\n");
 5133: 	
 5134:   free_vector(xm,1,npar);
 5135:   free_vector(xp,1,npar);
 5136:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
 5137:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
 5138:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
 5139: }
 5140:  
 5141: /************ Variance ******************/
 5142:  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[])
 5143:  {
 5144:    /* Variance of health expectancies */
 5145:    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
 5146:    /* double **newm;*/
 5147:    /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
 5148:   
 5149:    /* int movingaverage(); */
 5150:    double **dnewm,**doldm;
 5151:    double **dnewmp,**doldmp;
 5152:    int i, j, nhstepm, hstepm, h, nstepm ;
 5153:    int k;
 5154:    double *xp;
 5155:    double **gp, **gm;  /* for var eij */
 5156:    double ***gradg, ***trgradg; /*for var eij */
 5157:    double **gradgp, **trgradgp; /* for var p point j */
 5158:    double *gpp, *gmp; /* for var p point j */
 5159:    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
 5160:    double ***p3mat;
 5161:    double age,agelim, hf;
 5162:    /* double ***mobaverage; */
 5163:    int theta;
 5164:    char digit[4];
 5165:    char digitp[25];
 5166: 
 5167:    char fileresprobmorprev[FILENAMELENGTH];
 5168: 
 5169:    if(popbased==1){
 5170:      if(mobilav!=0)
 5171:        strcpy(digitp,"-POPULBASED-MOBILAV_");
 5172:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
 5173:    }
 5174:    else 
 5175:      strcpy(digitp,"-STABLBASED_");
 5176: 
 5177:    /* if (mobilav!=0) { */
 5178:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 5179:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
 5180:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
 5181:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
 5182:    /*   } */
 5183:    /* } */
 5184: 
 5185:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
 5186:    sprintf(digit,"%-d",ij);
 5187:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
 5188:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
 5189:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
 5190:    strcat(fileresprobmorprev,fileresu);
 5191:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
 5192:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
 5193:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
 5194:    }
 5195:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 5196:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 5197:    pstamp(ficresprobmorprev);
 5198:    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);
 5199:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
 5200:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 5201:      fprintf(ficresprobmorprev," p.%-d SE",j);
 5202:      for(i=1; i<=nlstate;i++)
 5203:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 5204:    }  
 5205:    fprintf(ficresprobmorprev,"\n");
 5206:   
 5207:    fprintf(ficgp,"\n# Routine varevsij");
 5208:    fprintf(ficgp,"\nunset title \n");
 5209:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
 5210:    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");
 5211:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
 5212:    /*   } */
 5213:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 5214:    pstamp(ficresvij);
 5215:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
 5216:    if(popbased==1)
 5217:      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);
 5218:    else
 5219:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
 5220:    fprintf(ficresvij,"# Age");
 5221:    for(i=1; i<=nlstate;i++)
 5222:      for(j=1; j<=nlstate;j++)
 5223:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
 5224:    fprintf(ficresvij,"\n");
 5225: 
 5226:    xp=vector(1,npar);
 5227:    dnewm=matrix(1,nlstate,1,npar);
 5228:    doldm=matrix(1,nlstate,1,nlstate);
 5229:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
 5230:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 5231: 
 5232:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
 5233:    gpp=vector(nlstate+1,nlstate+ndeath);
 5234:    gmp=vector(nlstate+1,nlstate+ndeath);
 5235:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 5236:   
 5237:    if(estepm < stepm){
 5238:      printf ("Problem %d lower than %d\n",estepm, stepm);
 5239:    }
 5240:    else  hstepm=estepm;   
 5241:    /* For example we decided to compute the life expectancy with the smallest unit */
 5242:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 5243:       nhstepm is the number of hstepm from age to agelim 
 5244:       nstepm is the number of stepm from age to agelim. 
 5245:       Look at function hpijx to understand why because of memory size limitations, 
 5246:       we decided (b) to get a life expectancy respecting the most precise curvature of the
 5247:       survival function given by stepm (the optimization length). Unfortunately it
 5248:       means that if the survival funtion is printed every two years of age and if
 5249:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 5250:       results. So we changed our mind and took the option of the best precision.
 5251:    */
 5252:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 5253:    agelim = AGESUP;
 5254:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 5255:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 5256:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 5257:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5258:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
 5259:      gp=matrix(0,nhstepm,1,nlstate);
 5260:      gm=matrix(0,nhstepm,1,nlstate);
 5261: 		
 5262: 		
 5263:      for(theta=1; theta <=npar; theta++){
 5264:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
 5265: 	 xp[i] = x[i] + (i==theta ?delti[theta]:0);
 5266:        }
 5267: 			
 5268:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 5269: 			
 5270:        if (popbased==1) {
 5271: 	 if(mobilav ==0){
 5272: 	   for(i=1; i<=nlstate;i++)
 5273: 	     prlim[i][i]=probs[(int)age][i][ij];
 5274: 	 }else{ /* mobilav */ 
 5275: 	   for(i=1; i<=nlstate;i++)
 5276: 	     prlim[i][i]=mobaverage[(int)age][i][ij];
 5277: 	 }
 5278:        }
 5279: 			
 5280:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
 5281:        for(j=1; j<= nlstate; j++){
 5282: 	 for(h=0; h<=nhstepm; h++){
 5283: 	   for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 5284: 	     gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 5285: 	 }
 5286:        }
 5287:        /* Next for computing probability of death (h=1 means
 5288: 	  computed over hstepm matrices product = hstepm*stepm months) 
 5289: 	  as a weighted average of prlim.
 5290:        */
 5291:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
 5292: 	 for(i=1,gpp[j]=0.; i<= nlstate; i++)
 5293: 	   gpp[j] += prlim[i][i]*p3mat[i][j][1];
 5294:        }    
 5295:        /* end probability of death */
 5296: 			
 5297:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
 5298: 	 xp[i] = x[i] - (i==theta ?delti[theta]:0);
 5299: 			
 5300:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
 5301: 			
 5302:        if (popbased==1) {
 5303: 	 if(mobilav ==0){
 5304: 	   for(i=1; i<=nlstate;i++)
 5305: 	     prlim[i][i]=probs[(int)age][i][ij];
 5306: 	 }else{ /* mobilav */ 
 5307: 	   for(i=1; i<=nlstate;i++)
 5308: 	     prlim[i][i]=mobaverage[(int)age][i][ij];
 5309: 	 }
 5310:        }
 5311: 			
 5312:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 5313: 			
 5314:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
 5315: 	 for(h=0; h<=nhstepm; h++){
 5316: 	   for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 5317: 	     gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 5318: 	 }
 5319:        }
 5320:        /* This for computing probability of death (h=1 means
 5321: 	  computed over hstepm matrices product = hstepm*stepm months) 
 5322: 	  as a weighted average of prlim.
 5323:        */
 5324:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
 5325: 	 for(i=1,gmp[j]=0.; i<= nlstate; i++)
 5326: 	   gmp[j] += prlim[i][i]*p3mat[i][j][1];
 5327:        }    
 5328:        /* end probability of death */
 5329: 			
 5330:        for(j=1; j<= nlstate; j++) /* vareij */
 5331: 	 for(h=0; h<=nhstepm; h++){
 5332: 	   gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 5333: 	 }
 5334: 			
 5335:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
 5336: 	 gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
 5337:        }
 5338: 			
 5339:      } /* End theta */
 5340: 		
 5341:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
 5342: 		
 5343:      for(h=0; h<=nhstepm; h++) /* veij */
 5344:        for(j=1; j<=nlstate;j++)
 5345: 	 for(theta=1; theta <=npar; theta++)
 5346: 	   trgradg[h][j][theta]=gradg[h][theta][j];
 5347: 		
 5348:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
 5349:        for(theta=1; theta <=npar; theta++)
 5350: 	 trgradgp[j][theta]=gradgp[theta][j];
 5351: 		
 5352: 		
 5353:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 5354:      for(i=1;i<=nlstate;i++)
 5355:        for(j=1;j<=nlstate;j++)
 5356: 	 vareij[i][j][(int)age] =0.;
 5357: 		
 5358:      for(h=0;h<=nhstepm;h++){
 5359:        for(k=0;k<=nhstepm;k++){
 5360: 	 matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 5361: 	 matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
 5362: 	 for(i=1;i<=nlstate;i++)
 5363: 	   for(j=1;j<=nlstate;j++)
 5364: 	     vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
 5365:        }
 5366:      }
 5367: 		
 5368:      /* pptj */
 5369:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
 5370:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
 5371:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
 5372:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
 5373: 	 varppt[j][i]=doldmp[j][i];
 5374:      /* end ppptj */
 5375:      /*  x centered again */
 5376: 		
 5377:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
 5378: 		
 5379:      if (popbased==1) {
 5380:        if(mobilav ==0){
 5381: 	 for(i=1; i<=nlstate;i++)
 5382: 	   prlim[i][i]=probs[(int)age][i][ij];
 5383:        }else{ /* mobilav */ 
 5384: 	 for(i=1; i<=nlstate;i++)
 5385: 	   prlim[i][i]=mobaverage[(int)age][i][ij];
 5386:        }
 5387:      }
 5388: 		
 5389:      /* This for computing probability of death (h=1 means
 5390: 	computed over hstepm (estepm) matrices product = hstepm*stepm months) 
 5391: 	as a weighted average of prlim.
 5392:      */
 5393:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
 5394:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
 5395:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
 5396: 	 gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
 5397:      }    
 5398:      /* end probability of death */
 5399: 		
 5400:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
 5401:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 5402:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
 5403:        for(i=1; i<=nlstate;i++){
 5404: 	 fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 5405:        }
 5406:      } 
 5407:      fprintf(ficresprobmorprev,"\n");
 5408: 		
 5409:      fprintf(ficresvij,"%.0f ",age );
 5410:      for(i=1; i<=nlstate;i++)
 5411:        for(j=1; j<=nlstate;j++){
 5412: 	 fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
 5413:        }
 5414:      fprintf(ficresvij,"\n");
 5415:      free_matrix(gp,0,nhstepm,1,nlstate);
 5416:      free_matrix(gm,0,nhstepm,1,nlstate);
 5417:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 5418:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 5419:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5420:    } /* End age */
 5421:    free_vector(gpp,nlstate+1,nlstate+ndeath);
 5422:    free_vector(gmp,nlstate+1,nlstate+ndeath);
 5423:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
 5424:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 5425:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
 5426:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
 5427:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
 5428:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
 5429:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
 5430:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
 5431:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
 5432:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
 5433:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
 5434:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
 5435:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
 5436:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
 5437:    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);
 5438:    /*  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);
 5439:     */
 5440:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
 5441:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
 5442: 
 5443:    free_vector(xp,1,npar);
 5444:    free_matrix(doldm,1,nlstate,1,nlstate);
 5445:    free_matrix(dnewm,1,nlstate,1,npar);
 5446:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 5447:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
 5448:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 5449:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 5450:    fclose(ficresprobmorprev);
 5451:    fflush(ficgp);
 5452:    fflush(fichtm); 
 5453:  }  /* end varevsij */
 5454: 
 5455: /************ Variance of prevlim ******************/
 5456:  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[])
 5457: {
 5458:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
 5459:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 5460: 
 5461:   double **dnewm,**doldm;
 5462:   int i, j, nhstepm, hstepm;
 5463:   double *xp;
 5464:   double *gp, *gm;
 5465:   double **gradg, **trgradg;
 5466:   double **mgm, **mgp;
 5467:   double age,agelim;
 5468:   int theta;
 5469:   
 5470:   pstamp(ficresvpl);
 5471:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
 5472:   fprintf(ficresvpl,"# Age");
 5473:   for(i=1; i<=nlstate;i++)
 5474:       fprintf(ficresvpl," %1d-%1d",i,i);
 5475:   fprintf(ficresvpl,"\n");
 5476: 
 5477:   xp=vector(1,npar);
 5478:   dnewm=matrix(1,nlstate,1,npar);
 5479:   doldm=matrix(1,nlstate,1,nlstate);
 5480:   
 5481:   hstepm=1*YEARM; /* Every year of age */
 5482:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 5483:   agelim = AGESUP;
 5484:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 5485:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 5486:     if (stepm >= YEARM) hstepm=1;
 5487:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 5488:     gradg=matrix(1,npar,1,nlstate);
 5489:     mgp=matrix(1,npar,1,nlstate);
 5490:     mgm=matrix(1,npar,1,nlstate);
 5491:     gp=vector(1,nlstate);
 5492:     gm=vector(1,nlstate);
 5493: 
 5494:     for(theta=1; theta <=npar; theta++){
 5495:       for(i=1; i<=npar; i++){ /* Computes gradient */
 5496: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 5497:       }
 5498:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
 5499: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 5500:       else
 5501: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 5502:       for(i=1;i<=nlstate;i++){
 5503: 	gp[i] = prlim[i][i];
 5504: 	mgp[theta][i] = prlim[i][i];
 5505:       }
 5506:       for(i=1; i<=npar; i++) /* Computes gradient */
 5507: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 5508:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
 5509: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 5510:       else
 5511: 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
 5512:       for(i=1;i<=nlstate;i++){
 5513: 	gm[i] = prlim[i][i];
 5514: 	mgm[theta][i] = prlim[i][i];
 5515:       }
 5516:       for(i=1;i<=nlstate;i++)
 5517: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 5518:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
 5519:     } /* End theta */
 5520: 
 5521:     trgradg =matrix(1,nlstate,1,npar);
 5522: 
 5523:     for(j=1; j<=nlstate;j++)
 5524:       for(theta=1; theta <=npar; theta++)
 5525: 	trgradg[j][theta]=gradg[theta][j];
 5526:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
 5527:     /*   printf("\nmgm mgp %d ",(int)age); */
 5528:     /*   for(j=1; j<=nlstate;j++){ */
 5529:     /* 	printf(" %d ",j); */
 5530:     /* 	for(theta=1; theta <=npar; theta++) */
 5531:     /* 	  printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
 5532:     /* 	printf("\n "); */
 5533:     /*   } */
 5534:     /* } */
 5535:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
 5536:     /*   printf("\n gradg %d ",(int)age); */
 5537:     /*   for(j=1; j<=nlstate;j++){ */
 5538:     /* 	printf("%d ",j); */
 5539:     /* 	for(theta=1; theta <=npar; theta++) */
 5540:     /* 	  printf("%d %lf ",theta,gradg[theta][j]); */
 5541:     /* 	printf("\n "); */
 5542:     /*   } */
 5543:     /* } */
 5544: 
 5545:     for(i=1;i<=nlstate;i++)
 5546:       varpl[i][(int)age] =0.;
 5547:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
 5548:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 5549:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 5550:     }else{
 5551:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 5552:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 5553:     }
 5554:     for(i=1;i<=nlstate;i++)
 5555:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 5556: 
 5557:     fprintf(ficresvpl,"%.0f ",age );
 5558:     for(i=1; i<=nlstate;i++)
 5559:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
 5560:     fprintf(ficresvpl,"\n");
 5561:     free_vector(gp,1,nlstate);
 5562:     free_vector(gm,1,nlstate);
 5563:     free_matrix(mgm,1,npar,1,nlstate);
 5564:     free_matrix(mgp,1,npar,1,nlstate);
 5565:     free_matrix(gradg,1,npar,1,nlstate);
 5566:     free_matrix(trgradg,1,nlstate,1,npar);
 5567:   } /* End age */
 5568: 
 5569:   free_vector(xp,1,npar);
 5570:   free_matrix(doldm,1,nlstate,1,npar);
 5571:   free_matrix(dnewm,1,nlstate,1,nlstate);
 5572: 
 5573: }
 5574: 
 5575: /************ Variance of one-step probabilities  ******************/
 5576: 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[])
 5577:  {
 5578:    int i, j=0,  k1, l1, tj;
 5579:    int k2, l2, j1,  z1;
 5580:    int k=0, l;
 5581:    int first=1, first1, first2;
 5582:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
 5583:    double **dnewm,**doldm;
 5584:    double *xp;
 5585:    double *gp, *gm;
 5586:    double **gradg, **trgradg;
 5587:    double **mu;
 5588:    double age, cov[NCOVMAX+1];
 5589:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
 5590:    int theta;
 5591:    char fileresprob[FILENAMELENGTH];
 5592:    char fileresprobcov[FILENAMELENGTH];
 5593:    char fileresprobcor[FILENAMELENGTH];
 5594:    double ***varpij;
 5595: 
 5596:    strcpy(fileresprob,"PROB_"); 
 5597:    strcat(fileresprob,fileres);
 5598:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
 5599:      printf("Problem with resultfile: %s\n", fileresprob);
 5600:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
 5601:    }
 5602:    strcpy(fileresprobcov,"PROBCOV_"); 
 5603:    strcat(fileresprobcov,fileresu);
 5604:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
 5605:      printf("Problem with resultfile: %s\n", fileresprobcov);
 5606:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 5607:    }
 5608:    strcpy(fileresprobcor,"PROBCOR_"); 
 5609:    strcat(fileresprobcor,fileresu);
 5610:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 5611:      printf("Problem with resultfile: %s\n", fileresprobcor);
 5612:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 5613:    }
 5614:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 5615:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 5616:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 5617:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 5618:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 5619:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 5620:    pstamp(ficresprob);
 5621:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
 5622:    fprintf(ficresprob,"# Age");
 5623:    pstamp(ficresprobcov);
 5624:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
 5625:    fprintf(ficresprobcov,"# Age");
 5626:    pstamp(ficresprobcor);
 5627:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 5628:    fprintf(ficresprobcor,"# Age");
 5629: 
 5630: 
 5631:    for(i=1; i<=nlstate;i++)
 5632:      for(j=1; j<=(nlstate+ndeath);j++){
 5633:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
 5634:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
 5635:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
 5636:      }  
 5637:    /* fprintf(ficresprob,"\n");
 5638:       fprintf(ficresprobcov,"\n");
 5639:       fprintf(ficresprobcor,"\n");
 5640:    */
 5641:    xp=vector(1,npar);
 5642:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 5643:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 5644:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
 5645:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 5646:    first=1;
 5647:    fprintf(ficgp,"\n# Routine varprob");
 5648:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
 5649:    fprintf(fichtm,"\n");
 5650: 
 5651:    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);
 5652:    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);
 5653:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
 5654: and drawn. It helps understanding how is the covariance between two incidences.\
 5655:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
 5656:    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. \
 5657: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
 5658: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
 5659: standard deviations wide on each axis. <br>\
 5660:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
 5661:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 5662: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
 5663: 
 5664:    cov[1]=1;
 5665:    /* tj=cptcoveff; */
 5666:    tj = (int) pow(2,cptcoveff);
 5667:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
 5668:    j1=0;
 5669:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
 5670:      if  (cptcovn>0) {
 5671:        fprintf(ficresprob, "\n#********** Variable "); 
 5672:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5673:        fprintf(ficresprob, "**********\n#\n");
 5674:        fprintf(ficresprobcov, "\n#********** Variable "); 
 5675:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5676:        fprintf(ficresprobcov, "**********\n#\n");
 5677: 			
 5678:        fprintf(ficgp, "\n#********** Variable "); 
 5679:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5680:        fprintf(ficgp, "**********\n#\n");
 5681: 			
 5682: 			
 5683:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
 5684:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5685:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
 5686: 			
 5687:        fprintf(ficresprobcor, "\n#********** Variable ");    
 5688:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
 5689:        fprintf(ficresprobcor, "**********\n#");    
 5690:        if(invalidvarcomb[j1]){
 5691: 	 fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
 5692: 	 fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
 5693: 	 continue;
 5694:        }
 5695:      }
 5696:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
 5697:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 5698:      gp=vector(1,(nlstate)*(nlstate+ndeath));
 5699:      gm=vector(1,(nlstate)*(nlstate+ndeath));
 5700:      for (age=bage; age<=fage; age ++){ 
 5701:        cov[2]=age;
 5702:        if(nagesqr==1)
 5703: 	 cov[3]= age*age;
 5704:        for (k=1; k<=cptcovn;k++) {
 5705: 	 cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
 5706: 	 /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
 5707: 								    * 1  1 1 1 1
 5708: 								    * 2  2 1 1 1
 5709: 								    * 3  1 2 1 1
 5710: 								    */
 5711: 	 /* nbcode[1][1]=0 nbcode[1][2]=1;*/
 5712:        }
 5713:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 5714:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
 5715:        for (k=1; k<=cptcovprod;k++)
 5716: 	 cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
 5717: 			
 5718: 			
 5719:        for(theta=1; theta <=npar; theta++){
 5720: 	 for(i=1; i<=npar; i++)
 5721: 	   xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
 5722: 				
 5723: 	 pmij(pmmij,cov,ncovmodel,xp,nlstate);
 5724: 				
 5725: 	 k=0;
 5726: 	 for(i=1; i<= (nlstate); i++){
 5727: 	   for(j=1; j<=(nlstate+ndeath);j++){
 5728: 	     k=k+1;
 5729: 	     gp[k]=pmmij[i][j];
 5730: 	   }
 5731: 	 }
 5732: 				
 5733: 	 for(i=1; i<=npar; i++)
 5734: 	   xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
 5735: 				
 5736: 	 pmij(pmmij,cov,ncovmodel,xp,nlstate);
 5737: 	 k=0;
 5738: 	 for(i=1; i<=(nlstate); i++){
 5739: 	   for(j=1; j<=(nlstate+ndeath);j++){
 5740: 	     k=k+1;
 5741: 	     gm[k]=pmmij[i][j];
 5742: 	   }
 5743: 	 }
 5744: 				
 5745: 	 for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
 5746: 	   gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
 5747:        }
 5748: 
 5749:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
 5750: 	 for(theta=1; theta <=npar; theta++)
 5751: 	   trgradg[j][theta]=gradg[theta][j];
 5752: 			
 5753:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
 5754:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
 5755: 			
 5756:        pmij(pmmij,cov,ncovmodel,x,nlstate);
 5757: 			
 5758:        k=0;
 5759:        for(i=1; i<=(nlstate); i++){
 5760: 	 for(j=1; j<=(nlstate+ndeath);j++){
 5761: 	   k=k+1;
 5762: 	   mu[k][(int) age]=pmmij[i][j];
 5763: 	 }
 5764:        }
 5765:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 5766: 	 for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 5767: 	   varpij[i][j][(int)age] = doldm[i][j];
 5768: 			
 5769:        /*printf("\n%d ",(int)age);
 5770: 	 for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 5771: 	 printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 5772: 	 fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 5773: 	 }*/
 5774: 			
 5775:        fprintf(ficresprob,"\n%d ",(int)age);
 5776:        fprintf(ficresprobcov,"\n%d ",(int)age);
 5777:        fprintf(ficresprobcor,"\n%d ",(int)age);
 5778: 			
 5779:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
 5780: 	 fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
 5781:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 5782: 	 fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
 5783: 	 fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
 5784:        }
 5785:        i=0;
 5786:        for (k=1; k<=(nlstate);k++){
 5787: 	 for (l=1; l<=(nlstate+ndeath);l++){ 
 5788: 	   i++;
 5789: 	   fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 5790: 	   fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
 5791: 	   for (j=1; j<=i;j++){
 5792: 	     /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
 5793: 	     fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
 5794: 	     fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
 5795: 	   }
 5796: 	 }
 5797:        }/* end of loop for state */
 5798:      } /* end of loop for age */
 5799:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
 5800:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 5801:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 5802:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 5803:     
 5804:      /* Confidence intervalle of pij  */
 5805:      /*
 5806:        fprintf(ficgp,"\nunset parametric;unset label");
 5807:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
 5808:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 5809:        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);
 5810:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
 5811:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
 5812:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
 5813:      */
 5814: 		
 5815:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
 5816:      first1=1;first2=2;
 5817:      for (k2=1; k2<=(nlstate);k2++){
 5818:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
 5819: 	 if(l2==k2) continue;
 5820: 	 j=(k2-1)*(nlstate+ndeath)+l2;
 5821: 	 for (k1=1; k1<=(nlstate);k1++){
 5822: 	   for (l1=1; l1<=(nlstate+ndeath);l1++){ 
 5823: 	     if(l1==k1) continue;
 5824: 	     i=(k1-1)*(nlstate+ndeath)+l1;
 5825: 	     if(i<=j) continue;
 5826: 	     for (age=bage; age<=fage; age ++){ 
 5827: 	       if ((int)age %5==0){
 5828: 		 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
 5829: 		 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
 5830: 		 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
 5831: 		 mu1=mu[i][(int) age]/stepm*YEARM ;
 5832: 		 mu2=mu[j][(int) age]/stepm*YEARM;
 5833: 		 c12=cv12/sqrt(v1*v2);
 5834: 		 /* Computing eigen value of matrix of covariance */
 5835: 		 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 5836: 		 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 5837: 		 if ((lc2 <0) || (lc1 <0) ){
 5838: 		   if(first2==1){
 5839: 		     first1=0;
 5840: 		     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);
 5841: 		   }
 5842: 		   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);
 5843: 		   /* lc1=fabs(lc1); */ /* If we want to have them positive */
 5844: 		   /* lc2=fabs(lc2); */
 5845: 		 }
 5846: 								
 5847: 		 /* Eigen vectors */
 5848: 		 v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
 5849: 		 /*v21=sqrt(1.-v11*v11); *//* error */
 5850: 		 v21=(lc1-v1)/cv12*v11;
 5851: 		 v12=-v21;
 5852: 		 v22=v11;
 5853: 		 tnalp=v21/v11;
 5854: 		 if(first1==1){
 5855: 		   first1=0;
 5856: 		   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);
 5857: 		 }
 5858: 		 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);
 5859: 		 /*printf(fignu*/
 5860: 		 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
 5861: 		 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
 5862: 		 if(first==1){
 5863: 		   first=0;
 5864: 		   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
 5865: 		   fprintf(ficgp,"\nset parametric;unset label");
 5866: 		   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);
 5867: 		   fprintf(ficgp,"\nset ter svg size 640, 480");
 5868: 		   fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
 5869:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">																		\
 5870: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
 5871: 			   subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,	\
 5872: 			   subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 5873: 		   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 5874: 		   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
 5875: 		   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 5876: 		   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 5877: 		   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 5878: 		   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",	\
 5879: 			   mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),										\
 5880: 			   mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 5881: 		 }else{
 5882: 		   first=0;
 5883: 		   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
 5884: 		   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 5885: 		   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 5886: 		   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", \
 5887: 			   mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),					\
 5888: 			   mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 5889: 		 }/* if first */
 5890: 	       } /* age mod 5 */
 5891: 	     } /* end loop age */
 5892: 	     fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 5893: 	     first=1;
 5894: 	   } /*l12 */
 5895: 	 } /* k12 */
 5896:        } /*l1 */
 5897:      }/* k1 */
 5898:    }  /* loop on combination of covariates j1 */
 5899:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 5900:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
 5901:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 5902:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
 5903:    free_vector(xp,1,npar);
 5904:    fclose(ficresprob);
 5905:    fclose(ficresprobcov);
 5906:    fclose(ficresprobcor);
 5907:    fflush(ficgp);
 5908:    fflush(fichtmcov);
 5909:  }
 5910: 
 5911: 
 5912: /******************* Printing html file ***********/
 5913: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
 5914: 		  int lastpass, int stepm, int weightopt, char model[],\
 5915: 		  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 5916: 		  int popforecast, int prevfcast, int backcast, int estepm , \
 5917: 		  double jprev1, double mprev1,double anprev1, double dateprev1, \
 5918: 		  double jprev2, double mprev2,double anprev2, double dateprev2){
 5919:   int jj1, k1, i1, cpt;
 5920: 
 5921:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
 5922:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
 5923: </ul>");
 5924:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
 5925:    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",
 5926: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
 5927:    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) ",
 5928: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
 5929:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
 5930:    fprintf(fichtm,"\
 5931:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 5932: 	   stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
 5933:    fprintf(fichtm,"\
 5934:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 5935: 	   stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
 5936:    fprintf(fichtm,"\
 5937:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 5938: 	   subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
 5939:    fprintf(fichtm,"\
 5940:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 5941: 	   subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
 5942:    fprintf(fichtm,"\
 5943:  - (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): \
 5944:    <a href=\"%s\">%s</a> <br>\n",
 5945: 	   estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
 5946:    if(prevfcast==1){
 5947:      fprintf(fichtm,"\
 5948:  - Prevalence projections by age and states:				\
 5949:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
 5950:    }
 5951: 
 5952:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
 5953: 
 5954:    m=pow(2,cptcoveff);
 5955:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 5956: 
 5957:    jj1=0;
 5958:    for(k1=1; k1<=m;k1++){
 5959: 
 5960:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
 5961:      jj1++;
 5962:      if (cptcovn > 0) {
 5963:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 5964:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
 5965: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
 5966: 	 printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
 5967:        }
 5968:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
 5969:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 5970:        if(invalidvarcomb[k1]){
 5971: 	 fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
 5972: 	 printf("\nCombination (%d) ignored because no cases \n",k1); 
 5973: 	 continue;
 5974:        }
 5975:      }
 5976:      /* aij, bij */
 5977:      fprintf(fichtm,"<br>- Logit model (yours is: 1+age+%s), for example: logit(pij)=log(pij/pii)= aij+ bij age + V1 age + etc. as a function of age: <a href=\"%s_%d-1.svg\">%s_%d-1.svg</a><br> \
 5978: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
 5979:      /* Pij */
 5980:      fprintf(fichtm,"<br>\n- P<sub>ij</sub> or conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s_%d-2.svg\">%s_%d-2.svg</a><br> \
 5981: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
 5982:      /* Quasi-incidences */
 5983:      fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
 5984:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
 5985:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
 5986: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
 5987: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
 5988:      /* Survival functions (period) in state j */
 5989:      for(cpt=1; cpt<=nlstate;cpt++){
 5990:        fprintf(fichtm,"<br>\n- Survival functions in state %d. Or probability to survive in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> \
 5991: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
 5992:      }
 5993:      /* State specific survival functions (period) */
 5994:      for(cpt=1; cpt<=nlstate;cpt++){
 5995:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
 5996:  Or probability to survive in various states (1 to %d) being in state %d at different ages.	\
 5997:  <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> <img src=\"%s_%d-%d.svg\">", cpt, nlstate, cpt, subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1);
 5998:      }
 5999:      /* Period (stable) prevalence in each health state */
 6000:      for(cpt=1; cpt<=nlstate;cpt++){
 6001:        fprintf(fichtm,"<br>\n- Convergence to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a><br> \
 6002: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
 6003:      }
 6004:      if(backcast==1){
 6005:        /* Period (stable) back prevalence in each health state */
 6006:        for(cpt=1; cpt<=nlstate;cpt++){
 6007: 	 fprintf(fichtm,"<br>\n- Convergence to period (stable) back prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a><br> \
 6008: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1);
 6009:        }
 6010:      }
 6011:      if(prevfcast==1){
 6012:        /* Projection of prevalence up to period (stable) prevalence in each health state */
 6013:        for(cpt=1; cpt<=nlstate;cpt++){
 6014: 	 fprintf(fichtm,"<br>\n- Projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f) up to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> \
 6015: <img src=\"%s_%d-%d.svg\">", dateprev1, dateprev2, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1);
 6016:        }
 6017:      }
 6018: 	 
 6019:      for(cpt=1; cpt<=nlstate;cpt++) {
 6020:        fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies in each alive state (1 to %d) (or area under each survival functions): <a href=\"%s_%d%d.svg\">%s_%d%d.svg</a> <br> \
 6021: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
 6022:      }
 6023:      /* } /\* end i1 *\/ */
 6024:    }/* End k1 */
 6025:    fprintf(fichtm,"</ul>");
 6026: 
 6027:    fprintf(fichtm,"\
 6028: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
 6029:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
 6030:  - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
 6031: But because parameters are usually highly correlated (a higher incidence of disability \
 6032: and a higher incidence of recovery can give very close observed transition) it might \
 6033: be very useful to look not only at linear confidence intervals estimated from the \
 6034: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
 6035: (parameters) of the logistic regression, it might be more meaningful to visualize the \
 6036: covariance matrix of the one-step probabilities. \
 6037: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
 6038: 
 6039:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 6040: 	   subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
 6041:    fprintf(fichtm,"\
 6042:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 6043: 	   subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
 6044: 
 6045:    fprintf(fichtm,"\
 6046:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 6047: 	   subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
 6048:    fprintf(fichtm,"\
 6049:  - 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): \
 6050:    <a href=\"%s\">%s</a> <br>\n</li>",
 6051: 	   estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
 6052:    fprintf(fichtm,"\
 6053:  - (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): \
 6054:    <a href=\"%s\">%s</a> <br>\n</li>",
 6055: 	   estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
 6056:    fprintf(fichtm,"\
 6057:  - 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",
 6058: 	   estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
 6059:    fprintf(fichtm,"\
 6060:  - 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",
 6061: 	   estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
 6062:    fprintf(fichtm,"\
 6063:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
 6064: 	   subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
 6065: 
 6066: /*  if(popforecast==1) fprintf(fichtm,"\n */
 6067: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
 6068: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
 6069: /* 	<br>",fileres,fileres,fileres,fileres); */
 6070: /*  else  */
 6071: /*    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); */
 6072:    fflush(fichtm);
 6073:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
 6074: 
 6075:    m=pow(2,cptcoveff);
 6076:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 6077: 
 6078:    jj1=0;
 6079:    for(k1=1; k1<=m;k1++){
 6080:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
 6081:      jj1++;
 6082:      if (cptcovn > 0) {
 6083:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 6084:        for (cpt=1; cpt<=cptcoveff;cpt++)  /**< cptcoveff number of variables */
 6085: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
 6086:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 6087: 
 6088:        if(invalidvarcomb[k1]){
 6089: 	 fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
 6090: 	 continue;
 6091:        }
 6092:      }
 6093:      for(cpt=1; cpt<=nlstate;cpt++) {
 6094:        fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
 6095: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d.svg\"> %s_%d-%d.svg</a>\n <br>\
 6096: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);  
 6097:      }
 6098:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
 6099: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
 6100: true period expectancies (those weighted with period prevalences are also\
 6101:  drawn in addition to the population based expectancies computed using\
 6102:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg</a>\n<br>\
 6103: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
 6104:      /* } /\* end i1 *\/ */
 6105:    }/* End k1 */
 6106:    fprintf(fichtm,"</ul>");
 6107:    fflush(fichtm);
 6108: }
 6109: 
 6110: /******************* Gnuplot file **************/
 6111: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
 6112: 
 6113:   char dirfileres[132],optfileres[132];
 6114:   char gplotcondition[132];
 6115:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
 6116:   int lv=0, vlv=0, kl=0;
 6117:   int ng=0;
 6118:   int vpopbased;
 6119:   int ioffset; /* variable offset for columns */
 6120: 
 6121: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
 6122: /*     printf("Problem with file %s",optionfilegnuplot); */
 6123: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
 6124: /*   } */
 6125: 
 6126:   /*#ifdef windows */
 6127:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 6128:   /*#endif */
 6129:   m=pow(2,cptcoveff);
 6130: 
 6131:   /* Contribution to likelihood */
 6132:   /* Plot the probability implied in the likelihood */
 6133:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
 6134:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
 6135:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
 6136:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
 6137: /* nice for mle=4 plot by number of matrix products.
 6138:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
 6139: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
 6140:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
 6141:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
 6142:   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));
 6143:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
 6144:   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));
 6145:   for (i=1; i<= nlstate ; i ++) {
 6146:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
 6147:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
 6148:     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);
 6149:     for (j=2; j<= nlstate+ndeath ; j ++) {
 6150:       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);
 6151:     }
 6152:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
 6153:   }
 6154:   /* 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 */		 
 6155:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
 6156:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
 6157:   fprintf(ficgp,"\nset out;unset log\n");
 6158:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
 6159: 
 6160:   strcpy(dirfileres,optionfilefiname);
 6161:   strcpy(optfileres,"vpl");
 6162:   /* 1eme*/
 6163:   for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
 6164:     for (k1=1; k1<= m && selected(k1) ; k1 ++) { /* For each valid combination of covariate */
 6165:       /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
 6166:       fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
 6167:       for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 6168: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
 6169: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6170: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6171: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6172: 	vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
 6173: 	/* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
 6174: 	fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6175:       }
 6176:       fprintf(ficgp,"\n#\n");
 6177:       if(invalidvarcomb[k1]){
 6178: 	fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6179: 	continue;
 6180:       }
 6181: 
 6182:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
 6183:       fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
 6184:       fprintf(ficgp,"set xlabel \"Age\" \n\
 6185: set ylabel \"Probability\" \n	\
 6186: set ter svg size 640, 480\n	\
 6187: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
 6188: 			
 6189:       for (i=1; i<= nlstate ; i ++) {
 6190: 	if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 6191: 	else        fprintf(ficgp," %%*lf (%%*lf)");
 6192:       }
 6193:       fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1);
 6194:       for (i=1; i<= nlstate ; i ++) {
 6195: 	if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 6196: 	else fprintf(ficgp," %%*lf (%%*lf)");
 6197:       } 
 6198:       fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1); 
 6199:       for (i=1; i<= nlstate ; i ++) {
 6200: 	if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 6201: 	else fprintf(ficgp," %%*lf (%%*lf)");
 6202:       }  
 6203:       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));
 6204:       if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
 6205: 	/* 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); */
 6206: 	fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1 */
 6207: 	if(cptcoveff ==0){
 6208: 	  fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line ",	 2+(cpt-1),  cpt );
 6209: 	}else{
 6210: 	  kl=0;
 6211: 	  for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
 6212: 	    lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
 6213: 	    /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6214: 	    /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6215: 	    /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6216: 	    vlv= nbcode[Tvaraff[k]][lv];
 6217: 	    kl++;
 6218: 	    /* 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 *\/ */
 6219: 	    /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
 6220: 	    /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
 6221: 	    /* ''  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*/
 6222: 	    if(k==cptcoveff){
 6223: 	      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], \
 6224: 		      4+(cpt-1),  cpt );  /* 4 or 6 ?*/
 6225: 	    }else{
 6226: 	      fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
 6227: 	      kl++;
 6228: 	    }
 6229: 	  } /* end covariate */
 6230: 	} /* end if no covariate */
 6231:       } /* end if backcast */
 6232:       fprintf(ficgp,"\nset out \n");
 6233:     } /* k1 */
 6234:   } /* cpt */
 6235:   /*2 eme*/
 6236:   for (k1=1; k1<= m ; k1 ++) { 
 6237: 
 6238:     fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
 6239:     for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 6240:       lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 6241:       /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6242:       /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6243:       /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6244:       vlv= nbcode[Tvaraff[k]][lv];
 6245:       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6246:     }
 6247:     fprintf(ficgp,"\n#\n");
 6248:     if(invalidvarcomb[k1]){
 6249:       fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6250:       continue;
 6251:     }
 6252: 			
 6253:     fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
 6254:     for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 6255:       if(vpopbased==0)
 6256: 	fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
 6257:       else
 6258: 	fprintf(ficgp,"\nreplot ");
 6259:       for (i=1; i<= nlstate+1 ; i ++) {
 6260: 	k=2*i;
 6261: 	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);
 6262: 	for (j=1; j<= nlstate+1 ; j ++) {
 6263: 	  if (j==i) fprintf(ficgp," %%lf (%%lf)");
 6264: 	  else fprintf(ficgp," %%*lf (%%*lf)");
 6265: 	}   
 6266: 	if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
 6267: 	else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
 6268: 	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);
 6269: 	for (j=1; j<= nlstate+1 ; j ++) {
 6270: 	  if (j==i) fprintf(ficgp," %%lf (%%lf)");
 6271: 	  else fprintf(ficgp," %%*lf (%%*lf)");
 6272: 	}   
 6273: 	fprintf(ficgp,"\" t\"\" w l lt 0,");
 6274: 	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);
 6275: 	for (j=1; j<= nlstate+1 ; j ++) {
 6276: 	  if (j==i) fprintf(ficgp," %%lf (%%lf)");
 6277: 	  else fprintf(ficgp," %%*lf (%%*lf)");
 6278: 	}   
 6279: 	if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
 6280: 	else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
 6281:       } /* state */
 6282:     } /* vpopbased */
 6283:     fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
 6284:   } /* k1 */
 6285: 	
 6286: 	
 6287:   /*3eme*/
 6288:   for (k1=1; k1<= m ; k1 ++) { 
 6289: 
 6290:     for (cpt=1; cpt<= nlstate ; cpt ++) {
 6291:       fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  cov=%d state=%d",k1, cpt);
 6292:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 6293: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 6294: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6295: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6296: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6297: 	vlv= nbcode[Tvaraff[k]][lv];
 6298: 	fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6299:       }
 6300:       fprintf(ficgp,"\n#\n");
 6301:       if(invalidvarcomb[k1]){
 6302: 	fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6303: 	continue;
 6304:       }
 6305: 			
 6306:       /*       k=2+nlstate*(2*cpt-2); */
 6307:       k=2+(nlstate+1)*(cpt-1);
 6308:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
 6309:       fprintf(ficgp,"set ter svg size 640, 480\n\
 6310: 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);
 6311:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 6312: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 6313: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 6314: 	fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 6315: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 6316: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 6317: 				
 6318:       */
 6319:       for (i=1; i< nlstate ; i ++) {
 6320: 	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);
 6321: 	/*	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);*/
 6322: 				
 6323:       } 
 6324:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
 6325:     }
 6326:   }
 6327:   
 6328:   /* 4eme */
 6329:   /* Survival functions (period) from state i in state j by initial state i */
 6330:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
 6331: 
 6332:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 6333:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
 6334:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 6335: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 6336: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6337: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6338: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6339: 	vlv= nbcode[Tvaraff[k]][lv];
 6340: 	fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6341:       }
 6342:       fprintf(ficgp,"\n#\n");
 6343:       if(invalidvarcomb[k1]){
 6344: 	fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6345: 	continue;
 6346:       }
 6347: 			
 6348:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
 6349:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
 6350: set ter svg size 640, 480\n																							\
 6351: unset log y\n																														\
 6352: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 6353:       k=3;
 6354:       for (i=1; i<= nlstate ; i ++){
 6355: 	if(i==1){
 6356: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 6357: 	}else{
 6358: 	  fprintf(ficgp,", '' ");
 6359: 	}
 6360: 	l=(nlstate+ndeath)*(i-1)+1;
 6361: 	fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 6362: 	for (j=2; j<= nlstate+ndeath ; j ++)
 6363: 	  fprintf(ficgp,"+$%d",k+l+j-1);
 6364: 	fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
 6365:       } /* nlstate */
 6366:       fprintf(ficgp,"\nset out\n");
 6367:     } /* end cpt state*/ 
 6368:   } /* end covariate */  
 6369: 	
 6370: /* 5eme */
 6371:   /* Survival functions (period) from state i in state j by final state j */
 6372:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
 6373:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
 6374: 			
 6375:       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);
 6376:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 6377: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 6378: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6379: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6380: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6381: 	vlv= nbcode[Tvaraff[k]][lv];
 6382: 	fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6383:       }
 6384:       fprintf(ficgp,"\n#\n");
 6385:       if(invalidvarcomb[k1]){
 6386: 	fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6387: 	continue;
 6388:       }
 6389:       
 6390:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
 6391:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
 6392: set ter svg size 640, 480\n						\
 6393: unset log y\n								\
 6394: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 6395:       k=3;
 6396:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
 6397: 	if(j==1)
 6398: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 6399: 	else
 6400: 	  fprintf(ficgp,", '' ");
 6401: 	l=(nlstate+ndeath)*(cpt-1) +j;
 6402: 	fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
 6403: 	/* for (i=2; i<= nlstate+ndeath ; i ++) */
 6404: 	/*   fprintf(ficgp,"+$%d",k+l+i-1); */
 6405: 	fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
 6406:       } /* nlstate */
 6407:       fprintf(ficgp,", '' ");
 6408:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
 6409:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
 6410: 	l=(nlstate+ndeath)*(cpt-1) +j;
 6411: 	if(j < nlstate)
 6412: 	  fprintf(ficgp,"$%d +",k+l);
 6413: 	else
 6414: 	  fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
 6415:       }
 6416:       fprintf(ficgp,"\nset out\n");
 6417:     } /* end cpt state*/ 
 6418:   } /* end covariate */  
 6419:   
 6420: /* 6eme */
 6421:   /* CV preval stable (period) for each covariate */
 6422:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
 6423:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 6424:       
 6425:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
 6426:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 6427: 	lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 6428: 	/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6429: 	/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6430: 	/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6431: 	vlv= nbcode[Tvaraff[k]][lv];
 6432: 	fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6433:       }
 6434:       fprintf(ficgp,"\n#\n");
 6435:       if(invalidvarcomb[k1]){
 6436: 	fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6437: 	continue;
 6438:       }
 6439:       
 6440:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
 6441:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 6442: set ter svg size 640, 480\n						\
 6443: unset log y\n								\
 6444: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 6445:       k=3; /* Offset */
 6446:       for (i=1; i<= nlstate ; i ++){
 6447: 	if(i==1)
 6448: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 6449: 	else
 6450: 	  fprintf(ficgp,", '' ");
 6451: 	l=(nlstate+ndeath)*(i-1)+1;
 6452: 	fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 6453: 	for (j=2; j<= nlstate ; j ++)
 6454: 	  fprintf(ficgp,"+$%d",k+l+j-1);
 6455: 	fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
 6456:       } /* nlstate */
 6457:       fprintf(ficgp,"\nset out\n");
 6458:     } /* end cpt state*/ 
 6459:   } /* end covariate */  
 6460:   
 6461:   
 6462: /* 7eme */
 6463:   if(backcast == 1){
 6464:     /* CV back preval stable (period) for each covariate */
 6465:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
 6466:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 6467: 	fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
 6468: 	for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
 6469: 	  lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
 6470: 	  /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6471: 	  /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6472: 	  /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6473: 	  vlv= nbcode[Tvaraff[k]][lv];
 6474: 	  fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6475: 	}
 6476: 	fprintf(ficgp,"\n#\n");
 6477: 	if(invalidvarcomb[k1]){
 6478: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6479: 	  continue;
 6480: 	}
 6481: 	
 6482: 	fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1);
 6483: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 6484: set ter svg size 640, 480\n						\
 6485: unset log y\n								\
 6486: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 6487: 	k=3; /* Offset */
 6488: 	for (i=1; i<= nlstate ; i ++){
 6489: 	  if(i==1)
 6490: 	    fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
 6491: 	  else
 6492: 	    fprintf(ficgp,", '' ");
 6493: 	  /* l=(nlstate+ndeath)*(i-1)+1; */
 6494: 	  l=(nlstate+ndeath)*(cpt-1)+1;
 6495: 	  /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
 6496: 	  /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
 6497: 	  fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */
 6498: 	  /* for (j=2; j<= nlstate ; j ++) */
 6499: 	  /* 	fprintf(ficgp,"+$%d",k+l+j-1); */
 6500: 	  /* 	/\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
 6501: 	  fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
 6502: 	} /* nlstate */
 6503: 	fprintf(ficgp,"\nset out\n");
 6504:       } /* end cpt state*/ 
 6505:     } /* end covariate */  
 6506:   } /* End if backcast */
 6507:   
 6508:   /* 8eme */
 6509:   if(prevfcast==1){
 6510:     /* Projection from cross-sectional to stable (period) for each covariate */
 6511:     
 6512:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
 6513:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 6514: 	fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
 6515: 	for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
 6516: 	  lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
 6517: 	  /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6518: 	  /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6519: 	  /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6520: 	  vlv= nbcode[Tvaraff[k]][lv];
 6521: 	  fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
 6522: 	}
 6523: 	fprintf(ficgp,"\n#\n");
 6524: 	if(invalidvarcomb[k1]){
 6525: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 6526: 	  continue;
 6527: 	}
 6528: 	
 6529: 	fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
 6530: 	fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
 6531: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
 6532: set ter svg size 640, 480\n						\
 6533: unset log y\n								\
 6534: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 6535: 	for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
 6536: 	  /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 6537: 	  /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 6538: 	  /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 6539: 	  /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 6540: 	  if(i==1){
 6541: 	    fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
 6542: 	  }else{
 6543: 	    fprintf(ficgp,",\\\n '' ");
 6544: 	  }
 6545: 	  if(cptcoveff ==0){ /* No covariate */
 6546: 	    ioffset=2; /* Age is in 2 */
 6547: 	    /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
 6548: 	    /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
 6549: 	    /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
 6550: 	    /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
 6551: 	    fprintf(ficgp," u %d:(", ioffset); 
 6552: 	    if(i==nlstate+1)
 6553: 	      fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ",	\
 6554: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
 6555: 	    else
 6556: 	      fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",	\
 6557: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
 6558: 	  }else{ /* more than 2 covariates */
 6559: 	    if(cptcoveff ==1){
 6560: 	      ioffset=4; /* Age is in 4 */
 6561: 	    }else{
 6562: 	      ioffset=6; /* Age is in 6 */
 6563: 	      /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 6564: 	      /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
 6565: 	    }   
 6566: 	    fprintf(ficgp," u %d:(",ioffset); 
 6567: 	    kl=0;
 6568: 	    strcpy(gplotcondition,"(");
 6569: 	    for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
 6570: 	      lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
 6571: 	      /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 6572: 	      /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 6573: 	      /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 6574: 	      vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
 6575: 	      kl++;
 6576: 	      sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
 6577: 	      kl++;
 6578: 	      if(k <cptcoveff && cptcoveff>1)
 6579: 		sprintf(gplotcondition+strlen(gplotcondition)," && ");
 6580: 	    }
 6581: 	    strcpy(gplotcondition+strlen(gplotcondition),")");
 6582: 	    /* 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 *\/ */
 6583: 	    /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
 6584: 	    /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
 6585: 	    /* ''  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*/
 6586: 	    if(i==nlstate+1){
 6587: 	      fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ", gplotcondition, \
 6588: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
 6589: 	    }else{
 6590: 	      fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
 6591: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
 6592: 	    }
 6593: 	  } /* end if covariate */
 6594: 	} /* nlstate */
 6595: 	fprintf(ficgp,"\nset out\n");
 6596:       } /* end cpt state*/
 6597:     } /* end covariate */
 6598:   } /* End if prevfcast */
 6599:   
 6600:   
 6601:   /* proba elementaires */
 6602:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
 6603:   for(i=1,jk=1; i <=nlstate; i++){
 6604:     fprintf(ficgp,"# initial state %d\n",i);
 6605:     for(k=1; k <=(nlstate+ndeath); k++){
 6606:       if (k != i) {
 6607: 	fprintf(ficgp,"#   current state %d\n",k);
 6608: 	for(j=1; j <=ncovmodel; j++){
 6609: 	  fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
 6610: 	  jk++; 
 6611: 	}
 6612: 	fprintf(ficgp,"\n");
 6613:       }
 6614:     }
 6615:   }
 6616:   fprintf(ficgp,"##############\n#\n");
 6617:   
 6618:   /*goto avoid;*/
 6619:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
 6620:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
 6621:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
 6622:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
 6623:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
 6624:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 6625:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 6626:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 6627:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 6628:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
 6629:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 6630:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
 6631:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
 6632:   fprintf(ficgp,"#\n");
 6633:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
 6634:     fprintf(ficgp,"# ng=%d\n",ng);
 6635:     fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
 6636:     for(jk=1; jk <=m; jk++) {
 6637:       fprintf(ficgp,"#    jk=%d\n",jk);
 6638:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
 6639:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
 6640:       if (ng==1){
 6641: 	fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
 6642: 	fprintf(ficgp,"\nunset log y");
 6643:       }else if (ng==2){
 6644: 	fprintf(ficgp,"\nset ylabel \"Probability\"\n");
 6645: 	fprintf(ficgp,"\nset log y");
 6646:       }else if (ng==3){
 6647: 	fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
 6648: 	fprintf(ficgp,"\nset log y");
 6649:       }else
 6650: 	fprintf(ficgp,"\nunset title ");
 6651:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
 6652:       i=1;
 6653:       for(k2=1; k2<=nlstate; k2++) {
 6654: 	k3=i;
 6655: 	for(k=1; k<=(nlstate+ndeath); k++) {
 6656: 	  if (k != k2){
 6657: 	    switch( ng) {
 6658: 	    case 1:
 6659: 	      if(nagesqr==0)
 6660: 		fprintf(ficgp," p%d+p%d*x",i,i+1);
 6661: 	      else /* nagesqr =1 */
 6662: 		fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
 6663: 	      break;
 6664: 	    case 2: /* ng=2 */
 6665: 	      if(nagesqr==0)
 6666: 		fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
 6667: 	      else /* nagesqr =1 */
 6668: 		fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
 6669: 	      break;
 6670: 	    case 3:
 6671: 	      if(nagesqr==0)
 6672: 		fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
 6673: 	      else /* nagesqr =1 */
 6674: 		fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
 6675: 	      break;
 6676: 	    }
 6677: 	    ij=1;/* To be checked else nbcode[0][0] wrong */
 6678: 	    for(j=3; j <=ncovmodel-nagesqr; j++) {
 6679: 	      /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
 6680: 	      if(ij <=cptcovage) { /* Bug valgrind */
 6681: 		if((j-2)==Tage[ij]) { /* Bug valgrind */
 6682: 		  fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
 6683: 		  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
 6684: 		  ij++;
 6685: 		}
 6686: 	      }
 6687: 	      else
 6688: 		fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]); /* Valgrind bug nbcode */
 6689: 	    }
 6690: 	  }else{
 6691: 	    i=i-ncovmodel;
 6692: 	    if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
 6693: 	      fprintf(ficgp," (1.");
 6694: 	  }
 6695: 	  
 6696: 	  if(ng != 1){
 6697: 	    fprintf(ficgp,")/(1");
 6698: 	    
 6699: 	    for(k1=1; k1 <=nlstate; k1++){ 
 6700: 	      if(nagesqr==0)
 6701: 		fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
 6702: 	      else /* nagesqr =1 */
 6703: 		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);
 6704: 	       
 6705: 	      ij=1;
 6706: 	      for(j=3; j <=ncovmodel-nagesqr; j++){
 6707: 		if(ij <=cptcovage) { /* Bug valgrind */
 6708: 		  if((j-2)==Tage[ij]) { /* Bug valgrind */
 6709: 		    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
 6710: 		    /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
 6711: 		    ij++;
 6712: 		  }
 6713: 		}
 6714: 		else
 6715: 		  fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);/* Valgrind bug nbcode */
 6716: 	      }
 6717: 	      fprintf(ficgp,")");
 6718: 	    }
 6719: 	    fprintf(ficgp,")");
 6720: 	    if(ng ==2)
 6721: 	      fprintf(ficgp," t \"p%d%d\" ", k2,k);
 6722: 	    else /* ng= 3 */
 6723: 	      fprintf(ficgp," t \"i%d%d\" ", k2,k);
 6724: 	  }else{ /* end ng <> 1 */
 6725: 	    if( k !=k2) /* logit p11 is hard to draw */
 6726: 	      fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
 6727: 	  }
 6728: 	  if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
 6729: 	    fprintf(ficgp,",");
 6730: 	  if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
 6731: 	    fprintf(ficgp,",");
 6732: 	  i=i+ncovmodel;
 6733: 	} /* end k */
 6734:       } /* end k2 */
 6735:       fprintf(ficgp,"\n set out\n");
 6736:     } /* end jk */
 6737:   } /* end ng */
 6738:   /* avoid: */
 6739:   fflush(ficgp); 
 6740: }  /* end gnuplot */
 6741: 
 6742: 
 6743: /*************** Moving average **************/
 6744: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
 6745:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
 6746:    
 6747:    int i, cpt, cptcod;
 6748:    int modcovmax =1;
 6749:    int mobilavrange, mob;
 6750:    int iage=0;
 6751: 
 6752:    double sum=0.;
 6753:    double age;
 6754:    double *sumnewp, *sumnewm;
 6755:    double *agemingood, *agemaxgood; /* Currently identical for all covariates */
 6756:   
 6757:   
 6758:    /* modcovmax=2*cptcoveff;/\* Max number of modalities. We suppose  */
 6759:    /* 		   a covariate has 2 modalities, should be equal to ncovcombmax  *\/ */
 6760: 
 6761:    sumnewp = vector(1,ncovcombmax);
 6762:    sumnewm = vector(1,ncovcombmax);
 6763:    agemingood = vector(1,ncovcombmax);	
 6764:    agemaxgood = vector(1,ncovcombmax);
 6765: 
 6766:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
 6767:      sumnewm[cptcod]=0.;
 6768:      sumnewp[cptcod]=0.;
 6769:      agemingood[cptcod]=0;
 6770:      agemaxgood[cptcod]=0;
 6771:    }
 6772:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
 6773:   
 6774:    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
 6775:      if(mobilav==1) mobilavrange=5; /* default */
 6776:      else mobilavrange=mobilav;
 6777:      for (age=bage; age<=fage; age++)
 6778:        for (i=1; i<=nlstate;i++)
 6779: 	 for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
 6780: 	   mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 6781:      /* We keep the original values on the extreme ages bage, fage and for 
 6782: 	fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
 6783: 	we use a 5 terms etc. until the borders are no more concerned. 
 6784:      */ 
 6785:      for (mob=3;mob <=mobilavrange;mob=mob+2){
 6786:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
 6787: 	 for (i=1; i<=nlstate;i++){
 6788: 	   for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
 6789: 	     mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
 6790: 	     for (cpt=1;cpt<=(mob-1)/2;cpt++){
 6791: 	       mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
 6792: 	       mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
 6793: 	     }
 6794: 	     mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
 6795: 	   }
 6796: 	 }
 6797:        }/* end age */
 6798:      }/* end mob */
 6799:    }else
 6800:      return -1;
 6801:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
 6802:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
 6803:      if(invalidvarcomb[cptcod]){
 6804:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
 6805:        continue;
 6806:      }
 6807: 
 6808:      agemingood[cptcod]=fage-(mob-1)/2;
 6809:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
 6810:        sumnewm[cptcod]=0.;
 6811:        for (i=1; i<=nlstate;i++){
 6812: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 6813:        }
 6814:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
 6815: 	 agemingood[cptcod]=age;
 6816:        }else{ /* bad */
 6817: 	 for (i=1; i<=nlstate;i++){
 6818: 	   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
 6819: 	 } /* i */
 6820:        } /* end bad */
 6821:      }/* age */
 6822:      sum=0.;
 6823:      for (i=1; i<=nlstate;i++){
 6824:        sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
 6825:      }
 6826:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
 6827:        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);
 6828:        /* for (i=1; i<=nlstate;i++){ */
 6829:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
 6830:        /* } /\* i *\/ */
 6831:      } /* end bad */
 6832:      /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
 6833:      /* From youngest, finding the oldest wrong */
 6834:      agemaxgood[cptcod]=bage+(mob-1)/2;
 6835:      for (age=bage+(mob-1)/2; age<=fage; age++){
 6836:        sumnewm[cptcod]=0.;
 6837:        for (i=1; i<=nlstate;i++){
 6838: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 6839:        }
 6840:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
 6841: 	 agemaxgood[cptcod]=age;
 6842:        }else{ /* bad */
 6843: 	 for (i=1; i<=nlstate;i++){
 6844: 	   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
 6845: 	 } /* i */
 6846:        } /* end bad */
 6847:      }/* age */
 6848:      sum=0.;
 6849:      for (i=1; i<=nlstate;i++){
 6850:        sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
 6851:      }
 6852:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
 6853:        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);
 6854:        /* for (i=1; i<=nlstate;i++){ */
 6855:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
 6856:        /* } /\* i *\/ */
 6857:      } /* end bad */
 6858: 		
 6859:      for (age=bage; age<=fage; age++){
 6860:        printf("%d %d ", cptcod, (int)age);
 6861:        sumnewp[cptcod]=0.;
 6862:        sumnewm[cptcod]=0.;
 6863:        for (i=1; i<=nlstate;i++){
 6864: 	 sumnewp[cptcod]+=probs[(int)age][i][cptcod];
 6865: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 6866: 	 /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
 6867:        }
 6868:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
 6869:      }
 6870:      /* printf("\n"); */
 6871:      /* } */
 6872:      /* brutal averaging */
 6873:      for (i=1; i<=nlstate;i++){
 6874:        for (age=1; age<=bage; age++){
 6875: 	 mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
 6876: 	 /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
 6877:        }	
 6878:        for (age=fage; age<=AGESUP; age++){
 6879: 	 mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
 6880: 	 /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
 6881:        }
 6882:      } /* end i status */
 6883:      for (i=nlstate+1; i<=nlstate+ndeath;i++){
 6884:        for (age=1; age<=AGESUP; age++){
 6885: 	 /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
 6886: 	 mobaverage[(int)age][i][cptcod]=0.;
 6887:        }
 6888:      }
 6889:    }/* end cptcod */
 6890:    free_vector(sumnewm,1, ncovcombmax);
 6891:    free_vector(sumnewp,1, ncovcombmax);
 6892:    free_vector(agemaxgood,1, ncovcombmax);
 6893:    free_vector(agemingood,1, ncovcombmax);
 6894:    return 0;
 6895:  }/* End movingaverage */
 6896:  
 6897: 
 6898: /************** Forecasting ******************/
 6899: 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){
 6900:   /* proj1, year, month, day of starting projection 
 6901:      agemin, agemax range of age
 6902:      dateprev1 dateprev2 range of dates during which prevalence is computed
 6903:      anproj2 year of en of projection (same day and month as proj1).
 6904:   */
 6905:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
 6906:   double agec; /* generic age */
 6907:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
 6908:   double *popeffectif,*popcount;
 6909:   double ***p3mat;
 6910:   /* double ***mobaverage; */
 6911:   char fileresf[FILENAMELENGTH];
 6912: 
 6913:   agelim=AGESUP;
 6914:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 6915:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 6916:      We still use firstpass and lastpass as another selection.
 6917:   */
 6918:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
 6919:   /* 	      firstpass, lastpass,  stepm,  weightopt, model); */
 6920:  
 6921:   strcpy(fileresf,"F_"); 
 6922:   strcat(fileresf,fileresu);
 6923:   if((ficresf=fopen(fileresf,"w"))==NULL) {
 6924:     printf("Problem with forecast resultfile: %s\n", fileresf);
 6925:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
 6926:   }
 6927:   printf("Computing forecasting: result on file '%s', please wait... \n", fileresf);
 6928:   fprintf(ficlog,"Computing forecasting: result on file '%s', please wait... \n", fileresf);
 6929: 
 6930:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 6931: 
 6932: 
 6933:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 6934:   if (stepm<=12) stepsize=1;
 6935:   if(estepm < stepm){
 6936:     printf ("Problem %d lower than %d\n",estepm, stepm);
 6937:   }
 6938:   else  hstepm=estepm;   
 6939: 
 6940:   hstepm=hstepm/stepm; 
 6941:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
 6942:                                fractional in yp1 */
 6943:   anprojmean=yp;
 6944:   yp2=modf((yp1*12),&yp);
 6945:   mprojmean=yp;
 6946:   yp1=modf((yp2*30.5),&yp);
 6947:   jprojmean=yp;
 6948:   if(jprojmean==0) jprojmean=1;
 6949:   if(mprojmean==0) jprojmean=1;
 6950: 
 6951:   i1=pow(2,cptcoveff);
 6952:   if (cptcovn < 1){i1=1;}
 6953:   
 6954:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
 6955:   
 6956:   fprintf(ficresf,"#****** Routine prevforecast **\n");
 6957:   
 6958: /* 	      if (h==(int)(YEARM*yearp)){ */
 6959:   for(k=1;k<=i1;k++){
 6960:     if(invalidvarcomb[k]){
 6961:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
 6962:       continue;
 6963:     }
 6964:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
 6965:     for(j=1;j<=cptcoveff;j++) {
 6966:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 6967:     }
 6968:     fprintf(ficresf," yearproj age");
 6969:     for(j=1; j<=nlstate+ndeath;j++){ 
 6970:       for(i=1; i<=nlstate;i++) 	      
 6971: 	fprintf(ficresf," p%d%d",i,j);
 6972:       fprintf(ficresf," wp.%d",j);
 6973:     }
 6974:     for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
 6975:       fprintf(ficresf,"\n");
 6976:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
 6977:       for (agec=fage; agec>=(ageminpar-1); agec--){ 
 6978: 	nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
 6979: 	nhstepm = nhstepm/hstepm; 
 6980: 	p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6981: 	oldm=oldms;savm=savms;
 6982: 	hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
 6983: 	
 6984: 	for (h=0; h<=nhstepm; h++){
 6985: 	  if (h*hstepm/YEARM*stepm ==yearp) {
 6986: 	    fprintf(ficresf,"\n");
 6987: 	    for(j=1;j<=cptcoveff;j++) 
 6988: 	      fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 6989: 	    fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
 6990: 	  } 
 6991: 	  for(j=1; j<=nlstate+ndeath;j++) {
 6992: 	    ppij=0.;
 6993: 	    for(i=1; i<=nlstate;i++) {
 6994: 	      if (mobilav==1) 
 6995: 		ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][k];
 6996: 	      else {
 6997: 		ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
 6998: 	      }
 6999: 	      if (h*hstepm/YEARM*stepm== yearp) {
 7000: 		fprintf(ficresf," %.3f", p3mat[i][j][h]);
 7001: 	      }
 7002: 	    } /* end i */
 7003: 	    if (h*hstepm/YEARM*stepm==yearp) {
 7004: 	      fprintf(ficresf," %.3f", ppij);
 7005: 	    }
 7006: 	  }/* end j */
 7007: 	} /* end h */
 7008: 	free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 7009:       } /* end agec */
 7010:     } /* end yearp */
 7011:   } /* end  k */
 7012: 	
 7013:   fclose(ficresf);
 7014:   printf("End of Computing forecasting \n");
 7015:   fprintf(ficlog,"End of Computing forecasting\n");
 7016: 
 7017: }
 7018: 
 7019: /* /\************** Back Forecasting ******************\/ */
 7020: /* 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){ */
 7021: /*   /\* back1, year, month, day of starting backection  */
 7022: /*      agemin, agemax range of age */
 7023: /*      dateprev1 dateprev2 range of dates during which prevalence is computed */
 7024: /*      anback2 year of en of backection (same day and month as back1). */
 7025: /*   *\/ */
 7026: /*   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
 7027: /*   double agec; /\* generic age *\/ */
 7028: /*   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
 7029: /*   double *popeffectif,*popcount; */
 7030: /*   double ***p3mat; */
 7031: /*   /\* double ***mobaverage; *\/ */
 7032: /*   char fileresfb[FILENAMELENGTH]; */
 7033: 	
 7034: /*   agelim=AGESUP; */
 7035: /*   /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
 7036: /*      in each health status at the date of interview (if between dateprev1 and dateprev2). */
 7037: /*      We still use firstpass and lastpass as another selection. */
 7038: /*   *\/ */
 7039: /*   /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
 7040: /*   /\* 	      firstpass, lastpass,  stepm,  weightopt, model); *\/ */
 7041: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
 7042: 	
 7043: /*   strcpy(fileresfb,"FB_");  */
 7044: /*   strcat(fileresfb,fileresu); */
 7045: /*   if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
 7046: /*     printf("Problem with back forecast resultfile: %s\n", fileresfb); */
 7047: /*     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
 7048: /*   } */
 7049: /*   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
 7050: /*   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
 7051: 	
 7052: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
 7053: 	
 7054: /*   /\* if (mobilav!=0) { *\/ */
 7055: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
 7056: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
 7057: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
 7058: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
 7059: /*   /\*   } *\/ */
 7060: /*   /\* } *\/ */
 7061: 	
 7062: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
 7063: /*   if (stepm<=12) stepsize=1; */
 7064: /*   if(estepm < stepm){ */
 7065: /*     printf ("Problem %d lower than %d\n",estepm, stepm); */
 7066: /*   } */
 7067: /*   else  hstepm=estepm;    */
 7068: 	
 7069: /*   hstepm=hstepm/stepm;  */
 7070: /*   yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
 7071: /*                                fractional in yp1 *\/ */
 7072: /*   anprojmean=yp; */
 7073: /*   yp2=modf((yp1*12),&yp); */
 7074: /*   mprojmean=yp; */
 7075: /*   yp1=modf((yp2*30.5),&yp); */
 7076: /*   jprojmean=yp; */
 7077: /*   if(jprojmean==0) jprojmean=1; */
 7078: /*   if(mprojmean==0) jprojmean=1; */
 7079: 	
 7080: /*   i1=cptcoveff; */
 7081: /*   if (cptcovn < 1){i1=1;} */
 7082:   
 7083: /*   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);  */
 7084:   
 7085: /*   fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
 7086: 	
 7087: /* 	/\* 	      if (h==(int)(YEARM*yearp)){ *\/ */
 7088: /*   for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
 7089: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
 7090: /*       k=k+1; */
 7091: /*       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
 7092: /*       for(j=1;j<=cptcoveff;j++) { */
 7093: /* 				fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
 7094: /*       } */
 7095: /*       fprintf(ficresfb," yearbproj age"); */
 7096: /*       for(j=1; j<=nlstate+ndeath;j++){  */
 7097: /* 				for(i=1; i<=nlstate;i++) 	       */
 7098: /*           fprintf(ficresfb," p%d%d",i,j); */
 7099: /* 				fprintf(ficresfb," p.%d",j); */
 7100: /*       } */
 7101: /*       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {  */
 7102: /* 				/\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  *\/ */
 7103: /* 				fprintf(ficresfb,"\n"); */
 7104: /* 				fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);    */
 7105: /* 				for (agec=fage; agec>=(ageminpar-1); agec--){  */
 7106: /* 					nhstepm=(int) rint((agelim-agec)*YEARM/stepm);  */
 7107: /* 					nhstepm = nhstepm/hstepm;  */
 7108: /* 					p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
 7109: /* 					oldm=oldms;savm=savms; */
 7110: /* 					hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k); 	 */
 7111: /* 					for (h=0; h<=nhstepm; h++){ */
 7112: /* 						if (h*hstepm/YEARM*stepm ==yearp) { */
 7113: /*               fprintf(ficresfb,"\n"); */
 7114: /*               for(j=1;j<=cptcoveff;j++)  */
 7115: /*                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
 7116: /* 							fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
 7117: /* 						}  */
 7118: /* 						for(j=1; j<=nlstate+ndeath;j++) { */
 7119: /* 							ppij=0.; */
 7120: /* 							for(i=1; i<=nlstate;i++) { */
 7121: /* 								if (mobilav==1)  */
 7122: /* 									ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
 7123: /* 								else { */
 7124: /* 									ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
 7125: /* 								} */
 7126: /* 								if (h*hstepm/YEARM*stepm== yearp) { */
 7127: /* 									fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
 7128: /* 								} */
 7129: /* 							} /\* end i *\/ */
 7130: /* 							if (h*hstepm/YEARM*stepm==yearp) { */
 7131: /* 								fprintf(ficresfb," %.3f", ppij); */
 7132: /* 							} */
 7133: /* 						}/\* end j *\/ */
 7134: /* 					} /\* end h *\/ */
 7135: /* 					free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
 7136: /* 				} /\* end agec *\/ */
 7137: /*       } /\* end yearp *\/ */
 7138: /*     } /\* end cptcod *\/ */
 7139: /*   } /\* end  cptcov *\/ */
 7140: 	
 7141: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
 7142: 	
 7143: /*   fclose(ficresfb); */
 7144: /*   printf("End of Computing Back forecasting \n"); */
 7145: /*   fprintf(ficlog,"End of Computing Back forecasting\n"); */
 7146: 	
 7147: /* } */
 7148: 
 7149: /************** Forecasting *****not tested NB*************/
 7150: /* 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){ */
 7151:   
 7152: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
 7153: /*   int *popage; */
 7154: /*   double calagedatem, agelim, kk1, kk2; */
 7155: /*   double *popeffectif,*popcount; */
 7156: /*   double ***p3mat,***tabpop,***tabpopprev; */
 7157: /*   /\* double ***mobaverage; *\/ */
 7158: /*   char filerespop[FILENAMELENGTH]; */
 7159: 
 7160: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 7161: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 7162: /*   agelim=AGESUP; */
 7163: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
 7164:   
 7165: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
 7166:   
 7167:   
 7168: /*   strcpy(filerespop,"POP_");  */
 7169: /*   strcat(filerespop,fileresu); */
 7170: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
 7171: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
 7172: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
 7173: /*   } */
 7174: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
 7175: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
 7176: 
 7177: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
 7178: 
 7179: /*   /\* if (mobilav!=0) { *\/ */
 7180: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
 7181: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
 7182: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
 7183: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
 7184: /*   /\*   } *\/ */
 7185: /*   /\* } *\/ */
 7186: 
 7187: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
 7188: /*   if (stepm<=12) stepsize=1; */
 7189:   
 7190: /*   agelim=AGESUP; */
 7191:   
 7192: /*   hstepm=1; */
 7193: /*   hstepm=hstepm/stepm;  */
 7194: 	
 7195: /*   if (popforecast==1) { */
 7196: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
 7197: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
 7198: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
 7199: /*     }  */
 7200: /*     popage=ivector(0,AGESUP); */
 7201: /*     popeffectif=vector(0,AGESUP); */
 7202: /*     popcount=vector(0,AGESUP); */
 7203:     
 7204: /*     i=1;    */
 7205: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
 7206:     
 7207: /*     imx=i; */
 7208: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
 7209: /*   } */
 7210:   
 7211: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
 7212: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
 7213: /*       k=k+1; */
 7214: /*       fprintf(ficrespop,"\n#******"); */
 7215: /*       for(j=1;j<=cptcoveff;j++) { */
 7216: /* 	fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
 7217: /*       } */
 7218: /*       fprintf(ficrespop,"******\n"); */
 7219: /*       fprintf(ficrespop,"# Age"); */
 7220: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
 7221: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
 7222:       
 7223: /*       for (cpt=0; cpt<=0;cpt++) {  */
 7224: /* 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
 7225: 	
 7226: /* 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
 7227: /* 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
 7228: /* 	  nhstepm = nhstepm/hstepm;  */
 7229: 	  
 7230: /* 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
 7231: /* 	  oldm=oldms;savm=savms; */
 7232: /* 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
 7233: 	  
 7234: /* 	  for (h=0; h<=nhstepm; h++){ */
 7235: /* 	    if (h==(int) (calagedatem+YEARM*cpt)) { */
 7236: /* 	      fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
 7237: /* 	    }  */
 7238: /* 	    for(j=1; j<=nlstate+ndeath;j++) { */
 7239: /* 	      kk1=0.;kk2=0; */
 7240: /* 	      for(i=1; i<=nlstate;i++) {	       */
 7241: /* 		if (mobilav==1)  */
 7242: /* 		  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
 7243: /* 		else { */
 7244: /* 		  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
 7245: /* 		} */
 7246: /* 	      } */
 7247: /* 	      if (h==(int)(calagedatem+12*cpt)){ */
 7248: /* 		tabpop[(int)(agedeb)][j][cptcod]=kk1; */
 7249: /* 		/\*fprintf(ficrespop," %.3f", kk1); */
 7250: /* 		  if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
 7251: /* 	      } */
 7252: /* 	    } */
 7253: /* 	    for(i=1; i<=nlstate;i++){ */
 7254: /* 	      kk1=0.; */
 7255: /* 	      for(j=1; j<=nlstate;j++){ */
 7256: /* 		kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
 7257: /* 	      } */
 7258: /* 	      tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
 7259: /* 	    } */
 7260: 	    
 7261: /* 	    if (h==(int)(calagedatem+12*cpt)) */
 7262: /* 	      for(j=1; j<=nlstate;j++)  */
 7263: /* 		fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
 7264: /* 	  } */
 7265: /* 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
 7266: /* 	} */
 7267: /*       } */
 7268:       
 7269: /*       /\******\/ */
 7270:       
 7271: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
 7272: /* 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
 7273: /* 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
 7274: /* 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
 7275: /* 	  nhstepm = nhstepm/hstepm;  */
 7276: 	  
 7277: /* 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
 7278: /* 	  oldm=oldms;savm=savms; */
 7279: /* 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
 7280: /* 	  for (h=0; h<=nhstepm; h++){ */
 7281: /* 	    if (h==(int) (calagedatem+YEARM*cpt)) { */
 7282: /* 	      fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
 7283: /* 	    }  */
 7284: /* 	    for(j=1; j<=nlstate+ndeath;j++) { */
 7285: /* 	      kk1=0.;kk2=0; */
 7286: /* 	      for(i=1; i<=nlstate;i++) {	       */
 7287: /* 		kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];	 */
 7288: /* 	      } */
 7289: /* 	      if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);	 */
 7290: /* 	    } */
 7291: /* 	  } */
 7292: /* 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
 7293: /* 	} */
 7294: /*       } */
 7295: /*     }  */
 7296: /*   } */
 7297:   
 7298: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
 7299:   
 7300: /*   if (popforecast==1) { */
 7301: /*     free_ivector(popage,0,AGESUP); */
 7302: /*     free_vector(popeffectif,0,AGESUP); */
 7303: /*     free_vector(popcount,0,AGESUP); */
 7304: /*   } */
 7305: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 7306: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 7307: /*   fclose(ficrespop); */
 7308: /* } /\* End of popforecast *\/ */
 7309:  
 7310: int fileappend(FILE *fichier, char *optionfich)
 7311: {
 7312:   if((fichier=fopen(optionfich,"a"))==NULL) {
 7313:     printf("Problem with file: %s\n", optionfich);
 7314:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
 7315:     return (0);
 7316:   }
 7317:   fflush(fichier);
 7318:   return (1);
 7319: }
 7320: 
 7321: 
 7322: /**************** function prwizard **********************/
 7323: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
 7324: {
 7325: 
 7326:   /* Wizard to print covariance matrix template */
 7327: 
 7328:   char ca[32], cb[32];
 7329:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
 7330:   int numlinepar;
 7331: 
 7332:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 7333:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 7334:   for(i=1; i <=nlstate; i++){
 7335:     jj=0;
 7336:     for(j=1; j <=nlstate+ndeath; j++){
 7337:       if(j==i) continue;
 7338:       jj++;
 7339:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
 7340:       printf("%1d%1d",i,j);
 7341:       fprintf(ficparo,"%1d%1d",i,j);
 7342:       for(k=1; k<=ncovmodel;k++){
 7343: 	/* 	  printf(" %lf",param[i][j][k]); */
 7344: 	/* 	  fprintf(ficparo," %lf",param[i][j][k]); */
 7345: 	printf(" 0.");
 7346: 	fprintf(ficparo," 0.");
 7347:       }
 7348:       printf("\n");
 7349:       fprintf(ficparo,"\n");
 7350:     }
 7351:   }
 7352:   printf("# Scales (for hessian or gradient estimation)\n");
 7353:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
 7354:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
 7355:   for(i=1; i <=nlstate; i++){
 7356:     jj=0;
 7357:     for(j=1; j <=nlstate+ndeath; j++){
 7358:       if(j==i) continue;
 7359:       jj++;
 7360:       fprintf(ficparo,"%1d%1d",i,j);
 7361:       printf("%1d%1d",i,j);
 7362:       fflush(stdout);
 7363:       for(k=1; k<=ncovmodel;k++){
 7364: 	/* 	printf(" %le",delti3[i][j][k]); */
 7365: 	/* 	fprintf(ficparo," %le",delti3[i][j][k]); */
 7366: 	printf(" 0.");
 7367: 	fprintf(ficparo," 0.");
 7368:       }
 7369:       numlinepar++;
 7370:       printf("\n");
 7371:       fprintf(ficparo,"\n");
 7372:     }
 7373:   }
 7374:   printf("# Covariance matrix\n");
 7375: /* # 121 Var(a12)\n\ */
 7376: /* # 122 Cov(b12,a12) Var(b12)\n\ */
 7377: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 7378: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 7379: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 7380: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 7381: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 7382: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 7383:   fflush(stdout);
 7384:   fprintf(ficparo,"# Covariance matrix\n");
 7385:   /* # 121 Var(a12)\n\ */
 7386:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
 7387:   /* #   ...\n\ */
 7388:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
 7389:   
 7390:   for(itimes=1;itimes<=2;itimes++){
 7391:     jj=0;
 7392:     for(i=1; i <=nlstate; i++){
 7393:       for(j=1; j <=nlstate+ndeath; j++){
 7394: 	if(j==i) continue;
 7395: 	for(k=1; k<=ncovmodel;k++){
 7396: 	  jj++;
 7397: 	  ca[0]= k+'a'-1;ca[1]='\0';
 7398: 	  if(itimes==1){
 7399: 	    printf("#%1d%1d%d",i,j,k);
 7400: 	    fprintf(ficparo,"#%1d%1d%d",i,j,k);
 7401: 	  }else{
 7402: 	    printf("%1d%1d%d",i,j,k);
 7403: 	    fprintf(ficparo,"%1d%1d%d",i,j,k);
 7404: 	    /* 	printf(" %.5le",matcov[i][j]); */
 7405: 	  }
 7406: 	  ll=0;
 7407: 	  for(li=1;li <=nlstate; li++){
 7408: 	    for(lj=1;lj <=nlstate+ndeath; lj++){
 7409: 	      if(lj==li) continue;
 7410: 	      for(lk=1;lk<=ncovmodel;lk++){
 7411: 		ll++;
 7412: 		if(ll<=jj){
 7413: 		  cb[0]= lk +'a'-1;cb[1]='\0';
 7414: 		  if(ll<jj){
 7415: 		    if(itimes==1){
 7416: 		      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 7417: 		      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 7418: 		    }else{
 7419: 		      printf(" 0.");
 7420: 		      fprintf(ficparo," 0.");
 7421: 		    }
 7422: 		  }else{
 7423: 		    if(itimes==1){
 7424: 		      printf(" Var(%s%1d%1d)",ca,i,j);
 7425: 		      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
 7426: 		    }else{
 7427: 		      printf(" 0.");
 7428: 		      fprintf(ficparo," 0.");
 7429: 		    }
 7430: 		  }
 7431: 		}
 7432: 	      } /* end lk */
 7433: 	    } /* end lj */
 7434: 	  } /* end li */
 7435: 	  printf("\n");
 7436: 	  fprintf(ficparo,"\n");
 7437: 	  numlinepar++;
 7438: 	} /* end k*/
 7439:       } /*end j */
 7440:     } /* end i */
 7441:   } /* end itimes */
 7442: 
 7443: } /* end of prwizard */
 7444: /******************* Gompertz Likelihood ******************************/
 7445: double gompertz(double x[])
 7446: { 
 7447:   double A,B,L=0.0,sump=0.,num=0.;
 7448:   int i,n=0; /* n is the size of the sample */
 7449: 
 7450:   for (i=1;i<=imx ; i++) {
 7451:     sump=sump+weight[i];
 7452:     /*    sump=sump+1;*/
 7453:     num=num+1;
 7454:   }
 7455:  
 7456:  
 7457:   /* for (i=0; i<=imx; i++) 
 7458:      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]);*/
 7459: 
 7460:   for (i=1;i<=imx ; i++)
 7461:     {
 7462:       if (cens[i] == 1 && wav[i]>1)
 7463: 	A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
 7464:       
 7465:       if (cens[i] == 0 && wav[i]>1)
 7466: 	A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
 7467: 	     +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
 7468:       
 7469:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 7470:       if (wav[i] > 1 ) { /* ??? */
 7471: 	L=L+A*weight[i];
 7472: 	/* 	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]);*/
 7473:       }
 7474:     }
 7475: 
 7476:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 7477:  
 7478:   return -2*L*num/sump;
 7479: }
 7480: 
 7481: #ifdef GSL
 7482: /******************* Gompertz_f Likelihood ******************************/
 7483: double gompertz_f(const gsl_vector *v, void *params)
 7484: { 
 7485:   double A,B,LL=0.0,sump=0.,num=0.;
 7486:   double *x= (double *) v->data;
 7487:   int i,n=0; /* n is the size of the sample */
 7488: 
 7489:   for (i=0;i<=imx-1 ; i++) {
 7490:     sump=sump+weight[i];
 7491:     /*    sump=sump+1;*/
 7492:     num=num+1;
 7493:   }
 7494:  
 7495:  
 7496:   /* for (i=0; i<=imx; i++) 
 7497:      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]);*/
 7498:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
 7499:   for (i=1;i<=imx ; i++)
 7500:     {
 7501:       if (cens[i] == 1 && wav[i]>1)
 7502: 	A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
 7503:       
 7504:       if (cens[i] == 0 && wav[i]>1)
 7505: 	A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
 7506: 	     +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
 7507:       
 7508:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 7509:       if (wav[i] > 1 ) { /* ??? */
 7510: 	LL=LL+A*weight[i];
 7511: 	/* 	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]);*/
 7512:       }
 7513:     }
 7514: 
 7515:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 7516:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
 7517:  
 7518:   return -2*LL*num/sump;
 7519: }
 7520: #endif
 7521: 
 7522: /******************* Printing html file ***********/
 7523: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
 7524: 		  int lastpass, int stepm, int weightopt, char model[],\
 7525: 		  int imx,  double p[],double **matcov,double agemortsup){
 7526:   int i,k;
 7527: 
 7528:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
 7529:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
 7530:   for (i=1;i<=2;i++) 
 7531:     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]));
 7532:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
 7533:   fprintf(fichtm,"</ul>");
 7534: 
 7535: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
 7536: 
 7537:  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>");
 7538: 
 7539:  for (k=agegomp;k<(agemortsup-2);k++) 
 7540:    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]);
 7541: 
 7542:  
 7543:   fflush(fichtm);
 7544: }
 7545: 
 7546: /******************* Gnuplot file **************/
 7547: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 7548: 
 7549:   char dirfileres[132],optfileres[132];
 7550: 
 7551:   int ng;
 7552: 
 7553: 
 7554:   /*#ifdef windows */
 7555:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 7556:     /*#endif */
 7557: 
 7558: 
 7559:   strcpy(dirfileres,optionfilefiname);
 7560:   strcpy(optfileres,"vpl");
 7561:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
 7562:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
 7563:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
 7564:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
 7565:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
 7566: 
 7567: } 
 7568: 
 7569: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
 7570: {
 7571: 
 7572:   /*-------- data file ----------*/
 7573:   FILE *fic;
 7574:   char dummy[]="                         ";
 7575:   int i=0, j=0, n=0, iv=0;
 7576:   int lstra;
 7577:   int linei, month, year,iout;
 7578:   char line[MAXLINE], linetmp[MAXLINE];
 7579:   char stra[MAXLINE], strb[MAXLINE];
 7580:   char *stratrunc;
 7581: 
 7582: 
 7583: 
 7584:   if((fic=fopen(datafile,"r"))==NULL)    {
 7585:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
 7586:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
 7587:   }
 7588: 
 7589:   i=1;
 7590:   linei=0;
 7591:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
 7592:     linei=linei+1;
 7593:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
 7594:       if(line[j] == '\t')
 7595: 	line[j] = ' ';
 7596:     }
 7597:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
 7598:       ;
 7599:     };
 7600:     line[j+1]=0;  /* Trims blanks at end of line */
 7601:     if(line[0]=='#'){
 7602:       fprintf(ficlog,"Comment line\n%s\n",line);
 7603:       printf("Comment line\n%s\n",line);
 7604:       continue;
 7605:     }
 7606:     trimbb(linetmp,line); /* Trims multiple blanks in line */
 7607:     strcpy(line, linetmp);
 7608:     
 7609:     /* Loops on waves */
 7610:     for (j=maxwav;j>=1;j--){
 7611:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
 7612: 				cutv(stra, strb, line, ' '); 
 7613: 				if(strb[0]=='.') { /* Missing value */
 7614: 					lval=-1;
 7615: 					cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
 7616: 					cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
 7617: 					if(isalpha(strb[1])) { /* .m or .d Really Missing value */
 7618: 						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);
 7619: 						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);
 7620: 						return 1;
 7621: 					}
 7622: 				}else{
 7623: 					errno=0;
 7624: 					/* what_kind_of_number(strb); */
 7625: 					dval=strtod(strb,&endptr); 
 7626: 					/* if( strb[0]=='\0' || (*endptr != '\0')){ */
 7627: 					/* if(strb != endptr && *endptr == '\0') */
 7628: 					/*    dval=dlval; */
 7629: 					/* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
 7630: 					if( strb[0]=='\0' || (*endptr != '\0')){
 7631: 						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);
 7632: 						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);
 7633: 						return 1;
 7634: 					}
 7635: 					cotqvar[j][iv][i]=dval; 
 7636: 					cotvar[j][ntv+iv][i]=dval; 
 7637: 				}
 7638: 				strcpy(line,stra);
 7639:       }/* end loop ntqv */
 7640:       
 7641:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
 7642: 				cutv(stra, strb, line, ' '); 
 7643: 				if(strb[0]=='.') { /* Missing value */
 7644: 					lval=-1;
 7645: 				}else{
 7646: 					errno=0;
 7647: 					lval=strtol(strb,&endptr,10); 
 7648: 					/*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
 7649: 					if( strb[0]=='\0' || (*endptr != '\0')){
 7650: 						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);
 7651: 						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);
 7652: 						return 1;
 7653: 					}
 7654: 				}
 7655: 				if(lval <-1 || lval >1){
 7656: 					printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 7657:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 7658:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 7659:  For example, for multinomial values like 1, 2 and 3,\n									\
 7660:  build V1=0 V2=0 for the reference value (1),\n													\
 7661:         V1=1 V2=0 for (2) \n																						\
 7662:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 7663:  output of IMaCh is often meaningless.\n																\
 7664:  Exiting.\n",lval,linei, i,line,j);
 7665: 					fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 7666:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 7667:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 7668:  For example, for multinomial values like 1, 2 and 3,\n									\
 7669:  build V1=0 V2=0 for the reference value (1),\n													\
 7670:         V1=1 V2=0 for (2) \n																						\
 7671:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 7672:  output of IMaCh is often meaningless.\n																\
 7673:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
 7674: 					return 1;
 7675: 				}
 7676: 				cotvar[j][iv][i]=(double)(lval);
 7677: 				strcpy(line,stra);
 7678:       }/* end loop ntv */
 7679:       
 7680:       /* Statuses  at wave */
 7681:       cutv(stra, strb, line, ' '); 
 7682:       if(strb[0]=='.') { /* Missing value */
 7683: 				lval=-1;
 7684:       }else{
 7685: 				errno=0;
 7686: 				lval=strtol(strb,&endptr,10); 
 7687: 				/*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
 7688: 				if( strb[0]=='\0' || (*endptr != '\0')){
 7689: 					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);
 7690: 					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);
 7691: 					return 1;
 7692: 				}
 7693:       }
 7694:       
 7695:       s[j][i]=lval;
 7696:       
 7697:       /* Date of Interview */
 7698:       strcpy(line,stra);
 7699:       cutv(stra, strb,line,' ');
 7700:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 7701:       }
 7702:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 7703: 	month=99;
 7704: 	year=9999;
 7705:       }else{
 7706: 	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);
 7707: 	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);
 7708: 	return 1;
 7709:       }
 7710:       anint[j][i]= (double) year; 
 7711:       mint[j][i]= (double)month; 
 7712:       strcpy(line,stra);
 7713:     } /* End loop on waves */
 7714:     
 7715:     /* Date of death */
 7716:     cutv(stra, strb,line,' '); 
 7717:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 7718:     }
 7719:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 7720:       month=99;
 7721:       year=9999;
 7722:     }else{
 7723:       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);
 7724:       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);
 7725:       return 1;
 7726:     }
 7727:     andc[i]=(double) year; 
 7728:     moisdc[i]=(double) month; 
 7729:     strcpy(line,stra);
 7730:     
 7731:     /* Date of birth */
 7732:     cutv(stra, strb,line,' '); 
 7733:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 7734:     }
 7735:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
 7736:       month=99;
 7737:       year=9999;
 7738:     }else{
 7739:       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);
 7740:       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);
 7741:       return 1;
 7742:     }
 7743:     if (year==9999) {
 7744:       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);
 7745:       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);
 7746:       return 1;
 7747:       
 7748:     }
 7749:     annais[i]=(double)(year);
 7750:     moisnais[i]=(double)(month); 
 7751:     strcpy(line,stra);
 7752:     
 7753:     /* Sample weight */
 7754:     cutv(stra, strb,line,' '); 
 7755:     errno=0;
 7756:     dval=strtod(strb,&endptr); 
 7757:     if( strb[0]=='\0' || (*endptr != '\0')){
 7758:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
 7759:       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);
 7760:       fflush(ficlog);
 7761:       return 1;
 7762:     }
 7763:     weight[i]=dval; 
 7764:     strcpy(line,stra);
 7765:     
 7766:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
 7767:       cutv(stra, strb, line, ' '); 
 7768:       if(strb[0]=='.') { /* Missing value */
 7769: 	lval=-1;
 7770:       }else{
 7771: 	errno=0;
 7772: 	/* what_kind_of_number(strb); */
 7773: 	dval=strtod(strb,&endptr);
 7774: 	/* if(strb != endptr && *endptr == '\0') */
 7775: 	/*   dval=dlval; */
 7776: 	/* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
 7777: 	if( strb[0]=='\0' || (*endptr != '\0')){
 7778: 	  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);
 7779: 	  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);
 7780: 	  return 1;
 7781: 	}
 7782: 	coqvar[iv][i]=dval; 
 7783: 	covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
 7784:       }
 7785:       strcpy(line,stra);
 7786:     }/* end loop nqv */
 7787:     
 7788:     /* Covariate values */
 7789:     for (j=ncovcol;j>=1;j--){
 7790:       cutv(stra, strb,line,' '); 
 7791:       if(strb[0]=='.') { /* Missing covariate value */
 7792: 	lval=-1;
 7793:       }else{
 7794: 	errno=0;
 7795: 	lval=strtol(strb,&endptr,10); 
 7796: 	if( strb[0]=='\0' || (*endptr != '\0')){
 7797: 	  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);
 7798: 	  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);
 7799: 	  return 1;
 7800: 	}
 7801:       }
 7802:       if(lval <-1 || lval >1){
 7803: 	printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 7804:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 7805:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 7806:  For example, for multinomial values like 1, 2 and 3,\n			\
 7807:  build V1=0 V2=0 for the reference value (1),\n				\
 7808:         V1=1 V2=0 for (2) \n						\
 7809:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 7810:  output of IMaCh is often meaningless.\n				\
 7811:  Exiting.\n",lval,linei, i,line,j);
 7812: 	fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 7813:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 7814:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 7815:  For example, for multinomial values like 1, 2 and 3,\n			\
 7816:  build V1=0 V2=0 for the reference value (1),\n				\
 7817:         V1=1 V2=0 for (2) \n						\
 7818:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 7819:  output of IMaCh is often meaningless.\n				\
 7820:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
 7821: 	return 1;
 7822:       }
 7823:       covar[j][i]=(double)(lval);
 7824:       strcpy(line,stra);
 7825:     }  
 7826:     lstra=strlen(stra);
 7827:     
 7828:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
 7829:       stratrunc = &(stra[lstra-9]);
 7830:       num[i]=atol(stratrunc);
 7831:     }
 7832:     else
 7833:       num[i]=atol(stra);
 7834:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
 7835:       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;}*/
 7836:     
 7837:     i=i+1;
 7838:   } /* End loop reading  data */
 7839:   
 7840:   *imax=i-1; /* Number of individuals */
 7841:   fclose(fic);
 7842:   
 7843:   return (0);
 7844:   /* endread: */
 7845:   printf("Exiting readdata: ");
 7846:   fclose(fic);
 7847:   return (1);
 7848: }
 7849: 
 7850: void removespace(char **stri){/*, char stro[]) {*/
 7851:   char *p1 = *stri, *p2 = *stri;
 7852:   do
 7853:     while (*p2 == ' ')
 7854:       p2++;
 7855:   while (*p1++ == *p2++);
 7856:   *stri=p1; 
 7857: }
 7858: 
 7859: int decoderesult ( char resultline[])
 7860: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
 7861: {
 7862:   int j=0, k=0;
 7863:   char resultsav[MAXLINE];
 7864:   char stra[80], strb[80], strc[80], strd[80],stre[80];
 7865: 
 7866:   removespace(&resultline);
 7867:   printf("decoderesult:%s\n",resultline);
 7868: 
 7869:   if (strstr(resultline,"v") !=0){
 7870:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
 7871:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
 7872:     return 1;
 7873:   }
 7874:   trimbb(resultsav, resultline);
 7875:   if (strlen(resultsav) >1){
 7876:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
 7877:   }
 7878: 
 7879:   for(k=1; k<=j;k++){ /* Loop on total covariates of the model */
 7880:     cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' 
 7881: 				     resultsav= V4=1 V5=25.1 V3=0 strb=V3=0 stra= V4=1 V5=25.1 */
 7882:     cutl(strc,strd,strb,'=');  /* strb:V4=1 strc=1 strd=V4 */
 7883:     Tvalsel[k]=atof(strc); /* 1 */
 7884: 
 7885:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
 7886:     Tvarsel[k]=atoi(strc);
 7887:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
 7888:     /* cptcovsel++;     */
 7889:     if (nbocc(stra,'=') >0)
 7890:       strcpy(resultsav,stra); /* and analyzes it */
 7891:   }
 7892:   return (0);
 7893: }
 7894: int selected( int kvar){ /* Selected combination of covariates */
 7895:   if(Tvarsel[kvar])
 7896:     return (0);
 7897:   else
 7898:     return(1);
 7899: }
 7900: int decodemodel( char model[], int lastobs)
 7901:  /**< This routine decodes the model and returns:
 7902: 	* Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
 7903: 	* - nagesqr = 1 if age*age in the model, otherwise 0.
 7904: 	* - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
 7905: 	* - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
 7906: 	* - cptcovage number of covariates with age*products =2
 7907: 	* - cptcovs number of simple covariates
 7908: 	* - 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
 7909: 	*     which is a new column after the 9 (ncovcol) variables. 
 7910: 	* - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
 7911: 	* - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
 7912: 	*    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
 7913: 	* - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
 7914: 	*/
 7915: {
 7916:   int i, j, k, ks;
 7917:   int  j1, k1, k2, k3, k4;
 7918:   char modelsav[80];
 7919:   char stra[80], strb[80], strc[80], strd[80],stre[80];
 7920:   char *strpt;
 7921: 
 7922:   /*removespace(model);*/
 7923:   if (strlen(model) >1){ /* If there is at least 1 covariate */
 7924:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
 7925:     if (strstr(model,"AGE") !=0){
 7926:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
 7927:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
 7928:       return 1;
 7929:     }
 7930:     if (strstr(model,"v") !=0){
 7931:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
 7932:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
 7933:       return 1;
 7934:     }
 7935:     strcpy(modelsav,model); 
 7936:     if ((strpt=strstr(model,"age*age")) !=0){
 7937:       printf(" strpt=%s, model=%s\n",strpt, model);
 7938:       if(strpt != model){
 7939: 				printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
 7940:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
 7941:  corresponding column of parameters.\n",model);
 7942: 				fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
 7943:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
 7944:  corresponding column of parameters.\n",model); fflush(ficlog);
 7945: 				return 1;
 7946:       }
 7947:       nagesqr=1;
 7948:       if (strstr(model,"+age*age") !=0)
 7949: 				substrchaine(modelsav, model, "+age*age");
 7950:       else if (strstr(model,"age*age+") !=0)
 7951: 				substrchaine(modelsav, model, "age*age+");
 7952:       else 
 7953: 				substrchaine(modelsav, model, "age*age");
 7954:     }else
 7955:       nagesqr=0;
 7956:     if (strlen(modelsav) >1){
 7957:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
 7958:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
 7959:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
 7960:       cptcovt= j+1; /* Number of total covariates in the model, not including
 7961: 		     * cst, age and age*age 
 7962: 		     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
 7963:       /* including age products which are counted in cptcovage.
 7964:        * but the covariates which are products must be treated 
 7965:        * separately: ncovn=4- 2=2 (V1+V3). */
 7966:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
 7967:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
 7968:       
 7969:       
 7970:       /*   Design
 7971:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
 7972:        *  <          ncovcol=8                >
 7973:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
 7974:        *   k=  1    2      3       4     5       6      7        8
 7975:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
 7976:        *  covar[k,i], value of kth covariate if not including age for individual i:
 7977:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
 7978:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
 7979:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
 7980:        *  Tage[++cptcovage]=k
 7981:        *       if products, new covar are created after ncovcol with k1
 7982:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
 7983:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
 7984:        *  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
 7985:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
 7986:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
 7987:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
 7988:        *  <          ncovcol=8                >
 7989:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
 7990:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
 7991:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
 7992:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 7993:        * p Tprod[1]@2={                         6, 5}
 7994:        *p Tvard[1][1]@4= {7, 8, 5, 6}
 7995:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
 7996:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 7997:        *How to reorganize?
 7998:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
 7999:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 8000:        *       {2,   1,     4,      8,    5,      6,     3,       7}
 8001:        * Struct []
 8002:        */
 8003:       
 8004:       /* This loop fills the array Tvar from the string 'model'.*/
 8005:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
 8006:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
 8007:       /* 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
 8008:       /* 	k=3 V4 Tvar[k=3]= 4 (from V4) */
 8009:       /* 	k=2 V1 Tvar[k=2]= 1 (from V1) */
 8010:       /* 	k=1 Tvar[1]=2 (from V2) */
 8011:       /* 	k=5 Tvar[5] */
 8012:       /* for (k=1; k<=cptcovn;k++) { */
 8013:       /* 	cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
 8014:       /* 	} */
 8015:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
 8016:       /*
 8017:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
 8018:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
 8019:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
 8020:       }
 8021:       cptcovage=0;
 8022:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
 8023: 				cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
 8024: 					 modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
 8025: 				if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
 8026: 				/*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
 8027: 				/*scanf("%d",i);*/
 8028: 				if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
 8029: 					cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
 8030: 					if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
 8031: 						/* covar is not filled and then is empty */
 8032: 						cptcovprod--;
 8033: 						cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
 8034: 						Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
 8035: 						Typevar[k]=1;  /* 1 for age product */
 8036: 						cptcovage++; /* Sums the number of covariates which include age as a product */
 8037: 						Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
 8038: 						/*printf("stre=%s ", stre);*/
 8039: 					} else if (strcmp(strd,"age")==0) { /* or age*Vn */
 8040: 						cptcovprod--;
 8041: 						cutl(stre,strb,strc,'V');
 8042: 						Tvar[k]=atoi(stre);
 8043: 						Typevar[k]=1;  /* 1 for age product */
 8044: 						cptcovage++;
 8045: 						Tage[cptcovage]=k;
 8046: 					} else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
 8047: 						/* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
 8048: 						cptcovn++;
 8049: 						cptcovprodnoage++;k1++;
 8050: 						cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
 8051: 						Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
 8052: 																								because this model-covariate is a construction we invent a new column
 8053: 																								which is after existing variables ncovcol+nqv+ntv+nqtv + k1
 8054: 																								If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
 8055: 																								Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
 8056: 						Typevar[k]=2;  /* 2 for double fixed dummy covariates */
 8057: 						cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
 8058: 						Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
 8059: 						Tposprod[k]=k1; /* Tpsprod[3]=1, Tposprod[2]=5 */
 8060: 						Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
 8061: 						Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
 8062: 						k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
 8063: 						/* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
 8064: 						/* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
 8065:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
 8066: 						/*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
 8067: 						for (i=1; i<=lastobs;i++){
 8068: 							/* Computes the new covariate which is a product of
 8069: 								 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
 8070: 							covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
 8071: 						}
 8072: 					} /* End age is not in the model */
 8073: 				} /* End if model includes a product */
 8074: 				else { /* no more sum */
 8075: 					/*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
 8076: 					/*  scanf("%d",i);*/
 8077: 					cutl(strd,strc,strb,'V');
 8078: 					ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
 8079: 					cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
 8080: 					Tvar[k]=atoi(strd);
 8081: 					Typevar[k]=0;  /* 0 for simple covariates */
 8082: 				}
 8083: 				strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
 8084: 				/*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
 8085: 				  scanf("%d",i);*/
 8086:       } /* end of loop + on total covariates */
 8087:     } /* end if strlen(modelsave == 0) age*age might exist */
 8088:   } /* end if strlen(model == 0) */
 8089:   
 8090:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
 8091:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
 8092:   
 8093:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
 8094:      printf("cptcovprod=%d ", cptcovprod);
 8095:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
 8096:      scanf("%d ",i);*/
 8097: 
 8098: 
 8099: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
 8100:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
 8101: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
 8102:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
 8103:    k =           1    2   3     4       5       6      7      8        9
 8104:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
 8105:    Typevar[k]=   0    0   0     2       1       0      2      1        1
 8106:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
 8107:    Dummy[k]      1    0   0     0       3       1      1      2        3
 8108: 	  Tmodelind[combination of covar]=k;
 8109: */  
 8110: /* Dispatching between quantitative and time varying covariates */
 8111:   /* If Tvar[k] >ncovcol it is a product */
 8112:   /* Tvar[k] is the value n of Vn with n varying for 1 to nvcol, or p  Vp=Vn*Vm for product */
 8113: 	/* Computing effective variables, ie used by the model, that is from the cptcovt variables */
 8114:   printf("Model=%s\n\
 8115: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
 8116: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
 8117: 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);
 8118:   fprintf(ficlog,"Model=%s\n\
 8119: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
 8120: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
 8121: 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);
 8122: 
 8123:   for(k=1, ncovf=0, ncovv=0, ncova=0, ncoveff=0, nqfveff=0, ntveff=0, nqtveff=0;k<=cptcovt; k++){ /* or cptocvt */
 8124:     if (Tvar[k] <=ncovcol && (Typevar[k]==0 || Typevar[k]==2)){ /* Simple or product fixed dummy (<=ncovcol) covariates */
 8125:       Fixed[k]= 0;
 8126:       Dummy[k]= 0;
 8127:       ncoveff++;
 8128:       ncovf++;
 8129: 			modell[k].maintype= FTYPE;
 8130: 			TvarF[ncovf]=Tvar[k];
 8131: 			TvarFind[ncovf]=k;
 8132:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 8133:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 8134:     }else if( Tvar[k] <=ncovcol+nqv && Typevar[k]==0){ /* Remind that product Vn*Vm are added in k*/ /* Only simple fixed quantitative variable */
 8135:       Fixed[k]= 0;
 8136:       Dummy[k]= 1;
 8137:       nqfveff++;
 8138: 			modell[k].maintype= FTYPE;
 8139: 			modell[k].subtype= FQ;
 8140:       ncovf++;
 8141: 			TvarF[ncovf]=Tvar[k];
 8142: 			TvarFind[ncovf]=k;
 8143:       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 */
 8144:       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 */
 8145:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){
 8146:       Fixed[k]= 1;
 8147:       Dummy[k]= 0;
 8148:       ntveff++; /* Only simple time varying dummy variable */
 8149: 			modell[k].maintype= VTYPE;
 8150: 			modell[k].subtype= VD;
 8151: 			ncovv++; /* Only simple time varying variables */
 8152: 			TvarV[ncovv]=Tvar[k];
 8153: 			TvarVind[ncovv]=k;
 8154:       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 */
 8155:       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 */
 8156:       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);
 8157:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
 8158:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
 8159: 			Fixed[k]= 1;
 8160: 			Dummy[k]= 1;
 8161: 			nqtveff++;
 8162: 			modell[k].maintype= VTYPE;
 8163: 			modell[k].subtype= VQ;
 8164: 			ncovv++; /* Only simple time varying variables */
 8165: 			TvarV[ncovv]=Tvar[k];
 8166: 			TvarVind[ncovv]=k;
 8167:       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 */
 8168:       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 */
 8169: 			TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
 8170: 			/* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
 8171: 			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);
 8172:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
 8173:     }else if (Typevar[k] == 1) {  /* product with age */
 8174: 			ncova++;
 8175: 			TvarA[ncova]=Tvar[k];
 8176: 			TvarAind[ncova]=k;
 8177:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
 8178: 				Fixed[k]= 2;
 8179: 				Dummy[k]= 2;
 8180: 				modell[k].maintype= ATYPE;
 8181: 				modell[k].subtype= APFD;
 8182: 				/* ncoveff++; */
 8183:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
 8184: 				Fixed[k]= 2;
 8185: 				Dummy[k]= 3;
 8186: 				modell[k].maintype= ATYPE;
 8187: 				modell[k].subtype= APFQ;		/*	Product age * fixed quantitative */
 8188: 				/* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
 8189:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
 8190: 				Fixed[k]= 3;
 8191: 				Dummy[k]= 2;
 8192: 				modell[k].maintype= ATYPE;
 8193: 				modell[k].subtype= APVD;		/*	Product age * varying dummy */
 8194: 				/* ntveff++; /\* Only simple time varying dummy variable *\/ */
 8195:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
 8196: 				Fixed[k]= 3;
 8197: 				Dummy[k]= 3;
 8198: 				modell[k].maintype= ATYPE;
 8199: 				modell[k].subtype= APVQ;		/*	Product age * varying quantitative */
 8200: 				/* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
 8201:       }
 8202:     }else if (Typevar[k] == 2) {  /* product without age */
 8203:       k1=Tposprod[k];
 8204:       if(Tvard[k1][1] <=ncovcol){
 8205: 				if(Tvard[k1][2] <=ncovcol){
 8206: 					Fixed[k]= 1;
 8207: 					Dummy[k]= 0;
 8208: 					modell[k].maintype= FTYPE;
 8209: 					modell[k].subtype= FPDD;		/*	Product fixed dummy * fixed dummy */
 8210: 					ncovf++; /* Fixed variables without age */
 8211: 					TvarF[ncovf]=Tvar[k];
 8212: 					TvarFind[ncovf]=k;
 8213: 				}else if(Tvard[k1][2] <=ncovcol+nqv){
 8214: 					Fixed[k]= 0;  /* or 2 ?*/
 8215: 					Dummy[k]= 1;
 8216: 					modell[k].maintype= FTYPE;
 8217: 					modell[k].subtype= FPDQ;		/*	Product fixed dummy * fixed quantitative */
 8218: 					ncovf++; /* Varying variables without age */
 8219: 					TvarF[ncovf]=Tvar[k];
 8220: 					TvarFind[ncovf]=k;
 8221: 				}else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
 8222: 					Fixed[k]= 1;
 8223: 					Dummy[k]= 0;
 8224: 					modell[k].maintype= VTYPE;
 8225: 					modell[k].subtype= VPDD;		/*	Product fixed dummy * varying dummy */
 8226: 					ncovv++; /* Varying variables without age */
 8227: 					TvarV[ncovv]=Tvar[k];
 8228: 					TvarVind[ncovv]=k;
 8229: 				}else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
 8230: 					Fixed[k]= 1;
 8231: 					Dummy[k]= 1;
 8232: 					modell[k].maintype= VTYPE;
 8233: 					modell[k].subtype= VPDQ;		/*	Product fixed dummy * varying quantitative */
 8234: 					ncovv++; /* Varying variables without age */
 8235: 					TvarV[ncovv]=Tvar[k];
 8236: 					TvarVind[ncovv]=k;
 8237: 				} 
 8238:       }else if(Tvard[k1][1] <=ncovcol+nqv){
 8239: 				if(Tvard[k1][2] <=ncovcol){
 8240: 					Fixed[k]= 0;  /* or 2 ?*/
 8241: 					Dummy[k]= 1;
 8242: 					modell[k].maintype= FTYPE;
 8243: 					modell[k].subtype= FPDQ;		/*	Product fixed quantitative * fixed dummy */
 8244: 					ncovf++; /* Fixed variables without age */
 8245: 					TvarF[ncovf]=Tvar[k];
 8246: 					TvarFind[ncovf]=k;
 8247: 				}else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
 8248: 					Fixed[k]= 1;
 8249: 					Dummy[k]= 1;
 8250: 					modell[k].maintype= VTYPE;
 8251: 					modell[k].subtype= VPDQ;		/*	Product fixed quantitative * varying dummy */
 8252: 					ncovv++; /* Varying variables without age */
 8253: 					TvarV[ncovv]=Tvar[k];
 8254: 					TvarVind[ncovv]=k;
 8255: 				}else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
 8256: 					Fixed[k]= 1;
 8257: 					Dummy[k]= 1;
 8258: 					modell[k].maintype= VTYPE;
 8259: 					modell[k].subtype= VPQQ;		/*	Product fixed quantitative * varying quantitative */
 8260: 					ncovv++; /* Varying variables without age */
 8261: 					TvarV[ncovv]=Tvar[k];
 8262: 					TvarVind[ncovv]=k;
 8263: 					ncovv++; /* Varying variables without age */
 8264: 					TvarV[ncovv]=Tvar[k];
 8265: 					TvarVind[ncovv]=k;
 8266: 				} 
 8267:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
 8268: 				if(Tvard[k1][2] <=ncovcol){
 8269: 					Fixed[k]= 1;
 8270: 					Dummy[k]= 1;
 8271: 					modell[k].maintype= VTYPE;
 8272: 					modell[k].subtype= VPDD;		/*	Product time varying dummy * fixed dummy */
 8273: 					ncovv++; /* Varying variables without age */
 8274: 					TvarV[ncovv]=Tvar[k];
 8275: 					TvarVind[ncovv]=k;
 8276: 				}else if(Tvard[k1][2] <=ncovcol+nqv){
 8277: 					Fixed[k]= 1;
 8278: 					Dummy[k]= 1;
 8279: 					modell[k].maintype= VTYPE;
 8280: 					modell[k].subtype= VPDQ;		/*	Product time varying dummy * fixed quantitative */
 8281: 					ncovv++; /* Varying variables without age */
 8282: 					TvarV[ncovv]=Tvar[k];
 8283: 					TvarVind[ncovv]=k;
 8284: 				}else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
 8285: 					Fixed[k]= 1;
 8286: 					Dummy[k]= 0;
 8287: 					modell[k].maintype= VTYPE;
 8288: 					modell[k].subtype= VPDD;		/*	Product time varying dummy * time varying dummy */
 8289: 					ncovv++; /* Varying variables without age */
 8290: 					TvarV[ncovv]=Tvar[k];
 8291: 					TvarVind[ncovv]=k;
 8292: 				}else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
 8293: 					Fixed[k]= 1;
 8294: 					Dummy[k]= 1;
 8295: 					modell[k].maintype= VTYPE;
 8296: 					modell[k].subtype= VPDQ;		/*	Product time varying dummy * time varying quantitative */
 8297: 					ncovv++; /* Varying variables without age */
 8298: 					TvarV[ncovv]=Tvar[k];
 8299: 					TvarVind[ncovv]=k;
 8300: 				} 
 8301:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
 8302: 				if(Tvard[k1][2] <=ncovcol){
 8303: 					Fixed[k]= 1;
 8304: 					Dummy[k]= 1;
 8305: 					modell[k].maintype= VTYPE;
 8306: 					modell[k].subtype= VPDQ;		/*	Product time varying quantitative * fixed dummy */
 8307: 					ncovv++; /* Varying variables without age */
 8308: 					TvarV[ncovv]=Tvar[k];
 8309: 					TvarVind[ncovv]=k;
 8310: 				}else if(Tvard[k1][2] <=ncovcol+nqv){
 8311: 					Fixed[k]= 1;
 8312: 					Dummy[k]= 1;
 8313: 					modell[k].maintype= VTYPE;
 8314: 					modell[k].subtype= VPQQ;		/*	Product time varying quantitative * fixed quantitative */
 8315: 					ncovv++; /* Varying variables without age */
 8316: 					TvarV[ncovv]=Tvar[k];
 8317: 					TvarVind[ncovv]=k;
 8318: 				}else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
 8319: 					Fixed[k]= 1;
 8320: 					Dummy[k]= 1;
 8321: 					modell[k].maintype= VTYPE;
 8322: 					modell[k].subtype= VPDQ;		/*	Product time varying quantitative * time varying dummy */
 8323: 					ncovv++; /* Varying variables without age */
 8324: 					TvarV[ncovv]=Tvar[k];
 8325: 					TvarVind[ncovv]=k;
 8326: 				}else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
 8327: 					Fixed[k]= 1;
 8328: 					Dummy[k]= 1;
 8329: 					modell[k].maintype= VTYPE;
 8330: 					modell[k].subtype= VPQQ;		/*	Product time varying quantitative * time varying quantitative */
 8331: 					ncovv++; /* Varying variables without age */
 8332: 					TvarV[ncovv]=Tvar[k];
 8333: 					TvarVind[ncovv]=k;
 8334: 				} 
 8335:       }else{
 8336: 				printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
 8337: 				fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
 8338:       } /* end k1 */
 8339:     }else{
 8340:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
 8341:       fprintf(ficlog,"Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
 8342:     }
 8343:     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]);
 8344:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
 8345:     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]);
 8346:   }
 8347:   /* Searching for doublons in the model */
 8348:   for(k1=1; k1<= cptcovt;k1++){
 8349:     for(k2=1; k2 <k1;k2++){
 8350:       if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){
 8351: 				if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
 8352: 					if(Tvar[k1]==Tvar[k2]){
 8353: 						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]]);
 8354: 						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);
 8355: 						return(1);
 8356: 					}
 8357: 				}else if (Typevar[k1] ==2){
 8358: 					k3=Tposprod[k1];
 8359: 					k4=Tposprod[k2];
 8360: 					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])) ){
 8361: 						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]]);
 8362: 						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);
 8363: 						return(1);
 8364: 					}
 8365: 				}
 8366:       }
 8367:     }
 8368:   }
 8369:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
 8370:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
 8371:   printf("ncovf=%d, ncovv=%d, ncova=%d\n",ncovf,ncovv,ncova);
 8372:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d\n",ncovf,ncovv,ncova);
 8373:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
 8374:   /*endread:*/
 8375:   printf("Exiting decodemodel: ");
 8376:   return (1);
 8377: }
 8378: 
 8379: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
 8380: {
 8381:   int i, m;
 8382:   int firstone=0;
 8383:   
 8384:   for (i=1; i<=imx; i++) {
 8385:     for(m=2; (m<= maxwav); m++) {
 8386:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
 8387: 	anint[m][i]=9999;
 8388: 	if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
 8389: 	  s[m][i]=-1;
 8390:       }
 8391:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
 8392: 	*nberr = *nberr + 1;
 8393: 	if(firstone == 0){
 8394: 	  firstone=1;
 8395: 	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);
 8396: 	}
 8397: 	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);
 8398: 	s[m][i]=-1;
 8399:       }
 8400:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
 8401: 	(*nberr)++;
 8402: 	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]); 
 8403: 	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]); 
 8404: 	s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
 8405:       }
 8406:     }
 8407:   }
 8408: 
 8409:   for (i=1; i<=imx; i++)  {
 8410:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
 8411:     for(m=firstpass; (m<= lastpass); m++){
 8412:       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 */
 8413: 	if (s[m][i] >= nlstate+1) {
 8414: 	  if(agedc[i]>0){
 8415: 	    if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
 8416: 	      agev[m][i]=agedc[i];
 8417: 	      /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
 8418: 	    }else {
 8419: 	      if ((int)andc[i]!=9999){
 8420: 		nbwarn++;
 8421: 		printf("Warning negative age at death: %ld line:%d\n",num[i],i);
 8422: 		fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
 8423: 		agev[m][i]=-1;
 8424: 	      }
 8425: 	    }
 8426: 	  } /* agedc > 0 */
 8427: 	} /* end if */
 8428: 	else if(s[m][i] !=9){ /* Standard case, age in fractional
 8429: 				 years but with the precision of a month */
 8430: 	  agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
 8431: 	  if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
 8432: 	    agev[m][i]=1;
 8433: 	  else if(agev[m][i] < *agemin){ 
 8434: 	    *agemin=agev[m][i];
 8435: 	    printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
 8436: 	  }
 8437: 	  else if(agev[m][i] >*agemax){
 8438: 	    *agemax=agev[m][i];
 8439: 	    /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
 8440: 	  }
 8441: 	  /*agev[m][i]=anint[m][i]-annais[i];*/
 8442: 	  /*	 agev[m][i] = age[i]+2*m;*/
 8443: 	} /* en if 9*/
 8444: 	else { /* =9 */
 8445: 	  /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
 8446: 	  agev[m][i]=1;
 8447: 	  s[m][i]=-1;
 8448: 	}
 8449:       }
 8450:       else if(s[m][i]==0) /*= 0 Unknown */
 8451: 	agev[m][i]=1;
 8452:       else{
 8453: 	printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
 8454: 	fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
 8455: 	agev[m][i]=0;
 8456:       }
 8457:     } /* End for lastpass */
 8458:   }
 8459:     
 8460:   for (i=1; i<=imx; i++)  {
 8461:     for(m=firstpass; (m<=lastpass); m++){
 8462:       if (s[m][i] > (nlstate+ndeath)) {
 8463: 	(*nberr)++;
 8464: 	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);	
 8465: 	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);	
 8466: 	return 1;
 8467:       }
 8468:     }
 8469:   }
 8470: 
 8471:   /*for (i=1; i<=imx; i++){
 8472:   for (m=firstpass; (m<lastpass); m++){
 8473:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
 8474: }
 8475: 
 8476: }*/
 8477: 
 8478: 
 8479:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
 8480:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
 8481: 
 8482:   return (0);
 8483:  /* endread:*/
 8484:     printf("Exiting calandcheckages: ");
 8485:     return (1);
 8486: }
 8487: 
 8488: #if defined(_MSC_VER)
 8489: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 8490: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 8491: //#include "stdafx.h"
 8492: //#include <stdio.h>
 8493: //#include <tchar.h>
 8494: //#include <windows.h>
 8495: //#include <iostream>
 8496: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
 8497: 
 8498: LPFN_ISWOW64PROCESS fnIsWow64Process;
 8499: 
 8500: BOOL IsWow64()
 8501: {
 8502: 	BOOL bIsWow64 = FALSE;
 8503: 
 8504: 	//typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
 8505: 	//  (HANDLE, PBOOL);
 8506: 
 8507: 	//LPFN_ISWOW64PROCESS fnIsWow64Process;
 8508: 
 8509: 	HMODULE module = GetModuleHandle(_T("kernel32"));
 8510: 	const char funcName[] = "IsWow64Process";
 8511: 	fnIsWow64Process = (LPFN_ISWOW64PROCESS)
 8512: 		GetProcAddress(module, funcName);
 8513: 
 8514: 	if (NULL != fnIsWow64Process)
 8515: 	{
 8516: 		if (!fnIsWow64Process(GetCurrentProcess(),
 8517: 			&bIsWow64))
 8518: 			//throw std::exception("Unknown error");
 8519: 			printf("Unknown error\n");
 8520: 	}
 8521: 	return bIsWow64 != FALSE;
 8522: }
 8523: #endif
 8524: 
 8525: void syscompilerinfo(int logged)
 8526:  {
 8527:    /* #include "syscompilerinfo.h"*/
 8528:    /* command line Intel compiler 32bit windows, XP compatible:*/
 8529:    /* /GS /W3 /Gy
 8530:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
 8531:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
 8532:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
 8533:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
 8534:    */ 
 8535:    /* 64 bits */
 8536:    /*
 8537:      /GS /W3 /Gy
 8538:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
 8539:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
 8540:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
 8541:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
 8542:    /* Optimization are useless and O3 is slower than O2 */
 8543:    /*
 8544:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
 8545:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
 8546:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
 8547:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
 8548:    */
 8549:    /* Link is */ /* /OUT:"visual studio
 8550:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
 8551:       /PDB:"visual studio
 8552:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
 8553:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
 8554:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
 8555:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
 8556:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
 8557:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
 8558:       uiAccess='false'"
 8559:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
 8560:       /NOLOGO /TLBID:1
 8561:    */
 8562: #if defined __INTEL_COMPILER
 8563: #if defined(__GNUC__)
 8564: 	struct utsname sysInfo;  /* For Intel on Linux and OS/X */
 8565: #endif
 8566: #elif defined(__GNUC__) 
 8567: #ifndef  __APPLE__
 8568: #include <gnu/libc-version.h>  /* Only on gnu */
 8569: #endif
 8570:    struct utsname sysInfo;
 8571:    int cross = CROSS;
 8572:    if (cross){
 8573: 	   printf("Cross-");
 8574: 	   if(logged) fprintf(ficlog, "Cross-");
 8575:    }
 8576: #endif
 8577: 
 8578: #include <stdint.h>
 8579: 
 8580:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
 8581: #if defined(__clang__)
 8582:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");	/* Clang/LLVM. ---------------------------------------------- */
 8583: #endif
 8584: #if defined(__ICC) || defined(__INTEL_COMPILER)
 8585:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
 8586: #endif
 8587: #if defined(__GNUC__) || defined(__GNUG__)
 8588:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
 8589: #endif
 8590: #if defined(__HP_cc) || defined(__HP_aCC)
 8591:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
 8592: #endif
 8593: #if defined(__IBMC__) || defined(__IBMCPP__)
 8594:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
 8595: #endif
 8596: #if defined(_MSC_VER)
 8597:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
 8598: #endif
 8599: #if defined(__PGI)
 8600:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
 8601: #endif
 8602: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
 8603:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
 8604: #endif
 8605:    printf(" for "); if (logged) fprintf(ficlog, " for ");
 8606:    
 8607: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
 8608: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
 8609:     // Windows (x64 and x86)
 8610:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
 8611: #elif __unix__ // all unices, not all compilers
 8612:     // Unix
 8613:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
 8614: #elif __linux__
 8615:     // linux
 8616:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
 8617: #elif __APPLE__
 8618:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
 8619:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
 8620: #endif
 8621: 
 8622: /*  __MINGW32__	  */
 8623: /*  __CYGWIN__	 */
 8624: /* __MINGW64__  */
 8625: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
 8626: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
 8627: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
 8628: /* _WIN64  // Defined for applications for Win64. */
 8629: /* _M_X64 // Defined for compilations that target x64 processors. */
 8630: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
 8631: 
 8632: #if UINTPTR_MAX == 0xffffffff
 8633:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
 8634: #elif UINTPTR_MAX == 0xffffffffffffffff
 8635:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
 8636: #else
 8637:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
 8638: #endif
 8639: 
 8640: #if defined(__GNUC__)
 8641: # if defined(__GNUC_PATCHLEVEL__)
 8642: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 8643:                             + __GNUC_MINOR__ * 100 \
 8644:                             + __GNUC_PATCHLEVEL__)
 8645: # else
 8646: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 8647:                             + __GNUC_MINOR__ * 100)
 8648: # endif
 8649:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
 8650:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
 8651: 
 8652:    if (uname(&sysInfo) != -1) {
 8653:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 8654: 	 if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 8655:    }
 8656:    else
 8657:       perror("uname() error");
 8658:    //#ifndef __INTEL_COMPILER 
 8659: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
 8660:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
 8661:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
 8662: #endif
 8663: #endif
 8664: 
 8665:    //   void main()
 8666:    //   {
 8667: #if defined(_MSC_VER)
 8668:    if (IsWow64()){
 8669: 	   printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 8670: 	   if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 8671:    }
 8672:    else{
 8673: 	   printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 8674: 	   if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 8675:    }
 8676:    //	   printf("\nPress Enter to continue...");
 8677:    //	   getchar();
 8678:    //   }
 8679: 
 8680: #endif
 8681:    
 8682: 
 8683: }
 8684: 
 8685: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
 8686:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 8687:   int i, j, k, i1 ;
 8688:   /* double ftolpl = 1.e-10; */
 8689:   double age, agebase, agelim;
 8690:   double tot;
 8691: 
 8692:   strcpy(filerespl,"PL_");
 8693:   strcat(filerespl,fileresu);
 8694:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
 8695:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
 8696:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
 8697:   }
 8698:   printf("\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
 8699:   fprintf(ficlog,"\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
 8700:   pstamp(ficrespl);
 8701:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
 8702:   fprintf(ficrespl,"#Age ");
 8703:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
 8704:   fprintf(ficrespl,"\n");
 8705:   
 8706:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
 8707: 
 8708:   agebase=ageminpar;
 8709:   agelim=agemaxpar;
 8710: 
 8711:   /* i1=pow(2,ncoveff); */
 8712:   i1=pow(2,cptcoveff); /* Number of dummy covariates */
 8713:   if (cptcovn < 1){i1=1;}
 8714: 
 8715:   for(k=1; k<=i1;k++){
 8716:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 8717:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
 8718:     //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 8719:     /* k=k+1; */
 8720:     /* to clean */
 8721:     //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
 8722:     fprintf(ficrespl,"#******");
 8723:     printf("#******");
 8724:     fprintf(ficlog,"#******");
 8725:     for(j=1;j<=cptcoveff ;j++) {/* all covariates */
 8726:       fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
 8727:       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8728:       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8729:     }
 8730:     fprintf(ficrespl,"******\n");
 8731:     printf("******\n");
 8732:     fprintf(ficlog,"******\n");
 8733:     if(invalidvarcomb[k]){
 8734:       printf("\nCombination (%d) ignored because no case \n",k); 
 8735:       fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
 8736:       fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
 8737: 						continue;
 8738:     }
 8739: 
 8740:     fprintf(ficrespl,"#Age ");
 8741:     for(j=1;j<=cptcoveff;j++) {
 8742:       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8743:     }
 8744:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
 8745:     fprintf(ficrespl,"Total Years_to_converge\n");
 8746:     
 8747:     for (age=agebase; age<=agelim; age++){
 8748:       /* for (age=agebase; age<=agebase; age++){ */
 8749:       prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
 8750:       fprintf(ficrespl,"%.0f ",age );
 8751:       for(j=1;j<=cptcoveff;j++)
 8752: 	fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8753:       tot=0.;
 8754:       for(i=1; i<=nlstate;i++){
 8755: 	tot +=  prlim[i][i];
 8756: 	fprintf(ficrespl," %.5f", prlim[i][i]);
 8757:       }
 8758:       fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
 8759:     } /* Age */
 8760:     /* was end of cptcod */
 8761:   } /* cptcov */
 8762:   return 0;
 8763: }
 8764: 
 8765: 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){
 8766: 	/*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
 8767: 	
 8768: 	/* Computes the back prevalence limit  for any combination	of covariate values 
 8769:    * at any age between ageminpar and agemaxpar
 8770: 	 */
 8771:   int i, j, k, i1 ;
 8772:   /* double ftolpl = 1.e-10; */
 8773:   double age, agebase, agelim;
 8774:   double tot;
 8775:   /* double ***mobaverage; */
 8776:   /* double	 **dnewm, **doldm, **dsavm;  /\* for use *\/ */
 8777: 
 8778:   strcpy(fileresplb,"PLB_");
 8779:   strcat(fileresplb,fileresu);
 8780:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
 8781:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
 8782:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
 8783:   }
 8784:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
 8785:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
 8786:   pstamp(ficresplb);
 8787:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
 8788:   fprintf(ficresplb,"#Age ");
 8789:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
 8790:   fprintf(ficresplb,"\n");
 8791:   
 8792:   
 8793:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
 8794:   
 8795:   agebase=ageminpar;
 8796:   agelim=agemaxpar;
 8797:   
 8798:   
 8799:   i1=pow(2,cptcoveff);
 8800:   if (cptcovn < 1){i1=1;}
 8801:   
 8802:   for(k=1; k<=i1;k++){ 
 8803:     //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
 8804:     fprintf(ficresplb,"#******");
 8805:     printf("#******");
 8806:     fprintf(ficlog,"#******");
 8807:     for(j=1;j<=cptcoveff ;j++) {/* all covariates */
 8808:       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8809:       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8810:       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8811:     }
 8812:     fprintf(ficresplb,"******\n");
 8813:     printf("******\n");
 8814:     fprintf(ficlog,"******\n");
 8815:     if(invalidvarcomb[k]){
 8816:       printf("\nCombination (%d) ignored because no cases \n",k); 
 8817:       fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
 8818:       fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
 8819:       continue;
 8820:     }
 8821:     
 8822:     fprintf(ficresplb,"#Age ");
 8823:     for(j=1;j<=cptcoveff;j++) {
 8824:       fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8825:     }
 8826:     for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
 8827:     fprintf(ficresplb,"Total Years_to_converge\n");
 8828:     
 8829:     
 8830:     for (age=agebase; age<=agelim; age++){
 8831:       /* for (age=agebase; age<=agebase; age++){ */
 8832:       if(mobilavproj > 0){
 8833: 	/* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
 8834: 	/* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
 8835: 	bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k);
 8836:       }else if (mobilavproj == 0){
 8837: 	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);
 8838: 	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);
 8839: 	exit(1);
 8840:       }else{
 8841: 	/* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
 8842: 	bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k);
 8843:       }
 8844:       fprintf(ficresplb,"%.0f ",age );
 8845:       for(j=1;j<=cptcoveff;j++)
 8846: 	fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8847:       tot=0.;
 8848:       for(i=1; i<=nlstate;i++){
 8849: 	tot +=  bprlim[i][i];
 8850: 	fprintf(ficresplb," %.5f", bprlim[i][i]);
 8851:       }
 8852:       fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
 8853:     } /* Age */
 8854:     /* was end of cptcod */
 8855:   } /* cptcov */
 8856:   
 8857:   /* hBijx(p, bage, fage); */
 8858:   /* fclose(ficrespijb); */
 8859:   
 8860:   return 0;
 8861: }
 8862:  
 8863: int hPijx(double *p, int bage, int fage){
 8864:     /*------------- h Pij x at various ages ------------*/
 8865: 
 8866:   int stepsize;
 8867:   int agelim;
 8868:   int hstepm;
 8869:   int nhstepm;
 8870:   int h, i, i1, j, k;
 8871: 
 8872:   double agedeb;
 8873:   double ***p3mat;
 8874: 
 8875:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
 8876:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
 8877:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
 8878:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
 8879:     }
 8880:     printf("Computing pij: result on file '%s' \n", filerespij);
 8881:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
 8882:   
 8883:     stepsize=(int) (stepm+YEARM-1)/YEARM;
 8884:     /*if (stepm<=24) stepsize=2;*/
 8885: 
 8886:     agelim=AGESUP;
 8887:     hstepm=stepsize*YEARM; /* Every year of age */
 8888:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
 8889: 		
 8890:     /* hstepm=1;   aff par mois*/
 8891:     pstamp(ficrespij);
 8892:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
 8893:     i1= pow(2,cptcoveff);
 8894: 		/* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 8895: 		/*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
 8896: 		/*  	k=k+1;  */
 8897:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 8898:       fprintf(ficrespij,"\n#****** ");
 8899:       for(j=1;j<=cptcoveff;j++) 
 8900: 	fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8901:       fprintf(ficrespij,"******\n");
 8902:       
 8903:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
 8904: 	nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 8905: 	nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 8906: 	
 8907: 	/*	  nhstepm=nhstepm*YEARM; aff par mois*/
 8908: 	
 8909: 	p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 8910: 	oldm=oldms;savm=savms;
 8911: 	hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 8912: 	fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
 8913: 	for(i=1; i<=nlstate;i++)
 8914: 	  for(j=1; j<=nlstate+ndeath;j++)
 8915: 	    fprintf(ficrespij," %1d-%1d",i,j);
 8916: 	fprintf(ficrespij,"\n");
 8917: 	for (h=0; h<=nhstepm; h++){
 8918: 	  /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
 8919: 	  fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
 8920: 	  for(i=1; i<=nlstate;i++)
 8921: 	    for(j=1; j<=nlstate+ndeath;j++)
 8922: 	      fprintf(ficrespij," %.5f", p3mat[i][j][h]);
 8923: 	  fprintf(ficrespij,"\n");
 8924: 	}
 8925: 	free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 8926: 	fprintf(ficrespij,"\n");
 8927:       }
 8928:       /*}*/
 8929:     }
 8930:     return 0;
 8931: }
 8932:  
 8933:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
 8934:     /*------------- h Bij x at various ages ------------*/
 8935: 
 8936:   int stepsize;
 8937:   /* int agelim; */
 8938: 	int ageminl;
 8939:   int hstepm;
 8940:   int nhstepm;
 8941:   int h, i, i1, j, k;
 8942: 	
 8943:   double agedeb;
 8944:   double ***p3mat;
 8945: 	
 8946:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
 8947:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
 8948:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
 8949:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
 8950:   }
 8951:   printf("Computing pij back: result on file '%s' \n", filerespijb);
 8952:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
 8953:   
 8954:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 8955:   /*if (stepm<=24) stepsize=2;*/
 8956:   
 8957:   /* agelim=AGESUP; */
 8958:   ageminl=30;
 8959:   hstepm=stepsize*YEARM; /* Every year of age */
 8960:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
 8961:   
 8962:   /* hstepm=1;   aff par mois*/
 8963:   pstamp(ficrespijb);
 8964:   fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
 8965:   i1= pow(2,cptcoveff);
 8966:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 8967:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
 8968:   /*  	k=k+1;  */
 8969:   for (k=1; k <= (int) pow(2,cptcoveff); k++){
 8970:     fprintf(ficrespijb,"\n#****** ");
 8971:     for(j=1;j<=cptcoveff;j++)
 8972:       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
 8973:     fprintf(ficrespijb,"******\n");
 8974:     if(invalidvarcomb[k]){
 8975:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
 8976:       continue;
 8977:     }
 8978:     
 8979:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
 8980:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
 8981:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
 8982:       nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
 8983:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
 8984:       
 8985:       /*	  nhstepm=nhstepm*YEARM; aff par mois*/
 8986:       
 8987:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 8988:       /* oldm=oldms;savm=savms; */
 8989:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
 8990:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
 8991:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
 8992:       fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
 8993:       for(i=1; i<=nlstate;i++)
 8994: 	for(j=1; j<=nlstate+ndeath;j++)
 8995: 	  fprintf(ficrespijb," %1d-%1d",i,j);
 8996:       fprintf(ficrespijb,"\n");
 8997:       for (h=0; h<=nhstepm; h++){
 8998: 	/*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
 8999: 	fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
 9000: 	/* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
 9001: 	for(i=1; i<=nlstate;i++)
 9002: 	  for(j=1; j<=nlstate+ndeath;j++)
 9003: 	    fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
 9004: 	fprintf(ficrespijb,"\n");
 9005:       }
 9006:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 9007:       fprintf(ficrespijb,"\n");
 9008:     }
 9009:     /*}*/
 9010:   }
 9011:   return 0;
 9012:  } /*  hBijx */
 9013: 
 9014: 
 9015: /***********************************************/
 9016: /**************** Main Program *****************/
 9017: /***********************************************/
 9018: 
 9019: int main(int argc, char *argv[])
 9020: {
 9021: #ifdef GSL
 9022:   const gsl_multimin_fminimizer_type *T;
 9023:   size_t iteri = 0, it;
 9024:   int rval = GSL_CONTINUE;
 9025:   int status = GSL_SUCCESS;
 9026:   double ssval;
 9027: #endif
 9028:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
 9029:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
 9030:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
 9031:   int jj, ll, li, lj, lk;
 9032:   int numlinepar=0; /* Current linenumber of parameter file */
 9033:   int num_filled;
 9034:   int itimes;
 9035:   int NDIM=2;
 9036:   int vpopbased=0;
 9037: 
 9038:   char ca[32], cb[32];
 9039:   /*  FILE *fichtm; *//* Html File */
 9040:   /* FILE *ficgp;*/ /*Gnuplot File */
 9041:   struct stat info;
 9042:   double agedeb=0.;
 9043: 
 9044:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
 9045:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
 9046: 
 9047:   double fret;
 9048:   double dum=0.; /* Dummy variable */
 9049:   double ***p3mat;
 9050:   /* double ***mobaverage; */
 9051: 
 9052:   char line[MAXLINE];
 9053:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
 9054: 
 9055:   char model[MAXLINE], modeltemp[MAXLINE];
 9056:   char resultline[MAXLINE];
 9057:   
 9058:   char pathr[MAXLINE], pathimach[MAXLINE]; 
 9059:   char *tok, *val; /* pathtot */
 9060:   int firstobs=1, lastobs=10;
 9061:   int c,  h , cpt, c2;
 9062:   int jl=0;
 9063:   int i1, j1, jk, stepsize=0;
 9064:   int count=0;
 9065: 
 9066:   int *tab; 
 9067:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
 9068:   int backcast=0;
 9069:   int mobilav=0,popforecast=0;
 9070:   int hstepm=0, nhstepm=0;
 9071:   int agemortsup;
 9072:   float  sumlpop=0.;
 9073:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
 9074:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
 9075: 
 9076:   double bage=0, fage=110., age, agelim=0., agebase=0.;
 9077:   double ftolpl=FTOL;
 9078:   double **prlim;
 9079:   double **bprlim;
 9080:   double ***param; /* Matrix of parameters */
 9081:   double  *p;
 9082:   double **matcov; /* Matrix of covariance */
 9083:   double **hess; /* Hessian matrix */
 9084:   double ***delti3; /* Scale */
 9085:   double *delti; /* Scale */
 9086:   double ***eij, ***vareij;
 9087:   double **varpl; /* Variances of prevalence limits by age */
 9088:   double *epj, vepp;
 9089: 
 9090:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
 9091:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
 9092: 
 9093:   double **ximort;
 9094:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
 9095:   int *dcwave;
 9096: 
 9097:   char z[1]="c";
 9098: 
 9099:   /*char  *strt;*/
 9100:   char strtend[80];
 9101: 
 9102: 
 9103: /*   setlocale (LC_ALL, ""); */
 9104: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
 9105: /*   textdomain (PACKAGE); */
 9106: /*   setlocale (LC_CTYPE, ""); */
 9107: /*   setlocale (LC_MESSAGES, ""); */
 9108: 
 9109:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
 9110:   rstart_time = time(NULL);  
 9111:   /*  (void) gettimeofday(&start_time,&tzp);*/
 9112:   start_time = *localtime(&rstart_time);
 9113:   curr_time=start_time;
 9114:   /*tml = *localtime(&start_time.tm_sec);*/
 9115:   /* strcpy(strstart,asctime(&tml)); */
 9116:   strcpy(strstart,asctime(&start_time));
 9117: 
 9118: /*  printf("Localtime (at start)=%s",strstart); */
 9119: /*  tp.tm_sec = tp.tm_sec +86400; */
 9120: /*  tm = *localtime(&start_time.tm_sec); */
 9121: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
 9122: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
 9123: /*   tmg.tm_hour=tmg.tm_hour + 1; */
 9124: /*   tp.tm_sec = mktime(&tmg); */
 9125: /*   strt=asctime(&tmg); */
 9126: /*   printf("Time(after) =%s",strstart);  */
 9127: /*  (void) time (&time_value);
 9128: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
 9129: *  tm = *localtime(&time_value);
 9130: *  strstart=asctime(&tm);
 9131: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
 9132: */
 9133: 
 9134:   nberr=0; /* Number of errors and warnings */
 9135:   nbwarn=0;
 9136: #ifdef WIN32
 9137:   _getcwd(pathcd, size);
 9138: #else
 9139:   getcwd(pathcd, size);
 9140: #endif
 9141:   syscompilerinfo(0);
 9142:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
 9143:   if(argc <=1){
 9144:     printf("\nEnter the parameter file name: ");
 9145:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
 9146:       printf("ERROR Empty parameter file name\n");
 9147:       goto end;
 9148:     }
 9149:     i=strlen(pathr);
 9150:     if(pathr[i-1]=='\n')
 9151:       pathr[i-1]='\0';
 9152:     i=strlen(pathr);
 9153:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
 9154:       pathr[i-1]='\0';
 9155:     }
 9156:     i=strlen(pathr);
 9157:     if( i==0 ){
 9158:       printf("ERROR Empty parameter file name\n");
 9159:       goto end;
 9160:     }
 9161:     for (tok = pathr; tok != NULL; ){
 9162:       printf("Pathr |%s|\n",pathr);
 9163:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
 9164:       printf("val= |%s| pathr=%s\n",val,pathr);
 9165:       strcpy (pathtot, val);
 9166:       if(pathr[0] == '\0') break; /* Dirty */
 9167:     }
 9168:   }
 9169:   else{
 9170:     strcpy(pathtot,argv[1]);
 9171:   }
 9172:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
 9173:   /*cygwin_split_path(pathtot,path,optionfile);
 9174:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
 9175:   /* cutv(path,optionfile,pathtot,'\\');*/
 9176: 
 9177:   /* Split argv[0], imach program to get pathimach */
 9178:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
 9179:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 9180:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 9181:  /*   strcpy(pathimach,argv[0]); */
 9182:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
 9183:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
 9184:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
 9185: #ifdef WIN32
 9186:   _chdir(path); /* Can be a relative path */
 9187:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
 9188: #else
 9189:   chdir(path); /* Can be a relative path */
 9190:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
 9191: #endif
 9192:   printf("Current directory %s!\n",pathcd);
 9193:   strcpy(command,"mkdir ");
 9194:   strcat(command,optionfilefiname);
 9195:   if((outcmd=system(command)) != 0){
 9196:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
 9197:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
 9198:     /* fclose(ficlog); */
 9199: /*     exit(1); */
 9200:   }
 9201: /*   if((imk=mkdir(optionfilefiname))<0){ */
 9202: /*     perror("mkdir"); */
 9203: /*   } */
 9204: 
 9205:   /*-------- arguments in the command line --------*/
 9206: 
 9207:   /* Main Log file */
 9208:   strcat(filelog, optionfilefiname);
 9209:   strcat(filelog,".log");    /* */
 9210:   if((ficlog=fopen(filelog,"w"))==NULL)    {
 9211:     printf("Problem with logfile %s\n",filelog);
 9212:     goto end;
 9213:   }
 9214:   fprintf(ficlog,"Log filename:%s\n",filelog);
 9215:   fprintf(ficlog,"Version %s %s",version,fullversion);
 9216:   fprintf(ficlog,"\nEnter the parameter file name: \n");
 9217:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
 9218:  path=%s \n\
 9219:  optionfile=%s\n\
 9220:  optionfilext=%s\n\
 9221:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
 9222: 
 9223:   syscompilerinfo(1);
 9224: 
 9225:   printf("Local time (at start):%s",strstart);
 9226:   fprintf(ficlog,"Local time (at start): %s",strstart);
 9227:   fflush(ficlog);
 9228: /*   (void) gettimeofday(&curr_time,&tzp); */
 9229: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
 9230: 
 9231:   /* */
 9232:   strcpy(fileres,"r");
 9233:   strcat(fileres, optionfilefiname);
 9234:   strcat(fileresu, optionfilefiname); /* Without r in front */
 9235:   strcat(fileres,".txt");    /* Other files have txt extension */
 9236:   strcat(fileresu,".txt");    /* Other files have txt extension */
 9237: 
 9238:   /* Main ---------arguments file --------*/
 9239: 
 9240:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
 9241:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 9242:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 9243:     fflush(ficlog);
 9244:     /* goto end; */
 9245:     exit(70); 
 9246:   }
 9247: 
 9248: 
 9249: 
 9250:   strcpy(filereso,"o");
 9251:   strcat(filereso,fileresu);
 9252:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
 9253:     printf("Problem with Output resultfile: %s\n", filereso);
 9254:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
 9255:     fflush(ficlog);
 9256:     goto end;
 9257:   }
 9258: 
 9259:   /* Reads comments: lines beginning with '#' */
 9260:   numlinepar=0;
 9261: 
 9262:     /* First parameter line */
 9263:   while(fgets(line, MAXLINE, ficpar)) {
 9264:     /* If line starts with a # it is a comment */
 9265:     if (line[0] == '#') {
 9266:       numlinepar++;
 9267:       fputs(line,stdout);
 9268:       fputs(line,ficparo);
 9269:       fputs(line,ficlog);
 9270:       continue;
 9271:     }else
 9272:       break;
 9273:   }
 9274:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
 9275: 			title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
 9276:     if (num_filled != 5) {
 9277:       printf("Should be 5 parameters\n");
 9278:     }
 9279:     numlinepar++;
 9280:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
 9281:   }
 9282:   /* Second parameter line */
 9283:   while(fgets(line, MAXLINE, ficpar)) {
 9284:     /* If line starts with a # it is a comment */
 9285:     if (line[0] == '#') {
 9286:       numlinepar++;
 9287:       fputs(line,stdout);
 9288:       fputs(line,ficparo);
 9289:       fputs(line,ficlog);
 9290:       continue;
 9291:     }else
 9292:       break;
 9293:   }
 9294:   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", \
 9295: 			&ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
 9296:     if (num_filled != 11) {
 9297:       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");
 9298:       printf("but line=%s\n",line);
 9299:     }
 9300:     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);
 9301:   }
 9302:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
 9303:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
 9304:   /* Third parameter line */
 9305:   while(fgets(line, MAXLINE, ficpar)) {
 9306:     /* If line starts with a # it is a comment */
 9307:     if (line[0] == '#') {
 9308:       numlinepar++;
 9309:       fputs(line,stdout);
 9310:       fputs(line,ficparo);
 9311:       fputs(line,ficlog);
 9312:       continue;
 9313:     }else
 9314:       break;
 9315:   }
 9316:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
 9317:     if (num_filled == 0)
 9318:             model[0]='\0';
 9319:     else if (num_filled != 1){
 9320:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
 9321:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
 9322:       model[0]='\0';
 9323:       goto end;
 9324:     }
 9325:     else{
 9326:       if (model[0]=='+'){
 9327: 	for(i=1; i<=strlen(model);i++)
 9328: 	  modeltemp[i-1]=model[i];
 9329: 	strcpy(model,modeltemp); 
 9330:       }
 9331:     }
 9332:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
 9333:     printf("model=1+age+%s\n",model);fflush(stdout);
 9334:   }
 9335:   /* 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); */
 9336:   /* numlinepar=numlinepar+3; /\* In general *\/ */
 9337:   /* 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); */
 9338:   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);
 9339:   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);
 9340:   fflush(ficlog);
 9341:   /* if(model[0]=='#'|| model[0]== '\0'){ */
 9342:   if(model[0]=='#'){
 9343:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
 9344:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
 9345:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");		\
 9346:     if(mle != -1){
 9347:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
 9348:       exit(1);
 9349:     }
 9350:   }
 9351:   while((c=getc(ficpar))=='#' && c!= EOF){
 9352:     ungetc(c,ficpar);
 9353:     fgets(line, MAXLINE, ficpar);
 9354:     numlinepar++;
 9355:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
 9356:       z[0]=line[1];
 9357:     }
 9358:     /* printf("****line [1] = %c \n",line[1]); */
 9359:     fputs(line, stdout);
 9360:     //puts(line);
 9361:     fputs(line,ficparo);
 9362:     fputs(line,ficlog);
 9363:   }
 9364:   ungetc(c,ficpar);
 9365: 
 9366:    
 9367:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
 9368:   coqvar=matrix(1,nqv,1,n);  /**< Fixed quantitative covariate */
 9369:   cotvar=ma3x(1,maxwav,1,ntv+nqtv,1,n);  /**< Time varying covariate (dummy and quantitative)*/
 9370:   cotqvar=ma3x(1,maxwav,1,nqtv,1,n);  /**< Time varying quantitative covariate */
 9371:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
 9372:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
 9373:      v1+v2*age+v2*v3 makes cptcovn = 3
 9374:   */
 9375:   if (strlen(model)>1) 
 9376:     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*/
 9377:   else
 9378:     ncovmodel=2; /* Constant and age */
 9379:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
 9380:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
 9381:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
 9382:     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);
 9383:     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);
 9384:     fflush(stdout);
 9385:     fclose (ficlog);
 9386:     goto end;
 9387:   }
 9388:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 9389:   delti=delti3[1][1];
 9390:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
 9391:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
 9392:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 9393:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 9394:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 9395:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 9396:     fclose (ficparo);
 9397:     fclose (ficlog);
 9398:     goto end;
 9399:     exit(0);
 9400:   }  else if(mle==-5) { /* Main Wizard */
 9401:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 9402:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 9403:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 9404:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 9405:     matcov=matrix(1,npar,1,npar);
 9406:     hess=matrix(1,npar,1,npar);
 9407:   }  else{ /* Begin of mle != -1 or -5 */
 9408:     /* Read guessed parameters */
 9409:     /* Reads comments: lines beginning with '#' */
 9410:     while((c=getc(ficpar))=='#' && c!= EOF){
 9411:       ungetc(c,ficpar);
 9412:       fgets(line, MAXLINE, ficpar);
 9413:       numlinepar++;
 9414:       fputs(line,stdout);
 9415:       fputs(line,ficparo);
 9416:       fputs(line,ficlog);
 9417:     }
 9418:     ungetc(c,ficpar);
 9419:     
 9420:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 9421:     for(i=1; i <=nlstate; i++){
 9422: 			j=0;
 9423:       for(jj=1; jj <=nlstate+ndeath; jj++){
 9424: 				if(jj==i) continue;
 9425: 				j++;
 9426: 				fscanf(ficpar,"%1d%1d",&i1,&j1);
 9427: 				if ((i1 != i) || (j1 != jj)){
 9428: 					printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
 9429: It might be a problem of design; if ncovcol and the model are correct\n \
 9430: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
 9431: 					exit(1);
 9432: 				}
 9433: 				fprintf(ficparo,"%1d%1d",i1,j1);
 9434: 				if(mle==1)
 9435: 					printf("%1d%1d",i,jj);
 9436: 				fprintf(ficlog,"%1d%1d",i,jj);
 9437: 				for(k=1; k<=ncovmodel;k++){
 9438: 					fscanf(ficpar," %lf",&param[i][j][k]);
 9439: 					if(mle==1){
 9440: 						printf(" %lf",param[i][j][k]);
 9441: 						fprintf(ficlog," %lf",param[i][j][k]);
 9442: 					}
 9443: 					else
 9444: 						fprintf(ficlog," %lf",param[i][j][k]);
 9445: 					fprintf(ficparo," %lf",param[i][j][k]);
 9446: 				}
 9447: 				fscanf(ficpar,"\n");
 9448: 				numlinepar++;
 9449: 				if(mle==1)
 9450: 					printf("\n");
 9451: 				fprintf(ficlog,"\n");
 9452: 				fprintf(ficparo,"\n");
 9453:       }
 9454:     }  
 9455:     fflush(ficlog);
 9456: 
 9457:     /* Reads scales values */
 9458:     p=param[1][1];
 9459:     
 9460:     /* Reads comments: lines beginning with '#' */
 9461:     while((c=getc(ficpar))=='#' && c!= EOF){
 9462:       ungetc(c,ficpar);
 9463:       fgets(line, MAXLINE, ficpar);
 9464:       numlinepar++;
 9465:       fputs(line,stdout);
 9466:       fputs(line,ficparo);
 9467:       fputs(line,ficlog);
 9468:     }
 9469:     ungetc(c,ficpar);
 9470: 
 9471:     for(i=1; i <=nlstate; i++){
 9472:       for(j=1; j <=nlstate+ndeath-1; j++){
 9473: 				fscanf(ficpar,"%1d%1d",&i1,&j1);
 9474: 				if ( (i1-i) * (j1-j) != 0){
 9475: 					printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
 9476: 					exit(1);
 9477: 				}
 9478: 				printf("%1d%1d",i,j);
 9479: 				fprintf(ficparo,"%1d%1d",i1,j1);
 9480: 				fprintf(ficlog,"%1d%1d",i1,j1);
 9481: 				for(k=1; k<=ncovmodel;k++){
 9482: 					fscanf(ficpar,"%le",&delti3[i][j][k]);
 9483: 					printf(" %le",delti3[i][j][k]);
 9484: 					fprintf(ficparo," %le",delti3[i][j][k]);
 9485: 					fprintf(ficlog," %le",delti3[i][j][k]);
 9486: 				}
 9487: 				fscanf(ficpar,"\n");
 9488: 				numlinepar++;
 9489: 				printf("\n");
 9490: 				fprintf(ficparo,"\n");
 9491: 				fprintf(ficlog,"\n");
 9492:       }
 9493:     }
 9494:     fflush(ficlog);
 9495: 		
 9496:     /* Reads covariance matrix */
 9497:     delti=delti3[1][1];
 9498: 		
 9499: 		
 9500:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
 9501: 		
 9502:     /* Reads comments: lines beginning with '#' */
 9503:     while((c=getc(ficpar))=='#' && c!= EOF){
 9504:       ungetc(c,ficpar);
 9505:       fgets(line, MAXLINE, ficpar);
 9506:       numlinepar++;
 9507:       fputs(line,stdout);
 9508:       fputs(line,ficparo);
 9509:       fputs(line,ficlog);
 9510:     }
 9511:     ungetc(c,ficpar);
 9512: 		
 9513:     matcov=matrix(1,npar,1,npar);
 9514:     hess=matrix(1,npar,1,npar);
 9515:     for(i=1; i <=npar; i++)
 9516:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
 9517: 		
 9518:     /* Scans npar lines */
 9519:     for(i=1; i <=npar; i++){
 9520:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
 9521:       if(count != 3){
 9522: 	printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
 9523: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
 9524: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
 9525: 	fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
 9526: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
 9527: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
 9528: 	exit(1);
 9529:       }else{
 9530: 	if(mle==1)
 9531: 	  printf("%1d%1d%d",i1,j1,jk);
 9532:       }
 9533:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
 9534:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
 9535:       for(j=1; j <=i; j++){
 9536: 	fscanf(ficpar," %le",&matcov[i][j]);
 9537: 	if(mle==1){
 9538: 	  printf(" %.5le",matcov[i][j]);
 9539: 	}
 9540: 	fprintf(ficlog," %.5le",matcov[i][j]);
 9541: 	fprintf(ficparo," %.5le",matcov[i][j]);
 9542:       }
 9543:       fscanf(ficpar,"\n");
 9544:       numlinepar++;
 9545:       if(mle==1)
 9546: 				printf("\n");
 9547:       fprintf(ficlog,"\n");
 9548:       fprintf(ficparo,"\n");
 9549:     }
 9550:     /* End of read covariance matrix npar lines */
 9551:     for(i=1; i <=npar; i++)
 9552:       for(j=i+1;j<=npar;j++)
 9553: 	matcov[i][j]=matcov[j][i];
 9554:     
 9555:     if(mle==1)
 9556:       printf("\n");
 9557:     fprintf(ficlog,"\n");
 9558:     
 9559:     fflush(ficlog);
 9560:     
 9561:     /*-------- Rewriting parameter file ----------*/
 9562:     strcpy(rfileres,"r");    /* "Rparameterfile */
 9563:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
 9564:     strcat(rfileres,".");    /* */
 9565:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
 9566:     if((ficres =fopen(rfileres,"w"))==NULL) {
 9567:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
 9568:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
 9569:     }
 9570:     fprintf(ficres,"#%s\n",version);
 9571:   }    /* End of mle != -3 */
 9572:   
 9573:   /*  Main data
 9574:    */
 9575:   n= lastobs;
 9576:   num=lvector(1,n);
 9577:   moisnais=vector(1,n);
 9578:   annais=vector(1,n);
 9579:   moisdc=vector(1,n);
 9580:   andc=vector(1,n);
 9581:   weight=vector(1,n);
 9582:   agedc=vector(1,n);
 9583:   cod=ivector(1,n);
 9584:   for(i=1;i<=n;i++){
 9585: 		num[i]=0;
 9586: 		moisnais[i]=0;
 9587: 		annais[i]=0;
 9588: 		moisdc[i]=0;
 9589: 		andc[i]=0;
 9590: 		agedc[i]=0;
 9591: 		cod[i]=0;
 9592: 		weight[i]=1.0; /* Equal weights, 1 by default */
 9593: 	}
 9594:   mint=matrix(1,maxwav,1,n);
 9595:   anint=matrix(1,maxwav,1,n);
 9596:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
 9597:   tab=ivector(1,NCOVMAX);
 9598:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
 9599:   ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
 9600: 
 9601:   /* Reads data from file datafile */
 9602:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
 9603:     goto end;
 9604: 
 9605:   /* Calculation of the number of parameters from char model */
 9606:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
 9607: 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
 9608: 	k=3 V4 Tvar[k=3]= 4 (from V4)
 9609: 	k=2 V1 Tvar[k=2]= 1 (from V1)
 9610: 	k=1 Tvar[1]=2 (from V2)
 9611:     */
 9612: 
 9613: 	Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
 9614:   TvarF=ivector(1,NCOVMAX); /*  */
 9615:   TvarFind=ivector(1,NCOVMAX); /*  */
 9616:   TvarV=ivector(1,NCOVMAX); /*  */
 9617:   TvarVind=ivector(1,NCOVMAX); /*  */
 9618:   TvarA=ivector(1,NCOVMAX); /*  */
 9619:   TvarAind=ivector(1,NCOVMAX); /*  */
 9620:   TvarFD=ivector(1,NCOVMAX); /*  */
 9621:   TvarFDind=ivector(1,NCOVMAX); /*  */
 9622:   TvarFQ=ivector(1,NCOVMAX); /*  */
 9623:   TvarFQind=ivector(1,NCOVMAX); /*  */
 9624:   TvarVD=ivector(1,NCOVMAX); /*  */
 9625:   TvarVDind=ivector(1,NCOVMAX); /*  */
 9626:   TvarVQ=ivector(1,NCOVMAX); /*  */
 9627:   TvarVQind=ivector(1,NCOVMAX); /*  */
 9628: 
 9629:   Tvalsel=vector(1,NCOVMAX); /*  */
 9630:   Tvarsel=ivector(1,NCOVMAX); /*  */
 9631:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
 9632:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
 9633:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
 9634:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
 9635:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
 9636:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
 9637:   */
 9638:   /* For model-covariate k tells which data-covariate to use but
 9639:     because this model-covariate is a construction we invent a new column
 9640:     ncovcol + k1
 9641:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
 9642:     Tvar[3=V1*V4]=4+1 etc */
 9643:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
 9644:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
 9645:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
 9646:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
 9647:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
 9648:   */
 9649:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
 9650:   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
 9651: 			    * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
 9652: 			    * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
 9653:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
 9654: 			 4 covariates (3 plus signs)
 9655: 			 Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
 9656: 		      */  
 9657:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
 9658: 				* individual dummy, fixed or varying:
 9659: 				* Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
 9660: 				* 3, 1, 0, 0, 0, 0, 0, 0},
 9661: 				* model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
 9662: 				* V1 df, V2 qf, V3 & V4 dv, V5 qv
 9663: 				* Tmodelind[1]@9={9,0,3,2,}*/
 9664:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
 9665:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
 9666: 				* individual quantitative, fixed or varying:
 9667: 				* Tmodelqind[1]=1,Tvaraff[1]@9={4,
 9668: 				* 3, 1, 0, 0, 0, 0, 0, 0},
 9669: 				* model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
 9670: /* Main decodemodel */
 9671: 
 9672: 
 9673:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
 9674:     goto end;
 9675: 
 9676:   if((double)(lastobs-imx)/(double)imx > 1.10){
 9677:     nbwarn++;
 9678:     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); 
 9679:     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); 
 9680:   }
 9681:     /*  if(mle==1){*/
 9682:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
 9683:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
 9684:   }
 9685: 
 9686:     /*-calculation of age at interview from date of interview and age at death -*/
 9687:   agev=matrix(1,maxwav,1,imx);
 9688: 
 9689:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
 9690:     goto end;
 9691: 
 9692: 
 9693:   agegomp=(int)agemin;
 9694:   free_vector(moisnais,1,n);
 9695:   free_vector(annais,1,n);
 9696:   /* free_matrix(mint,1,maxwav,1,n);
 9697:      free_matrix(anint,1,maxwav,1,n);*/
 9698:   /* free_vector(moisdc,1,n); */
 9699:   /* free_vector(andc,1,n); */
 9700:   /* */
 9701:   
 9702:   wav=ivector(1,imx);
 9703:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
 9704:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
 9705:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
 9706:   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.*/
 9707:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
 9708:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
 9709:    
 9710:   /* Concatenates waves */
 9711:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 9712:      Death is a valid wave (if date is known).
 9713:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
 9714:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 9715:      and mw[mi+1][i]. dh depends on stepm.
 9716:   */
 9717: 
 9718:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
 9719:   /* */
 9720:  
 9721:   free_vector(moisdc,1,n);
 9722:   free_vector(andc,1,n);
 9723: 
 9724:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
 9725:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
 9726:   ncodemax[1]=1;
 9727:   Ndum =ivector(-1,NCOVMAX);  
 9728:   cptcoveff=0;
 9729:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
 9730:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
 9731:   }
 9732:   
 9733:   ncovcombmax=pow(2,cptcoveff);
 9734:   invalidvarcomb=ivector(1, ncovcombmax); 
 9735:   for(i=1;i<ncovcombmax;i++)
 9736:     invalidvarcomb[i]=0;
 9737:   
 9738:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
 9739:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
 9740:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
 9741:   
 9742:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
 9743:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
 9744:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
 9745:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
 9746:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
 9747:    * (currently 0 or 1) in the data.
 9748:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
 9749:    * corresponding modality (h,j).
 9750:    */
 9751: 
 9752:   h=0;
 9753:   /*if (cptcovn > 0) */
 9754:   m=pow(2,cptcoveff);
 9755:  
 9756: 	  /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
 9757: 	   * For k=4 covariates, h goes from 1 to m=2**k
 9758: 	   * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
 9759:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
 9760: 	   *     h\k   1     2     3     4
 9761: 	   *______________________________  
 9762: 	   *     1 i=1 1 i=1 1 i=1 1 i=1 1
 9763: 	   *     2     2     1     1     1
 9764: 	   *     3 i=2 1     2     1     1
 9765: 	   *     4     2     2     1     1
 9766: 	   *     5 i=3 1 i=2 1     2     1
 9767: 	   *     6     2     1     2     1
 9768: 	   *     7 i=4 1     2     2     1
 9769: 	   *     8     2     2     2     1
 9770: 	   *     9 i=5 1 i=3 1 i=2 1     2
 9771: 	   *    10     2     1     1     2
 9772: 	   *    11 i=6 1     2     1     2
 9773: 	   *    12     2     2     1     2
 9774: 	   *    13 i=7 1 i=4 1     2     2    
 9775: 	   *    14     2     1     2     2
 9776: 	   *    15 i=8 1     2     2     2
 9777: 	   *    16     2     2     2     2
 9778: 	   */
 9779:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
 9780:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
 9781:      * and the value of each covariate?
 9782:      * V1=1, V2=1, V3=2, V4=1 ?
 9783:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
 9784:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
 9785:      * In order to get the real value in the data, we use nbcode
 9786:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
 9787:      * We are keeping this crazy system in order to be able (in the future?) 
 9788:      * to have more than 2 values (0 or 1) for a covariate.
 9789:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
 9790:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
 9791:      *              bbbbbbbb
 9792:      *              76543210     
 9793:      *   h-1        00000101 (6-1=5)
 9794:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
 9795:      *           &
 9796:      *     1        00000001 (1)
 9797:      *              00000000        = 1 & ((h-1) >> (k-1))
 9798:      *          +1= 00000001 =1 
 9799:      *
 9800:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
 9801:      *          h'      1101 =2^3+2^2+0x2^1+2^0
 9802:      *    >>k'            11
 9803:      *          &   00000001
 9804:      *            = 00000001
 9805:      *      +1    = 00000010=2    =  codtabm(14,3)   
 9806:      * Reverse h=6 and m=16?
 9807:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
 9808:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
 9809:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
 9810:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
 9811:      * V3=decodtabm(14,3,2**4)=2
 9812:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
 9813:      *(h-1) >> (j-1)    0011 =13 >> 2
 9814:      *          &1 000000001
 9815:      *           = 000000001
 9816:      *         +1= 000000010 =2
 9817:      *                  2211
 9818:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
 9819:      *                  V3=2
 9820: 		 * codtabm and decodtabm are identical
 9821:      */
 9822: 
 9823: 
 9824:  free_ivector(Ndum,-1,NCOVMAX);
 9825: 
 9826: 
 9827:     
 9828:   /* Initialisation of ----------- gnuplot -------------*/
 9829:   strcpy(optionfilegnuplot,optionfilefiname);
 9830:   if(mle==-3)
 9831:     strcat(optionfilegnuplot,"-MORT_");
 9832:   strcat(optionfilegnuplot,".gp");
 9833: 
 9834:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
 9835:     printf("Problem with file %s",optionfilegnuplot);
 9836:   }
 9837:   else{
 9838:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
 9839:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
 9840:     //fprintf(ficgp,"set missing 'NaNq'\n");
 9841:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
 9842:   }
 9843:   /*  fclose(ficgp);*/
 9844: 
 9845: 
 9846:   /* Initialisation of --------- index.htm --------*/
 9847: 
 9848:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
 9849:   if(mle==-3)
 9850:     strcat(optionfilehtm,"-MORT_");
 9851:   strcat(optionfilehtm,".htm");
 9852:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
 9853:     printf("Problem with %s \n",optionfilehtm);
 9854:     exit(0);
 9855:   }
 9856: 
 9857:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
 9858:   strcat(optionfilehtmcov,"-cov.htm");
 9859:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
 9860:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
 9861:   }
 9862:   else{
 9863:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 9864: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 9865: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
 9866: 	  optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 9867:   }
 9868: 
 9869:   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>  \
 9870: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 9871: <font size=\"2\">IMaCh-%s <br> %s</font> \
 9872: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 9873: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
 9874: \n\
 9875: <hr  size=\"2\" color=\"#EC5E5E\">\
 9876:  <ul><li><h4>Parameter files</h4>\n\
 9877:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
 9878:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
 9879:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
 9880:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
 9881:  - Date and time at start: %s</ul>\n",\
 9882: 	  optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
 9883: 	  optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
 9884: 	  fileres,fileres,\
 9885: 	  filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
 9886:   fflush(fichtm);
 9887: 
 9888:   strcpy(pathr,path);
 9889:   strcat(pathr,optionfilefiname);
 9890: #ifdef WIN32
 9891:   _chdir(optionfilefiname); /* Move to directory named optionfile */
 9892: #else
 9893:   chdir(optionfilefiname); /* Move to directory named optionfile */
 9894: #endif
 9895: 	  
 9896:   
 9897:   /* Calculates basic frequencies. Computes observed prevalence at single age 
 9898: 		 and for any valid combination of covariates
 9899:      and prints on file fileres'p'. */
 9900:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
 9901: 	      firstpass, lastpass,  stepm,  weightopt, model);
 9902: 
 9903:   fprintf(fichtm,"\n");
 9904:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
 9905: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
 9906: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
 9907: 	  imx,agemin,agemax,jmin,jmax,jmean);
 9908:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 9909: 	oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 9910: 	newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 9911: 	savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 9912: 	oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
 9913: 
 9914:   /* For Powell, parameters are in a vector p[] starting at p[1]
 9915:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
 9916:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
 9917: 
 9918:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
 9919:   /* For mortality only */
 9920:   if (mle==-3){
 9921:     ximort=matrix(1,NDIM,1,NDIM); 
 9922: 		for(i=1;i<=NDIM;i++)
 9923: 			for(j=1;j<=NDIM;j++)
 9924: 				ximort[i][j]=0.;
 9925:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
 9926:     cens=ivector(1,n);
 9927:     ageexmed=vector(1,n);
 9928:     agecens=vector(1,n);
 9929:     dcwave=ivector(1,n);
 9930: 		
 9931:     for (i=1; i<=imx; i++){
 9932:       dcwave[i]=-1;
 9933:       for (m=firstpass; m<=lastpass; m++)
 9934: 	if (s[m][i]>nlstate) {
 9935: 	  dcwave[i]=m;
 9936: 	  /*	printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
 9937: 	  break;
 9938: 	}
 9939:     }
 9940:     
 9941:     for (i=1; i<=imx; i++) {
 9942:       if (wav[i]>0){
 9943: 	ageexmed[i]=agev[mw[1][i]][i];
 9944: 	j=wav[i];
 9945: 	agecens[i]=1.; 
 9946: 	
 9947: 	if (ageexmed[i]> 1 && wav[i] > 0){
 9948: 	  agecens[i]=agev[mw[j][i]][i];
 9949: 	  cens[i]= 1;
 9950: 	}else if (ageexmed[i]< 1) 
 9951: 	  cens[i]= -1;
 9952: 	if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
 9953: 	  cens[i]=0 ;
 9954:       }
 9955:       else cens[i]=-1;
 9956:     }
 9957:     
 9958:     for (i=1;i<=NDIM;i++) {
 9959:       for (j=1;j<=NDIM;j++)
 9960: 	ximort[i][j]=(i == j ? 1.0 : 0.0);
 9961:     }
 9962:     
 9963:     /*p[1]=0.0268; p[NDIM]=0.083;*/
 9964:     /*printf("%lf %lf", p[1], p[2]);*/
 9965:     
 9966:     
 9967: #ifdef GSL
 9968:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
 9969: #else
 9970:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
 9971: #endif
 9972:     strcpy(filerespow,"POW-MORT_"); 
 9973:     strcat(filerespow,fileresu);
 9974:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
 9975:       printf("Problem with resultfile: %s\n", filerespow);
 9976:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 9977:     }
 9978: #ifdef GSL
 9979:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
 9980: #else
 9981:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
 9982: #endif
 9983:     /*  for (i=1;i<=nlstate;i++)
 9984: 	for(j=1;j<=nlstate+ndeath;j++)
 9985: 	if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 9986:     */
 9987:     fprintf(ficrespow,"\n");
 9988: #ifdef GSL
 9989:     /* gsl starts here */ 
 9990:     T = gsl_multimin_fminimizer_nmsimplex;
 9991:     gsl_multimin_fminimizer *sfm = NULL;
 9992:     gsl_vector *ss, *x;
 9993:     gsl_multimin_function minex_func;
 9994: 
 9995:     /* Initial vertex size vector */
 9996:     ss = gsl_vector_alloc (NDIM);
 9997:     
 9998:     if (ss == NULL){
 9999:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
10000:     }
10001:     /* Set all step sizes to 1 */
10002:     gsl_vector_set_all (ss, 0.001);
10003: 
10004:     /* Starting point */
10005:     
10006:     x = gsl_vector_alloc (NDIM);
10007:     
10008:     if (x == NULL){
10009:       gsl_vector_free(ss);
10010:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
10011:     }
10012:   
10013:     /* Initialize method and iterate */
10014:     /*     p[1]=0.0268; p[NDIM]=0.083; */
10015:     /*     gsl_vector_set(x, 0, 0.0268); */
10016:     /*     gsl_vector_set(x, 1, 0.083); */
10017:     gsl_vector_set(x, 0, p[1]);
10018:     gsl_vector_set(x, 1, p[2]);
10019: 
10020:     minex_func.f = &gompertz_f;
10021:     minex_func.n = NDIM;
10022:     minex_func.params = (void *)&p; /* ??? */
10023:     
10024:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
10025:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
10026:     
10027:     printf("Iterations beginning .....\n\n");
10028:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
10029: 
10030:     iteri=0;
10031:     while (rval == GSL_CONTINUE){
10032:       iteri++;
10033:       status = gsl_multimin_fminimizer_iterate(sfm);
10034:       
10035:       if (status) printf("error: %s\n", gsl_strerror (status));
10036:       fflush(0);
10037:       
10038:       if (status) 
10039:         break;
10040:       
10041:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
10042:       ssval = gsl_multimin_fminimizer_size (sfm);
10043:       
10044:       if (rval == GSL_SUCCESS)
10045:         printf ("converged to a local maximum at\n");
10046:       
10047:       printf("%5d ", iteri);
10048:       for (it = 0; it < NDIM; it++){
10049: 	printf ("%10.5f ", gsl_vector_get (sfm->x, it));
10050:       }
10051:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
10052:     }
10053:     
10054:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
10055:     
10056:     gsl_vector_free(x); /* initial values */
10057:     gsl_vector_free(ss); /* inital step size */
10058:     for (it=0; it<NDIM; it++){
10059:       p[it+1]=gsl_vector_get(sfm->x,it);
10060:       fprintf(ficrespow," %.12lf", p[it]);
10061:     }
10062:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
10063: #endif
10064: #ifdef POWELL
10065:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
10066: #endif  
10067:     fclose(ficrespow);
10068:     
10069:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
10070: 
10071:     for(i=1; i <=NDIM; i++)
10072:       for(j=i+1;j<=NDIM;j++)
10073: 				matcov[i][j]=matcov[j][i];
10074:     
10075:     printf("\nCovariance matrix\n ");
10076:     fprintf(ficlog,"\nCovariance matrix\n ");
10077:     for(i=1; i <=NDIM; i++) {
10078:       for(j=1;j<=NDIM;j++){ 
10079: 				printf("%f ",matcov[i][j]);
10080: 				fprintf(ficlog,"%f ",matcov[i][j]);
10081:       }
10082:       printf("\n ");  fprintf(ficlog,"\n ");
10083:     }
10084:     
10085:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
10086:     for (i=1;i<=NDIM;i++) {
10087:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
10088:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
10089:     }
10090:     lsurv=vector(1,AGESUP);
10091:     lpop=vector(1,AGESUP);
10092:     tpop=vector(1,AGESUP);
10093:     lsurv[agegomp]=100000;
10094:     
10095:     for (k=agegomp;k<=AGESUP;k++) {
10096:       agemortsup=k;
10097:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
10098:     }
10099:     
10100:     for (k=agegomp;k<agemortsup;k++)
10101:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
10102:     
10103:     for (k=agegomp;k<agemortsup;k++){
10104:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
10105:       sumlpop=sumlpop+lpop[k];
10106:     }
10107:     
10108:     tpop[agegomp]=sumlpop;
10109:     for (k=agegomp;k<(agemortsup-3);k++){
10110:       /*  tpop[k+1]=2;*/
10111:       tpop[k+1]=tpop[k]-lpop[k];
10112:     }
10113:     
10114:     
10115:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
10116:     for (k=agegomp;k<(agemortsup-2);k++) 
10117:       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]);
10118:     
10119:     
10120:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
10121: 		ageminpar=50;
10122: 		agemaxpar=100;
10123:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
10124:       	printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
10125: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
10126: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
10127:       	fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
10128: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
10129: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
10130:     }else{
10131: 			printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
10132: 			fprintf(ficlog,"Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
10133:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
10134: 		}
10135:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
10136: 		     stepm, weightopt,\
10137: 		     model,imx,p,matcov,agemortsup);
10138:     
10139:     free_vector(lsurv,1,AGESUP);
10140:     free_vector(lpop,1,AGESUP);
10141:     free_vector(tpop,1,AGESUP);
10142:     free_matrix(ximort,1,NDIM,1,NDIM);
10143:     free_ivector(cens,1,n);
10144:     free_vector(agecens,1,n);
10145:     free_ivector(dcwave,1,n);
10146: #ifdef GSL
10147: #endif
10148:   } /* Endof if mle==-3 mortality only */
10149:   /* Standard  */
10150:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
10151:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
10152:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
10153:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
10154:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
10155:     for (k=1; k<=npar;k++)
10156:       printf(" %d %8.5f",k,p[k]);
10157:     printf("\n");
10158:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
10159:       /* mlikeli uses func not funcone */
10160:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
10161:     }
10162:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
10163:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
10164:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
10165:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
10166:     }
10167:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
10168:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
10169:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
10170:     for (k=1; k<=npar;k++)
10171:       printf(" %d %8.5f",k,p[k]);
10172:     printf("\n");
10173:     
10174:     /*--------- results files --------------*/
10175:     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);
10176:     
10177:     
10178:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
10179:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
10180:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
10181:     for(i=1,jk=1; i <=nlstate; i++){
10182:       for(k=1; k <=(nlstate+ndeath); k++){
10183: 	if (k != i) {
10184: 	  printf("%d%d ",i,k);
10185: 	  fprintf(ficlog,"%d%d ",i,k);
10186: 	  fprintf(ficres,"%1d%1d ",i,k);
10187: 	  for(j=1; j <=ncovmodel; j++){
10188: 	    printf("%12.7f ",p[jk]);
10189: 	    fprintf(ficlog,"%12.7f ",p[jk]);
10190: 	    fprintf(ficres,"%12.7f ",p[jk]);
10191: 	    jk++; 
10192: 	  }
10193: 	  printf("\n");
10194: 	  fprintf(ficlog,"\n");
10195: 	  fprintf(ficres,"\n");
10196: 	}
10197:       }
10198:     }
10199:     if(mle != 0){
10200:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
10201:       ftolhess=ftol; /* Usually correct */
10202:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
10203:       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");
10204:       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");
10205:       for(i=1,jk=1; i <=nlstate; i++){
10206: 	for(k=1; k <=(nlstate+ndeath); k++){
10207: 	  if (k != i) {
10208: 	    printf("%d%d ",i,k);
10209: 	    fprintf(ficlog,"%d%d ",i,k);
10210: 	    for(j=1; j <=ncovmodel; j++){
10211: 	      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]));
10212: 	      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]));
10213: 	      jk++; 
10214: 	    }
10215: 	    printf("\n");
10216: 	    fprintf(ficlog,"\n");
10217: 	  }
10218: 	}
10219:       }
10220:     } /* end of hesscov and Wald tests */
10221:     
10222:     /*  */
10223:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
10224:     printf("# Scales (for hessian or gradient estimation)\n");
10225:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
10226:     for(i=1,jk=1; i <=nlstate; i++){
10227:       for(j=1; j <=nlstate+ndeath; j++){
10228: 	if (j!=i) {
10229: 	  fprintf(ficres,"%1d%1d",i,j);
10230: 	  printf("%1d%1d",i,j);
10231: 	  fprintf(ficlog,"%1d%1d",i,j);
10232: 	  for(k=1; k<=ncovmodel;k++){
10233: 	    printf(" %.5e",delti[jk]);
10234: 	    fprintf(ficlog," %.5e",delti[jk]);
10235: 	    fprintf(ficres," %.5e",delti[jk]);
10236: 	    jk++;
10237: 	  }
10238: 	  printf("\n");
10239: 	  fprintf(ficlog,"\n");
10240: 	  fprintf(ficres,"\n");
10241: 	}
10242:       }
10243:     }
10244:     
10245:     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");
10246:     if(mle >= 1) /* To big for the screen */
10247:       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");
10248:     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");
10249:     /* # 121 Var(a12)\n\ */
10250:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
10251:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
10252:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
10253:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
10254:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
10255:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
10256:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
10257:     
10258:     
10259:     /* Just to have a covariance matrix which will be more understandable
10260:        even is we still don't want to manage dictionary of variables
10261:     */
10262:     for(itimes=1;itimes<=2;itimes++){
10263:       jj=0;
10264:       for(i=1; i <=nlstate; i++){
10265: 	for(j=1; j <=nlstate+ndeath; j++){
10266: 	  if(j==i) continue;
10267: 	  for(k=1; k<=ncovmodel;k++){
10268: 	    jj++;
10269: 	    ca[0]= k+'a'-1;ca[1]='\0';
10270: 	    if(itimes==1){
10271: 	      if(mle>=1)
10272: 		printf("#%1d%1d%d",i,j,k);
10273: 	      fprintf(ficlog,"#%1d%1d%d",i,j,k);
10274: 	      fprintf(ficres,"#%1d%1d%d",i,j,k);
10275: 	    }else{
10276: 	      if(mle>=1)
10277: 		printf("%1d%1d%d",i,j,k);
10278: 	      fprintf(ficlog,"%1d%1d%d",i,j,k);
10279: 	      fprintf(ficres,"%1d%1d%d",i,j,k);
10280: 	    }
10281: 	    ll=0;
10282: 	    for(li=1;li <=nlstate; li++){
10283: 	      for(lj=1;lj <=nlstate+ndeath; lj++){
10284: 		if(lj==li) continue;
10285: 		for(lk=1;lk<=ncovmodel;lk++){
10286: 		  ll++;
10287: 		  if(ll<=jj){
10288: 		    cb[0]= lk +'a'-1;cb[1]='\0';
10289: 		    if(ll<jj){
10290: 		      if(itimes==1){
10291: 			if(mle>=1)
10292: 			  printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
10293: 			fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
10294: 			fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
10295: 		      }else{
10296: 			if(mle>=1)
10297: 			  printf(" %.5e",matcov[jj][ll]); 
10298: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
10299: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
10300: 		      }
10301: 		    }else{
10302: 		      if(itimes==1){
10303: 			if(mle>=1)
10304: 			  printf(" Var(%s%1d%1d)",ca,i,j);
10305: 			fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
10306: 			fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
10307: 		      }else{
10308: 			if(mle>=1)
10309: 			  printf(" %.7e",matcov[jj][ll]); 
10310: 			fprintf(ficlog," %.7e",matcov[jj][ll]); 
10311: 			fprintf(ficres," %.7e",matcov[jj][ll]); 
10312: 		      }
10313: 		    }
10314: 		  }
10315: 		} /* end lk */
10316: 	      } /* end lj */
10317: 	    } /* end li */
10318: 	    if(mle>=1)
10319: 	      printf("\n");
10320: 	    fprintf(ficlog,"\n");
10321: 	    fprintf(ficres,"\n");
10322: 	    numlinepar++;
10323: 	  } /* end k*/
10324: 	} /*end j */
10325:       } /* end i */
10326:     } /* end itimes */
10327:     
10328:     fflush(ficlog);
10329:     fflush(ficres);
10330:     while(fgets(line, MAXLINE, ficpar)) {
10331:       /* If line starts with a # it is a comment */
10332:       if (line[0] == '#') {
10333: 	numlinepar++;
10334: 	fputs(line,stdout);
10335: 	fputs(line,ficparo);
10336: 	fputs(line,ficlog);
10337: 	continue;
10338:       }else
10339: 	break;
10340:     }
10341:     
10342:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
10343:     /*   ungetc(c,ficpar); */
10344:     /*   fgets(line, MAXLINE, ficpar); */
10345:     /*   fputs(line,stdout); */
10346:     /*   fputs(line,ficparo); */
10347:     /* } */
10348:     /* ungetc(c,ficpar); */
10349:     
10350:     estepm=0;
10351:     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){
10352:       
10353:       if (num_filled != 6) {
10354: 	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);
10355: 	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);
10356: 	goto end;
10357:       }
10358:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
10359:     }
10360:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
10361:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
10362:     
10363:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
10364:     if (estepm==0 || estepm < stepm) estepm=stepm;
10365:     if (fage <= 2) {
10366:       bage = ageminpar;
10367:       fage = agemaxpar;
10368:     }
10369:     
10370:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
10371:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
10372:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
10373: 		
10374:     /* Other stuffs, more or less useful */    
10375:     while((c=getc(ficpar))=='#' && c!= EOF){
10376:       ungetc(c,ficpar);
10377:       fgets(line, MAXLINE, ficpar);
10378:       fputs(line,stdout);
10379:       fputs(line,ficparo);
10380:     }
10381:     ungetc(c,ficpar);
10382:     
10383:     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);
10384:     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);
10385:     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);
10386:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
10387:     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);
10388:     
10389:     while((c=getc(ficpar))=='#' && c!= EOF){
10390:       ungetc(c,ficpar);
10391:       fgets(line, MAXLINE, ficpar);
10392:       fputs(line,stdout);
10393:       fputs(line,ficparo);
10394:     }
10395:     ungetc(c,ficpar);
10396:     
10397:     
10398:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
10399:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
10400:     
10401:     fscanf(ficpar,"pop_based=%d\n",&popbased);
10402:     fprintf(ficlog,"pop_based=%d\n",popbased);
10403:     fprintf(ficparo,"pop_based=%d\n",popbased);   
10404:     fprintf(ficres,"pop_based=%d\n",popbased);   
10405:     
10406:     while((c=getc(ficpar))=='#' && c!= EOF){
10407:       ungetc(c,ficpar);
10408:       fgets(line, MAXLINE, ficpar);
10409:       fputs(line,stdout);
10410:       fputs(line,ficparo);
10411:     }
10412:     ungetc(c,ficpar);
10413:     
10414:     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);
10415:     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);
10416:     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);
10417:     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);
10418:     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);
10419:     /* day and month of proj2 are not used but only year anproj2.*/
10420:     
10421:     while((c=getc(ficpar))=='#' && c!= EOF){
10422:       ungetc(c,ficpar);
10423:       fgets(line, MAXLINE, ficpar);
10424:       fputs(line,stdout);
10425:       fputs(line,ficparo);
10426:     }
10427:     ungetc(c,ficpar);
10428:     
10429:     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);
10430:     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);
10431:     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);
10432:     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);
10433:     /* day and month of proj2 are not used but only year anproj2.*/
10434:     
10435:     /* Results */
10436:     while(fgets(line, MAXLINE, ficpar)) {
10437:       /* If line starts with a # it is a comment */
10438:       if (line[0] == '#') {
10439: 	numlinepar++;
10440: 	fputs(line,stdout);
10441: 	fputs(line,ficparo);
10442: 	fputs(line,ficlog);
10443: 	continue;
10444:       }else
10445: 	break;
10446:     }
10447:     while((num_filled=sscanf(line,"result:%[^\n]\n",resultline)) !=EOF){
10448:       if (num_filled == 0)
10449: 	resultline[0]='\0';
10450:       else if (num_filled != 1){
10451: 	printf("ERROR %d: result line should be at minimum 'result=' %s\n",num_filled, line);
10452:       }
10453:       printf("Result %d: result line should be at minimum 'line=' %s, result=%s\n",num_filled, line, resultline);
10454:       decoderesult(resultline);
10455:       while(fgets(line, MAXLINE, ficpar)) {
10456: 	/* If line starts with a # it is a comment */
10457: 	if (line[0] == '#') {
10458: 	  numlinepar++;
10459: 	  fputs(line,stdout);
10460: 	  fputs(line,ficparo);
10461: 	  fputs(line,ficlog);
10462: 	  continue;
10463: 	}else
10464: 	  break;
10465:       }
10466:       if (feof(ficpar))
10467: 	break;
10468:       else{ /* Processess output results for this combination of covariate values */
10469:       }				   
10470:     }
10471: 
10472: 
10473:     
10474:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
10475:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
10476:     
10477:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
10478:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
10479:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
10480: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
10481: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
10482:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
10483: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
10484: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
10485:     }else{
10486:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
10487:     }
10488:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
10489: 		 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
10490: 		 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
10491: 		
10492:     /*------------ free_vector  -------------*/
10493:     /*  chdir(path); */
10494: 		
10495:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
10496:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
10497:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
10498:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
10499:     free_lvector(num,1,n);
10500:     free_vector(agedc,1,n);
10501:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
10502:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
10503:     fclose(ficparo);
10504:     fclose(ficres);
10505: 		
10506: 		
10507:     /* Other results (useful)*/
10508: 		
10509: 		
10510:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
10511:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
10512:     prlim=matrix(1,nlstate,1,nlstate);
10513:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
10514:     fclose(ficrespl);
10515: 
10516:     /*------------- h Pij x at various ages ------------*/
10517:     /*#include "hpijx.h"*/
10518:     hPijx(p, bage, fage);
10519:     fclose(ficrespij);
10520:     
10521:     /* ncovcombmax=  pow(2,cptcoveff); */
10522:     /*-------------- Variance of one-step probabilities---*/
10523:     k=1;
10524:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
10525:     
10526:     /* Prevalence for each covariates in probs[age][status][cov] */
10527:     probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
10528:     for(i=1;i<=AGESUP;i++)
10529:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
10530: 	for(k=1;k<=ncovcombmax;k++)
10531: 	  probs[i][j][k]=0.;
10532:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
10533:     if (mobilav!=0 ||mobilavproj !=0 ) {
10534:       mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
10535:       for(i=1;i<=AGESUP;i++)
10536: 	for(j=1;j<=nlstate;j++)
10537: 	  for(k=1;k<=ncovcombmax;k++)
10538: 	    mobaverages[i][j][k]=0.;
10539:       mobaverage=mobaverages;
10540:       if (mobilav!=0) {
10541: 	if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
10542: 	  fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
10543: 	  printf(" Error in movingaverage mobilav=%d\n",mobilav);
10544: 	}
10545:       }
10546:       /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
10547:       /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
10548:       else if (mobilavproj !=0) {
10549: 	if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
10550: 	  fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
10551: 	  printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
10552: 	}
10553:       }
10554:     }/* end if moving average */
10555:     
10556:     /*---------- Forecasting ------------------*/
10557:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
10558:     if(prevfcast==1){
10559:       /*    if(stepm ==1){*/
10560:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
10561:     }
10562:     if(backcast==1){
10563:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath); 	
10564:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath); 	
10565:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
10566: 
10567:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
10568: 
10569:       bprlim=matrix(1,nlstate,1,nlstate);
10570:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
10571:       fclose(ficresplb);
10572: 
10573:       hBijx(p, bage, fage, mobaverage);
10574:       fclose(ficrespijb);
10575:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
10576: 
10577:       /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
10578: 	 bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
10579:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
10580:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
10581:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
10582:     }
10583:     
10584:  
10585:     /* ------ Other prevalence ratios------------ */
10586: 
10587:     free_ivector(wav,1,imx);
10588:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
10589:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
10590:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
10591: 		
10592: 		
10593:     /*---------- Health expectancies, no variances ------------*/
10594: 		
10595:     strcpy(filerese,"E_");
10596:     strcat(filerese,fileresu);
10597:     if((ficreseij=fopen(filerese,"w"))==NULL) {
10598:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
10599:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
10600:     }
10601:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
10602:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
10603:  		
10604:     for (k=1; k <= (int) pow(2,cptcoveff); k++){ /* For any combination of dummy covariates, fixed and varying */
10605:       fprintf(ficreseij,"\n#****** ");
10606:       for(j=1;j<=cptcoveff;j++) {
10607: 	fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
10608:       }
10609:       fprintf(ficreseij,"******\n");
10610:       
10611:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
10612:       oldm=oldms;savm=savms;
10613:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
10614:       
10615:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
10616:     }
10617:     fclose(ficreseij);
10618:     printf("done evsij\n");fflush(stdout);
10619:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
10620: 		
10621:     /*---------- State-specific expectancies and variances ------------*/
10622: 		
10623: 		
10624:     strcpy(filerest,"T_");
10625:     strcat(filerest,fileresu);
10626:     if((ficrest=fopen(filerest,"w"))==NULL) {
10627:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
10628:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
10629:     }
10630:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
10631:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
10632: 		
10633: 
10634:     strcpy(fileresstde,"STDE_");
10635:     strcat(fileresstde,fileresu);
10636:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
10637:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
10638:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
10639:     }
10640:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
10641:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
10642: 
10643:     strcpy(filerescve,"CVE_");
10644:     strcat(filerescve,fileresu);
10645:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
10646:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
10647:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
10648:     }
10649:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
10650:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
10651: 
10652:     strcpy(fileresv,"V_");
10653:     strcat(fileresv,fileresu);
10654:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
10655:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
10656:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
10657:     }
10658:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
10659:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
10660: 
10661:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
10662:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
10663:           
10664:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
10665:       printf("\n#****** ");
10666:       fprintf(ficrest,"\n#****** ");
10667:       fprintf(ficlog,"\n#****** ");
10668:       for(j=1;j<=cptcoveff;j++){ 
10669: 	printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
10670: 	fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
10671: 	fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
10672:       }
10673:       fprintf(ficrest,"******\n");
10674:       fprintf(ficlog,"******\n");
10675:       printf("******\n");
10676:       
10677:       fprintf(ficresstdeij,"\n#****** ");
10678:       fprintf(ficrescveij,"\n#****** ");
10679:       for(j=1;j<=cptcoveff;j++) {
10680: 	fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
10681: 	fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
10682:       }
10683:       fprintf(ficresstdeij,"******\n");
10684:       fprintf(ficrescveij,"******\n");
10685:       
10686:       fprintf(ficresvij,"\n#****** ");
10687:       for(j=1;j<=cptcoveff;j++) 
10688: 	fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
10689:       fprintf(ficresvij,"******\n");
10690:       
10691:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
10692:       oldm=oldms;savm=savms;
10693:       printf(" cvevsij combination#=%d, ",k);
10694:       fprintf(ficlog, " cvevsij combination#=%d, ",k);
10695:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
10696:       printf(" end cvevsij \n ");
10697:       fprintf(ficlog, " end cvevsij \n ");
10698:       
10699:       /*
10700:        */
10701:       /* goto endfree; */
10702:       
10703:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
10704:       pstamp(ficrest);
10705:       
10706:       
10707:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
10708: 	oldm=oldms;savm=savms; /* ZZ Segmentation fault */
10709: 	cptcod= 0; /* To be deleted */
10710: 	printf("varevsij vpopbased=%d \n",vpopbased);
10711: 	fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
10712: 	varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); /* cptcod not initialized Intel */
10713: 	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 ");
10714: 	if(vpopbased==1)
10715: 	  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);
10716: 	else
10717: 	  fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
10718: 	fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
10719: 	for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
10720: 	fprintf(ficrest,"\n");
10721: 	/* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
10722: 	epj=vector(1,nlstate+1);
10723: 	printf("Computing age specific period (stable) prevalences in each health state \n");
10724: 	fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
10725: 	for(age=bage; age <=fage ;age++){
10726: 	  prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
10727: 	  if (vpopbased==1) {
10728: 	    if(mobilav ==0){
10729: 	      for(i=1; i<=nlstate;i++)
10730: 		prlim[i][i]=probs[(int)age][i][k];
10731: 	    }else{ /* mobilav */ 
10732: 	      for(i=1; i<=nlstate;i++)
10733: 		prlim[i][i]=mobaverage[(int)age][i][k];
10734: 	    }
10735: 	  }
10736: 	  
10737: 	  fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
10738: 	  /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
10739: 	  /* printf(" age %4.0f ",age); */
10740: 	  for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
10741: 	    for(i=1, epj[j]=0.;i <=nlstate;i++) {
10742: 	      epj[j] += prlim[i][i]*eij[i][j][(int)age];
10743: 	      /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
10744: 	      /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
10745: 	    }
10746: 	    epj[nlstate+1] +=epj[j];
10747: 	  }
10748: 	  /* printf(" age %4.0f \n",age); */
10749: 	  
10750: 	  for(i=1, vepp=0.;i <=nlstate;i++)
10751: 	    for(j=1;j <=nlstate;j++)
10752: 	      vepp += vareij[i][j][(int)age];
10753: 	  fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
10754: 	  for(j=1;j <=nlstate;j++){
10755: 	    fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
10756: 	  }
10757: 	  fprintf(ficrest,"\n");
10758: 	}
10759:       } /* End vpopbased */
10760:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
10761:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
10762:       free_vector(epj,1,nlstate+1);
10763:       printf("done \n");fflush(stdout);
10764:       fprintf(ficlog,"done\n");fflush(ficlog);
10765:       
10766:       /*}*/
10767:     } /* End k */
10768: 
10769:     printf("done State-specific expectancies\n");fflush(stdout);
10770:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
10771: 
10772:     /*------- Variance of period (stable) prevalence------*/   
10773:     
10774:     strcpy(fileresvpl,"VPL_");
10775:     strcat(fileresvpl,fileresu);
10776:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
10777:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
10778:       exit(0);
10779:     }
10780:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
10781:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
10782:     
10783:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
10784:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
10785:     
10786:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
10787:       fprintf(ficresvpl,"\n#****** ");
10788:       printf("\n#****** ");
10789:       fprintf(ficlog,"\n#****** ");
10790:       for(j=1;j<=cptcoveff;j++) {
10791: 	fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
10792: 	fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
10793: 	printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
10794:       }
10795:       fprintf(ficresvpl,"******\n");
10796:       printf("******\n");
10797:       fprintf(ficlog,"******\n");
10798:       
10799:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
10800:       oldm=oldms;savm=savms;
10801:       varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
10802:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
10803:       /*}*/
10804:     }
10805:     
10806:     fclose(ficresvpl);
10807:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
10808:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
10809:     
10810:     free_vector(weight,1,n);
10811:     free_imatrix(Tvard,1,NCOVMAX,1,2);
10812:     free_imatrix(s,1,maxwav+1,1,n);
10813:     free_matrix(anint,1,maxwav,1,n); 
10814:     free_matrix(mint,1,maxwav,1,n);
10815:     free_ivector(cod,1,n);
10816:     free_ivector(tab,1,NCOVMAX);
10817:     fclose(ficresstdeij);
10818:     fclose(ficrescveij);
10819:     fclose(ficresvij);
10820:     fclose(ficrest);
10821:     fclose(ficpar);
10822:     
10823:     
10824:     /*---------- End : free ----------------*/
10825:     if (mobilav!=0 ||mobilavproj !=0)
10826:       free_ma3x(mobaverages,1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
10827:     free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
10828:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
10829:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
10830:   }  /* mle==-3 arrives here for freeing */
10831:   /* endfree:*/
10832:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
10833:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
10834:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
10835:   free_ma3x(cotqvar,1,maxwav,1,nqtv,1,n);
10836:   free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,1,n);
10837:   free_matrix(coqvar,1,maxwav,1,n);
10838:   free_matrix(covar,0,NCOVMAX,1,n);
10839:   free_matrix(matcov,1,npar,1,npar);
10840:   free_matrix(hess,1,npar,1,npar);
10841:   /*free_vector(delti,1,npar);*/
10842:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
10843:   free_matrix(agev,1,maxwav,1,imx);
10844:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
10845:   
10846:   free_ivector(ncodemax,1,NCOVMAX);
10847:   free_ivector(ncodemaxwundef,1,NCOVMAX);
10848:   free_ivector(Dummy,-1,NCOVMAX);
10849:   free_ivector(Fixed,-1,NCOVMAX);
10850:   free_ivector(Typevar,-1,NCOVMAX);
10851:   free_ivector(Tvar,1,NCOVMAX);
10852:   free_ivector(TvarFD,1,NCOVMAX);
10853:   free_ivector(TvarFDind,1,NCOVMAX);
10854:   free_ivector(TvarF,1,NCOVMAX);
10855:   free_ivector(TvarFind,1,NCOVMAX);
10856:   free_ivector(TvarV,1,NCOVMAX);
10857:   free_ivector(TvarVind,1,NCOVMAX);
10858:   free_ivector(TvarA,1,NCOVMAX);
10859:   free_ivector(TvarAind,1,NCOVMAX);
10860:   free_ivector(TvarFQ,1,NCOVMAX);
10861:   free_ivector(TvarFQind,1,NCOVMAX);
10862:   free_ivector(TvarVD,1,NCOVMAX);
10863:   free_ivector(TvarVDind,1,NCOVMAX);
10864:   free_ivector(TvarVQ,1,NCOVMAX);
10865:   free_ivector(TvarVQind,1,NCOVMAX);
10866:   free_ivector(Tvarsel,1,NCOVMAX);
10867:   free_vector(Tvalsel,1,NCOVMAX);
10868:   free_ivector(Tposprod,1,NCOVMAX);
10869:   free_ivector(Tprod,1,NCOVMAX);
10870:   free_ivector(Tvaraff,1,NCOVMAX);
10871:   free_ivector(invalidvarcomb,1,ncovcombmax);
10872:   free_ivector(Tage,1,NCOVMAX);
10873:   free_ivector(Tmodelind,1,NCOVMAX);
10874:   free_ivector(TmodelInvind,1,NCOVMAX);
10875:   free_ivector(TmodelInvQind,1,NCOVMAX);
10876:   
10877:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
10878:   /* free_imatrix(codtab,1,100,1,10); */
10879:   fflush(fichtm);
10880:   fflush(ficgp);
10881:   
10882:   
10883:   if((nberr >0) || (nbwarn>0)){
10884:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
10885:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d. Please look at the log file for details.\n",nberr,nbwarn);
10886:   }else{
10887:     printf("End of Imach\n");
10888:     fprintf(ficlog,"End of Imach\n");
10889:   }
10890:   printf("See log file on %s\n",filelog);
10891:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
10892:   /*(void) gettimeofday(&end_time,&tzp);*/
10893:   rend_time = time(NULL);  
10894:   end_time = *localtime(&rend_time);
10895:   /* tml = *localtime(&end_time.tm_sec); */
10896:   strcpy(strtend,asctime(&end_time));
10897:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
10898:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
10899:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
10900:   
10901:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
10902:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
10903:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
10904:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
10905: /*   if(fileappend(fichtm,optionfilehtm)){ */
10906:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
10907:   fclose(fichtm);
10908:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
10909:   fclose(fichtmcov);
10910:   fclose(ficgp);
10911:   fclose(ficlog);
10912:   /*------ End -----------*/
10913:   
10914:   
10915:   printf("Before Current directory %s!\n",pathcd);
10916: #ifdef WIN32
10917:   if (_chdir(pathcd) != 0)
10918:     printf("Can't move to directory %s!\n",path);
10919:   if(_getcwd(pathcd,MAXLINE) > 0)
10920: #else
10921:     if(chdir(pathcd) != 0)
10922:       printf("Can't move to directory %s!\n", path);
10923:   if (getcwd(pathcd, MAXLINE) > 0)
10924: #endif 
10925:     printf("Current directory %s!\n",pathcd);
10926:   /*strcat(plotcmd,CHARSEPARATOR);*/
10927:   sprintf(plotcmd,"gnuplot");
10928: #ifdef _WIN32
10929:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
10930: #endif
10931:   if(!stat(plotcmd,&info)){
10932:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
10933:     if(!stat(getenv("GNUPLOTBIN"),&info)){
10934:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
10935:     }else
10936:       strcpy(pplotcmd,plotcmd);
10937: #ifdef __unix
10938:     strcpy(plotcmd,GNUPLOTPROGRAM);
10939:     if(!stat(plotcmd,&info)){
10940:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
10941:     }else
10942:       strcpy(pplotcmd,plotcmd);
10943: #endif
10944:   }else
10945:     strcpy(pplotcmd,plotcmd);
10946:   
10947:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
10948:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
10949:   
10950:   if((outcmd=system(plotcmd)) != 0){
10951:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
10952:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
10953:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
10954:     if((outcmd=system(plotcmd)) != 0)
10955:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
10956:   }
10957:   printf(" Successful, please wait...");
10958:   while (z[0] != 'q') {
10959:     /* chdir(path); */
10960:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
10961:     scanf("%s",z);
10962: /*     if (z[0] == 'c') system("./imach"); */
10963:     if (z[0] == 'e') {
10964: #ifdef __APPLE__
10965:       sprintf(pplotcmd, "open %s", optionfilehtm);
10966: #elif __linux
10967:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
10968: #else
10969:       sprintf(pplotcmd, "%s", optionfilehtm);
10970: #endif
10971:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
10972:       system(pplotcmd);
10973:     }
10974:     else if (z[0] == 'g') system(plotcmd);
10975:     else if (z[0] == 'q') exit(0);
10976:   }
10977: end:
10978:   while (z[0] != 'q') {
10979:     printf("\nType  q for exiting: "); fflush(stdout);
10980:     scanf("%s",z);
10981:   }
10982: }

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