File:  [Local Repository] / imach / src / imach.c
Revision 1.355: download - view: text, annotated - select for diffs
Mon May 22 17:03:18 2023 UTC (11 months, 3 weeks ago) by brouard
Branches: MAIN
CVS tags: HEAD
Summary: 0.99r46

* imach.c (Module): In the ILK....txt file, the number of columns
before the covariates values is dependent of the number of states (16+nlstate): 0.99r46

    1: /* $Id: imach.c,v 1.355 2023/05/22 17:03:18 brouard Exp $
    2:   $State: Exp $
    3:   $Log: imach.c,v $
    4:   Revision 1.355  2023/05/22 17:03:18  brouard
    5:   Summary: 0.99r46
    6: 
    7:   * imach.c (Module): In the ILK....txt file, the number of columns
    8:   before the covariates values is dependent of the number of states (16+nlstate): 0.99r46
    9: 
   10:   Revision 1.354  2023/05/21 05:05:17  brouard
   11:   Summary: Temporary change for imachprax
   12: 
   13:   Revision 1.353  2023/05/08 18:48:22  brouard
   14:   *** empty log message ***
   15: 
   16:   Revision 1.352  2023/04/29 10:46:21  brouard
   17:   *** empty log message ***
   18: 
   19:   Revision 1.351  2023/04/29 10:43:47  brouard
   20:   Summary: 099r45
   21: 
   22:   Revision 1.350  2023/04/24 11:38:06  brouard
   23:   *** empty log message ***
   24: 
   25:   Revision 1.349  2023/01/31 09:19:37  brouard
   26:   Summary: Improvements in models with age*Vn*Vm
   27: 
   28:   Revision 1.347  2022/09/18 14:36:44  brouard
   29:   Summary: version 0.99r42
   30: 
   31:   Revision 1.346  2022/09/16 13:52:36  brouard
   32:   * src/imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
   33: 
   34:   Revision 1.345  2022/09/16 13:40:11  brouard
   35:   Summary: Version 0.99r41
   36: 
   37:   * imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
   38: 
   39:   Revision 1.344  2022/09/14 19:33:30  brouard
   40:   Summary: version 0.99r40
   41: 
   42:   * imach.c (Module): Fixing names of variables in T_ (thanks to Feinuo)
   43: 
   44:   Revision 1.343  2022/09/14 14:22:16  brouard
   45:   Summary: version 0.99r39
   46: 
   47:   * imach.c (Module): Version 0.99r39 with colored dummy covariates
   48:   (fixed or time varying), using new last columns of
   49:   ILK_parameter.txt file.
   50: 
   51:   Revision 1.342  2022/09/11 19:54:09  brouard
   52:   Summary: 0.99r38
   53: 
   54:   * imach.c (Module): Adding timevarying products of any kinds,
   55:   should work before shifting cotvar from ncovcol+nqv columns in
   56:   order to have a correspondance between the column of cotvar and
   57:   the id of column.
   58:   (Module): Some cleaning and adding covariates in ILK.txt
   59: 
   60:   Revision 1.341  2022/09/11 07:58:42  brouard
   61:   Summary: Version 0.99r38
   62: 
   63:   After adding change in cotvar.
   64: 
   65:   Revision 1.340  2022/09/11 07:53:11  brouard
   66:   Summary: Version imach 0.99r37
   67: 
   68:   * imach.c (Module): Adding timevarying products of any kinds,
   69:   should work before shifting cotvar from ncovcol+nqv columns in
   70:   order to have a correspondance between the column of cotvar and
   71:   the id of column.
   72: 
   73:   Revision 1.339  2022/09/09 17:55:22  brouard
   74:   Summary: version 0.99r37
   75: 
   76:   * imach.c (Module): Many improvements for fixing products of fixed
   77:   timevarying as well as fixed * fixed, and test with quantitative
   78:   covariate.
   79: 
   80:   Revision 1.338  2022/09/04 17:40:33  brouard
   81:   Summary: 0.99r36
   82: 
   83:   * imach.c (Module): Now the easy runs i.e. without result or
   84:   model=1+age only did not work. The defautl combination should be 1
   85:   and not 0 because everything hasn't been tranformed yet.
   86: 
   87:   Revision 1.337  2022/09/02 14:26:02  brouard
   88:   Summary: version 0.99r35
   89: 
   90:   * src/imach.c: Version 0.99r35 because it outputs same results with
   91:   1+age+V1+V1*age for females and 1+age for females only
   92:   (education=1 noweight)
   93: 
   94:   Revision 1.336  2022/08/31 09:52:36  brouard
   95:   *** empty log message ***
   96: 
   97:   Revision 1.335  2022/08/31 08:23:16  brouard
   98:   Summary: improvements...
   99: 
  100:   Revision 1.334  2022/08/25 09:08:41  brouard
  101:   Summary: In progress for quantitative
  102: 
  103:   Revision 1.333  2022/08/21 09:10:30  brouard
  104:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
  105:   reassigning covariates: my first idea was that people will always
  106:   use the first covariate V1 into the model but in fact they are
  107:   producing data with many covariates and can use an equation model
  108:   with some of the covariate; it means that in a model V2+V3 instead
  109:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
  110:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
  111:   the equation model is restricted to two variables only (V2, V3)
  112:   and the combination for V2 should be codtabm(k,1) instead of
  113:   (codtabm(k,2), and the code should be
  114:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
  115:   made. All of these should be simplified once a day like we did in
  116:   hpxij() for example by using precov[nres] which is computed in
  117:   decoderesult for each nres of each resultline. Loop should be done
  118:   on the equation model globally by distinguishing only product with
  119:   age (which are changing with age) and no more on type of
  120:   covariates, single dummies, single covariates.
  121: 
  122:   Revision 1.332  2022/08/21 09:06:25  brouard
  123:   Summary: Version 0.99r33
  124: 
  125:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
  126:   reassigning covariates: my first idea was that people will always
  127:   use the first covariate V1 into the model but in fact they are
  128:   producing data with many covariates and can use an equation model
  129:   with some of the covariate; it means that in a model V2+V3 instead
  130:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
  131:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
  132:   the equation model is restricted to two variables only (V2, V3)
  133:   and the combination for V2 should be codtabm(k,1) instead of
  134:   (codtabm(k,2), and the code should be
  135:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
  136:   made. All of these should be simplified once a day like we did in
  137:   hpxij() for example by using precov[nres] which is computed in
  138:   decoderesult for each nres of each resultline. Loop should be done
  139:   on the equation model globally by distinguishing only product with
  140:   age (which are changing with age) and no more on type of
  141:   covariates, single dummies, single covariates.
  142: 
  143:   Revision 1.331  2022/08/07 05:40:09  brouard
  144:   *** empty log message ***
  145: 
  146:   Revision 1.330  2022/08/06 07:18:25  brouard
  147:   Summary: last 0.99r31
  148: 
  149:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
  150: 
  151:   Revision 1.329  2022/08/03 17:29:54  brouard
  152:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
  153: 
  154:   Revision 1.328  2022/07/27 17:40:48  brouard
  155:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
  156: 
  157:   Revision 1.327  2022/07/27 14:47:35  brouard
  158:   Summary: Still a problem for one-step probabilities in case of quantitative variables
  159: 
  160:   Revision 1.326  2022/07/26 17:33:55  brouard
  161:   Summary: some test with nres=1
  162: 
  163:   Revision 1.325  2022/07/25 14:27:23  brouard
  164:   Summary: r30
  165: 
  166:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
  167:   coredumped, revealed by Feiuno, thank you.
  168: 
  169:   Revision 1.324  2022/07/23 17:44:26  brouard
  170:   *** empty log message ***
  171: 
  172:   Revision 1.323  2022/07/22 12:30:08  brouard
  173:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
  174: 
  175:   Revision 1.322  2022/07/22 12:27:48  brouard
  176:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
  177: 
  178:   Revision 1.321  2022/07/22 12:04:24  brouard
  179:   Summary: r28
  180: 
  181:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
  182: 
  183:   Revision 1.320  2022/06/02 05:10:11  brouard
  184:   *** empty log message ***
  185: 
  186:   Revision 1.319  2022/06/02 04:45:11  brouard
  187:   * imach.c (Module): Adding the Wald tests from the log to the main
  188:   htm for better display of the maximum likelihood estimators.
  189: 
  190:   Revision 1.318  2022/05/24 08:10:59  brouard
  191:   * imach.c (Module): Some attempts to find a bug of wrong estimates
  192:   of confidencce intervals with product in the equation modelC
  193: 
  194:   Revision 1.317  2022/05/15 15:06:23  brouard
  195:   * imach.c (Module):  Some minor improvements
  196: 
  197:   Revision 1.316  2022/05/11 15:11:31  brouard
  198:   Summary: r27
  199: 
  200:   Revision 1.315  2022/05/11 15:06:32  brouard
  201:   *** empty log message ***
  202: 
  203:   Revision 1.314  2022/04/13 17:43:09  brouard
  204:   * imach.c (Module): Adding link to text data files
  205: 
  206:   Revision 1.313  2022/04/11 15:57:42  brouard
  207:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
  208: 
  209:   Revision 1.312  2022/04/05 21:24:39  brouard
  210:   *** empty log message ***
  211: 
  212:   Revision 1.311  2022/04/05 21:03:51  brouard
  213:   Summary: Fixed quantitative covariates
  214: 
  215:   	  Fixed covariates (dummy or quantitative)
  216:   	with missing values have never been allowed but are ERRORS and
  217:   	program quits. Standard deviations of fixed covariates were
  218:   	wrongly computed. Mean and standard deviations of time varying
  219:   	covariates are still not computed.
  220: 
  221:   Revision 1.310  2022/03/17 08:45:53  brouard
  222:   Summary: 99r25
  223: 
  224:   Improving detection of errors: result lines should be compatible with
  225:   the model.
  226: 
  227:   Revision 1.309  2021/05/20 12:39:14  brouard
  228:   Summary: Version 0.99r24
  229: 
  230:   Revision 1.308  2021/03/31 13:11:57  brouard
  231:   Summary: Version 0.99r23
  232: 
  233: 
  234:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
  235: 
  236:   Revision 1.307  2021/03/08 18:11:32  brouard
  237:   Summary: 0.99r22 fixed bug on result:
  238: 
  239:   Revision 1.306  2021/02/20 15:44:02  brouard
  240:   Summary: Version 0.99r21
  241: 
  242:   * imach.c (Module): Fix bug on quitting after result lines!
  243:   (Module): Version 0.99r21
  244: 
  245:   Revision 1.305  2021/02/20 15:28:30  brouard
  246:   * imach.c (Module): Fix bug on quitting after result lines!
  247: 
  248:   Revision 1.304  2021/02/12 11:34:20  brouard
  249:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
  250: 
  251:   Revision 1.303  2021/02/11 19:50:15  brouard
  252:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
  253: 
  254:   Revision 1.302  2020/02/22 21:00:05  brouard
  255:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
  256:   and life table from the data without any state)
  257: 
  258:   Revision 1.301  2019/06/04 13:51:20  brouard
  259:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
  260: 
  261:   Revision 1.300  2019/05/22 19:09:45  brouard
  262:   Summary: version 0.99r19 of May 2019
  263: 
  264:   Revision 1.299  2019/05/22 18:37:08  brouard
  265:   Summary: Cleaned 0.99r19
  266: 
  267:   Revision 1.298  2019/05/22 18:19:56  brouard
  268:   *** empty log message ***
  269: 
  270:   Revision 1.297  2019/05/22 17:56:10  brouard
  271:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
  272: 
  273:   Revision 1.296  2019/05/20 13:03:18  brouard
  274:   Summary: Projection syntax simplified
  275: 
  276: 
  277:   We can now start projections, forward or backward, from the mean date
  278:   of inteviews up to or down to a number of years of projection:
  279:   prevforecast=1 yearsfproj=15.3 mobil_average=0
  280:   or
  281:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
  282:   or
  283:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
  284:   or
  285:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
  286: 
  287:   Revision 1.295  2019/05/18 09:52:50  brouard
  288:   Summary: doxygen tex bug
  289: 
  290:   Revision 1.294  2019/05/16 14:54:33  brouard
  291:   Summary: There was some wrong lines added
  292: 
  293:   Revision 1.293  2019/05/09 15:17:34  brouard
  294:   *** empty log message ***
  295: 
  296:   Revision 1.292  2019/05/09 14:17:20  brouard
  297:   Summary: Some updates
  298: 
  299:   Revision 1.291  2019/05/09 13:44:18  brouard
  300:   Summary: Before ncovmax
  301: 
  302:   Revision 1.290  2019/05/09 13:39:37  brouard
  303:   Summary: 0.99r18 unlimited number of individuals
  304: 
  305:   The number n which was limited to 20,000 cases is now unlimited, from firstobs to lastobs. If the number is too for the virtual memory, probably an error will occur.
  306: 
  307:   Revision 1.289  2018/12/13 09:16:26  brouard
  308:   Summary: Bug for young ages (<-30) will be in r17
  309: 
  310:   Revision 1.288  2018/05/02 20:58:27  brouard
  311:   Summary: Some bugs fixed
  312: 
  313:   Revision 1.287  2018/05/01 17:57:25  brouard
  314:   Summary: Bug fixed by providing frequencies only for non missing covariates
  315: 
  316:   Revision 1.286  2018/04/27 14:27:04  brouard
  317:   Summary: some minor bugs
  318: 
  319:   Revision 1.285  2018/04/21 21:02:16  brouard
  320:   Summary: Some bugs fixed, valgrind tested
  321: 
  322:   Revision 1.284  2018/04/20 05:22:13  brouard
  323:   Summary: Computing mean and stdeviation of fixed quantitative variables
  324: 
  325:   Revision 1.283  2018/04/19 14:49:16  brouard
  326:   Summary: Some minor bugs fixed
  327: 
  328:   Revision 1.282  2018/02/27 22:50:02  brouard
  329:   *** empty log message ***
  330: 
  331:   Revision 1.281  2018/02/27 19:25:23  brouard
  332:   Summary: Adding second argument for quitting
  333: 
  334:   Revision 1.280  2018/02/21 07:58:13  brouard
  335:   Summary: 0.99r15
  336: 
  337:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
  338: 
  339:   Revision 1.279  2017/07/20 13:35:01  brouard
  340:   Summary: temporary working
  341: 
  342:   Revision 1.278  2017/07/19 14:09:02  brouard
  343:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
  344: 
  345:   Revision 1.277  2017/07/17 08:53:49  brouard
  346:   Summary: BOM files can be read now
  347: 
  348:   Revision 1.276  2017/06/30 15:48:31  brouard
  349:   Summary: Graphs improvements
  350: 
  351:   Revision 1.275  2017/06/30 13:39:33  brouard
  352:   Summary: Saito's color
  353: 
  354:   Revision 1.274  2017/06/29 09:47:08  brouard
  355:   Summary: Version 0.99r14
  356: 
  357:   Revision 1.273  2017/06/27 11:06:02  brouard
  358:   Summary: More documentation on projections
  359: 
  360:   Revision 1.272  2017/06/27 10:22:40  brouard
  361:   Summary: Color of backprojection changed from 6 to 5(yellow)
  362: 
  363:   Revision 1.271  2017/06/27 10:17:50  brouard
  364:   Summary: Some bug with rint
  365: 
  366:   Revision 1.270  2017/05/24 05:45:29  brouard
  367:   *** empty log message ***
  368: 
  369:   Revision 1.269  2017/05/23 08:39:25  brouard
  370:   Summary: Code into subroutine, cleanings
  371: 
  372:   Revision 1.268  2017/05/18 20:09:32  brouard
  373:   Summary: backprojection and confidence intervals of backprevalence
  374: 
  375:   Revision 1.267  2017/05/13 10:25:05  brouard
  376:   Summary: temporary save for backprojection
  377: 
  378:   Revision 1.266  2017/05/13 07:26:12  brouard
  379:   Summary: Version 0.99r13 (improvements and bugs fixed)
  380: 
  381:   Revision 1.265  2017/04/26 16:22:11  brouard
  382:   Summary: imach 0.99r13 Some bugs fixed
  383: 
  384:   Revision 1.264  2017/04/26 06:01:29  brouard
  385:   Summary: Labels in graphs
  386: 
  387:   Revision 1.263  2017/04/24 15:23:15  brouard
  388:   Summary: to save
  389: 
  390:   Revision 1.262  2017/04/18 16:48:12  brouard
  391:   *** empty log message ***
  392: 
  393:   Revision 1.261  2017/04/05 10:14:09  brouard
  394:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
  395: 
  396:   Revision 1.260  2017/04/04 17:46:59  brouard
  397:   Summary: Gnuplot indexations fixed (humm)
  398: 
  399:   Revision 1.259  2017/04/04 13:01:16  brouard
  400:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
  401: 
  402:   Revision 1.258  2017/04/03 10:17:47  brouard
  403:   Summary: Version 0.99r12
  404: 
  405:   Some cleanings, conformed with updated documentation.
  406: 
  407:   Revision 1.257  2017/03/29 16:53:30  brouard
  408:   Summary: Temp
  409: 
  410:   Revision 1.256  2017/03/27 05:50:23  brouard
  411:   Summary: Temporary
  412: 
  413:   Revision 1.255  2017/03/08 16:02:28  brouard
  414:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
  415: 
  416:   Revision 1.254  2017/03/08 07:13:00  brouard
  417:   Summary: Fixing data parameter line
  418: 
  419:   Revision 1.253  2016/12/15 11:59:41  brouard
  420:   Summary: 0.99 in progress
  421: 
  422:   Revision 1.252  2016/09/15 21:15:37  brouard
  423:   *** empty log message ***
  424: 
  425:   Revision 1.251  2016/09/15 15:01:13  brouard
  426:   Summary: not working
  427: 
  428:   Revision 1.250  2016/09/08 16:07:27  brouard
  429:   Summary: continue
  430: 
  431:   Revision 1.249  2016/09/07 17:14:18  brouard
  432:   Summary: Starting values from frequencies
  433: 
  434:   Revision 1.248  2016/09/07 14:10:18  brouard
  435:   *** empty log message ***
  436: 
  437:   Revision 1.247  2016/09/02 11:11:21  brouard
  438:   *** empty log message ***
  439: 
  440:   Revision 1.246  2016/09/02 08:49:22  brouard
  441:   *** empty log message ***
  442: 
  443:   Revision 1.245  2016/09/02 07:25:01  brouard
  444:   *** empty log message ***
  445: 
  446:   Revision 1.244  2016/09/02 07:17:34  brouard
  447:   *** empty log message ***
  448: 
  449:   Revision 1.243  2016/09/02 06:45:35  brouard
  450:   *** empty log message ***
  451: 
  452:   Revision 1.242  2016/08/30 15:01:20  brouard
  453:   Summary: Fixing a lots
  454: 
  455:   Revision 1.241  2016/08/29 17:17:25  brouard
  456:   Summary: gnuplot problem in Back projection to fix
  457: 
  458:   Revision 1.240  2016/08/29 07:53:18  brouard
  459:   Summary: Better
  460: 
  461:   Revision 1.239  2016/08/26 15:51:03  brouard
  462:   Summary: Improvement in Powell output in order to copy and paste
  463: 
  464:   Author:
  465: 
  466:   Revision 1.238  2016/08/26 14:23:35  brouard
  467:   Summary: Starting tests of 0.99
  468: 
  469:   Revision 1.237  2016/08/26 09:20:19  brouard
  470:   Summary: to valgrind
  471: 
  472:   Revision 1.236  2016/08/25 10:50:18  brouard
  473:   *** empty log message ***
  474: 
  475:   Revision 1.235  2016/08/25 06:59:23  brouard
  476:   *** empty log message ***
  477: 
  478:   Revision 1.234  2016/08/23 16:51:20  brouard
  479:   *** empty log message ***
  480: 
  481:   Revision 1.233  2016/08/23 07:40:50  brouard
  482:   Summary: not working
  483: 
  484:   Revision 1.232  2016/08/22 14:20:21  brouard
  485:   Summary: not working
  486: 
  487:   Revision 1.231  2016/08/22 07:17:15  brouard
  488:   Summary: not working
  489: 
  490:   Revision 1.230  2016/08/22 06:55:53  brouard
  491:   Summary: Not working
  492: 
  493:   Revision 1.229  2016/07/23 09:45:53  brouard
  494:   Summary: Completing for func too
  495: 
  496:   Revision 1.228  2016/07/22 17:45:30  brouard
  497:   Summary: Fixing some arrays, still debugging
  498: 
  499:   Revision 1.226  2016/07/12 18:42:34  brouard
  500:   Summary: temp
  501: 
  502:   Revision 1.225  2016/07/12 08:40:03  brouard
  503:   Summary: saving but not running
  504: 
  505:   Revision 1.224  2016/07/01 13:16:01  brouard
  506:   Summary: Fixes
  507: 
  508:   Revision 1.223  2016/02/19 09:23:35  brouard
  509:   Summary: temporary
  510: 
  511:   Revision 1.222  2016/02/17 08:14:50  brouard
  512:   Summary: Probably last 0.98 stable version 0.98r6
  513: 
  514:   Revision 1.221  2016/02/15 23:35:36  brouard
  515:   Summary: minor bug
  516: 
  517:   Revision 1.219  2016/02/15 00:48:12  brouard
  518:   *** empty log message ***
  519: 
  520:   Revision 1.218  2016/02/12 11:29:23  brouard
  521:   Summary: 0.99 Back projections
  522: 
  523:   Revision 1.217  2015/12/23 17:18:31  brouard
  524:   Summary: Experimental backcast
  525: 
  526:   Revision 1.216  2015/12/18 17:32:11  brouard
  527:   Summary: 0.98r4 Warning and status=-2
  528: 
  529:   Version 0.98r4 is now:
  530:    - displaying an error when status is -1, date of interview unknown and date of death known;
  531:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
  532:   Older changes concerning s=-2, dating from 2005 have been supersed.
  533: 
  534:   Revision 1.215  2015/12/16 08:52:24  brouard
  535:   Summary: 0.98r4 working
  536: 
  537:   Revision 1.214  2015/12/16 06:57:54  brouard
  538:   Summary: temporary not working
  539: 
  540:   Revision 1.213  2015/12/11 18:22:17  brouard
  541:   Summary: 0.98r4
  542: 
  543:   Revision 1.212  2015/11/21 12:47:24  brouard
  544:   Summary: minor typo
  545: 
  546:   Revision 1.211  2015/11/21 12:41:11  brouard
  547:   Summary: 0.98r3 with some graph of projected cross-sectional
  548: 
  549:   Author: Nicolas Brouard
  550: 
  551:   Revision 1.210  2015/11/18 17:41:20  brouard
  552:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
  553:   Summary: Adding ftolpl parameter
  554:   Author: N Brouard
  555: 
  556:   We had difficulties to get smoothed confidence intervals. It was due
  557:   to the period prevalence which wasn't computed accurately. The inner
  558:   parameter ftolpl is now an outer parameter of the .imach parameter
  559:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
  560:   computation are long.
  561: 
  562:   Revision 1.208  2015/11/17 14:31:57  brouard
  563:   Summary: temporary
  564: 
  565:   Revision 1.207  2015/10/27 17:36:57  brouard
  566:   *** empty log message ***
  567: 
  568:   Revision 1.206  2015/10/24 07:14:11  brouard
  569:   *** empty log message ***
  570: 
  571:   Revision 1.205  2015/10/23 15:50:53  brouard
  572:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
  573: 
  574:   Revision 1.204  2015/10/01 16:20:26  brouard
  575:   Summary: Some new graphs of contribution to likelihood
  576: 
  577:   Revision 1.203  2015/09/30 17:45:14  brouard
  578:   Summary: looking at better estimation of the hessian
  579: 
  580:   Also a better criteria for convergence to the period prevalence And
  581:   therefore adding the number of years needed to converge. (The
  582:   prevalence in any alive state shold sum to one
  583: 
  584:   Revision 1.202  2015/09/22 19:45:16  brouard
  585:   Summary: Adding some overall graph on contribution to likelihood. Might change
  586: 
  587:   Revision 1.201  2015/09/15 17:34:58  brouard
  588:   Summary: 0.98r0
  589: 
  590:   - Some new graphs like suvival functions
  591:   - Some bugs fixed like model=1+age+V2.
  592: 
  593:   Revision 1.200  2015/09/09 16:53:55  brouard
  594:   Summary: Big bug thanks to Flavia
  595: 
  596:   Even model=1+age+V2. did not work anymore
  597: 
  598:   Revision 1.199  2015/09/07 14:09:23  brouard
  599:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
  600: 
  601:   Revision 1.198  2015/09/03 07:14:39  brouard
  602:   Summary: 0.98q5 Flavia
  603: 
  604:   Revision 1.197  2015/09/01 18:24:39  brouard
  605:   *** empty log message ***
  606: 
  607:   Revision 1.196  2015/08/18 23:17:52  brouard
  608:   Summary: 0.98q5
  609: 
  610:   Revision 1.195  2015/08/18 16:28:39  brouard
  611:   Summary: Adding a hack for testing purpose
  612: 
  613:   After reading the title, ftol and model lines, if the comment line has
  614:   a q, starting with #q, the answer at the end of the run is quit. It
  615:   permits to run test files in batch with ctest. The former workaround was
  616:   $ echo q | imach foo.imach
  617: 
  618:   Revision 1.194  2015/08/18 13:32:00  brouard
  619:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
  620: 
  621:   Revision 1.193  2015/08/04 07:17:42  brouard
  622:   Summary: 0.98q4
  623: 
  624:   Revision 1.192  2015/07/16 16:49:02  brouard
  625:   Summary: Fixing some outputs
  626: 
  627:   Revision 1.191  2015/07/14 10:00:33  brouard
  628:   Summary: Some fixes
  629: 
  630:   Revision 1.190  2015/05/05 08:51:13  brouard
  631:   Summary: Adding digits in output parameters (7 digits instead of 6)
  632: 
  633:   Fix 1+age+.
  634: 
  635:   Revision 1.189  2015/04/30 14:45:16  brouard
  636:   Summary: 0.98q2
  637: 
  638:   Revision 1.188  2015/04/30 08:27:53  brouard
  639:   *** empty log message ***
  640: 
  641:   Revision 1.187  2015/04/29 09:11:15  brouard
  642:   *** empty log message ***
  643: 
  644:   Revision 1.186  2015/04/23 12:01:52  brouard
  645:   Summary: V1*age is working now, version 0.98q1
  646: 
  647:   Some codes had been disabled in order to simplify and Vn*age was
  648:   working in the optimization phase, ie, giving correct MLE parameters,
  649:   but, as usual, outputs were not correct and program core dumped.
  650: 
  651:   Revision 1.185  2015/03/11 13:26:42  brouard
  652:   Summary: Inclusion of compile and links command line for Intel Compiler
  653: 
  654:   Revision 1.184  2015/03/11 11:52:39  brouard
  655:   Summary: Back from Windows 8. Intel Compiler
  656: 
  657:   Revision 1.183  2015/03/10 20:34:32  brouard
  658:   Summary: 0.98q0, trying with directest, mnbrak fixed
  659: 
  660:   We use directest instead of original Powell test; probably no
  661:   incidence on the results, but better justifications;
  662:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
  663:   wrong results.
  664: 
  665:   Revision 1.182  2015/02/12 08:19:57  brouard
  666:   Summary: Trying to keep directest which seems simpler and more general
  667:   Author: Nicolas Brouard
  668: 
  669:   Revision 1.181  2015/02/11 23:22:24  brouard
  670:   Summary: Comments on Powell added
  671: 
  672:   Author:
  673: 
  674:   Revision 1.180  2015/02/11 17:33:45  brouard
  675:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
  676: 
  677:   Revision 1.179  2015/01/04 09:57:06  brouard
  678:   Summary: back to OS/X
  679: 
  680:   Revision 1.178  2015/01/04 09:35:48  brouard
  681:   *** empty log message ***
  682: 
  683:   Revision 1.177  2015/01/03 18:40:56  brouard
  684:   Summary: Still testing ilc32 on OSX
  685: 
  686:   Revision 1.176  2015/01/03 16:45:04  brouard
  687:   *** empty log message ***
  688: 
  689:   Revision 1.175  2015/01/03 16:33:42  brouard
  690:   *** empty log message ***
  691: 
  692:   Revision 1.174  2015/01/03 16:15:49  brouard
  693:   Summary: Still in cross-compilation
  694: 
  695:   Revision 1.173  2015/01/03 12:06:26  brouard
  696:   Summary: trying to detect cross-compilation
  697: 
  698:   Revision 1.172  2014/12/27 12:07:47  brouard
  699:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
  700: 
  701:   Revision 1.171  2014/12/23 13:26:59  brouard
  702:   Summary: Back from Visual C
  703: 
  704:   Still problem with utsname.h on Windows
  705: 
  706:   Revision 1.170  2014/12/23 11:17:12  brouard
  707:   Summary: Cleaning some \%% back to %%
  708: 
  709:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
  710: 
  711:   Revision 1.169  2014/12/22 23:08:31  brouard
  712:   Summary: 0.98p
  713: 
  714:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
  715: 
  716:   Revision 1.168  2014/12/22 15:17:42  brouard
  717:   Summary: update
  718: 
  719:   Revision 1.167  2014/12/22 13:50:56  brouard
  720:   Summary: Testing uname and compiler version and if compiled 32 or 64
  721: 
  722:   Testing on Linux 64
  723: 
  724:   Revision 1.166  2014/12/22 11:40:47  brouard
  725:   *** empty log message ***
  726: 
  727:   Revision 1.165  2014/12/16 11:20:36  brouard
  728:   Summary: After compiling on Visual C
  729: 
  730:   * imach.c (Module): Merging 1.61 to 1.162
  731: 
  732:   Revision 1.164  2014/12/16 10:52:11  brouard
  733:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
  734: 
  735:   * imach.c (Module): Merging 1.61 to 1.162
  736: 
  737:   Revision 1.163  2014/12/16 10:30:11  brouard
  738:   * imach.c (Module): Merging 1.61 to 1.162
  739: 
  740:   Revision 1.162  2014/09/25 11:43:39  brouard
  741:   Summary: temporary backup 0.99!
  742: 
  743:   Revision 1.1  2014/09/16 11:06:58  brouard
  744:   Summary: With some code (wrong) for nlopt
  745: 
  746:   Author:
  747: 
  748:   Revision 1.161  2014/09/15 20:41:41  brouard
  749:   Summary: Problem with macro SQR on Intel compiler
  750: 
  751:   Revision 1.160  2014/09/02 09:24:05  brouard
  752:   *** empty log message ***
  753: 
  754:   Revision 1.159  2014/09/01 10:34:10  brouard
  755:   Summary: WIN32
  756:   Author: Brouard
  757: 
  758:   Revision 1.158  2014/08/27 17:11:51  brouard
  759:   *** empty log message ***
  760: 
  761:   Revision 1.157  2014/08/27 16:26:55  brouard
  762:   Summary: Preparing windows Visual studio version
  763:   Author: Brouard
  764: 
  765:   In order to compile on Visual studio, time.h is now correct and time_t
  766:   and tm struct should be used. difftime should be used but sometimes I
  767:   just make the differences in raw time format (time(&now).
  768:   Trying to suppress #ifdef LINUX
  769:   Add xdg-open for __linux in order to open default browser.
  770: 
  771:   Revision 1.156  2014/08/25 20:10:10  brouard
  772:   *** empty log message ***
  773: 
  774:   Revision 1.155  2014/08/25 18:32:34  brouard
  775:   Summary: New compile, minor changes
  776:   Author: Brouard
  777: 
  778:   Revision 1.154  2014/06/20 17:32:08  brouard
  779:   Summary: Outputs now all graphs of convergence to period prevalence
  780: 
  781:   Revision 1.153  2014/06/20 16:45:46  brouard
  782:   Summary: If 3 live state, convergence to period prevalence on same graph
  783:   Author: Brouard
  784: 
  785:   Revision 1.152  2014/06/18 17:54:09  brouard
  786:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
  787: 
  788:   Revision 1.151  2014/06/18 16:43:30  brouard
  789:   *** empty log message ***
  790: 
  791:   Revision 1.150  2014/06/18 16:42:35  brouard
  792:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
  793:   Author: brouard
  794: 
  795:   Revision 1.149  2014/06/18 15:51:14  brouard
  796:   Summary: Some fixes in parameter files errors
  797:   Author: Nicolas Brouard
  798: 
  799:   Revision 1.148  2014/06/17 17:38:48  brouard
  800:   Summary: Nothing new
  801:   Author: Brouard
  802: 
  803:   Just a new packaging for OS/X version 0.98nS
  804: 
  805:   Revision 1.147  2014/06/16 10:33:11  brouard
  806:   *** empty log message ***
  807: 
  808:   Revision 1.146  2014/06/16 10:20:28  brouard
  809:   Summary: Merge
  810:   Author: Brouard
  811: 
  812:   Merge, before building revised version.
  813: 
  814:   Revision 1.145  2014/06/10 21:23:15  brouard
  815:   Summary: Debugging with valgrind
  816:   Author: Nicolas Brouard
  817: 
  818:   Lot of changes in order to output the results with some covariates
  819:   After the Edimburgh REVES conference 2014, it seems mandatory to
  820:   improve the code.
  821:   No more memory valgrind error but a lot has to be done in order to
  822:   continue the work of splitting the code into subroutines.
  823:   Also, decodemodel has been improved. Tricode is still not
  824:   optimal. nbcode should be improved. Documentation has been added in
  825:   the source code.
  826: 
  827:   Revision 1.143  2014/01/26 09:45:38  brouard
  828:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
  829: 
  830:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  831:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
  832: 
  833:   Revision 1.142  2014/01/26 03:57:36  brouard
  834:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
  835: 
  836:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  837: 
  838:   Revision 1.141  2014/01/26 02:42:01  brouard
  839:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  840: 
  841:   Revision 1.140  2011/09/02 10:37:54  brouard
  842:   Summary: times.h is ok with mingw32 now.
  843: 
  844:   Revision 1.139  2010/06/14 07:50:17  brouard
  845:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
  846:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
  847: 
  848:   Revision 1.138  2010/04/30 18:19:40  brouard
  849:   *** empty log message ***
  850: 
  851:   Revision 1.137  2010/04/29 18:11:38  brouard
  852:   (Module): Checking covariates for more complex models
  853:   than V1+V2. A lot of change to be done. Unstable.
  854: 
  855:   Revision 1.136  2010/04/26 20:30:53  brouard
  856:   (Module): merging some libgsl code. Fixing computation
  857:   of likelione (using inter/intrapolation if mle = 0) in order to
  858:   get same likelihood as if mle=1.
  859:   Some cleaning of code and comments added.
  860: 
  861:   Revision 1.135  2009/10/29 15:33:14  brouard
  862:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  863: 
  864:   Revision 1.134  2009/10/29 13:18:53  brouard
  865:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  866: 
  867:   Revision 1.133  2009/07/06 10:21:25  brouard
  868:   just nforces
  869: 
  870:   Revision 1.132  2009/07/06 08:22:05  brouard
  871:   Many tings
  872: 
  873:   Revision 1.131  2009/06/20 16:22:47  brouard
  874:   Some dimensions resccaled
  875: 
  876:   Revision 1.130  2009/05/26 06:44:34  brouard
  877:   (Module): Max Covariate is now set to 20 instead of 8. A
  878:   lot of cleaning with variables initialized to 0. Trying to make
  879:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
  880: 
  881:   Revision 1.129  2007/08/31 13:49:27  lievre
  882:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
  883: 
  884:   Revision 1.128  2006/06/30 13:02:05  brouard
  885:   (Module): Clarifications on computing e.j
  886: 
  887:   Revision 1.127  2006/04/28 18:11:50  brouard
  888:   (Module): Yes the sum of survivors was wrong since
  889:   imach-114 because nhstepm was no more computed in the age
  890:   loop. Now we define nhstepma in the age loop.
  891:   (Module): In order to speed up (in case of numerous covariates) we
  892:   compute health expectancies (without variances) in a first step
  893:   and then all the health expectancies with variances or standard
  894:   deviation (needs data from the Hessian matrices) which slows the
  895:   computation.
  896:   In the future we should be able to stop the program is only health
  897:   expectancies and graph are needed without standard deviations.
  898: 
  899:   Revision 1.126  2006/04/28 17:23:28  brouard
  900:   (Module): Yes the sum of survivors was wrong since
  901:   imach-114 because nhstepm was no more computed in the age
  902:   loop. Now we define nhstepma in the age loop.
  903:   Version 0.98h
  904: 
  905:   Revision 1.125  2006/04/04 15:20:31  lievre
  906:   Errors in calculation of health expectancies. Age was not initialized.
  907:   Forecasting file added.
  908: 
  909:   Revision 1.124  2006/03/22 17:13:53  lievre
  910:   Parameters are printed with %lf instead of %f (more numbers after the comma).
  911:   The log-likelihood is printed in the log file
  912: 
  913:   Revision 1.123  2006/03/20 10:52:43  brouard
  914:   * imach.c (Module): <title> changed, corresponds to .htm file
  915:   name. <head> headers where missing.
  916: 
  917:   * imach.c (Module): Weights can have a decimal point as for
  918:   English (a comma might work with a correct LC_NUMERIC environment,
  919:   otherwise the weight is truncated).
  920:   Modification of warning when the covariates values are not 0 or
  921:   1.
  922:   Version 0.98g
  923: 
  924:   Revision 1.122  2006/03/20 09:45:41  brouard
  925:   (Module): Weights can have a decimal point as for
  926:   English (a comma might work with a correct LC_NUMERIC environment,
  927:   otherwise the weight is truncated).
  928:   Modification of warning when the covariates values are not 0 or
  929:   1.
  930:   Version 0.98g
  931: 
  932:   Revision 1.121  2006/03/16 17:45:01  lievre
  933:   * imach.c (Module): Comments concerning covariates added
  934: 
  935:   * imach.c (Module): refinements in the computation of lli if
  936:   status=-2 in order to have more reliable computation if stepm is
  937:   not 1 month. Version 0.98f
  938: 
  939:   Revision 1.120  2006/03/16 15:10:38  lievre
  940:   (Module): refinements in the computation of lli if
  941:   status=-2 in order to have more reliable computation if stepm is
  942:   not 1 month. Version 0.98f
  943: 
  944:   Revision 1.119  2006/03/15 17:42:26  brouard
  945:   (Module): Bug if status = -2, the loglikelihood was
  946:   computed as likelihood omitting the logarithm. Version O.98e
  947: 
  948:   Revision 1.118  2006/03/14 18:20:07  brouard
  949:   (Module): varevsij Comments added explaining the second
  950:   table of variances if popbased=1 .
  951:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  952:   (Module): Function pstamp added
  953:   (Module): Version 0.98d
  954: 
  955:   Revision 1.117  2006/03/14 17:16:22  brouard
  956:   (Module): varevsij Comments added explaining the second
  957:   table of variances if popbased=1 .
  958:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  959:   (Module): Function pstamp added
  960:   (Module): Version 0.98d
  961: 
  962:   Revision 1.116  2006/03/06 10:29:27  brouard
  963:   (Module): Variance-covariance wrong links and
  964:   varian-covariance of ej. is needed (Saito).
  965: 
  966:   Revision 1.115  2006/02/27 12:17:45  brouard
  967:   (Module): One freematrix added in mlikeli! 0.98c
  968: 
  969:   Revision 1.114  2006/02/26 12:57:58  brouard
  970:   (Module): Some improvements in processing parameter
  971:   filename with strsep.
  972: 
  973:   Revision 1.113  2006/02/24 14:20:24  brouard
  974:   (Module): Memory leaks checks with valgrind and:
  975:   datafile was not closed, some imatrix were not freed and on matrix
  976:   allocation too.
  977: 
  978:   Revision 1.112  2006/01/30 09:55:26  brouard
  979:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
  980: 
  981:   Revision 1.111  2006/01/25 20:38:18  brouard
  982:   (Module): Lots of cleaning and bugs added (Gompertz)
  983:   (Module): Comments can be added in data file. Missing date values
  984:   can be a simple dot '.'.
  985: 
  986:   Revision 1.110  2006/01/25 00:51:50  brouard
  987:   (Module): Lots of cleaning and bugs added (Gompertz)
  988: 
  989:   Revision 1.109  2006/01/24 19:37:15  brouard
  990:   (Module): Comments (lines starting with a #) are allowed in data.
  991: 
  992:   Revision 1.108  2006/01/19 18:05:42  lievre
  993:   Gnuplot problem appeared...
  994:   To be fixed
  995: 
  996:   Revision 1.107  2006/01/19 16:20:37  brouard
  997:   Test existence of gnuplot in imach path
  998: 
  999:   Revision 1.106  2006/01/19 13:24:36  brouard
 1000:   Some cleaning and links added in html output
 1001: 
 1002:   Revision 1.105  2006/01/05 20:23:19  lievre
 1003:   *** empty log message ***
 1004: 
 1005:   Revision 1.104  2005/09/30 16:11:43  lievre
 1006:   (Module): sump fixed, loop imx fixed, and simplifications.
 1007:   (Module): If the status is missing at the last wave but we know
 1008:   that the person is alive, then we can code his/her status as -2
 1009:   (instead of missing=-1 in earlier versions) and his/her
 1010:   contributions to the likelihood is 1 - Prob of dying from last
 1011:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
 1012:   the healthy state at last known wave). Version is 0.98
 1013: 
 1014:   Revision 1.103  2005/09/30 15:54:49  lievre
 1015:   (Module): sump fixed, loop imx fixed, and simplifications.
 1016: 
 1017:   Revision 1.102  2004/09/15 17:31:30  brouard
 1018:   Add the possibility to read data file including tab characters.
 1019: 
 1020:   Revision 1.101  2004/09/15 10:38:38  brouard
 1021:   Fix on curr_time
 1022: 
 1023:   Revision 1.100  2004/07/12 18:29:06  brouard
 1024:   Add version for Mac OS X. Just define UNIX in Makefile
 1025: 
 1026:   Revision 1.99  2004/06/05 08:57:40  brouard
 1027:   *** empty log message ***
 1028: 
 1029:   Revision 1.98  2004/05/16 15:05:56  brouard
 1030:   New version 0.97 . First attempt to estimate force of mortality
 1031:   directly from the data i.e. without the need of knowing the health
 1032:   state at each age, but using a Gompertz model: log u =a + b*age .
 1033:   This is the basic analysis of mortality and should be done before any
 1034:   other analysis, in order to test if the mortality estimated from the
 1035:   cross-longitudinal survey is different from the mortality estimated
 1036:   from other sources like vital statistic data.
 1037: 
 1038:   The same imach parameter file can be used but the option for mle should be -3.
 1039: 
 1040:   Agnès, who wrote this part of the code, tried to keep most of the
 1041:   former routines in order to include the new code within the former code.
 1042: 
 1043:   The output is very simple: only an estimate of the intercept and of
 1044:   the slope with 95% confident intervals.
 1045: 
 1046:   Current limitations:
 1047:   A) Even if you enter covariates, i.e. with the
 1048:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
 1049:   B) There is no computation of Life Expectancy nor Life Table.
 1050: 
 1051:   Revision 1.97  2004/02/20 13:25:42  lievre
 1052:   Version 0.96d. Population forecasting command line is (temporarily)
 1053:   suppressed.
 1054: 
 1055:   Revision 1.96  2003/07/15 15:38:55  brouard
 1056:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
 1057:   rewritten within the same printf. Workaround: many printfs.
 1058: 
 1059:   Revision 1.95  2003/07/08 07:54:34  brouard
 1060:   * imach.c (Repository):
 1061:   (Repository): Using imachwizard code to output a more meaningful covariance
 1062:   matrix (cov(a12,c31) instead of numbers.
 1063: 
 1064:   Revision 1.94  2003/06/27 13:00:02  brouard
 1065:   Just cleaning
 1066: 
 1067:   Revision 1.93  2003/06/25 16:33:55  brouard
 1068:   (Module): On windows (cygwin) function asctime_r doesn't
 1069:   exist so I changed back to asctime which exists.
 1070:   (Module): Version 0.96b
 1071: 
 1072:   Revision 1.92  2003/06/25 16:30:45  brouard
 1073:   (Module): On windows (cygwin) function asctime_r doesn't
 1074:   exist so I changed back to asctime which exists.
 1075: 
 1076:   Revision 1.91  2003/06/25 15:30:29  brouard
 1077:   * imach.c (Repository): Duplicated warning errors corrected.
 1078:   (Repository): Elapsed time after each iteration is now output. It
 1079:   helps to forecast when convergence will be reached. Elapsed time
 1080:   is stamped in powell.  We created a new html file for the graphs
 1081:   concerning matrix of covariance. It has extension -cov.htm.
 1082: 
 1083:   Revision 1.90  2003/06/24 12:34:15  brouard
 1084:   (Module): Some bugs corrected for windows. Also, when
 1085:   mle=-1 a template is output in file "or"mypar.txt with the design
 1086:   of the covariance matrix to be input.
 1087: 
 1088:   Revision 1.89  2003/06/24 12:30:52  brouard
 1089:   (Module): Some bugs corrected for windows. Also, when
 1090:   mle=-1 a template is output in file "or"mypar.txt with the design
 1091:   of the covariance matrix to be input.
 1092: 
 1093:   Revision 1.88  2003/06/23 17:54:56  brouard
 1094:   * 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.
 1095: 
 1096:   Revision 1.87  2003/06/18 12:26:01  brouard
 1097:   Version 0.96
 1098: 
 1099:   Revision 1.86  2003/06/17 20:04:08  brouard
 1100:   (Module): Change position of html and gnuplot routines and added
 1101:   routine fileappend.
 1102: 
 1103:   Revision 1.85  2003/06/17 13:12:43  brouard
 1104:   * imach.c (Repository): Check when date of death was earlier that
 1105:   current date of interview. It may happen when the death was just
 1106:   prior to the death. In this case, dh was negative and likelihood
 1107:   was wrong (infinity). We still send an "Error" but patch by
 1108:   assuming that the date of death was just one stepm after the
 1109:   interview.
 1110:   (Repository): Because some people have very long ID (first column)
 1111:   we changed int to long in num[] and we added a new lvector for
 1112:   memory allocation. But we also truncated to 8 characters (left
 1113:   truncation)
 1114:   (Repository): No more line truncation errors.
 1115: 
 1116:   Revision 1.84  2003/06/13 21:44:43  brouard
 1117:   * imach.c (Repository): Replace "freqsummary" at a correct
 1118:   place. It differs from routine "prevalence" which may be called
 1119:   many times. Probs is memory consuming and must be used with
 1120:   parcimony.
 1121:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
 1122: 
 1123:   Revision 1.83  2003/06/10 13:39:11  lievre
 1124:   *** empty log message ***
 1125: 
 1126:   Revision 1.82  2003/06/05 15:57:20  brouard
 1127:   Add log in  imach.c and  fullversion number is now printed.
 1128: 
 1129: */
 1130: /*
 1131:    Interpolated Markov Chain
 1132: 
 1133:   Short summary of the programme:
 1134:   
 1135:   This program computes Healthy Life Expectancies or State-specific
 1136:   (if states aren't health statuses) Expectancies from
 1137:   cross-longitudinal data. Cross-longitudinal data consist in: 
 1138: 
 1139:   -1- a first survey ("cross") where individuals from different ages
 1140:   are interviewed on their health status or degree of disability (in
 1141:   the case of a health survey which is our main interest)
 1142: 
 1143:   -2- at least a second wave of interviews ("longitudinal") which
 1144:   measure each change (if any) in individual health status.  Health
 1145:   expectancies are computed from the time spent in each health state
 1146:   according to a model. More health states you consider, more time is
 1147:   necessary to reach the Maximum Likelihood of the parameters involved
 1148:   in the model.  The simplest model is the multinomial logistic model
 1149:   where pij is the probability to be observed in state j at the second
 1150:   wave conditional to be observed in state i at the first
 1151:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
 1152:   etc , where 'age' is age and 'sex' is a covariate. If you want to
 1153:   have a more complex model than "constant and age", you should modify
 1154:   the program where the markup *Covariates have to be included here
 1155:   again* invites you to do it.  More covariates you add, slower the
 1156:   convergence.
 1157: 
 1158:   The advantage of this computer programme, compared to a simple
 1159:   multinomial logistic model, is clear when the delay between waves is not
 1160:   identical for each individual. Also, if a individual missed an
 1161:   intermediate interview, the information is lost, but taken into
 1162:   account using an interpolation or extrapolation.  
 1163: 
 1164:   hPijx is the probability to be observed in state i at age x+h
 1165:   conditional to the observed state i at age x. The delay 'h' can be
 1166:   split into an exact number (nh*stepm) of unobserved intermediate
 1167:   states. This elementary transition (by month, quarter,
 1168:   semester or year) is modelled as a multinomial logistic.  The hPx
 1169:   matrix is simply the matrix product of nh*stepm elementary matrices
 1170:   and the contribution of each individual to the likelihood is simply
 1171:   hPijx.
 1172: 
 1173:   Also this programme outputs the covariance matrix of the parameters but also
 1174:   of the life expectancies. It also computes the period (stable) prevalence.
 1175: 
 1176: Back prevalence and projections:
 1177: 
 1178:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
 1179:    double agemaxpar, double ftolpl, int *ncvyearp, double
 1180:    dateprev1,double dateprev2, int firstpass, int lastpass, int
 1181:    mobilavproj)
 1182: 
 1183:     Computes the back prevalence limit for any combination of
 1184:     covariate values k at any age between ageminpar and agemaxpar and
 1185:     returns it in **bprlim. In the loops,
 1186: 
 1187:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
 1188:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
 1189: 
 1190:    - hBijx Back Probability to be in state i at age x-h being in j at x
 1191:    Computes for any combination of covariates k and any age between bage and fage 
 1192:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 1193:  			oldm=oldms;savm=savms;
 1194: 
 1195:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
 1196:      Computes the transition matrix starting at age 'age' over
 1197:      'nhstepm*hstepm*stepm' months (i.e. until
 1198:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
 1199:      nhstepm*hstepm matrices. 
 1200: 
 1201:      Returns p3mat[i][j][h] after calling
 1202:      p3mat[i][j][h]=matprod2(newm,
 1203:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
 1204:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
 1205:      oldm);
 1206: 
 1207: Important routines
 1208: 
 1209: - func (or funcone), computes logit (pij) distinguishing
 1210:   o fixed variables (single or product dummies or quantitative);
 1211:   o varying variables by:
 1212:    (1) wave (single, product dummies, quantitative), 
 1213:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
 1214:        % fixed dummy (treated) or quantitative (not done because time-consuming);
 1215:        % varying dummy (not done) or quantitative (not done);
 1216: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
 1217:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
 1218: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
 1219:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
 1220:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
 1221: 
 1222: 
 1223:   
 1224:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
 1225:            Institut national d'études démographiques, Paris.
 1226:   This software have been partly granted by Euro-REVES, a concerted action
 1227:   from the European Union.
 1228:   It is copyrighted identically to a GNU software product, ie programme and
 1229:   software can be distributed freely for non commercial use. Latest version
 1230:   can be accessed at http://euroreves.ined.fr/imach .
 1231: 
 1232:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
 1233:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
 1234:   
 1235:   **********************************************************************/
 1236: /*
 1237:   main
 1238:   read parameterfile
 1239:   read datafile
 1240:   concatwav
 1241:   freqsummary
 1242:   if (mle >= 1)
 1243:     mlikeli
 1244:   print results files
 1245:   if mle==1 
 1246:      computes hessian
 1247:   read end of parameter file: agemin, agemax, bage, fage, estepm
 1248:       begin-prev-date,...
 1249:   open gnuplot file
 1250:   open html file
 1251:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
 1252:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
 1253:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
 1254:     freexexit2 possible for memory heap.
 1255: 
 1256:   h Pij x                         | pij_nom  ficrestpij
 1257:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
 1258:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
 1259:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
 1260: 
 1261:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
 1262:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
 1263:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
 1264:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
 1265:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
 1266: 
 1267:   forecasting if prevfcast==1 prevforecast call prevalence()
 1268:   health expectancies
 1269:   Variance-covariance of DFLE
 1270:   prevalence()
 1271:    movingaverage()
 1272:   varevsij() 
 1273:   if popbased==1 varevsij(,popbased)
 1274:   total life expectancies
 1275:   Variance of period (stable) prevalence
 1276:  end
 1277: */
 1278: 
 1279: /* #define DEBUG */
 1280: /* #define DEBUGBRENT */
 1281: /* #define DEBUGLINMIN */
 1282: /* #define DEBUGHESS */
 1283: #define DEBUGHESSIJ
 1284: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
 1285: #define POWELL /* Instead of NLOPT */
 1286: #define POWELLNOF3INFF1TEST /* Skip test */
 1287: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
 1288: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
 1289: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
 1290: 
 1291: #include <math.h>
 1292: #include <stdio.h>
 1293: #include <stdlib.h>
 1294: #include <string.h>
 1295: #include <ctype.h>
 1296: 
 1297: #ifdef _WIN32
 1298: #include <io.h>
 1299: #include <windows.h>
 1300: #include <tchar.h>
 1301: #else
 1302: #include <unistd.h>
 1303: #endif
 1304: 
 1305: #include <limits.h>
 1306: #include <sys/types.h>
 1307: 
 1308: #if defined(__GNUC__)
 1309: #include <sys/utsname.h> /* Doesn't work on Windows */
 1310: #endif
 1311: 
 1312: #include <sys/stat.h>
 1313: #include <errno.h>
 1314: /* extern int errno; */
 1315: 
 1316: /* #ifdef LINUX */
 1317: /* #include <time.h> */
 1318: /* #include "timeval.h" */
 1319: /* #else */
 1320: /* #include <sys/time.h> */
 1321: /* #endif */
 1322: 
 1323: #include <time.h>
 1324: 
 1325: #ifdef GSL
 1326: #include <gsl/gsl_errno.h>
 1327: #include <gsl/gsl_multimin.h>
 1328: #endif
 1329: 
 1330: 
 1331: #ifdef NLOPT
 1332: #include <nlopt.h>
 1333: typedef struct {
 1334:   double (* function)(double [] );
 1335: } myfunc_data ;
 1336: #endif
 1337: 
 1338: /* #include <libintl.h> */
 1339: /* #define _(String) gettext (String) */
 1340: 
 1341: #define MAXLINE 16384 /* Was 256 and 1024 and 2048. Overflow with 312 with 2 states and 4 covariates. Should be ok */
 1342: 
 1343: #define GNUPLOTPROGRAM "gnuplot"
 1344: #define GNUPLOTVERSION 5.1
 1345: double gnuplotversion=GNUPLOTVERSION;
 1346: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
 1347: #define FILENAMELENGTH 256
 1348: 
 1349: #define	GLOCK_ERROR_NOPATH		-1	/* empty path */
 1350: #define	GLOCK_ERROR_GETCWD		-2	/* cannot get cwd */
 1351: 
 1352: #define MAXPARM 216 /**< Maximum number of parameters for the optimization was 128 */
 1353: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
 1354: 
 1355: #define NINTERVMAX 8
 1356: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
 1357: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
 1358: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
 1359: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
 1360: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
 1361: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
 1362: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
 1363: #define YEARM 12. /**< Number of months per year */
 1364: /* #define AGESUP 130 */
 1365: /* #define AGESUP 150 */
 1366: #define AGESUP 200
 1367: #define AGEINF 0
 1368: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
 1369: #define AGEBASE 40
 1370: #define AGEOVERFLOW 1.e20
 1371: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
 1372: #ifdef _WIN32
 1373: #define DIRSEPARATOR '\\'
 1374: #define CHARSEPARATOR "\\"
 1375: #define ODIRSEPARATOR '/'
 1376: #else
 1377: #define DIRSEPARATOR '/'
 1378: #define CHARSEPARATOR "/"
 1379: #define ODIRSEPARATOR '\\'
 1380: #endif
 1381: 
 1382: /* $Id: imach.c,v 1.355 2023/05/22 17:03:18 brouard Exp $ */
 1383: /* $State: Exp $ */
 1384: #include "version.h"
 1385: char version[]=__IMACH_VERSION__;
 1386: char copyright[]="April 2023,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015-2020, Nihon University 2021-202, INED 2000-2022";
 1387: char fullversion[]="$Revision: 1.355 $ $Date: 2023/05/22 17:03:18 $"; 
 1388: char strstart[80];
 1389: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
 1390: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
 1391: int debugILK=0; /* debugILK is set by a #d in a comment line */
 1392: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
 1393: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
 1394: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
 1395: int cptcovn=0; /**< cptcovn decodemodel: number of covariates k of the models excluding age*products =6 and age*age but including products */
 1396: int cptcovt=0; /**< cptcovt: total number of covariates of the model (2) nbocc(+)+1 = 8 excepting constant and age and age*age */
 1397: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
 1398: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
 1399: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
 1400: int cptcovprodage=0; /**< Number of fixed covariates with age: V3*age or V2*V3*age 1 */
 1401: int cptcovprodvage=0; /**< Number of varying covariates with age: V7*age or V7*V6*age */
 1402: int cptcovdageprod=0; /**< Number of doubleproducts with age, since 0.99r44 only: age*Vn*Vm for gnuplot printing*/
 1403: int cptcovprodnoage=0; /**< Number of covariate products without age */   
 1404: int cptcoveff=0; /* Total number of single dummy covariates (fixed or time varying) to vary for printing results (2**cptcoveff combinations of dummies)(computed in tricode as cptcov) */
 1405: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
 1406: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
 1407: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
 1408: int ncovvta=0; /*  +age*V6 + age*V7+ age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 Total number of expandend products [with age]) in the model */
 1409: int ncovta=0; /*age*V3*V2 +age*V2+agev3+ageV4  +age*V6 + age*V7+ age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 Total number of expandend products [with age]) in the model */
 1410: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (single or product, dummy or quantitative) in the model */
 1411: int ncovva=0; /* +age*V6 + age*V7+ge*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 Total number of effective (wave and stepm) varying with age covariates (single or product, dummy or quantitative) in the model */
 1412: int nsd=0; /**< Total number of single dummy variables (output) */
 1413: int nsq=0; /**< Total number of single quantitative variables (output) */
 1414: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
 1415: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
 1416: int ntveff=0; /**< ntveff number of effective time varying variables */
 1417: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
 1418: int cptcov=0; /* Working variable */
 1419: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
 1420: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
 1421: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
 1422: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
 1423: int nlstate=2; /* Number of live states */
 1424: int ndeath=1; /* Number of dead states */
 1425: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
 1426: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
 1427: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
 1428: int popbased=0;
 1429: 
 1430: int *wav; /* Number of waves for this individuual 0 is possible */
 1431: int maxwav=0; /* Maxim number of waves */
 1432: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
 1433: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
 1434: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
 1435: 		   to the likelihood and the sum of weights (done by funcone)*/
 1436: int mle=1, weightopt=0;
 1437: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
 1438: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
 1439: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
 1440: 	   * wave mi and wave mi+1 is not an exact multiple of stepm. */
 1441: int countcallfunc=0;  /* Count the number of calls to func */
 1442: int selected(int kvar); /* Is covariate kvar selected for printing results */
 1443: 
 1444: double jmean=1; /* Mean space between 2 waves */
 1445: double **matprod2(); /* test */
 1446: double **oldm, **newm, **savm; /* Working pointers to matrices */
 1447: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
 1448: double	 **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
 1449: 
 1450: /*FILE *fic ; */ /* Used in readdata only */
 1451: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
 1452: FILE *ficlog, *ficrespow;
 1453: int globpr=0; /* Global variable for printing or not */
 1454: double fretone; /* Only one call to likelihood */
 1455: long ipmx=0; /* Number of contributions */
 1456: double sw; /* Sum of weights */
 1457: char filerespow[FILENAMELENGTH];
 1458: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
 1459: FILE *ficresilk;
 1460: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
 1461: FILE *ficresprobmorprev;
 1462: FILE *fichtm, *fichtmcov; /* Html File */
 1463: FILE *ficreseij;
 1464: char filerese[FILENAMELENGTH];
 1465: FILE *ficresstdeij;
 1466: char fileresstde[FILENAMELENGTH];
 1467: FILE *ficrescveij;
 1468: char filerescve[FILENAMELENGTH];
 1469: FILE  *ficresvij;
 1470: char fileresv[FILENAMELENGTH];
 1471: 
 1472: char title[MAXLINE];
 1473: char model[MAXLINE]; /**< The model line */
 1474: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
 1475: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
 1476: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
 1477: char command[FILENAMELENGTH];
 1478: int  outcmd=0;
 1479: 
 1480: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
 1481: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
 1482: char filelog[FILENAMELENGTH]; /* Log file */
 1483: char filerest[FILENAMELENGTH];
 1484: char fileregp[FILENAMELENGTH];
 1485: char popfile[FILENAMELENGTH];
 1486: 
 1487: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
 1488: 
 1489: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
 1490: /* struct timezone tzp; */
 1491: /* extern int gettimeofday(); */
 1492: struct tm tml, *gmtime(), *localtime();
 1493: 
 1494: extern time_t time();
 1495: 
 1496: struct tm start_time, end_time, curr_time, last_time, forecast_time;
 1497: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
 1498: time_t   rlast_btime; /* raw time */
 1499: struct tm tm;
 1500: 
 1501: char strcurr[80], strfor[80];
 1502: 
 1503: char *endptr;
 1504: long lval;
 1505: double dval;
 1506: 
 1507: #define NR_END 1
 1508: #define FREE_ARG char*
 1509: #define FTOL 1.0e-10
 1510: 
 1511: #define NRANSI 
 1512: #define ITMAX 200
 1513: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
 1514: 
 1515: #define TOL 2.0e-4 
 1516: 
 1517: #define CGOLD 0.3819660 
 1518: #define ZEPS 1.0e-10 
 1519: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
 1520: 
 1521: #define GOLD 1.618034 
 1522: #define GLIMIT 100.0 
 1523: #define TINY 1.0e-20 
 1524: 
 1525: static double maxarg1,maxarg2;
 1526: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
 1527: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
 1528:   
 1529: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
 1530: #define rint(a) floor(a+0.5)
 1531: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
 1532: #define mytinydouble 1.0e-16
 1533: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
 1534: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
 1535: /* static double dsqrarg; */
 1536: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
 1537: static double sqrarg;
 1538: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
 1539: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
 1540: int agegomp= AGEGOMP;
 1541: 
 1542: int imx; 
 1543: int stepm=1;
 1544: /* Stepm, step in month: minimum step interpolation*/
 1545: 
 1546: int estepm;
 1547: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
 1548: 
 1549: int m,nb;
 1550: long *num;
 1551: int firstpass=0, lastpass=4,*cod, *cens;
 1552: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
 1553: 		   covariate for which somebody answered excluding 
 1554: 		   undefined. Usually 2: 0 and 1. */
 1555: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
 1556: 			     covariate for which somebody answered including 
 1557: 			     undefined. Usually 3: -1, 0 and 1. */
 1558: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
 1559: double **pmmij, ***probs; /* Global pointer */
 1560: double ***mobaverage, ***mobaverages; /* New global variable */
 1561: double **precov; /* New global variable to store for each resultline, values of model covariates given by the resultlines (in order to speed up)  */
 1562: double *ageexmed,*agecens;
 1563: double dateintmean=0;
 1564:   double anprojd, mprojd, jprojd; /* For eventual projections */
 1565:   double anprojf, mprojf, jprojf;
 1566: 
 1567:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
 1568:   double anbackf, mbackf, jbackf;
 1569:   double jintmean,mintmean,aintmean;  
 1570: double *weight;
 1571: int **s; /* Status */
 1572: double *agedc;
 1573: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
 1574: 		  * covar=matrix(0,NCOVMAX,1,n); 
 1575: 		  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
 1576: double **coqvar; /* Fixed quantitative covariate nqv */
 1577: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
 1578: double ***cotqvar; /* Time varying quantitative covariate itqv */
 1579: double  idx; 
 1580: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
 1581: /* Some documentation */
 1582:       /*   Design original data
 1583:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
 1584:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
 1585:        *                                                             ntv=3     nqtv=1
 1586:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
 1587:        * For time varying covariate, quanti or dummies
 1588:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
 1589:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
 1590:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
 1591:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
 1592:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
 1593:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
 1594:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
 1595:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
 1596:        */
 1597: /* According to the model, more columns can be added to covar by the product of covariates */
 1598: /* ncovcol=1(Males=0 Females=1) nqv=1(raedyrs) ntv=2(withoutiadl=0 withiadl=1, witoutadl=0 withoutadl=1) nqtv=1(bmi) nlstate=3 ndeath=1
 1599:   # States 1=Coresidence, 2 Living alone, 3 Institution
 1600:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
 1601: */
 1602: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1+V4*V3*age */
 1603: /*    kmodel  1  2   3    4     5     6    7     8     9    10 */
 1604: /*Typevar[k]=  0  0   0   2     1    0    2     1     0    3 *//*0 for simple covariate (dummy, quantitative,*/
 1605:                                                                /* fixed or varying), 1 for age product, 2 for*/
 1606:                                                                /* product without age, 3 for age and double product   */
 1607: /*Dummy[k]=    1  0   0   1     3    1    1     2     0     3  *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
 1608:                                                                 /*(single or product without age), 2 dummy*/
 1609:                                                                /* with age product, 3 quant with age product*/
 1610: /*Tvar[k]=     5  4   3   6     5    2    7     1     1     6 */
 1611: /*    nsd         1   2                               3 */ /* Counting single dummies covar fixed or tv */
 1612: /*TnsdVar[Tvar]   1   2                               3 */ 
 1613: /*Tvaraff[nsd]    4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
 1614: /*TvarsD[nsd]     4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
 1615: /*TvarsDind[nsd]  2   3                               9 */ /* position K of single dummy cova */
 1616: /*    nsq      1                     2                  */ /* Counting single quantit tv */
 1617: /* TvarsQ[k]   5                     2                  */ /* Number of single quantitative cova */
 1618: /* TvarsQind   1                     6                  */ /* position K of single quantitative cova */
 1619: /* Tprod[i]=k             1               2             */ /* Position in model of the ith prod without age */
 1620: /* cptcovage                    1               2         3 */ /* Counting cov*age in the model equation */
 1621: /* Tage[cptcovage]=k            5               8         10 */ /* Position in the model of ith cov*age */
 1622: /* model="V2+V3+V4+V6+V7+V6*V2+V7*V2+V6*V3+V7*V3+V6*V4+V7*V4+age*V2+age*V3+age*V4+age*V6+age*V7+age*V6*V2+age*V6*V3+age*V7*V3+age*V6*V4+age*V7*V4\r"*/
 1623: /*  p Tvard[1][1]@21 = {6, 2, 7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0}*/
 1624: /*  p Tvard[2][1]@21 = {7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0 <repeats 11 times>} */
 1625: /* p Tvardk[1][1]@24 = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 2, 7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0, 0}*/
 1626: /* p Tvardk[1][1]@22 = {0, 0, 0, 0, 0, 0, 0, 0, 6, 2, 7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0, 0} */
 1627: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2               */ /* Position in model of the ith prod without age */
 1628: /* Tvardk[4][1]=4;Tvardk[4][2]=3;Tvardk[7][1]=1;Tvardk[7][2]=2 */ /* Variables of a prod at position in the model equation*/
 1629: /* TvarF TvarF[1]=Tvar[6]=2,  TvarF[2]=Tvar[7]=7, TvarF[3]=Tvar[9]=1  ID of fixed covariates or product V2, V1*V2, V1 */
 1630: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
 1631: /* Type                    */
 1632: /* V         1  2  3  4  5 */
 1633: /*           F  F  V  V  V */
 1634: /*           D  Q  D  D  Q */
 1635: /*                         */
 1636: int *TvarsD;
 1637: int *TnsdVar;
 1638: int *TvarsDind;
 1639: int *TvarsQ;
 1640: int *TvarsQind;
 1641: 
 1642: #define MAXRESULTLINESPONE 10+1
 1643: int nresult=0;
 1644: int parameterline=0; /* # of the parameter (type) line */
 1645: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
 1646: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
 1647: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
 1648: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
 1649: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
 1650: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
 1651: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
 1652: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
 1653: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
 1654: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
 1655: 
 1656: /* ncovcol=1(Males=0 Females=1) nqv=1(raedyrs) ntv=2(withoutiadl=0 withiadl=1, witoutadl=0 withoutadl=1) nqtv=1(bmi) nlstate=3 ndeath=1
 1657:   # States 1=Coresidence, 2 Living alone, 3 Institution
 1658:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
 1659: */
 1660: /* int *TDvar; /\**< TDvar[1]=4,  TDvarF[2]=3, TDvar[3]=6  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
 1661: 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 */
 1662: 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 */
 1663: 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 */
 1664: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1665: 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 */
 1666: int *TvarAind; /**< TvarindA[1]=5, TvarAind[2]=8  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1667: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1668: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1669: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
 1670: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
 1671: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
 1672: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
 1673: 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 */
 1674: 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 */
 1675: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
 1676: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
 1677: int *TvarVVA; /* We count ncovvt time varying covariates (single or products with age) and put their name into TvarVVA */
 1678: int *TvarVVAind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
 1679: int *TvarAVVA; /* We count ALL ncovta time varying covariates (single or products with age) and put their name into TvarVVA */
 1680: int *TvarAVVAind; /* We count ALL ncovta time varying covariates (single or products without age) and put their name into TvarVV */
 1681:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
 1682:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age */
 1683:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
 1684:       /* TvarVV={3,1,3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */	       
 1685:       /* TvarVVind={2,5,5,6,6}, for V3 and then the product V1*V3 is decomposed into V1 and V3 and V1*V3*age into 6,6 */	       
 1686: int *Tvarsel; /**< Selected covariates for output */
 1687: double *Tvalsel; /**< Selected modality value of covariate for output */
 1688: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product, 3 age*Vn*Vm */
 1689: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
 1690: 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 */ 
 1691: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
 1692: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
 1693: int *Tage;
 1694: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
 1695: 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*/
 1696: 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*/ 
 1697: 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  */
 1698: int *Ndum; /** Freq of modality (tricode */
 1699: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
 1700: int **Tvard;
 1701: int **Tvardk;
 1702: int *Tprod;/**< Gives the k position of the k1 product */
 1703: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
 1704: int *Tposprod; /**< Gives the k1 product from the k position */
 1705:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
 1706:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
 1707: int cptcovprod, *Tvaraff, *invalidvarcomb;
 1708: double *lsurv, *lpop, *tpop;
 1709: 
 1710: #define FD 1; /* Fixed dummy covariate */
 1711: #define FQ 2; /* Fixed quantitative covariate */
 1712: #define FP 3; /* Fixed product covariate */
 1713: #define FPDD 7; /* Fixed product dummy*dummy covariate */
 1714: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
 1715: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
 1716: #define VD 10; /* Varying dummy covariate */
 1717: #define VQ 11; /* Varying quantitative covariate */
 1718: #define VP 12; /* Varying product covariate */
 1719: #define VPDD 13; /* Varying product dummy*dummy covariate */
 1720: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
 1721: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
 1722: #define APFD 16; /* Age product * fixed dummy covariate */
 1723: #define APFQ 17; /* Age product * fixed quantitative covariate */
 1724: #define APVD 18; /* Age product * varying dummy covariate */
 1725: #define APVQ 19; /* Age product * varying quantitative covariate */
 1726: 
 1727: #define FTYPE 1; /* Fixed covariate */
 1728: #define VTYPE 2; /* Varying covariate (loop in wave) */
 1729: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
 1730: 
 1731: struct kmodel{
 1732: 	int maintype; /* main type */
 1733: 	int subtype; /* subtype */
 1734: };
 1735: struct kmodel modell[NCOVMAX];
 1736: 
 1737: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
 1738: double ftolhess; /**< Tolerance for computing hessian */
 1739: 
 1740: /**************** split *************************/
 1741: static	int split( char *path, char *dirc, char *name, char *ext, char *finame )
 1742: {
 1743:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
 1744:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
 1745:   */ 
 1746:   char	*ss;				/* pointer */
 1747:   int	l1=0, l2=0;				/* length counters */
 1748: 
 1749:   l1 = strlen(path );			/* length of path */
 1750:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
 1751:   ss= strrchr( path, DIRSEPARATOR );		/* find last / */
 1752:   if ( ss == NULL ) {			/* no directory, so determine current directory */
 1753:     strcpy( name, path );		/* we got the fullname name because no directory */
 1754:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
 1755:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
 1756:     /* get current working directory */
 1757:     /*    extern  char* getcwd ( char *buf , int len);*/
 1758: #ifdef WIN32
 1759:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
 1760: #else
 1761: 	if (getcwd(dirc, FILENAME_MAX) == NULL) {
 1762: #endif
 1763:       return( GLOCK_ERROR_GETCWD );
 1764:     }
 1765:     /* got dirc from getcwd*/
 1766:     printf(" DIRC = %s \n",dirc);
 1767:   } else {				/* strip directory from path */
 1768:     ss++;				/* after this, the filename */
 1769:     l2 = strlen( ss );			/* length of filename */
 1770:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
 1771:     strcpy( name, ss );		/* save file name */
 1772:     strncpy( dirc, path, l1 - l2 );	/* now the directory */
 1773:     dirc[l1-l2] = '\0';			/* add zero */
 1774:     printf(" DIRC2 = %s \n",dirc);
 1775:   }
 1776:   /* We add a separator at the end of dirc if not exists */
 1777:   l1 = strlen( dirc );			/* length of directory */
 1778:   if( dirc[l1-1] != DIRSEPARATOR ){
 1779:     dirc[l1] =  DIRSEPARATOR;
 1780:     dirc[l1+1] = 0; 
 1781:     printf(" DIRC3 = %s \n",dirc);
 1782:   }
 1783:   ss = strrchr( name, '.' );		/* find last / */
 1784:   if (ss >0){
 1785:     ss++;
 1786:     strcpy(ext,ss);			/* save extension */
 1787:     l1= strlen( name);
 1788:     l2= strlen(ss)+1;
 1789:     strncpy( finame, name, l1-l2);
 1790:     finame[l1-l2]= 0;
 1791:   }
 1792: 
 1793:   return( 0 );				/* we're done */
 1794: }
 1795: 
 1796: 
 1797: /******************************************/
 1798: 
 1799: void replace_back_to_slash(char *s, char*t)
 1800: {
 1801:   int i;
 1802:   int lg=0;
 1803:   i=0;
 1804:   lg=strlen(t);
 1805:   for(i=0; i<= lg; i++) {
 1806:     (s[i] = t[i]);
 1807:     if (t[i]== '\\') s[i]='/';
 1808:   }
 1809: }
 1810: 
 1811: char *trimbb(char *out, char *in)
 1812: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
 1813:   char *s;
 1814:   s=out;
 1815:   while (*in != '\0'){
 1816:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
 1817:       in++;
 1818:     }
 1819:     *out++ = *in++;
 1820:   }
 1821:   *out='\0';
 1822:   return s;
 1823: }
 1824: 
 1825: char *trimbtab(char *out, char *in)
 1826: { /* Trim  blanks or tabs in line but keeps first blanks if line starts with blanks */
 1827:   char *s;
 1828:   s=out;
 1829:   while (*in != '\0'){
 1830:     while( (*in == ' ' || *in == '\t')){ /* && *(in+1) != '\0'){*/
 1831:       in++;
 1832:     }
 1833:     *out++ = *in++;
 1834:   }
 1835:   *out='\0';
 1836:   return s;
 1837: }
 1838: 
 1839: /* char *substrchaine(char *out, char *in, char *chain) */
 1840: /* { */
 1841: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
 1842: /*   char *s, *t; */
 1843: /*   t=in;s=out; */
 1844: /*   while ((*in != *chain) && (*in != '\0')){ */
 1845: /*     *out++ = *in++; */
 1846: /*   } */
 1847: 
 1848: /*   /\* *in matches *chain *\/ */
 1849: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
 1850: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1851: /*   } */
 1852: /*   in--; chain--; */
 1853: /*   while ( (*in != '\0')){ */
 1854: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1855: /*     *out++ = *in++; */
 1856: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1857: /*   } */
 1858: /*   *out='\0'; */
 1859: /*   out=s; */
 1860: /*   return out; */
 1861: /* } */
 1862: char *substrchaine(char *out, char *in, char *chain)
 1863: {
 1864:   /* Substract chain 'chain' from 'in', return and output 'out' */
 1865:   /* in="V1+V1*age+age*age+V2", chain="+age*age" out="V1+V1*age+V2" */
 1866: 
 1867:   char *strloc;
 1868: 
 1869:   strcpy (out, in);                   /* out="V1+V1*age+age*age+V2" */
 1870:   strloc = strstr(out, chain); /* strloc points to out at "+age*age+V2"  */
 1871:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out); /* strloc=+age*age+V2 chain="+age*age", out="V1+V1*age+age*age+V2" */
 1872:   if(strloc != NULL){ 
 1873:     /* will affect out */ /* strloc+strlen(chain)=|+V2 = "V1+V1*age+age*age|+V2" */ /* Will also work in Unicodek */
 1874:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1); /* move number of bytes corresponding to the length of "+V2" which is 3, plus one is 4 (including the null)*/
 1875:     /* equivalent to strcpy (strloc, strloc +strlen(chain)) if no overlap; Copies from "+V2" to V1+V1*age+ */
 1876:   }
 1877:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);  /* strloc=+V2 chain="+age*age", in="V1+V1*age+age*age+V2", out="V1+V1*age+V2" */
 1878:   return out;
 1879: }
 1880: 
 1881: 
 1882: char *cutl(char *blocc, char *alocc, char *in, char occ)
 1883: {
 1884:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
 1885:      and alocc starts after first occurence of char 'occ' : ex cutl(blocc,alocc,"abcdef2ghi2j",'2')
 1886:      gives alocc="abcdef" and blocc="ghi2j".
 1887:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
 1888:   */
 1889:   char *s, *t;
 1890:   t=in;s=in;
 1891:   while ((*in != occ) && (*in != '\0')){
 1892:     *alocc++ = *in++;
 1893:   }
 1894:   if( *in == occ){
 1895:     *(alocc)='\0';
 1896:     s=++in;
 1897:   }
 1898:  
 1899:   if (s == t) {/* occ not found */
 1900:     *(alocc-(in-s))='\0';
 1901:     in=s;
 1902:   }
 1903:   while ( *in != '\0'){
 1904:     *blocc++ = *in++;
 1905:   }
 1906: 
 1907:   *blocc='\0';
 1908:   return t;
 1909: }
 1910: char *cutv(char *blocc, char *alocc, char *in, char occ)
 1911: {
 1912:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
 1913:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
 1914:      gives blocc="abcdef2ghi" and alocc="j".
 1915:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
 1916:   */
 1917:   char *s, *t;
 1918:   t=in;s=in;
 1919:   while (*in != '\0'){
 1920:     while( *in == occ){
 1921:       *blocc++ = *in++;
 1922:       s=in;
 1923:     }
 1924:     *blocc++ = *in++;
 1925:   }
 1926:   if (s == t) /* occ not found */
 1927:     *(blocc-(in-s))='\0';
 1928:   else
 1929:     *(blocc-(in-s)-1)='\0';
 1930:   in=s;
 1931:   while ( *in != '\0'){
 1932:     *alocc++ = *in++;
 1933:   }
 1934: 
 1935:   *alocc='\0';
 1936:   return s;
 1937: }
 1938: 
 1939: int nbocc(char *s, char occ)
 1940: {
 1941:   int i,j=0;
 1942:   int lg=20;
 1943:   i=0;
 1944:   lg=strlen(s);
 1945:   for(i=0; i<= lg; i++) {
 1946:     if  (s[i] == occ ) j++;
 1947:   }
 1948:   return j;
 1949: }
 1950: 
 1951: int nboccstr(char *textin, char *chain)
 1952: {
 1953:   /* Counts the number of occurence of "chain"  in string textin */
 1954:   /*  in="+V7*V4+age*V2+age*V3+age*V4"  chain="age" */
 1955:   char *strloc;
 1956:   
 1957:   int i,j=0;
 1958: 
 1959:   i=0;
 1960: 
 1961:   strloc=textin; /* strloc points to "^+V7*V4+age+..." in textin */
 1962:   for(;;) {
 1963:     strloc= strstr(strloc,chain); /* strloc points to first character of chain in textin if found. Example strloc points^ to "+V7*V4+^age" in textin  */
 1964:     if(strloc != NULL){
 1965:       strloc = strloc+strlen(chain); /* strloc points to "+V7*V4+age^" in textin */
 1966:       j++;
 1967:     }else
 1968:       break;
 1969:   }
 1970:   return j;
 1971:   
 1972: }
 1973: /* void cutv(char *u,char *v, char*t, char occ) */
 1974: /* { */
 1975: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
 1976: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
 1977: /*      gives u="abcdef2ghi" and v="j" *\/ */
 1978: /*   int i,lg,j,p=0; */
 1979: /*   i=0; */
 1980: /*   lg=strlen(t); */
 1981: /*   for(j=0; j<=lg-1; j++) { */
 1982: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
 1983: /*   } */
 1984: 
 1985: /*   for(j=0; j<p; j++) { */
 1986: /*     (u[j] = t[j]); */
 1987: /*   } */
 1988: /*      u[p]='\0'; */
 1989: 
 1990: /*    for(j=0; j<= lg; j++) { */
 1991: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
 1992: /*   } */
 1993: /* } */
 1994: 
 1995: #ifdef _WIN32
 1996: char * strsep(char **pp, const char *delim)
 1997: {
 1998:   char *p, *q;
 1999:          
 2000:   if ((p = *pp) == NULL)
 2001:     return 0;
 2002:   if ((q = strpbrk (p, delim)) != NULL)
 2003:   {
 2004:     *pp = q + 1;
 2005:     *q = '\0';
 2006:   }
 2007:   else
 2008:     *pp = 0;
 2009:   return p;
 2010: }
 2011: #endif
 2012: 
 2013: /********************** nrerror ********************/
 2014: 
 2015: void nrerror(char error_text[])
 2016: {
 2017:   fprintf(stderr,"ERREUR ...\n");
 2018:   fprintf(stderr,"%s\n",error_text);
 2019:   exit(EXIT_FAILURE);
 2020: }
 2021: /*********************** vector *******************/
 2022: double *vector(int nl, int nh)
 2023: {
 2024:   double *v;
 2025:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
 2026:   if (!v) nrerror("allocation failure in vector");
 2027:   return v-nl+NR_END;
 2028: }
 2029: 
 2030: /************************ free vector ******************/
 2031: void free_vector(double*v, int nl, int nh)
 2032: {
 2033:   free((FREE_ARG)(v+nl-NR_END));
 2034: }
 2035: 
 2036: /************************ivector *******************************/
 2037: int *ivector(long nl,long nh)
 2038: {
 2039:   int *v;
 2040:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
 2041:   if (!v) nrerror("allocation failure in ivector");
 2042:   return v-nl+NR_END;
 2043: }
 2044: 
 2045: /******************free ivector **************************/
 2046: void free_ivector(int *v, long nl, long nh)
 2047: {
 2048:   free((FREE_ARG)(v+nl-NR_END));
 2049: }
 2050: 
 2051: /************************lvector *******************************/
 2052: long *lvector(long nl,long nh)
 2053: {
 2054:   long *v;
 2055:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
 2056:   if (!v) nrerror("allocation failure in ivector");
 2057:   return v-nl+NR_END;
 2058: }
 2059: 
 2060: /******************free lvector **************************/
 2061: void free_lvector(long *v, long nl, long nh)
 2062: {
 2063:   free((FREE_ARG)(v+nl-NR_END));
 2064: }
 2065: 
 2066: /******************* imatrix *******************************/
 2067: int **imatrix(long nrl, long nrh, long ncl, long nch) 
 2068:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
 2069: { 
 2070:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
 2071:   int **m; 
 2072:   
 2073:   /* allocate pointers to rows */ 
 2074:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
 2075:   if (!m) nrerror("allocation failure 1 in matrix()"); 
 2076:   m += NR_END; 
 2077:   m -= nrl; 
 2078:   
 2079:   
 2080:   /* allocate rows and set pointers to them */ 
 2081:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
 2082:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
 2083:   m[nrl] += NR_END; 
 2084:   m[nrl] -= ncl; 
 2085:   
 2086:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
 2087:   
 2088:   /* return pointer to array of pointers to rows */ 
 2089:   return m; 
 2090: } 
 2091: 
 2092: /****************** free_imatrix *************************/
 2093: void free_imatrix(m,nrl,nrh,ncl,nch)
 2094:       int **m;
 2095:       long nch,ncl,nrh,nrl; 
 2096:      /* free an int matrix allocated by imatrix() */ 
 2097: { 
 2098:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
 2099:   free((FREE_ARG) (m+nrl-NR_END)); 
 2100: } 
 2101: 
 2102: /******************* matrix *******************************/
 2103: double **matrix(long nrl, long nrh, long ncl, long nch)
 2104: {
 2105:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
 2106:   double **m;
 2107: 
 2108:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 2109:   if (!m) nrerror("allocation failure 1 in matrix()");
 2110:   m += NR_END;
 2111:   m -= nrl;
 2112: 
 2113:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 2114:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 2115:   m[nrl] += NR_END;
 2116:   m[nrl] -= ncl;
 2117: 
 2118:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 2119:   return m;
 2120:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
 2121: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
 2122: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
 2123:    */
 2124: }
 2125: 
 2126: /*************************free matrix ************************/
 2127: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
 2128: {
 2129:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 2130:   free((FREE_ARG)(m+nrl-NR_END));
 2131: }
 2132: 
 2133: /******************* ma3x *******************************/
 2134: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
 2135: {
 2136:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
 2137:   double ***m;
 2138: 
 2139:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 2140:   if (!m) nrerror("allocation failure 1 in matrix()");
 2141:   m += NR_END;
 2142:   m -= nrl;
 2143: 
 2144:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 2145:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 2146:   m[nrl] += NR_END;
 2147:   m[nrl] -= ncl;
 2148: 
 2149:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 2150: 
 2151:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
 2152:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
 2153:   m[nrl][ncl] += NR_END;
 2154:   m[nrl][ncl] -= nll;
 2155:   for (j=ncl+1; j<=nch; j++) 
 2156:     m[nrl][j]=m[nrl][j-1]+nlay;
 2157:   
 2158:   for (i=nrl+1; i<=nrh; i++) {
 2159:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
 2160:     for (j=ncl+1; j<=nch; j++) 
 2161:       m[i][j]=m[i][j-1]+nlay;
 2162:   }
 2163:   return m; 
 2164:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
 2165:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
 2166:   */
 2167: }
 2168: 
 2169: /*************************free ma3x ************************/
 2170: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
 2171: {
 2172:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
 2173:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 2174:   free((FREE_ARG)(m+nrl-NR_END));
 2175: }
 2176: 
 2177: /*************** function subdirf ***********/
 2178: char *subdirf(char fileres[])
 2179: {
 2180:   /* Caution optionfilefiname is hidden */
 2181:   strcpy(tmpout,optionfilefiname);
 2182:   strcat(tmpout,"/"); /* Add to the right */
 2183:   strcat(tmpout,fileres);
 2184:   return tmpout;
 2185: }
 2186: 
 2187: /*************** function subdirf2 ***********/
 2188: char *subdirf2(char fileres[], char *preop)
 2189: {
 2190:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
 2191:  Errors in subdirf, 2, 3 while printing tmpout is
 2192:  rewritten within the same printf. Workaround: many printfs */
 2193:   /* Caution optionfilefiname is hidden */
 2194:   strcpy(tmpout,optionfilefiname);
 2195:   strcat(tmpout,"/");
 2196:   strcat(tmpout,preop);
 2197:   strcat(tmpout,fileres);
 2198:   return tmpout;
 2199: }
 2200: 
 2201: /*************** function subdirf3 ***********/
 2202: char *subdirf3(char fileres[], char *preop, char *preop2)
 2203: {
 2204:   
 2205:   /* Caution optionfilefiname is hidden */
 2206:   strcpy(tmpout,optionfilefiname);
 2207:   strcat(tmpout,"/");
 2208:   strcat(tmpout,preop);
 2209:   strcat(tmpout,preop2);
 2210:   strcat(tmpout,fileres);
 2211:   return tmpout;
 2212: }
 2213:  
 2214: /*************** function subdirfext ***********/
 2215: char *subdirfext(char fileres[], char *preop, char *postop)
 2216: {
 2217:   
 2218:   strcpy(tmpout,preop);
 2219:   strcat(tmpout,fileres);
 2220:   strcat(tmpout,postop);
 2221:   return tmpout;
 2222: }
 2223: 
 2224: /*************** function subdirfext3 ***********/
 2225: char *subdirfext3(char fileres[], char *preop, char *postop)
 2226: {
 2227:   
 2228:   /* Caution optionfilefiname is hidden */
 2229:   strcpy(tmpout,optionfilefiname);
 2230:   strcat(tmpout,"/");
 2231:   strcat(tmpout,preop);
 2232:   strcat(tmpout,fileres);
 2233:   strcat(tmpout,postop);
 2234:   return tmpout;
 2235: }
 2236:  
 2237: char *asc_diff_time(long time_sec, char ascdiff[])
 2238: {
 2239:   long sec_left, days, hours, minutes;
 2240:   days = (time_sec) / (60*60*24);
 2241:   sec_left = (time_sec) % (60*60*24);
 2242:   hours = (sec_left) / (60*60) ;
 2243:   sec_left = (sec_left) %(60*60);
 2244:   minutes = (sec_left) /60;
 2245:   sec_left = (sec_left) % (60);
 2246:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
 2247:   return ascdiff;
 2248: }
 2249: 
 2250: /***************** f1dim *************************/
 2251: extern int ncom; 
 2252: extern double *pcom,*xicom;
 2253: extern double (*nrfunc)(double []); 
 2254:  
 2255: double f1dim(double x) 
 2256: { 
 2257:   int j; 
 2258:   double f;
 2259:   double *xt; 
 2260:  
 2261:   xt=vector(1,ncom); 
 2262:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
 2263:   f=(*nrfunc)(xt); 
 2264:   free_vector(xt,1,ncom); 
 2265:   return f; 
 2266: } 
 2267: 
 2268: /*****************brent *************************/
 2269: double brent(double ax, double bx, double cx, double (*f)(double), double tol, 	double *xmin) 
 2270: {
 2271:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
 2272:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
 2273:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
 2274:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
 2275:    * returned function value. 
 2276:   */
 2277:   int iter; 
 2278:   double a,b,d,etemp;
 2279:   double fu=0,fv,fw,fx;
 2280:   double ftemp=0.;
 2281:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
 2282:   double e=0.0; 
 2283:  
 2284:   a=(ax < cx ? ax : cx); 
 2285:   b=(ax > cx ? ax : cx); 
 2286:   x=w=v=bx; 
 2287:   fw=fv=fx=(*f)(x); 
 2288:   for (iter=1;iter<=ITMAX;iter++) { 
 2289:     xm=0.5*(a+b); 
 2290:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
 2291:     /*		if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
 2292:     printf(".");fflush(stdout);
 2293:     fprintf(ficlog,".");fflush(ficlog);
 2294: #ifdef DEBUGBRENT
 2295:     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);
 2296:     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);
 2297:     /*		if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
 2298: #endif
 2299:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
 2300:       *xmin=x; 
 2301:       return fx; 
 2302:     } 
 2303:     ftemp=fu;
 2304:     if (fabs(e) > tol1) { 
 2305:       r=(x-w)*(fx-fv); 
 2306:       q=(x-v)*(fx-fw); 
 2307:       p=(x-v)*q-(x-w)*r; 
 2308:       q=2.0*(q-r); 
 2309:       if (q > 0.0) p = -p; 
 2310:       q=fabs(q); 
 2311:       etemp=e; 
 2312:       e=d; 
 2313:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
 2314: 				d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 2315:       else { 
 2316: 				d=p/q; 
 2317: 				u=x+d; 
 2318: 				if (u-a < tol2 || b-u < tol2) 
 2319: 					d=SIGN(tol1,xm-x); 
 2320:       } 
 2321:     } else { 
 2322:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 2323:     } 
 2324:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
 2325:     fu=(*f)(u); 
 2326:     if (fu <= fx) { 
 2327:       if (u >= x) a=x; else b=x; 
 2328:       SHFT(v,w,x,u) 
 2329:       SHFT(fv,fw,fx,fu) 
 2330:     } else { 
 2331:       if (u < x) a=u; else b=u; 
 2332:       if (fu <= fw || w == x) { 
 2333: 				v=w; 
 2334: 				w=u; 
 2335: 				fv=fw; 
 2336: 				fw=fu; 
 2337:       } else if (fu <= fv || v == x || v == w) { 
 2338: 				v=u; 
 2339: 				fv=fu; 
 2340:       } 
 2341:     } 
 2342:   } 
 2343:   nrerror("Too many iterations in brent"); 
 2344:   *xmin=x; 
 2345:   return fx; 
 2346: } 
 2347: 
 2348: /****************** mnbrak ***********************/
 2349: 
 2350: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
 2351: 	    double (*func)(double)) 
 2352: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
 2353: the downhill direction (defined by the function as evaluated at the initial points) and returns
 2354: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
 2355: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
 2356:    */
 2357:   double ulim,u,r,q, dum;
 2358:   double fu; 
 2359: 
 2360:   double scale=10.;
 2361:   int iterscale=0;
 2362: 
 2363:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
 2364:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
 2365: 
 2366: 
 2367:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
 2368:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
 2369:   /*   *bx = *ax - (*ax - *bx)/scale; */
 2370:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
 2371:   /* } */
 2372: 
 2373:   if (*fb > *fa) { 
 2374:     SHFT(dum,*ax,*bx,dum) 
 2375:     SHFT(dum,*fb,*fa,dum) 
 2376:   } 
 2377:   *cx=(*bx)+GOLD*(*bx-*ax); 
 2378:   *fc=(*func)(*cx); 
 2379: #ifdef DEBUG
 2380:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
 2381:   fprintf(ficlog,"mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
 2382: #endif
 2383:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc. If fc=inf it exits and if flat fb=fc it exits too.*/
 2384:     r=(*bx-*ax)*(*fb-*fc); 
 2385:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
 2386:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
 2387:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
 2388:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
 2389:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
 2390:       fu=(*func)(u); 
 2391: #ifdef DEBUG
 2392:       /* f(x)=A(x-u)**2+f(u) */
 2393:       double A, fparabu; 
 2394:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 2395:       fparabu= *fa - A*(*ax-u)*(*ax-u);
 2396:       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);
 2397:       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);
 2398:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
 2399:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
 2400:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
 2401:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
 2402: #endif 
 2403: #ifdef MNBRAKORIGINAL
 2404: #else
 2405: /*       if (fu > *fc) { */
 2406: /* #ifdef DEBUG */
 2407: /*       printf("mnbrak4  fu > fc \n"); */
 2408: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
 2409: /* #endif */
 2410: /* 	/\* 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 *\\/  *\/ */
 2411: /* 	/\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
 2412: /* 	dum=u; /\* Shifting c and u *\/ */
 2413: /* 	u = *cx; */
 2414: /* 	*cx = dum; */
 2415: /* 	dum = fu; */
 2416: /* 	fu = *fc; */
 2417: /* 	*fc =dum; */
 2418: /*       } else { /\* end *\/ */
 2419: /* #ifdef DEBUG */
 2420: /*       printf("mnbrak3  fu < fc \n"); */
 2421: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
 2422: /* #endif */
 2423: /* 	dum=u; /\* Shifting c and u *\/ */
 2424: /* 	u = *cx; */
 2425: /* 	*cx = dum; */
 2426: /* 	dum = fu; */
 2427: /* 	fu = *fc; */
 2428: /* 	*fc =dum; */
 2429: /*       } */
 2430: #ifdef DEBUGMNBRAK
 2431: 		 double A, fparabu; 
 2432:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 2433:      fparabu= *fa - A*(*ax-u)*(*ax-u);
 2434:      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);
 2435:      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);
 2436: #endif
 2437:       dum=u; /* Shifting c and u */
 2438:       u = *cx;
 2439:       *cx = dum;
 2440:       dum = fu;
 2441:       fu = *fc;
 2442:       *fc =dum;
 2443: #endif
 2444:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
 2445: #ifdef DEBUG
 2446:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
 2447:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
 2448: #endif
 2449:       fu=(*func)(u); 
 2450:       if (fu < *fc) { 
 2451: #ifdef DEBUG
 2452: 				printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
 2453: 			  fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
 2454: #endif
 2455: 			  SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
 2456: 				SHFT(*fb,*fc,fu,(*func)(u)) 
 2457: #ifdef DEBUG
 2458: 					printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
 2459: #endif
 2460:       } 
 2461:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
 2462: #ifdef DEBUG
 2463:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
 2464:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
 2465: #endif
 2466:       u=ulim; 
 2467:       fu=(*func)(u); 
 2468:     } else { /* u could be left to b (if r > q parabola has a maximum) */
 2469: #ifdef DEBUG
 2470:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
 2471:       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);
 2472: #endif
 2473:       u=(*cx)+GOLD*(*cx-*bx); 
 2474:       fu=(*func)(u); 
 2475: #ifdef DEBUG
 2476:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
 2477:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
 2478: #endif
 2479:     } /* end tests */
 2480:     SHFT(*ax,*bx,*cx,u) 
 2481:     SHFT(*fa,*fb,*fc,fu) 
 2482: #ifdef DEBUG
 2483:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
 2484:       fprintf(ficlog, "\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
 2485: #endif
 2486:   } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
 2487: } 
 2488: 
 2489: /*************** linmin ************************/
 2490: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
 2491: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
 2492: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
 2493: the value of func at the returned location p . This is actually all accomplished by calling the
 2494: routines mnbrak and brent .*/
 2495: int ncom; 
 2496: double *pcom,*xicom;
 2497: double (*nrfunc)(double []); 
 2498:  
 2499: #ifdef LINMINORIGINAL
 2500: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
 2501: #else
 2502: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
 2503: #endif
 2504: { 
 2505:   double brent(double ax, double bx, double cx, 
 2506: 	       double (*f)(double), double tol, double *xmin); 
 2507:   double f1dim(double x); 
 2508:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
 2509: 	      double *fc, double (*func)(double)); 
 2510:   int j; 
 2511:   double xx,xmin,bx,ax; 
 2512:   double fx,fb,fa;
 2513: 
 2514: #ifdef LINMINORIGINAL
 2515: #else
 2516:   double scale=10., axs, xxs; /* Scale added for infinity */
 2517: #endif
 2518:   
 2519:   ncom=n; 
 2520:   pcom=vector(1,n); 
 2521:   xicom=vector(1,n); 
 2522:   nrfunc=func; 
 2523:   for (j=1;j<=n;j++) { 
 2524:     pcom[j]=p[j]; 
 2525:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
 2526:   } 
 2527: 
 2528: #ifdef LINMINORIGINAL
 2529:   xx=1.;
 2530: #else
 2531:   axs=0.0;
 2532:   xxs=1.;
 2533:   do{
 2534:     xx= xxs;
 2535: #endif
 2536:     ax=0.;
 2537:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
 2538:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
 2539:     /* 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))   */
 2540:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
 2541:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
 2542:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
 2543:     /* 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]]*/
 2544: #ifdef LINMINORIGINAL
 2545: #else
 2546:     if (fx != fx){
 2547: 			xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
 2548: 			printf("|");
 2549: 			fprintf(ficlog,"|");
 2550: #ifdef DEBUGLINMIN
 2551: 			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);
 2552: #endif
 2553:     }
 2554:   }while(fx != fx && xxs > 1.e-5);
 2555: #endif
 2556:   
 2557: #ifdef DEBUGLINMIN
 2558:   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);
 2559:   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);
 2560: #endif
 2561: #ifdef LINMINORIGINAL
 2562: #else
 2563:   if(fb == fx){ /* Flat function in the direction */
 2564:     xmin=xx;
 2565:     *flat=1;
 2566:   }else{
 2567:     *flat=0;
 2568: #endif
 2569: 		/*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
 2570:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
 2571:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
 2572:   /* fmin = f(p[j] + xmin * xi[j]) */
 2573:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
 2574:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
 2575: #ifdef DEBUG
 2576:   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);
 2577:   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);
 2578: #endif
 2579: #ifdef LINMINORIGINAL
 2580: #else
 2581: 			}
 2582: #endif
 2583: #ifdef DEBUGLINMIN
 2584:   printf("linmin end ");
 2585:   fprintf(ficlog,"linmin end ");
 2586: #endif
 2587:   for (j=1;j<=n;j++) { 
 2588: #ifdef LINMINORIGINAL
 2589:     xi[j] *= xmin; 
 2590: #else
 2591: #ifdef DEBUGLINMIN
 2592:     if(xxs <1.0)
 2593:       printf(" before xi[%d]=%12.8f", j,xi[j]);
 2594: #endif
 2595:     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) */
 2596: #ifdef DEBUGLINMIN
 2597:     if(xxs <1.0)
 2598:       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 );
 2599: #endif
 2600: #endif
 2601:     p[j] += xi[j]; /* Parameters values are updated accordingly */
 2602:   } 
 2603: #ifdef DEBUGLINMIN
 2604:   printf("\n");
 2605:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
 2606:   fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
 2607:   for (j=1;j<=n;j++) { 
 2608:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
 2609:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
 2610:     if(j % ncovmodel == 0){
 2611:       printf("\n");
 2612:       fprintf(ficlog,"\n");
 2613:     }
 2614:   }
 2615: #else
 2616: #endif
 2617:   free_vector(xicom,1,n); 
 2618:   free_vector(pcom,1,n); 
 2619: } 
 2620: 
 2621: 
 2622: /*************** powell ************************/
 2623: /*
 2624: Minimization of a function func of n variables. Input consists in an initial starting point
 2625: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
 2626: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
 2627: such that failure to decrease by more than this amount in one iteration signals doneness. On
 2628: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
 2629: function value at p , and iter is the number of iterations taken. The routine linmin is used.
 2630:  */
 2631: #ifdef LINMINORIGINAL
 2632: #else
 2633: 	int *flatdir; /* Function is vanishing in that direction */
 2634: 	int flat=0, flatd=0; /* Function is vanishing in that direction */
 2635: #endif
 2636: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
 2637: 	    double (*func)(double [])) 
 2638: { 
 2639: #ifdef LINMINORIGINAL
 2640:  void linmin(double p[], double xi[], int n, double *fret, 
 2641: 	      double (*func)(double [])); 
 2642: #else 
 2643:  void linmin(double p[], double xi[], int n, double *fret,
 2644: 	     double (*func)(double []),int *flat); 
 2645: #endif
 2646:  int i,ibig,j,jk,k; 
 2647:   double del,t,*pt,*ptt,*xit;
 2648:   double directest;
 2649:   double fp,fptt;
 2650:   double *xits;
 2651:   int niterf, itmp;
 2652:   int Bigter=0, nBigterf=1;
 2653:   
 2654:   pt=vector(1,n); 
 2655:   ptt=vector(1,n); 
 2656:   xit=vector(1,n); 
 2657:   xits=vector(1,n); 
 2658:   *fret=(*func)(p); 
 2659:   for (j=1;j<=n;j++) pt[j]=p[j]; 
 2660:   rcurr_time = time(NULL);
 2661:   fp=(*fret); /* Initialisation */
 2662:   for (*iter=1;;++(*iter)) { 
 2663:     ibig=0; 
 2664:     del=0.0; 
 2665:     rlast_time=rcurr_time;
 2666:     rlast_btime=rcurr_time;
 2667:     /* (void) gettimeofday(&curr_time,&tzp); */
 2668:     rcurr_time = time(NULL);  
 2669:     curr_time = *localtime(&rcurr_time);
 2670:     /* printf("\nPowell iter=%d -2*LL=%.12f gain=%.12f=%.3g %ld sec. %ld sec.",*iter,*fret, fp-*fret,fp-*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout); */
 2671:     /* fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f gain=%.12f=%.3g %ld sec. %ld sec.",*iter,*fret, fp-*fret,fp-*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog); */
 2672:     Bigter=(*iter - *iter % ncovmodel)/ncovmodel +1; /* Big iteration, i.e on ncovmodel cycle */
 2673:     printf("\nPowell iter=%d Big Iter=%d -2*LL=%.12f gain=%.3lg %ld sec. %ld sec.",*iter,Bigter,*fret,fp-*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
 2674:     fprintf(ficlog,"\nPowell iter=%d Big Iter=%d -2*LL=%.12f gain=%.3lg %ld sec. %ld sec.",*iter,Bigter,*fret,fp-*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
 2675:     fprintf(ficrespow,"%d %d %.12f %d",*iter,Bigter, *fret,curr_time.tm_sec-start_time.tm_sec);
 2676:     fp=(*fret); /* From former iteration or initial value */
 2677:     for (i=1;i<=n;i++) {
 2678:       fprintf(ficrespow," %.12lf", p[i]);
 2679:     }
 2680:     fprintf(ficrespow,"\n");fflush(ficrespow);
 2681:     printf("\n#model=  1      +     age ");
 2682:     fprintf(ficlog,"\n#model=  1      +     age ");
 2683:     if(nagesqr==1){
 2684: 	printf("  + age*age  ");
 2685: 	fprintf(ficlog,"  + age*age  ");
 2686:     }
 2687:     for(j=1;j <=ncovmodel-2;j++){
 2688:       if(Typevar[j]==0) {
 2689: 	printf("  +      V%d  ",Tvar[j]);
 2690: 	fprintf(ficlog,"  +      V%d  ",Tvar[j]);
 2691:       }else if(Typevar[j]==1) {
 2692: 	printf("  +    V%d*age ",Tvar[j]);
 2693: 	fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
 2694:       }else if(Typevar[j]==2) {
 2695: 	printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
 2696: 	fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
 2697:       }else if(Typevar[j]==3) {
 2698: 	printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
 2699: 	fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
 2700:       }
 2701:     }
 2702:     printf("\n");
 2703: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
 2704: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
 2705:     fprintf(ficlog,"\n");
 2706:     for(i=1,jk=1; i <=nlstate; i++){
 2707:       for(k=1; k <=(nlstate+ndeath); k++){
 2708: 	if (k != i) {
 2709: 	  printf("%d%d ",i,k);
 2710: 	  fprintf(ficlog,"%d%d ",i,k);
 2711: 	  for(j=1; j <=ncovmodel; j++){
 2712: 	    printf("%12.7f ",p[jk]);
 2713: 	    fprintf(ficlog,"%12.7f ",p[jk]);
 2714: 	    jk++; 
 2715: 	  }
 2716: 	  printf("\n");
 2717: 	  fprintf(ficlog,"\n");
 2718: 	}
 2719:       }
 2720:     }
 2721:     if(*iter <=3 && *iter >1){
 2722:       tml = *localtime(&rcurr_time);
 2723:       strcpy(strcurr,asctime(&tml));
 2724:       rforecast_time=rcurr_time; 
 2725:       itmp = strlen(strcurr);
 2726:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
 2727: 	strcurr[itmp-1]='\0';
 2728:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 2729:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 2730:       for(nBigterf=1;nBigterf<=31;nBigterf+=10){
 2731: 	niterf=nBigterf*ncovmodel;
 2732: 	/* rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time); */
 2733: 	rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
 2734: 	forecast_time = *localtime(&rforecast_time);
 2735: 	strcpy(strfor,asctime(&forecast_time));
 2736: 	itmp = strlen(strfor);
 2737: 	if(strfor[itmp-1]=='\n')
 2738: 	  strfor[itmp-1]='\0';
 2739: 	printf("   - if your program needs %d BIG iterations (%d iterations) to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",nBigterf, niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
 2740: 	fprintf(ficlog,"   - if your program needs %d BIG iterations  (%d iterations) to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",nBigterf, niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
 2741:       }
 2742:     }
 2743:     for (i=1;i<=n;i++) { /* For each direction i */
 2744:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
 2745:       fptt=(*fret); 
 2746: #ifdef DEBUG
 2747:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 2748:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 2749: #endif
 2750:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
 2751:       fprintf(ficlog,"%d",i);fflush(ficlog);
 2752: #ifdef LINMINORIGINAL
 2753:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
 2754: #else
 2755:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
 2756: 			flatdir[i]=flat; /* Function is vanishing in that direction i */
 2757: #endif
 2758: 			/* Outputs are fret(new point p) p is updated and xit rescaled */
 2759:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
 2760: 				/* because that direction will be replaced unless the gain del is small */
 2761: 				/* in comparison with the 'probable' gain, mu^2, with the last average direction. */
 2762: 				/* Unless the n directions are conjugate some gain in the determinant may be obtained */
 2763: 				/* with the new direction. */
 2764: 				del=fabs(fptt-(*fret)); 
 2765: 				ibig=i; 
 2766:       } 
 2767: #ifdef DEBUG
 2768:       printf("%d %.12e",i,(*fret));
 2769:       fprintf(ficlog,"%d %.12e",i,(*fret));
 2770:       for (j=1;j<=n;j++) {
 2771: 				xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
 2772: 				printf(" x(%d)=%.12e",j,xit[j]);
 2773: 				fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
 2774:       }
 2775:       for(j=1;j<=n;j++) {
 2776: 				printf(" p(%d)=%.12e",j,p[j]);
 2777: 				fprintf(ficlog," p(%d)=%.12e",j,p[j]);
 2778:       }
 2779:       printf("\n");
 2780:       fprintf(ficlog,"\n");
 2781: #endif
 2782:     } /* end loop on each direction i */
 2783:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
 2784:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
 2785:     /* New value of last point Pn is not computed, P(n-1) */
 2786:     for(j=1;j<=n;j++) {
 2787:       if(flatdir[j] >0){
 2788:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
 2789:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
 2790:       }
 2791:       /* printf("\n"); */
 2792:       /* fprintf(ficlog,"\n"); */
 2793:     }
 2794:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
 2795:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
 2796:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
 2797:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
 2798:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
 2799:       /* decreased of more than 3.84  */
 2800:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
 2801:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
 2802:       /* By adding 10 parameters more the gain should be 18.31 */
 2803: 			
 2804:       /* Starting the program with initial values given by a former maximization will simply change */
 2805:       /* the scales of the directions and the directions, because the are reset to canonical directions */
 2806:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
 2807:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
 2808: #ifdef DEBUG
 2809:       int k[2],l;
 2810:       k[0]=1;
 2811:       k[1]=-1;
 2812:       printf("Max: %.12e",(*func)(p));
 2813:       fprintf(ficlog,"Max: %.12e",(*func)(p));
 2814:       for (j=1;j<=n;j++) {
 2815: 	printf(" %.12e",p[j]);
 2816: 	fprintf(ficlog," %.12e",p[j]);
 2817:       }
 2818:       printf("\n");
 2819:       fprintf(ficlog,"\n");
 2820:       for(l=0;l<=1;l++) {
 2821: 	for (j=1;j<=n;j++) {
 2822: 	  ptt[j]=p[j]+(p[j]-pt[j])*k[l];
 2823: 	  printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 2824: 	  fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 2825: 	}
 2826: 	printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 2827: 	fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 2828:       }
 2829: #endif
 2830: 
 2831:       free_vector(xit,1,n); 
 2832:       free_vector(xits,1,n); 
 2833:       free_vector(ptt,1,n); 
 2834:       free_vector(pt,1,n); 
 2835:       return; 
 2836:     } /* enough precision */ 
 2837:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
 2838:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
 2839:       ptt[j]=2.0*p[j]-pt[j]; 
 2840:       xit[j]=p[j]-pt[j]; 
 2841:       pt[j]=p[j]; 
 2842:     } 
 2843:     fptt=(*func)(ptt); /* f_3 */
 2844: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
 2845: 		if (*iter <=4) {
 2846: #else
 2847: #endif
 2848: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
 2849: #else
 2850:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
 2851: #endif
 2852:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
 2853:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
 2854:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
 2855:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
 2856:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
 2857:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
 2858:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
 2859:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
 2860:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
 2861:       /*  Even if f3 <f1, directest can be negative and t >0 */
 2862:       /* mu² and del² are equal when f3=f1 */
 2863: 			/* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
 2864: 			/* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
 2865: 			/* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
 2866: 			/* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
 2867: #ifdef NRCORIGINAL
 2868:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
 2869: #else
 2870:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
 2871:       t= t- del*SQR(fp-fptt);
 2872: #endif
 2873:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
 2874: #ifdef DEBUG
 2875:       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);
 2876:       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);
 2877:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 2878: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 2879:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 2880: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 2881:       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);
 2882:       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);
 2883: #endif
 2884: #ifdef POWELLORIGINAL
 2885:       if (t < 0.0) { /* Then we use it for new direction */
 2886: #else
 2887:       if (directest*t < 0.0) { /* Contradiction between both tests */
 2888: 				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);
 2889:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 2890:         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);
 2891:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 2892:       } 
 2893:       if (directest < 0.0) { /* Then we use it for new direction */
 2894: #endif
 2895: #ifdef DEBUGLINMIN
 2896: 	printf("Before linmin in direction P%d-P0\n",n);
 2897: 	for (j=1;j<=n;j++) {
 2898: 	  printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2899: 	  fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2900: 	  if(j % ncovmodel == 0){
 2901: 	    printf("\n");
 2902: 	    fprintf(ficlog,"\n");
 2903: 	  }
 2904: 	}
 2905: #endif
 2906: #ifdef LINMINORIGINAL
 2907: 	linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
 2908: #else
 2909: 	linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
 2910: 	flatdir[i]=flat; /* Function is vanishing in that direction i */
 2911: #endif
 2912: 	
 2913: #ifdef DEBUGLINMIN
 2914: 	for (j=1;j<=n;j++) { 
 2915: 	  printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2916: 	  fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2917: 	  if(j % ncovmodel == 0){
 2918: 	    printf("\n");
 2919: 	    fprintf(ficlog,"\n");
 2920: 	  }
 2921: 	}
 2922: #endif
 2923: 	for (j=1;j<=n;j++) { 
 2924: 	  xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
 2925: 	  xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
 2926: 	}
 2927: #ifdef LINMINORIGINAL
 2928: #else
 2929: 	for (j=1, flatd=0;j<=n;j++) {
 2930: 	  if(flatdir[j]>0)
 2931: 	    flatd++;
 2932: 	}
 2933: 	if(flatd >0){
 2934: 	  printf("%d flat directions: ",flatd);
 2935: 	  fprintf(ficlog,"%d flat directions :",flatd);
 2936: 	  for (j=1;j<=n;j++) { 
 2937: 	    if(flatdir[j]>0){
 2938: 	      printf("%d ",j);
 2939: 	      fprintf(ficlog,"%d ",j);
 2940: 	    }
 2941: 	  }
 2942: 	  printf("\n");
 2943: 	  fprintf(ficlog,"\n");
 2944: #ifdef FLATSUP
 2945:           free_vector(xit,1,n); 
 2946:           free_vector(xits,1,n); 
 2947:           free_vector(ptt,1,n); 
 2948:           free_vector(pt,1,n); 
 2949:           return;
 2950: #endif
 2951: 	}
 2952: #endif
 2953: 	printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 2954: 	fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 2955: 	
 2956: #ifdef DEBUG
 2957: 	printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 2958: 	fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 2959: 	for(j=1;j<=n;j++){
 2960: 	  printf(" %lf",xit[j]);
 2961: 	  fprintf(ficlog," %lf",xit[j]);
 2962: 	}
 2963: 	printf("\n");
 2964: 	fprintf(ficlog,"\n");
 2965: #endif
 2966:       } /* end of t or directest negative */
 2967: #ifdef POWELLNOF3INFF1TEST
 2968: #else
 2969:       } /* end if (fptt < fp)  */
 2970: #endif
 2971: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
 2972:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
 2973: #else
 2974: #endif
 2975: 		} /* loop iteration */ 
 2976: } 
 2977:   
 2978: /**** Prevalence limit (stable or period prevalence)  ****************/
 2979:   
 2980:   double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij, int nres)
 2981:   {
 2982:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
 2983:      *   (and selected quantitative values in nres)
 2984:      *  by left multiplying the unit
 2985:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
 2986:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
 2987:      * Wx is row vector: population in state 1, population in state 2, population dead
 2988:      * or prevalence in state 1, prevalence in state 2, 0
 2989:      * newm is the matrix after multiplications, its rows are identical at a factor.
 2990:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
 2991:      * Output is prlim.
 2992:      * Initial matrix pimij 
 2993:      */
 2994:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
 2995:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
 2996:   /*  0,                   0                  , 1} */
 2997:   /*
 2998:    * and after some iteration: */
 2999:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
 3000:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
 3001:   /*  0,                   0                  , 1} */
 3002:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
 3003:   /* {0.51571254859325999, 0.4842874514067399, */
 3004:   /*  0.51326036147820708, 0.48673963852179264} */
 3005:   /* If we start from prlim again, prlim tends to a constant matrix */
 3006:     
 3007:     int i, ii,j,k, k1;
 3008:   double *min, *max, *meandiff, maxmax,sumnew=0.;
 3009:   /* double **matprod2(); */ /* test */
 3010:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
 3011:   double **newm;
 3012:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
 3013:   int ncvloop=0;
 3014:   int first=0;
 3015:   
 3016:   min=vector(1,nlstate);
 3017:   max=vector(1,nlstate);
 3018:   meandiff=vector(1,nlstate);
 3019: 
 3020: 	/* Starting with matrix unity */
 3021:   for (ii=1;ii<=nlstate+ndeath;ii++)
 3022:     for (j=1;j<=nlstate+ndeath;j++){
 3023:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3024:     }
 3025:   
 3026:   cov[1]=1.;
 3027:   
 3028:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 3029:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
 3030:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
 3031:     ncvloop++;
 3032:     newm=savm;
 3033:     /* Covariates have to be included here again */
 3034:     cov[2]=agefin;
 3035:      if(nagesqr==1){
 3036:       cov[3]= agefin*agefin;
 3037:      }
 3038:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
 3039:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
 3040:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
 3041:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
 3042: 	 cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
 3043:        }else{
 3044: 	 cov[2+nagesqr+k1]=precov[nres][k1];
 3045:        }
 3046:      }/* End of loop on model equation */
 3047:      
 3048: /* Start of old code (replaced by a loop on position in the model equation */
 3049:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
 3050:     /* 			/\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
 3051:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
 3052:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
 3053:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
 3054:     /*    * k                  1        2      3    4      5      6     7        8 */
 3055:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
 3056:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
 3057:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
 3058:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
 3059:     /*    *nsd=3                              (1)  (2)           (3) */
 3060:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
 3061:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
 3062:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
 3063:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
 3064:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
 3065:     /*    *                   [1][2]=3                                           [2][2]=2 */
 3066:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
 3067:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
 3068:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
 3069:     /*    *TvarsDpType */
 3070:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
 3071:     /*    * nsd=1              (1)           (2) */
 3072:     /*    *TvarsD[nsd]          3             2 */
 3073:     /*    *TnsdVar           (3)=1          (2)=2 */
 3074:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
 3075:     /*    *Tage[]                  [1]=2           [2]= 3    */
 3076:     /*    *\/ */
 3077:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
 3078:     /*   /\* printf("prevalim Dummy combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov=%lf codtabm(%d,Tvar[%d])=%d \n",ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,k)],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,k)); *\/ */
 3079:     /* } */
 3080:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
 3081:     /* 			/\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
 3082:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
 3083:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
 3084:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
 3085:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
 3086:     /*   /\* printf("prevalim Quantitative k=%d  TvarsQind[%d]=%d, TvarsQ[%d]=V%d,Tqresult[%d][%d]=%f\n",k,k,TvarsQind[k],k,TvarsQ[k],nres,k,Tqresult[nres][k]); *\/ */
 3087:     /* } */
 3088:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
 3089:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
 3090:     /* 	cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
 3091:     /* 	/\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
 3092:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
 3093:     /* 	cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
 3094:     /* 	/\* cov[++k1]=Tqresult[nres][k];  *\/ */
 3095:     /*   } */
 3096:     /*   /\* printf("prevalim Age combi=%d k=%d  Tage[%d]=V%d Tqresult[%d][%d]=%f\n",ij,k,k,Tage[k],nres,k,Tqresult[nres][k]); *\/ */
 3097:     /* } */
 3098:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
 3099:     /*   /\* printf("prevalim Prod ij=%d k=%d  Tprod[%d]=%d Tvard[%d][1]=V%d, Tvard[%d][2]=V%d\n",ij,k,k,Tprod[k], k,Tvard[k][1], k,Tvard[k][2]); *\/ */
 3100:     /*   if(Dummy[Tvard[k][1]]==0){ */
 3101:     /* 	if(Dummy[Tvard[k][2]]==0){ */
 3102:     /* 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 3103:     /* 	  /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
 3104:     /* 	}else{ */
 3105:     /* 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
 3106:     /* 	  /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
 3107:     /* 	} */
 3108:     /*   }else{ */
 3109:     /* 	if(Dummy[Tvard[k][2]]==0){ */
 3110:     /* 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
 3111:     /* 	  /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
 3112:     /* 	}else{ */
 3113:     /* 	  cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
 3114:     /* 	  /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
 3115:     /* 	} */
 3116:     /*   } */
 3117:     /* } /\* End product without age *\/ */
 3118: /* ENd of old code */
 3119:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 3120:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 3121:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 3122:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 3123:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 3124:     /* age and covariate values of ij are in 'cov' */
 3125:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
 3126:     
 3127:     savm=oldm;
 3128:     oldm=newm;
 3129: 
 3130:     for(j=1; j<=nlstate; j++){
 3131:       max[j]=0.;
 3132:       min[j]=1.;
 3133:     }
 3134:     for(i=1;i<=nlstate;i++){
 3135:       sumnew=0;
 3136:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
 3137:       for(j=1; j<=nlstate; j++){ 
 3138: 	prlim[i][j]= newm[i][j]/(1-sumnew);
 3139: 	max[j]=FMAX(max[j],prlim[i][j]);
 3140: 	min[j]=FMIN(min[j],prlim[i][j]);
 3141:       }
 3142:     }
 3143: 
 3144:     maxmax=0.;
 3145:     for(j=1; j<=nlstate; j++){
 3146:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
 3147:       maxmax=FMAX(maxmax,meandiff[j]);
 3148:       /* 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); */
 3149:     } /* j loop */
 3150:     *ncvyear= (int)age- (int)agefin;
 3151:     /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
 3152:     if(maxmax < ftolpl){
 3153:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
 3154:       free_vector(min,1,nlstate);
 3155:       free_vector(max,1,nlstate);
 3156:       free_vector(meandiff,1,nlstate);
 3157:       return prlim;
 3158:     }
 3159:   } /* agefin loop */
 3160:     /* After some age loop it doesn't converge */
 3161:   if(!first){
 3162:     first=1;
 3163:     printf("Warning: the stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.d years and %d loops. Try to lower 'ftolpl'. Youngest age to start was %d=(%d-%d). Others in log file only...\n", (int)age, maxmax, ftolpl, *ncvyear, ncvloop, (int)(agefin+stepm/YEARM),  (int)(age-stepm/YEARM), (int)delaymax);
 3164:     fprintf(ficlog, "Warning: the stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.d years and %d loops. Try to lower 'ftolpl'. Youngest age to start was %d=(%d-%d).\n", (int)age, maxmax, ftolpl, *ncvyear, ncvloop, (int)(agefin+stepm/YEARM),  (int)(age-stepm/YEARM), (int)delaymax);
 3165:   }else if (first >=1 && first <10){
 3166:     fprintf(ficlog, "Warning: the stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.d years and %d loops. Try to lower 'ftolpl'. Youngest age to start was %d=(%d-%d).\n", (int)age, maxmax, ftolpl, *ncvyear, ncvloop, (int)(agefin+stepm/YEARM),  (int)(age-stepm/YEARM), (int)delaymax);
 3167:     first++;
 3168:   }else if (first ==10){
 3169:     fprintf(ficlog, "Warning: the stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.d years and %d loops. Try to lower 'ftolpl'. Youngest age to start was %d=(%d-%d).\n", (int)age, maxmax, ftolpl, *ncvyear, ncvloop, (int)(agefin+stepm/YEARM),  (int)(age-stepm/YEARM), (int)delaymax);
 3170:     printf("Warning: the stable prevalence dit not converge. This warning came too often, IMaCh will stop notifying, even in its log file. Look at the graphs to appreciate the non convergence.\n");
 3171:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
 3172:     first++;
 3173:   }
 3174: 
 3175:   /* 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); */
 3176:   free_vector(min,1,nlstate);
 3177:   free_vector(max,1,nlstate);
 3178:   free_vector(meandiff,1,nlstate);
 3179:   
 3180:   return prlim; /* should not reach here */
 3181: }
 3182: 
 3183: 
 3184:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
 3185: 
 3186:  /* 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) */
 3187:  /* 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) */
 3188:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
 3189: {
 3190:   /* Computes the prevalence limit in each live state at age x and for covariate combination ij (<=2**cptcoveff) by left multiplying the unit
 3191:      matrix by transitions matrix until convergence is reached with precision ftolpl */
 3192:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
 3193:   /* Wx is row vector: population in state 1, population in state 2, population dead */
 3194:   /* or prevalence in state 1, prevalence in state 2, 0 */
 3195:   /* newm is the matrix after multiplications, its rows are identical at a factor */
 3196:   /* Initial matrix pimij */
 3197:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
 3198:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
 3199:   /*  0,                   0                  , 1} */
 3200:   /*
 3201:    * and after some iteration: */
 3202:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
 3203:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
 3204:   /*  0,                   0                  , 1} */
 3205:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
 3206:   /* {0.51571254859325999, 0.4842874514067399, */
 3207:   /*  0.51326036147820708, 0.48673963852179264} */
 3208:   /* If we start from prlim again, prlim tends to a constant matrix */
 3209: 
 3210:   int i, ii,j,k, k1;
 3211:   int first=0;
 3212:   double *min, *max, *meandiff, maxmax,sumnew=0.;
 3213:   /* double **matprod2(); */ /* test */
 3214:   double **out, cov[NCOVMAX+1], **bmij();
 3215:   double **newm;
 3216:   double	 **dnewm, **doldm, **dsavm;  /* for use */
 3217:   double	 **oldm, **savm;  /* for use */
 3218: 
 3219:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
 3220:   int ncvloop=0;
 3221:   
 3222:   min=vector(1,nlstate);
 3223:   max=vector(1,nlstate);
 3224:   meandiff=vector(1,nlstate);
 3225: 
 3226:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
 3227:   oldm=oldms; savm=savms;
 3228:   
 3229:   /* Starting with matrix unity */
 3230:   for (ii=1;ii<=nlstate+ndeath;ii++)
 3231:     for (j=1;j<=nlstate+ndeath;j++){
 3232:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3233:     }
 3234:   
 3235:   cov[1]=1.;
 3236:   
 3237:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 3238:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
 3239:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
 3240:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
 3241:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
 3242:     ncvloop++;
 3243:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
 3244: 		/* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
 3245:     /* Covariates have to be included here again */
 3246:     cov[2]=agefin;
 3247:     if(nagesqr==1){
 3248:       cov[3]= agefin*agefin;;
 3249:     }
 3250:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
 3251:       if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
 3252: 	cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
 3253:       }else{
 3254: 	cov[2+nagesqr+k1]=precov[nres][k1];
 3255:       }
 3256:     }/* End of loop on model equation */
 3257: 
 3258: /* Old code */ 
 3259: 
 3260:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
 3261:     /* 			/\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
 3262:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
 3263:     /*   /\* printf("bprevalim Dummy agefin=%.0f combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov[%d]=%lf codtabm(%d,Tvar[%d])=%d \n",agefin,ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,k)],2+nagesqr+TvarsDind[k],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,k)); *\/ */
 3264:     /* } */
 3265:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
 3266:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
 3267:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
 3268:     /* /\*   /\\* 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])]); *\\/ *\/ */
 3269:     /* /\* } *\/ */
 3270:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
 3271:     /* 			/\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
 3272:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
 3273:     /*   /\* printf("prevalim Quantitative k=%d  TvarsQind[%d]=%d, TvarsQ[%d]=V%d,Tqresult[%d][%d]=%f\n",k,k,TvarsQind[k],k,TvarsQ[k],nres,k,Tqresult[nres][k]); *\/ */
 3274:     /* } */
 3275:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
 3276:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
 3277:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
 3278:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
 3279:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
 3280:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
 3281:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
 3282:     /* 	cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
 3283:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
 3284:     /* 	cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
 3285:     /*   } */
 3286:     /*   /\* printf("prevalim Age combi=%d k=%d  Tage[%d]=V%d Tqresult[%d][%d]=%f\n",ij,k,k,Tage[k],nres,k,Tqresult[nres][k]); *\/ */
 3287:     /* } */
 3288:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
 3289:     /*   /\* printf("prevalim Prod ij=%d k=%d  Tprod[%d]=%d Tvard[%d][1]=V%d, Tvard[%d][2]=V%d\n",ij,k,k,Tprod[k], k,Tvard[k][1], k,Tvard[k][2]); *\/ */
 3290:     /*   if(Dummy[Tvard[k][1]]==0){ */
 3291:     /* 	if(Dummy[Tvard[k][2]]==0){ */
 3292:     /* 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 3293:     /* 	}else{ */
 3294:     /* 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
 3295:     /* 	} */
 3296:     /*   }else{ */
 3297:     /* 	if(Dummy[Tvard[k][2]]==0){ */
 3298:     /* 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
 3299:     /* 	}else{ */
 3300:     /* 	  cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
 3301:     /* 	} */
 3302:     /*   } */
 3303:     /* } */
 3304:     
 3305:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 3306:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 3307:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 3308:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 3309:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 3310: 		/* ij should be linked to the correct index of cov */
 3311: 		/* age and covariate values ij are in 'cov', but we need to pass
 3312: 		 * ij for the observed prevalence at age and status and covariate
 3313: 		 * number:  prevacurrent[(int)agefin][ii][ij]
 3314: 		 */
 3315:     /* 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 *\/ */
 3316:     /* 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 *\/ */
 3317:     out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij)); /* Bug Valgrind */
 3318:     /* if((int)age == 86 || (int)age == 87){ */
 3319:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
 3320:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
 3321:     /* 	printf("%d newm= ",i); */
 3322:     /* 	for(j=1;j<=nlstate+ndeath;j++) { */
 3323:     /* 	  printf("%f ",newm[i][j]); */
 3324:     /* 	} */
 3325:     /* 	printf("oldm * "); */
 3326:     /* 	for(j=1;j<=nlstate+ndeath;j++) { */
 3327:     /* 	  printf("%f ",oldm[i][j]); */
 3328:     /* 	} */
 3329:     /* 	printf(" bmmij "); */
 3330:     /* 	for(j=1;j<=nlstate+ndeath;j++) { */
 3331:     /* 	  printf("%f ",pmmij[i][j]); */
 3332:     /* 	} */
 3333:     /* 	printf("\n"); */
 3334:     /*   } */
 3335:     /* } */
 3336:     savm=oldm;
 3337:     oldm=newm;
 3338: 
 3339:     for(j=1; j<=nlstate; j++){
 3340:       max[j]=0.;
 3341:       min[j]=1.;
 3342:     }
 3343:     for(j=1; j<=nlstate; j++){ 
 3344:       for(i=1;i<=nlstate;i++){
 3345: 	/* bprlim[i][j]= newm[i][j]/(1-sumnew); */
 3346: 	bprlim[i][j]= newm[i][j];
 3347: 	max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
 3348: 	min[i]=FMIN(min[i],bprlim[i][j]);
 3349:       }
 3350:     }
 3351: 		
 3352:     maxmax=0.;
 3353:     for(i=1; i<=nlstate; i++){
 3354:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
 3355:       maxmax=FMAX(maxmax,meandiff[i]);
 3356:       /* 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); */
 3357:     } /* i loop */
 3358:     *ncvyear= -( (int)age- (int)agefin);
 3359:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
 3360:     if(maxmax < ftolpl){
 3361:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
 3362:       free_vector(min,1,nlstate);
 3363:       free_vector(max,1,nlstate);
 3364:       free_vector(meandiff,1,nlstate);
 3365:       return bprlim;
 3366:     }
 3367:   } /* agefin loop */
 3368:     /* After some age loop it doesn't converge */
 3369:   if(!first){
 3370:     first=1;
 3371:     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'. Others in log file only...\n\
 3372: 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);
 3373:   }
 3374:   fprintf(ficlog,"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\
 3375: 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);
 3376:   /* 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); */
 3377:   free_vector(min,1,nlstate);
 3378:   free_vector(max,1,nlstate);
 3379:   free_vector(meandiff,1,nlstate);
 3380:   
 3381:   return bprlim; /* should not reach here */
 3382: }
 3383: 
 3384: /*************** transition probabilities ***************/ 
 3385: 
 3386: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 3387: {
 3388:   /* According to parameters values stored in x and the covariate's values stored in cov,
 3389:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
 3390:      model to the ncovmodel covariates (including constant and age).
 3391:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 3392:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 3393:      ncth covariate in the global vector x is given by the formula:
 3394:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 3395:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 3396:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 3397:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 3398:      Outputs ps[i][j] or probability to be observed in j being in i according to
 3399:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 3400:      Sum on j ps[i][j] should equal to 1.
 3401:   */
 3402:   double s1, lnpijopii;
 3403:   /*double t34;*/
 3404:   int i,j, nc, ii, jj;
 3405: 
 3406:   for(i=1; i<= nlstate; i++){
 3407:     for(j=1; j<i;j++){
 3408:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 3409: 	/*lnpijopii += param[i][j][nc]*cov[nc];*/
 3410: 	lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 3411: 	/* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 3412:       }
 3413:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 3414:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
 3415:     }
 3416:     for(j=i+1; j<=nlstate+ndeath;j++){
 3417:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 3418: 	/*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 3419: 	lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 3420: 	/* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 3421:       }
 3422:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 3423:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
 3424:     }
 3425:   }
 3426:   
 3427:   for(i=1; i<= nlstate; i++){
 3428:     s1=0;
 3429:     for(j=1; j<i; j++){
 3430:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
 3431:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 3432:     }
 3433:     for(j=i+1; j<=nlstate+ndeath; j++){
 3434:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
 3435:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 3436:     }
 3437:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 3438:     ps[i][i]=1./(s1+1.);
 3439:     /* Computing other pijs */
 3440:     for(j=1; j<i; j++)
 3441:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
 3442:     for(j=i+1; j<=nlstate+ndeath; j++)
 3443:       ps[i][j]= exp(ps[i][j])*ps[i][i];
 3444:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 3445:   } /* end i */
 3446:   
 3447:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 3448:     for(jj=1; jj<= nlstate+ndeath; jj++){
 3449:       ps[ii][jj]=0;
 3450:       ps[ii][ii]=1;
 3451:     }
 3452:   }
 3453: 
 3454: 
 3455:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 3456:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 3457:   /* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 3458:   /*   } */
 3459:   /*   printf("\n "); */
 3460:   /* } */
 3461:   /* printf("\n ");printf("%lf ",cov[2]);*/
 3462:   /*
 3463:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
 3464: 		goto end;*/
 3465:   return ps; /* Pointer is unchanged since its call */
 3466: }
 3467: 
 3468: /*************** backward transition probabilities ***************/ 
 3469: 
 3470:  /* 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 ) */
 3471: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
 3472:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
 3473: {
 3474:   /* Computes the backward probability at age agefin, cov[2], and covariate combination 'ij'. In fact cov is already filled and x too.
 3475:    * Call to pmij(cov and x), call to cross prevalence, sums and inverses, left multiply, and returns in **ps as well as **bmij.
 3476:    */
 3477:   int i, ii, j,k;
 3478:   
 3479:   double **out, **pmij();
 3480:   double sumnew=0.;
 3481:   double agefin;
 3482:   double k3=0.; /* constant of the w_x diagonal matrix (in order for B to sum to 1 even for death state) */
 3483:   double **dnewm, **dsavm, **doldm;
 3484:   double **bbmij;
 3485:   
 3486:   doldm=ddoldms; /* global pointers */
 3487:   dnewm=ddnewms;
 3488:   dsavm=ddsavms;
 3489: 
 3490:   /* Debug */
 3491:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
 3492:   agefin=cov[2];
 3493:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
 3494:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
 3495:      the observed prevalence (with this covariate ij) at beginning of transition */
 3496:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 3497: 
 3498:   /* P_x */
 3499:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
 3500:   /* outputs pmmij which is a stochastic matrix in row */
 3501: 
 3502:   /* Diag(w_x) */
 3503:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
 3504:   sumnew=0.;
 3505:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
 3506:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
 3507:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
 3508:     sumnew+=prevacurrent[(int)agefin][ii][ij];
 3509:   }
 3510:   if(sumnew >0.01){  /* At least some value in the prevalence */
 3511:     for (ii=1;ii<=nlstate+ndeath;ii++){
 3512:       for (j=1;j<=nlstate+ndeath;j++)
 3513: 	doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
 3514:     }
 3515:   }else{
 3516:     for (ii=1;ii<=nlstate+ndeath;ii++){
 3517:       for (j=1;j<=nlstate+ndeath;j++)
 3518:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
 3519:     }
 3520:     /* if(sumnew <0.9){ */
 3521:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
 3522:     /* } */
 3523:   }
 3524:   k3=0.0;  /* We put the last diagonal to 0 */
 3525:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
 3526:       doldm[ii][ii]= k3;
 3527:   }
 3528:   /* End doldm, At the end doldm is diag[(w_i)] */
 3529:   
 3530:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
 3531:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
 3532: 
 3533:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
 3534:   /* w1 p11 + w2 p21 only on live states N1./N..*N11/N1. + N2./N..*N21/N2.=(N11+N21)/N..=N.1/N.. */
 3535:   for (j=1;j<=nlstate+ndeath;j++){
 3536:     sumnew=0.;
 3537:     for (ii=1;ii<=nlstate;ii++){
 3538:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
 3539:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
 3540:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
 3541:     for (ii=1;ii<=nlstate+ndeath;ii++){
 3542: 	/* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
 3543: 	/* 	dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
 3544: 	/* }else if(agefin >= agemaxpar+stepm/YEARM){ */
 3545: 	/* 	dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
 3546: 	/* }else */
 3547:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
 3548:     } /*End ii */
 3549:   } /* End j, At the end dsavm is diag[1/(w_1p1i+w_2 p2i)] for ALL states even if the sum is only for live states */
 3550: 
 3551:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
 3552:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
 3553:   /* end bmij */
 3554:   return ps; /*pointer is unchanged */
 3555: }
 3556: /*************** transition probabilities ***************/ 
 3557: 
 3558: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 3559: {
 3560:   /* According to parameters values stored in x and the covariate's values stored in cov,
 3561:      computes the probability to be observed in state j being in state i by appying the
 3562:      model to the ncovmodel covariates (including constant and age).
 3563:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 3564:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 3565:      ncth covariate in the global vector x is given by the formula:
 3566:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 3567:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 3568:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 3569:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 3570:      Outputs ps[i][j] the probability to be observed in j being in j according to
 3571:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 3572:   */
 3573:   double s1, lnpijopii;
 3574:   /*double t34;*/
 3575:   int i,j, nc, ii, jj;
 3576: 
 3577:   for(i=1; i<= nlstate; i++){
 3578:     for(j=1; j<i;j++){
 3579:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 3580: 	/*lnpijopii += param[i][j][nc]*cov[nc];*/
 3581: 	lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 3582: 	/* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 3583:       }
 3584:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 3585:       /* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 3586:     }
 3587:     for(j=i+1; j<=nlstate+ndeath;j++){
 3588:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 3589: 	/*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 3590: 	lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 3591: 	/* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 3592:       }
 3593:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 3594:     }
 3595:   }
 3596:   
 3597:   for(i=1; i<= nlstate; i++){
 3598:     s1=0;
 3599:     for(j=1; j<i; j++){
 3600:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 3601:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 3602:     }
 3603:     for(j=i+1; j<=nlstate+ndeath; j++){
 3604:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 3605:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 3606:     }
 3607:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 3608:     ps[i][i]=1./(s1+1.);
 3609:     /* Computing other pijs */
 3610:     for(j=1; j<i; j++)
 3611:       ps[i][j]= exp(ps[i][j])*ps[i][i];
 3612:     for(j=i+1; j<=nlstate+ndeath; j++)
 3613:       ps[i][j]= exp(ps[i][j])*ps[i][i];
 3614:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 3615:   } /* end i */
 3616:   
 3617:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 3618:     for(jj=1; jj<= nlstate+ndeath; jj++){
 3619:       ps[ii][jj]=0;
 3620:       ps[ii][ii]=1;
 3621:     }
 3622:   }
 3623:   /* Added for prevbcast */ /* Transposed matrix too */
 3624:   for(jj=1; jj<= nlstate+ndeath; jj++){
 3625:     s1=0.;
 3626:     for(ii=1; ii<= nlstate+ndeath; ii++){
 3627:       s1+=ps[ii][jj];
 3628:     }
 3629:     for(ii=1; ii<= nlstate; ii++){
 3630:       ps[ii][jj]=ps[ii][jj]/s1;
 3631:     }
 3632:   }
 3633:   /* Transposition */
 3634:   for(jj=1; jj<= nlstate+ndeath; jj++){
 3635:     for(ii=jj; ii<= nlstate+ndeath; ii++){
 3636:       s1=ps[ii][jj];
 3637:       ps[ii][jj]=ps[jj][ii];
 3638:       ps[jj][ii]=s1;
 3639:     }
 3640:   }
 3641:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 3642:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 3643:   /* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 3644:   /*   } */
 3645:   /*   printf("\n "); */
 3646:   /* } */
 3647:   /* printf("\n ");printf("%lf ",cov[2]);*/
 3648:   /*
 3649:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
 3650:     goto end;*/
 3651:   return ps;
 3652: }
 3653: 
 3654: 
 3655: /**************** Product of 2 matrices ******************/
 3656: 
 3657: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
 3658: {
 3659:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
 3660:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
 3661:   /* in, b, out are matrice of pointers which should have been initialized 
 3662:      before: only the contents of out is modified. The function returns
 3663:      a pointer to pointers identical to out */
 3664:   int i, j, k;
 3665:   for(i=nrl; i<= nrh; i++)
 3666:     for(k=ncolol; k<=ncoloh; k++){
 3667:       out[i][k]=0.;
 3668:       for(j=ncl; j<=nch; j++)
 3669:   	out[i][k] +=in[i][j]*b[j][k];
 3670:     }
 3671:   return out;
 3672: }
 3673: 
 3674: 
 3675: /************* Higher Matrix Product ***************/
 3676: 
 3677: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij, int nres )
 3678: {
 3679:   /* Already optimized with precov.
 3680:      Computes the transition matrix starting at age 'age' and dummies values in each resultline (loop on ij to find the corresponding combination) to over 
 3681:      'nhstepm*hstepm*stepm' months (i.e. until
 3682:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
 3683:      nhstepm*hstepm matrices. 
 3684:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
 3685:      (typically every 2 years instead of every month which is too big 
 3686:      for the memory).
 3687:      Model is determined by parameters x and covariates have to be 
 3688:      included manually here. 
 3689: 
 3690:      */
 3691: 
 3692:   int i, j, d, h, k, k1;
 3693:   double **out, cov[NCOVMAX+1];
 3694:   double **newm;
 3695:   double agexact;
 3696:   double agebegin, ageend;
 3697: 
 3698:   /* Hstepm could be zero and should return the unit matrix */
 3699:   for (i=1;i<=nlstate+ndeath;i++)
 3700:     for (j=1;j<=nlstate+ndeath;j++){
 3701:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 3702:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 3703:     }
 3704:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 3705:   for(h=1; h <=nhstepm; h++){
 3706:     for(d=1; d <=hstepm; d++){
 3707:       newm=savm;
 3708:       /* Covariates have to be included here again */
 3709:       cov[1]=1.;
 3710:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
 3711:       cov[2]=agexact;
 3712:       if(nagesqr==1){
 3713: 	cov[3]= agexact*agexact;
 3714:       }
 3715:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
 3716:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
 3717:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
 3718: 	if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
 3719: 	  cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
 3720: 	}else{
 3721: 	  cov[2+nagesqr+k1]=precov[nres][k1];
 3722: 	}
 3723:       }/* End of loop on model equation */
 3724: 	/* Old code */ 
 3725: /* 	if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
 3726: /* /\*	   V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
 3727: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
 3728: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
 3729: /* 	/\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
 3730: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
 3731: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
 3732: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
 3733: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
 3734: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
 3735: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
 3736: /* 	  /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
 3737: /* 	  cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
 3738: /* 	  /\* printf("hpxij Dummy combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov=%lf codtabm(%d,TnsdVar[TvarsD[%d])=%d \n",ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,TnsdVar[TvarsD[k]])); *\/ */
 3739: /* 	  printf("hpxij Dummy combi=%d k1=%d Tvar[%d]=V%d cov[2+%d+%d]=%lf resultmodel[nres][%d]=%d nres/nresult=%d/%d \n",ij,k1,k1, Tvar[k1],nagesqr,k1,cov[2+nagesqr+k1],k1,resultmodel[nres][k1],nres,nresult); */
 3740: /* 	  printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
 3741: /* 	}else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
 3742: /* 	  /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
 3743: /* 	  cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
 3744: /* 	  /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
 3745: /* 	  /\* 	/\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
 3746: /* 	  /\* 	cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
 3747: /* 	  printf("hPxij Quantitative k1=%d resultmodel[nres][%d]=%d,Tqresult[%d][%d]=%f\n",k1,k1,resultmodel[nres][k1],nres,resultmodel[nres][k1],Tqresult[nres][resultmodel[nres][k1]]); */
 3748: /* 	  printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
 3749: /* 	}else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
 3750: /* 	  /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
 3751: /* 	  /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
 3752: /* 	  cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
 3753: /* 	  printf("DhPxij Dummy with age k1=%d Tvar[%d]=%d TinvDoQresult[nres=%d][%d]=%.f age=%.2f,cov[2+%d+%d]=%.3f\n",k1,k1,Tvar[k1],nres,TinvDoQresult[nres][Tvar[k1]],cov[2],nagesqr,k1,cov[2+nagesqr+k1]); */
 3754: /* 	  printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
 3755: 
 3756: /* 	  /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];	 *\/ */
 3757: /* 	  /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
 3758: /* 	  /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
 3759: /* 	  /\* *\/ */
 3760: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
 3761: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
 3762: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
 3763: /* /\*cptcovage=2                   1               2      *\/ */
 3764: /* /\*Tage[k]=                      5               8      *\/	 */
 3765: /* 	}else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
 3766: /* 	  cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];	 */
 3767: /* 	  printf("QhPxij Quant with age k1=%d resultmodel[nres][%d]=%d,Tqresult[%d][%d]=%f\n",k1,k1,resultmodel[nres][k1],nres,resultmodel[nres][k1],Tqresult[nres][resultmodel[nres][k1]]); */
 3768: /* 	  printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
 3769: /* 	  /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
 3770: /* 	  /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
 3771: /* 	  /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
 3772: /* 	  /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
 3773: /* 	  /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
 3774: /* 	  /\*   printf("hPxij Age combi=%d k=%d cptcovage=%d Tage[%d]=%d Tvar[Tage[%d]]=V%d nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[Tvar[Tage[k]]]])]=%d nres=%d\n",ij,k,cptcovage,k,Tage[k],k,Tvar[Tage[k]], nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[Tvar[Tage[k]]])],nres); *\/ */
 3775: /* 	  /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
 3776: /* 	  /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
 3777: /* 	  /\* } *\/ */
 3778: /* 	  /\* printf("hPxij Age combi=%d k=%d  Tage[%d]=V%d Tqresult[%d][%d]=%f\n",ij,k,k,Tage[k],nres,k,Tqresult[nres][k]); *\/ */
 3779: /* 	}else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
 3780: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
 3781: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
 3782: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
 3783: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
 3784: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
 3785: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
 3786: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
 3787: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
 3788: 	  
 3789: /* 	  /\* printf("hPxij Prod ij=%d k=%d  Tprod[%d]=%d Tvard[%d][1]=V%d, Tvard[%d][2]=V%d nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]=%d nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]=%d\n",ij,k,k,Tprod[k], k,Tvard[k][1], k,Tvard[k][2],nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])],nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]); *\/ */
 3790: /* 	  /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
 3791: /* 	  cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];	 */
 3792: /* 	  printf("hPxij Prod ij=%d k1=%d  cov[2+%d+%d]=%.5f Tvard[%d][1]=V%d * Tvard[%d][2]=V%d ; TinvDoQresult[nres][Tvardk[k1][1]]=%.4f * TinvDoQresult[nres][Tvardk[k1][1]]=%.4f\n",ij,k1,nagesqr,k1,cov[2+nagesqr+k1],k1,Tvardk[k1][1], k1,Tvardk[k1][2], TinvDoQresult[nres][Tvardk[k1][1]], TinvDoQresult[nres][Tvardk[k1][2]]); */
 3793: /* 	  printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
 3794: 
 3795: /* 	  /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
 3796: /* 	  /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
 3797: /* 	      /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
 3798: /* 	      /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];	 *\/ */
 3799: /* 	      /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])]; *\/ */
 3800: /* 	    /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
 3801: /* 	      /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
 3802: /* 	      /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
 3803: /* 	  /\*   } *\/ */
 3804: /* 	  /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
 3805: /* 	  /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
 3806: /* 	  /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
 3807: /* 	  /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
 3808: /* 	  /\*   }else{ /\\* Product of two quant *\\/ *\/ */
 3809: /* 	  /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
 3810: /* 	  /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
 3811: /* 	  /\*   } *\/ */
 3812: /* 	  /\* }/\\*end of products quantitative *\\/ *\/ */
 3813: /* 	}/\*end of products *\/ */
 3814:       /* } /\* End of loop on model equation *\/ */
 3815:       /* for (k=1; k<=cptcovn;k++)  */
 3816:       /* 	cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
 3817:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
 3818:       /* 	cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
 3819:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
 3820:       /* 	cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
 3821:       
 3822:       
 3823:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 3824:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 3825:       /* right multiplication of oldm by the current matrix */
 3826:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
 3827: 		   pmij(pmmij,cov,ncovmodel,x,nlstate));
 3828:       /* if((int)age == 70){ */
 3829:       /* 	printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
 3830:       /* 	for(i=1; i<=nlstate+ndeath; i++) { */
 3831:       /* 	  printf("%d pmmij ",i); */
 3832:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 3833:       /* 	    printf("%f ",pmmij[i][j]); */
 3834:       /* 	  } */
 3835:       /* 	  printf(" oldm "); */
 3836:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 3837:       /* 	    printf("%f ",oldm[i][j]); */
 3838:       /* 	  } */
 3839:       /* 	  printf("\n"); */
 3840:       /* 	} */
 3841:       /* } */
 3842:       savm=oldm;
 3843:       oldm=newm;
 3844:     }
 3845:     for(i=1; i<=nlstate+ndeath; i++)
 3846:       for(j=1;j<=nlstate+ndeath;j++) {
 3847: 	po[i][j][h]=newm[i][j];
 3848: 	/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 3849:       }
 3850:     /*printf("h=%d ",h);*/
 3851:   } /* end h */
 3852:   /*     printf("\n H=%d \n",h); */
 3853:   return po;
 3854: }
 3855: 
 3856: /************* Higher Back Matrix Product ***************/
 3857: /* 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 ) */
 3858: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij, int nres )
 3859: {
 3860:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
 3861:      computes the transition matrix starting at age 'age' over
 3862:      'nhstepm*hstepm*stepm' months (i.e. until
 3863:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
 3864:      nhstepm*hstepm matrices.
 3865:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
 3866:      (typically every 2 years instead of every month which is too big
 3867:      for the memory).
 3868:      Model is determined by parameters x and covariates have to be
 3869:      included manually here. Then we use a call to bmij(x and cov)
 3870:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
 3871:   */
 3872: 
 3873:   int i, j, d, h, k, k1;
 3874:   double **out, cov[NCOVMAX+1], **bmij();
 3875:   double **newm, ***newmm;
 3876:   double agexact;
 3877:   double agebegin, ageend;
 3878:   double **oldm, **savm;
 3879: 
 3880:   newmm=po; /* To be saved */
 3881:   oldm=oldms;savm=savms; /* Global pointers */
 3882:   /* Hstepm could be zero and should return the unit matrix */
 3883:   for (i=1;i<=nlstate+ndeath;i++)
 3884:     for (j=1;j<=nlstate+ndeath;j++){
 3885:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 3886:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 3887:     }
 3888:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 3889:   for(h=1; h <=nhstepm; h++){
 3890:     for(d=1; d <=hstepm; d++){
 3891:       newm=savm;
 3892:       /* Covariates have to be included here again */
 3893:       cov[1]=1.;
 3894:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
 3895:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
 3896:         /* Debug */
 3897:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
 3898:       cov[2]=agexact;
 3899:       if(nagesqr==1){
 3900: 	cov[3]= agexact*agexact;
 3901:       }
 3902:       /** New code */
 3903:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
 3904: 	if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
 3905: 	  cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
 3906: 	}else{
 3907: 	  cov[2+nagesqr+k1]=precov[nres][k1];
 3908: 	}
 3909:       }/* End of loop on model equation */
 3910:       /** End of new code */
 3911:   /** This was old code */
 3912:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
 3913:       /* /\* 	cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
 3914:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
 3915:       /* 	cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
 3916:       /*   /\* printf("hbxij Dummy agexact=%.0f combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov[%d]=%lf codtabm(%d,Tvar[%d])=%d \n",agexact,ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,k)],2+nagesqr+TvarsDind[k],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,k)); *\/ */
 3917:       /* } */
 3918:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
 3919:       /* 	/\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
 3920:       /* 	cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
 3921:       /* 	/\* printf("hPxij Quantitative k=%d  TvarsQind[%d]=%d, TvarsQ[%d]=V%d,Tqresult[%d][%d]=%f\n",k,k,TvarsQind[k],k,TvarsQ[k],nres,k,Tqresult[nres][k]); *\/ */
 3922:       /* } */
 3923:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
 3924:       /* 	/\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
 3925:       /* 	if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
 3926:       /* 	  cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
 3927:       /* 	} else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
 3928:       /* 	  cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
 3929:       /* 	} */
 3930:       /* 	/\* printf("hBxij Age combi=%d k=%d  Tage[%d]=V%d Tqresult[%d][%d]=%f\n",ij,k,k,Tage[k],nres,k,Tqresult[nres][k]); *\/ */
 3931:       /* } */
 3932:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
 3933:       /* 	cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 3934:       /* 	if(Dummy[Tvard[k][1]]==0){ */
 3935:       /* 	  if(Dummy[Tvard[k][2]]==0){ */
 3936:       /* 	    cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
 3937:       /* 	  }else{ */
 3938:       /* 	    cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
 3939:       /* 	  } */
 3940:       /* 	}else{ */
 3941:       /* 	  if(Dummy[Tvard[k][2]]==0){ */
 3942:       /* 	    cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
 3943:       /* 	  }else{ */
 3944:       /* 	    cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
 3945:       /* 	  } */
 3946:       /* 	} */
 3947:       /* }			 */
 3948:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
 3949:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
 3950: /** End of old code */
 3951:       
 3952:       /* Careful transposed matrix */
 3953:       /* age is in cov[2], prevacurrent at beginning of transition. */
 3954:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
 3955:       /* 						 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
 3956:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
 3957: 		   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
 3958:       /* if((int)age == 70){ */
 3959:       /* 	printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
 3960:       /* 	for(i=1; i<=nlstate+ndeath; i++) { */
 3961:       /* 	  printf("%d pmmij ",i); */
 3962:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 3963:       /* 	    printf("%f ",pmmij[i][j]); */
 3964:       /* 	  } */
 3965:       /* 	  printf(" oldm "); */
 3966:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 3967:       /* 	    printf("%f ",oldm[i][j]); */
 3968:       /* 	  } */
 3969:       /* 	  printf("\n"); */
 3970:       /* 	} */
 3971:       /* } */
 3972:       savm=oldm;
 3973:       oldm=newm;
 3974:     }
 3975:     for(i=1; i<=nlstate+ndeath; i++)
 3976:       for(j=1;j<=nlstate+ndeath;j++) {
 3977: 	po[i][j][h]=newm[i][j];
 3978: 	/* if(h==nhstepm) */
 3979: 	/*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
 3980:       }
 3981:     /* printf("h=%d %.1f ",h, agexact); */
 3982:   } /* end h */
 3983:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
 3984:   return po;
 3985: }
 3986: 
 3987: 
 3988: #ifdef NLOPT
 3989:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
 3990:   double fret;
 3991:   double *xt;
 3992:   int j;
 3993:   myfunc_data *d2 = (myfunc_data *) pd;
 3994: /* xt = (p1-1); */
 3995:   xt=vector(1,n); 
 3996:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
 3997: 
 3998:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
 3999:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
 4000:   printf("Function = %.12lf ",fret);
 4001:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
 4002:   printf("\n");
 4003:  free_vector(xt,1,n);
 4004:   return fret;
 4005: }
 4006: #endif
 4007: 
 4008: /*************** log-likelihood *************/
 4009: double func( double *x)
 4010: {
 4011:   int i, ii, j, k, mi, d, kk, kf=0;
 4012:   int ioffset=0;
 4013:   int ipos=0,iposold=0,ncovv=0;
 4014: 
 4015:   double cotvarv, cotvarvold;
 4016:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 4017:   double **out;
 4018:   double lli; /* Individual log likelihood */
 4019:   int s1, s2;
 4020:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
 4021: 
 4022:   double bbh, survp;
 4023:   double agexact;
 4024:   double agebegin, ageend;
 4025:   /*extern weight */
 4026:   /* We are differentiating ll according to initial status */
 4027:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 4028:   /*for(i=1;i<imx;i++) 
 4029:     printf(" %d\n",s[4][i]);
 4030:   */
 4031: 
 4032:   ++countcallfunc;
 4033: 
 4034:   cov[1]=1.;
 4035: 
 4036:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 4037:   ioffset=0;
 4038:   if(mle==1){
 4039:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 4040:       /* Computes the values of the ncovmodel covariates of the model
 4041: 	 depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
 4042: 	 Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
 4043: 	 to be observed in j being in i according to the model.
 4044:       */
 4045:       ioffset=2+nagesqr ;
 4046:    /* Fixed */
 4047:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummy or quant or prod */
 4048: 	/* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
 4049:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 4050: 	/*  TvarF[1]=Tvar[6]=2,  TvarF[2]=Tvar[7]=7, TvarF[3]=Tvar[9]=1  ID of fixed covariates or product V2, V1*V2, V1 */
 4051:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
 4052: 	cov[ioffset+TvarFind[kf]]=covar[Tvar[TvarFind[kf]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (TvarFind[1]=6)*/
 4053: 	/* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
 4054:       }
 4055:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
 4056: 	 is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
 4057: 	 has been calculated etc */
 4058:       /* For an individual i, wav[i] gives the number of effective waves */
 4059:       /* We compute the contribution to Likelihood of each effective transition
 4060: 	 mw[mi][i] is real wave of the mi th effectve wave */
 4061:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
 4062: 	 s2=s[mw[mi+1][i]][i];
 4063: 	 And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i] because now is moved after nvocol+nqv 
 4064: 	 But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
 4065: 	 meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
 4066:       */
 4067:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
 4068:       /* Wave varying (but not age varying) */
 4069: 	/* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates in the model (single and product but no age )"V5+V4+V3+V4*V3+V5*age+V1*age+V1" +TvarVind 1,2,3,4(V4*V3)  Tvar[1]@7{5, 4, 3, 6, 5, 1, 1 ; 6 because the created covar is after V5 and is 6, minus 1+1, 3,2,1,4 positions in cotvar*\/ */
 4070: 	/*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
 4071: 	/*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
 4072: 	/* } */
 4073: 	for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
 4074: 	  itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
 4075: 	  ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
 4076: 	  if(FixedV[itv]!=0){ /* Not a fixed covariate */
 4077: 	    cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
 4078: 	  }else{ /* fixed covariate */
 4079: 	    cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
 4080: 	  }
 4081: 	  if(ipos!=iposold){ /* Not a product or first of a product */
 4082: 	    cotvarvold=cotvarv;
 4083: 	  }else{ /* A second product */
 4084: 	    cotvarv=cotvarv*cotvarvold;
 4085: 	  }
 4086: 	  iposold=ipos;
 4087: 	  cov[ioffset+ipos]=cotvarv;
 4088: 	}
 4089: 	/* for products of time varying to be done */
 4090: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 4091: 	  for (j=1;j<=nlstate+ndeath;j++){
 4092: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 4093: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 4094: 	  }
 4095: 
 4096: 	agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
 4097: 	ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
 4098: 	for(d=0; d<dh[mi][i]; d++){
 4099: 	  newm=savm;
 4100: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 4101: 	  cov[2]=agexact;
 4102: 	  if(nagesqr==1)
 4103: 	    cov[3]= agexact*agexact;  /* Should be changed here */
 4104: 	  /* for (kk=1; kk<=cptcovage;kk++) { */
 4105: 	  /*   if(!FixedV[Tvar[Tage[kk]]]) */
 4106: 	  /*     cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /\* Tage[kk] gives the data-covariate associated with age *\/ */
 4107: 	  /*   else */
 4108: 	  /*     cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]*agexact; /\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
 4109: 	  /* } */
 4110: 	  for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
 4111: 	    itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
 4112: 	    ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
 4113: 	    if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
 4114: 	      cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
 4115: 	    }else{ /* fixed covariate */
 4116: 	      cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
 4117: 	    }
 4118: 	    if(ipos!=iposold){ /* Not a product or first of a product */
 4119: 	      cotvarvold=cotvarv;
 4120: 	    }else{ /* A second product */
 4121: 	      cotvarv=cotvarv*cotvarvold;
 4122: 	    }
 4123: 	    iposold=ipos;
 4124: 	    cov[ioffset+ipos]=cotvarv*agexact;
 4125: 	    /* For products */
 4126: 	  }
 4127: 	  
 4128: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 4129: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 4130: 	  savm=oldm;
 4131: 	  oldm=newm;
 4132: 	} /* end mult */
 4133: 	
 4134: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 4135: 	/* But now since version 0.9 we anticipate for bias at large stepm.
 4136: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 4137: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
 4138: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
 4139: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 4140: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
 4141: 	 * probability in order to take into account the bias as a fraction of the way
 4142: 				 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
 4143: 				 * -stepm/2 to stepm/2 .
 4144: 				 * For stepm=1 the results are the same as for previous versions of Imach.
 4145: 				 * For stepm > 1 the results are less biased than in previous versions. 
 4146: 				 */
 4147: 	s1=s[mw[mi][i]][i];
 4148: 	s2=s[mw[mi+1][i]][i];
 4149: 	bbh=(double)bh[mi][i]/(double)stepm; 
 4150: 	/* bias bh is positive if real duration
 4151: 	 * is higher than the multiple of stepm and negative otherwise.
 4152: 	 */
 4153: 	/* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
 4154: 	if( s2 > nlstate){ 
 4155: 	  /* i.e. if s2 is a death state and if the date of death is known 
 4156: 	     then the contribution to the likelihood is the probability to 
 4157: 	     die between last step unit time and current  step unit time, 
 4158: 	     which is also equal to probability to die before dh 
 4159: 	     minus probability to die before dh-stepm . 
 4160: 	     In version up to 0.92 likelihood was computed
 4161: 	     as if date of death was unknown. Death was treated as any other
 4162: 	     health state: the date of the interview describes the actual state
 4163: 	     and not the date of a change in health state. The former idea was
 4164: 	     to consider that at each interview the state was recorded
 4165: 	     (healthy, disable or death) and IMaCh was corrected; but when we
 4166: 	     introduced the exact date of death then we should have modified
 4167: 	     the contribution of an exact death to the likelihood. This new
 4168: 	     contribution is smaller and very dependent of the step unit
 4169: 	     stepm. It is no more the probability to die between last interview
 4170: 	     and month of death but the probability to survive from last
 4171: 	     interview up to one month before death multiplied by the
 4172: 	     probability to die within a month. Thanks to Chris
 4173: 	     Jackson for correcting this bug.  Former versions increased
 4174: 	     mortality artificially. The bad side is that we add another loop
 4175: 	     which slows down the processing. The difference can be up to 10%
 4176: 	     lower mortality.
 4177: 	  */
 4178: 	  /* If, at the beginning of the maximization mostly, the
 4179: 	     cumulative probability or probability to be dead is
 4180: 	     constant (ie = 1) over time d, the difference is equal to
 4181: 	     0.  out[s1][3] = savm[s1][3]: probability, being at state
 4182: 	     s1 at precedent wave, to be dead a month before current
 4183: 	     wave is equal to probability, being at state s1 at
 4184: 	     precedent wave, to be dead at mont of the current
 4185: 	     wave. Then the observed probability (that this person died)
 4186: 	     is null according to current estimated parameter. In fact,
 4187: 	     it should be very low but not zero otherwise the log go to
 4188: 	     infinity.
 4189: 	  */
 4190: /* #ifdef INFINITYORIGINAL */
 4191: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 4192: /* #else */
 4193: /* 	  if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
 4194: /* 	    lli=log(mytinydouble); */
 4195: /* 	  else */
 4196: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 4197: /* #endif */
 4198: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 4199: 	  
 4200: 	} else if  ( s2==-1 ) { /* alive */
 4201: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 4202: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 4203: 	  /*survp += out[s1][j]; */
 4204: 	  lli= log(survp);
 4205: 	}
 4206: 	/* else if  (s2==-4) {  */
 4207: 	/*   for (j=3,survp=0. ; j<=nlstate; j++)   */
 4208: 	/*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
 4209: 	/*   lli= log(survp);  */
 4210: 	/* }  */
 4211: 	/* else if  (s2==-5) {  */
 4212: 	/*   for (j=1,survp=0. ; j<=2; j++)   */
 4213: 	/*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
 4214: 	/*   lli= log(survp);  */
 4215: 	/* }  */
 4216: 	else{
 4217: 	  lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 4218: 	  /*  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 */
 4219: 	} 
 4220: 	/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 4221: 	/*if(lli ==000.0)*/
 4222: 	/* printf("num[i], i=%d, 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); */
 4223: 	ipmx +=1;
 4224: 	sw += weight[i];
 4225: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 4226: 	/* if (lli < log(mytinydouble)){ */
 4227: 	/*   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); */
 4228: 	/*   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]); */
 4229: 	/* } */
 4230:       } /* end of wave */
 4231:     } /* end of individual */
 4232:   }  else if(mle==2){
 4233:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 4234:       ioffset=2+nagesqr ;
 4235:       for (k=1; k<=ncovf;k++)
 4236: 	cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
 4237:       for(mi=1; mi<= wav[i]-1; mi++){
 4238: 	for(k=1; k <= ncovv ; k++){
 4239: 	  cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; /* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
 4240: 	}
 4241: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 4242: 	  for (j=1;j<=nlstate+ndeath;j++){
 4243: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 4244: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 4245: 	  }
 4246: 	for(d=0; d<=dh[mi][i]; d++){
 4247: 	  newm=savm;
 4248: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 4249: 	  cov[2]=agexact;
 4250: 	  if(nagesqr==1)
 4251: 	    cov[3]= agexact*agexact;
 4252: 	  for (kk=1; kk<=cptcovage;kk++) {
 4253: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 4254: 	  }
 4255: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 4256: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 4257: 	  savm=oldm;
 4258: 	  oldm=newm;
 4259: 	} /* end mult */
 4260:       
 4261: 	s1=s[mw[mi][i]][i];
 4262: 	s2=s[mw[mi+1][i]][i];
 4263: 	bbh=(double)bh[mi][i]/(double)stepm; 
 4264: 	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 */
 4265: 	ipmx +=1;
 4266: 	sw += weight[i];
 4267: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 4268:       } /* end of wave */
 4269:     } /* end of individual */
 4270:   }  else if(mle==3){  /* exponential inter-extrapolation */
 4271:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 4272:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 4273:       for(mi=1; mi<= wav[i]-1; mi++){
 4274: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 4275: 	  for (j=1;j<=nlstate+ndeath;j++){
 4276: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 4277: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 4278: 	  }
 4279: 	for(d=0; d<dh[mi][i]; d++){
 4280: 	  newm=savm;
 4281: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 4282: 	  cov[2]=agexact;
 4283: 	  if(nagesqr==1)
 4284: 	    cov[3]= agexact*agexact;
 4285: 	  for (kk=1; kk<=cptcovage;kk++) {
 4286: 	    if(!FixedV[Tvar[Tage[kk]]])
 4287: 	      cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
 4288: 	    else
 4289: 	      cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]*agexact; /* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
 4290: 	  }
 4291: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 4292: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 4293: 	  savm=oldm;
 4294: 	  oldm=newm;
 4295: 	} /* end mult */
 4296:       
 4297: 	s1=s[mw[mi][i]][i];
 4298: 	s2=s[mw[mi+1][i]][i];
 4299: 	bbh=(double)bh[mi][i]/(double)stepm; 
 4300: 	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 */
 4301: 	ipmx +=1;
 4302: 	sw += weight[i];
 4303: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 4304:       } /* end of wave */
 4305:     } /* end of individual */
 4306:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
 4307:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 4308:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 4309:       for(mi=1; mi<= wav[i]-1; mi++){
 4310: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 4311: 	  for (j=1;j<=nlstate+ndeath;j++){
 4312: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 4313: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 4314: 	  }
 4315: 	for(d=0; d<dh[mi][i]; d++){
 4316: 	  newm=savm;
 4317: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 4318: 	  cov[2]=agexact;
 4319: 	  if(nagesqr==1)
 4320: 	    cov[3]= agexact*agexact;
 4321: 	  for (kk=1; kk<=cptcovage;kk++) {
 4322: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 4323: 	  }
 4324: 	
 4325: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 4326: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 4327: 	  savm=oldm;
 4328: 	  oldm=newm;
 4329: 	} /* end mult */
 4330:       
 4331: 	s1=s[mw[mi][i]][i];
 4332: 	s2=s[mw[mi+1][i]][i];
 4333: 	if( s2 > nlstate){ 
 4334: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 4335: 	} else if  ( s2==-1 ) { /* alive */
 4336: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 4337: 	    survp += out[s1][j];
 4338: 	  lli= log(survp);
 4339: 	}else{
 4340: 	  lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 4341: 	}
 4342: 	ipmx +=1;
 4343: 	sw += weight[i];
 4344: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 4345: 	/* printf("num[i]=%09ld, 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",num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
 4346:       } /* end of wave */
 4347:     } /* end of individual */
 4348:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
 4349:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 4350:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 4351:       for(mi=1; mi<= wav[i]-1; mi++){
 4352: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 4353: 	  for (j=1;j<=nlstate+ndeath;j++){
 4354: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 4355: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 4356: 	  }
 4357: 	for(d=0; d<dh[mi][i]; d++){
 4358: 	  newm=savm;
 4359: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 4360: 	  cov[2]=agexact;
 4361: 	  if(nagesqr==1)
 4362: 	    cov[3]= agexact*agexact;
 4363: 	  for (kk=1; kk<=cptcovage;kk++) {
 4364: 	    if(!FixedV[Tvar[Tage[kk]]])
 4365: 	      cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
 4366: 	    else
 4367: 	      cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]*agexact; /* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
 4368: 	  }
 4369: 	
 4370: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 4371: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 4372: 	  savm=oldm;
 4373: 	  oldm=newm;
 4374: 	} /* end mult */
 4375:       
 4376: 	s1=s[mw[mi][i]][i];
 4377: 	s2=s[mw[mi+1][i]][i];
 4378: 	lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 4379: 	ipmx +=1;
 4380: 	sw += weight[i];
 4381: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 4382: 	/*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]);*/
 4383:       } /* end of wave */
 4384:     } /* end of individual */
 4385:   } /* End of if */
 4386:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 4387:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 4388:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 4389:   return -l;
 4390: }
 4391: 
 4392: /*************** log-likelihood *************/
 4393: double funcone( double *x)
 4394: {
 4395:   /* Same as func but slower because of a lot of printf and if */
 4396:   int i, ii, j, k, mi, d, kk, kv=0, kf=0;
 4397:   int ioffset=0;
 4398:   int ipos=0,iposold=0,ncovv=0;
 4399: 
 4400:   double cotvarv, cotvarvold;
 4401:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 4402:   double **out;
 4403:   double lli; /* Individual log likelihood */
 4404:   double llt;
 4405:   int s1, s2;
 4406:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
 4407: 
 4408:   double bbh, survp;
 4409:   double agexact;
 4410:   double agebegin, ageend;
 4411:   /*extern weight */
 4412:   /* We are differentiating ll according to initial status */
 4413:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 4414:   /*for(i=1;i<imx;i++) 
 4415:     printf(" %d\n",s[4][i]);
 4416:   */
 4417:   cov[1]=1.;
 4418: 
 4419:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 4420:   ioffset=0;
 4421:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 4422:     /* Computes the values of the ncovmodel covariates of the model
 4423:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
 4424:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
 4425:        to be observed in j being in i according to the model.
 4426:     */
 4427:     /* ioffset=2+nagesqr+cptcovage; */
 4428:     ioffset=2+nagesqr;
 4429:     /* Fixed */
 4430:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
 4431:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
 4432:     for (kf=1; kf<=ncovf;kf++){ /*  V2  +  V3  +  V4  Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
 4433:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
 4434:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
 4435:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
 4436:       cov[ioffset+TvarFind[kf]]=covar[Tvar[TvarFind[kf]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (k=6)*/
 4437: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
 4438: /*    cov[2+6]=covar[Tvar[6]][i];  */
 4439: /*    cov[2+6]=covar[2][i]; V2  */
 4440: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
 4441: /*    cov[2+7]=covar[Tvar[7]][i];  */
 4442: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
 4443: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
 4444: /*    cov[2+9]=covar[Tvar[9]][i];  */
 4445: /*    cov[2+9]=covar[1][i]; V1  */
 4446:     }
 4447:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
 4448: 	 is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
 4449: 	 has been calculated etc */
 4450:       /* For an individual i, wav[i] gives the number of effective waves */
 4451:       /* We compute the contribution to Likelihood of each effective transition
 4452: 	 mw[mi][i] is real wave of the mi th effectve wave */
 4453:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
 4454: 	 s2=s[mw[mi+1][i]][i];
 4455: 	 And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
 4456:       */
 4457:     /* This part may be useless now because everythin should be in covar */
 4458:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
 4459:     /*   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?)*\/ */
 4460:     /* } */
 4461:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
 4462:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
 4463:     /* } */
 4464:     
 4465: 
 4466:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
 4467:       /* Wave varying (but not age varying) *//* V1+V3+age*V1+age*V3+V1*V3 with V4 tv and V5 tvq k= 1 to 5 and extra at V(5+1)=6 for V1*V3 */
 4468:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
 4469:       /* 	/\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
 4470:       /* 	cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
 4471:       /* } */
 4472:       
 4473:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
 4474:       /* model V1+V3+age*V1+age*V3+V1*V3 */
 4475:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
 4476:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
 4477:       /* We need the position of the time varying or product in the model */
 4478:       /* TvarVVind={2,5,5}, for V3 at position 2 and then the product V1*V3 is decomposed into V1 and V3 but at same position 5 */	       
 4479:       /* TvarVV gives the variable name */
 4480:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
 4481:       *      k=         1   2     3     4         5        6        7       8        9
 4482:       *  varying            1     2                                 3       4        5
 4483:       *  ncovv              1     2                                3 4     5 6      7 8
 4484:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
 4485:       * TvarVVind           2     3                                7 7     8 8      9 9
 4486:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
 4487:       */
 4488:       /* Other model ncovcol=5 nqv=0 ntv=3 nqtv=0 nlstate=3
 4489:        * V2 V3 V4 are fixed V6 V7 are timevarying so V8 and V5 are not in the model and product column will start at 9 Tvar[(v6*V2)6]=9
 4490: 	* FixedV[ncovcol+qv+ntv+nqtv]       V5
 4491: 	* 3           V1  V2     V3    V4   V5 V6     V7  V8 V3*V2 V7*V2  V6*V3 V7*V3 V6*V4 V7*V4
 4492: 	*             0   0      0      0    0  1      1   1  0, 0, 1,1,   1, 0, 1, 0, 1, 0, 1, 0}
 4493: 	* 3           0   0      0      0    0  1      1   1  0,     1      1    1      1    1}
 4494: 	* model=          V2  +  V3  +  V4  +  V6  +  V7  +  V6*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
 4495:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
 4496:         *                +age*V6*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
 4497: 	* model2=          V2  +  V3  +  V4  +  V6  +  V7  +  V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
 4498:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
 4499:         *                +age*V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
 4500: 	* model3=          V2  +  V3  +  V4  +  V6  +  V7  + age*V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
 4501:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
 4502:         *                +V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
 4503: 	* kmodel           1     2      3      4      5        6         7         8         9        10        11    
 4504: 	*                  12       13      14      15       16
 4505: 	*                    17        18         19        20         21
 4506: 	* Tvar[kmodel]     2     3      4      6      7        9        10        11        12        13        14
 4507: 	*                   2       3        4       6        7
 4508: 	*                     9         11          12        13         14            
 4509: 	* cptcovage=5+5 total of covariates with age 
 4510: 	* Tage[cptcovage] age*V2=12      13      14      15       16
 4511: 	*1                   17            18         19        20         21 gives the position in model of covariates associated with age
 4512: 	*3 Tage[cptcovage] age*V3*V2=6  
 4513: 	*3                age*V2=12         13      14      15       16
 4514: 	*3                age*V6*V3=18      19    20   21
 4515: 	* Tvar[Tage[cptcovage]]    Tvar[12]=2      3      4       6         Tvar[16]=7(age*V7)
 4516: 	*     Tvar[17]age*V6*V2=9      Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
 4517: 	* 2   Tvar[17]age*V3*V2=9      Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
 4518: 	* 3 Tvar[Tage[cptcovage]]    Tvar[6]=9      Tvar[12]=2      3     4       6         Tvar[16]=7(age*V7)
 4519: 	* 3     Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
 4520: 	* 3 Tage[cptcovage] age*V3*V2=6   age*V2=12 age*V3 13    14      15       16
 4521: 	*                    age*V6*V3=18         19        20         21 gives the position in model of covariates associated with age
 4522: 	* 3   Tvar[17]age*V3*V2=9      Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
 4523: 	* Tvar=                {2, 3, 4, 6, 7,
 4524: 	*                       9, 10, 11, 12, 13, 14,
 4525: 	*              Tvar[12]=2, 3, 4, 6, 7,
 4526: 	*              Tvar[17]=9, 11, 12, 13, 14}
 4527: 	* Typevar[1]@21 = {0, 0, 0, 0, 0,
 4528: 	*                  2, 2, 2, 2, 2, 2,
 4529: 	* 3                3, 2, 2, 2, 2, 2,
 4530: 	*                  1, 1, 1, 1, 1, 
 4531: 	*                  3, 3, 3, 3, 3}
 4532: 	* 3                 2, 3, 3, 3, 3}
 4533: 	* p Tposprod[1]@21 {0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 1, 3, 4, 5, 6} Id of the prod at position k in the model
 4534: 	* p Tprod[1]@21 {6, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
 4535: 	* 3 Tposprod[1]@21 {0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 1, 3, 4, 5, 6}
 4536: 	* 3 Tprod[1]@21 {17, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
 4537: 	* cptcovprod=11 (6+5)
 4538: 	* FixedV[Tvar[Tage[cptcovage]]]]  FixedV[2]=0      FixedV[3]=0      0      1          (age*V7)Tvar[16]=1 FixedV[absolute] not [kmodel]
 4539: 	*   FixedV[Tvar[17]=FixedV[age*V6*V2]=FixedV[9]=1        1         1          1         1  
 4540: 	* 3 FixedV[Tvar[17]=FixedV[age*V3*V2]=FixedV[9]=0        [11]=1         1          1         1  
 4541: 	* FixedV[]          V1=0     V2=0   V3=0  v4=0    V5=0  V6=1    V7=1 v8=1  OK then model dependent
 4542: 	*                   9=1  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
 4543: 	* 3                 9=0  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
 4544: 	* cptcovdageprod=5  for gnuplot printing
 4545: 	* cptcovprodvage=6 
 4546: 	* ncova=15           1        2       3       4       5
 4547: 	*                      6 7        8 9      10 11        12 13     14 15
 4548: 	* TvarA              2        3       4       6       7
 4549: 	*                      6 2        6 7       7 3          6 4       7 4
 4550: 	* TvaAind             12 12      13 13     14 14      15 15       16 16        
 4551: 	* ncovf            1     2      3
 4552: 	*                                    V6       V7      V6*V2     V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
 4553: 	* ncovvt=14                            1      2        3 4       5 6       7 8       9 10     11 12     13 14     
 4554: 	* TvarVV[1]@14 = itv               {V6=6,     7, V6*V2=6, 2,     7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
 4555: 	* TvarVVind[1]@14=                    {4,     5,       6, 6,     7, 7,     8, 8,      9, 9,   10, 10,   11, 11}
 4556: 	* 3 ncovvt=12                        V6       V7      V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
 4557: 	* 3 TvarVV[1]@12 = itv                {6,     7, V7*V2=7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
 4558: 	* 3                                    1      2        3  4      5  6      7  8      9 10     11 12
 4559: 	* TvarVVind[1]@12=         {V6 is in k=4,     5,  7,(4isV2)=7,   8, 8,      9, 9,   10,10,    11,11}TvarVVind[12]=k=11
 4560: 	* TvarV              6, 7, 9, 10, 11, 12, 13, 14
 4561: 	* 3 cptcovprodvage=6
 4562: 	* 3 ncovta=15    +age*V3*V2+age*V2+agev3+ageV4 +age*V6 + age*V7 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
 4563: 	* 3 TvarAVVA[1]@15= itva 3 2    2      3    4        6       7        6 3         7 3         6 4         7 4 
 4564: 	* 3 ncovta             1 2      3      4    5        6       7        8 9       10 11       12 13        14 15
 4565: 	*?TvarAVVAind[1]@15= V3 is in k=2 1 1  2    3        4       5        4,2         5,2,      4,3           5 3}TvarVVAind[]
 4566: 	* TvarAVVAind[1]@15= V3 is in k=6 6 12  13   14      15      16       18 18       19,19,     20,20        21,21}TvarVVAind[]
 4567: 	* 3 ncovvta=10     +age*V6 + age*V7 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
 4568: 	* 3 we want to compute =cotvar[mw[mi][i]][TvarVVA[ncovva]][i] at position TvarVVAind[ncovva]
 4569: 	* 3 TvarVVA[1]@10= itva   6       7        6 3         7 3         6 4         7 4 
 4570: 	* 3 ncovva                1       2        3 4         5 6         7 8         9 10
 4571: 	* TvarVVAind[1]@10= V6 is in k=4  5        8,8         9, 9,      10,10        11 11}TvarVVAind[]
 4572: 	* TvarVVAind[1]@10=       15       16     18,18        19,19,      20,20        21 21}TvarVVAind[]
 4573: 	* TvarVA              V3*V2=6 6 , 1, 2, 11, 12, 13, 14
 4574: 	* TvarFind[1]@14= {1,    2,     3,     0 <repeats 12 times>}
 4575: 	* Tvar[1]@21=     {2,    3,     4,    6,      7,      9,      10,        11,       12,      13,       14,
 4576: 	*                   2, 3, 4, 6, 7,
 4577: 	*                     6, 8, 9, 10, 11}
 4578: 	* TvarFind[itv]                        0      0       0
 4579: 	* FixedV[itv]                          1      1       1  0      1 0       1 0       1 0       0
 4580: 	*? FixedV[itv]                          1      1       1  0      1 0       1 0       1 0      1 0     1 0
 4581: 	* Tvar[TvarFind[ncovf]]=[1]=2 [2]=3 [4]=4
 4582: 	* Tvar[TvarFind[itv]]                [0]=?      ?ncovv 1 à ncovvt]
 4583: 	*   Not a fixed cotvar[mw][itv][i]     6       7      6  2      7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
 4584: 	*   fixed covar[itv]                  [6]     [7]    [6][2] 
 4585: 	*/
 4586: 
 4587:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /*  V6       V7      V7*V2     V6*V3     V7*V3     V6*V4     V7*V4 Time varying  covariates (single and extended product but no age) including individual from products, product is computed dynamically */
 4588: 	itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, or fixed covariate of a varying product after exploding product Vn*Vm into Vn and then Vm  */
 4589: 	ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
 4590: 	/* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
 4591: 	if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
 4592: 	  /* printf("DEBUG ncovv=%d, Varying TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
 4593: 	  cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
 4594: 	  /* printf("DEBUG Varying cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
 4595: 	}else{ /* fixed covariate */
 4596: 	  /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
 4597: 	  /* printf("DEBUG ncovv=%d, Fixed TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
 4598: 	  cotvarv=covar[itv][i];  /* Good: In V6*V3, 3 is fixed at position of the data */
 4599: 	  /* printf("DEBUG Fixed cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
 4600: 	}
 4601: 	if(ipos!=iposold){ /* Not a product or first of a product */
 4602: 	  cotvarvold=cotvarv;
 4603: 	}else{ /* A second product */
 4604: 	  cotvarv=cotvarv*cotvarvold;
 4605: 	}
 4606: 	iposold=ipos;
 4607: 	cov[ioffset+ipos]=cotvarv;
 4608: 	/* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
 4609: 	/* For products */
 4610:       }
 4611:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
 4612:       /* 	iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
 4613:       /* 	/\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
 4614:       /* 	/\*           1  2   3      4      5                         *\/ */
 4615:       /* 	/\*itv           1                                           *\/ */
 4616:       /* 	/\* TvarVInd[1]= 2                                           *\/ */
 4617:       /* 	/\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
 4618:       /* 	/\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
 4619:       /* 	/\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
 4620:       /* 	/\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
 4621:       /* 	/\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
 4622:       /* 	cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
 4623:       /* 	/\* printf(" i=%d,mi=%d,itv=%d,TmodelInvind[itv]=%d,cotvar[mw[mi][i]][itv][i]=%f\n", i, mi, itv, TvarVDind[itv],cotvar[mw[mi][i]][itv][i]); *\/ */
 4624:       /* } */
 4625:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
 4626:       /* 	iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
 4627:       /* 	/\* 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]); *\/ */
 4628:       /* 	cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
 4629:       /* } */
 4630:       for (ii=1;ii<=nlstate+ndeath;ii++)
 4631: 	for (j=1;j<=nlstate+ndeath;j++){
 4632: 	  oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 4633: 	  savm[ii][j]=(ii==j ? 1.0 : 0.0);
 4634: 	}
 4635:       
 4636:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
 4637:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
 4638:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
 4639:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
 4640: 	/*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 4641: 	  and mw[mi+1][i]. dh depends on stepm.*/
 4642: 	newm=savm;
 4643: 	agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
 4644: 	cov[2]=agexact;
 4645: 	if(nagesqr==1)
 4646: 	  cov[3]= agexact*agexact;
 4647: 	for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
 4648: 	  itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
 4649: 	  ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
 4650: 	  /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
 4651: 	  if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
 4652: 	    /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
 4653: 	    cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
 4654: 	  }else{ /* fixed covariate */
 4655: 	    /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
 4656: 	    /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
 4657: 	    cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
 4658: 	  }
 4659: 	  if(ipos!=iposold){ /* Not a product or first of a product */
 4660: 	    cotvarvold=cotvarv;
 4661: 	  }else{ /* A second product */
 4662: 	    /* printf("DEBUG * \n"); */
 4663: 	    cotvarv=cotvarv*cotvarvold;
 4664: 	  }
 4665: 	  iposold=ipos;
 4666: 	  /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
 4667: 	  cov[ioffset+ipos]=cotvarv*agexact;
 4668: 	  /* For products */
 4669: 	}
 4670: 
 4671: 	/* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
 4672: 	/* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 4673: 	out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 4674: 		     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 4675: 	/* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
 4676: 	/* 	     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
 4677: 	savm=oldm;
 4678: 	oldm=newm;
 4679:       } /* end mult */
 4680: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 4681: 	/* But now since version 0.9 we anticipate for bias at large stepm.
 4682: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 4683: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
 4684: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
 4685: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 4686: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
 4687: 	 * probability in order to take into account the bias as a fraction of the way
 4688: 				 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
 4689: 				 * -stepm/2 to stepm/2 .
 4690: 				 * For stepm=1 the results are the same as for previous versions of Imach.
 4691: 				 * For stepm > 1 the results are less biased than in previous versions. 
 4692: 				 */
 4693:       s1=s[mw[mi][i]][i];
 4694:       s2=s[mw[mi+1][i]][i];
 4695:       /* if(s2==-1){ */
 4696:       /* 	printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
 4697:       /* 	/\* exit(1); *\/ */
 4698:       /* } */
 4699:       bbh=(double)bh[mi][i]/(double)stepm; 
 4700:       /* bias is positive if real duration
 4701:        * is higher than the multiple of stepm and negative otherwise.
 4702:        */
 4703:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
 4704: 	lli=log(out[s1][s2] - savm[s1][s2]);
 4705:       } else if  ( s2==-1 ) { /* alive */
 4706: 	for (j=1,survp=0. ; j<=nlstate; j++) 
 4707: 	  survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 4708: 	lli= log(survp);
 4709:       }else if (mle==1){
 4710: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 4711:       } else if(mle==2){
 4712: 	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 */
 4713:       } else if(mle==3){  /* exponential inter-extrapolation */
 4714: 	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 */
 4715:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
 4716: 	lli=log(out[s1][s2]); /* Original formula */
 4717:       } else{  /* mle=0 back to 1 */
 4718: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 4719: 	/*lli=log(out[s1][s2]); */ /* Original formula */
 4720:       } /* End of if */
 4721:       ipmx +=1;
 4722:       sw += weight[i];
 4723:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 4724:       /* Printing covariates values for each contribution for checking */
 4725:       /* printf("num[i]=%09ld, 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",num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
 4726:       if(globpr){
 4727: 	fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
 4728:  %11.6f %11.6f %11.6f ", \
 4729: 		num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
 4730: 		2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
 4731: 	/* 	printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
 4732: 	/* %11.6f %11.6f %11.6f ", \ */
 4733: 	/* 		num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
 4734: 	/* 		2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
 4735: 	for(k=1,llt=0.,l=0.; k<=nlstate; k++){
 4736: 	  llt +=ll[k]*gipmx/gsw;
 4737: 	  fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
 4738: 	  /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
 4739: 	}
 4740: 	fprintf(ficresilk," %10.6f ", -llt);
 4741: 	/* printf(" %10.6f\n", -llt); */
 4742: 	/* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
 4743: 	/* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
 4744: 	for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
 4745: 	  fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
 4746: 	}
 4747: 	for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
 4748: 	  ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
 4749: 	  if(ipos!=iposold){ /* Not a product or first of a product */
 4750: 	    fprintf(ficresilk," %g",cov[ioffset+ipos]);
 4751: 	    /* printf(" %g",cov[ioffset+ipos]); */
 4752: 	  }else{
 4753: 	    fprintf(ficresilk,"*");
 4754: 	    /* printf("*"); */
 4755: 	  }
 4756: 	  iposold=ipos;
 4757: 	}
 4758: 	/* for (kk=1; kk<=cptcovage;kk++) { */
 4759: 	/*   if(!FixedV[Tvar[Tage[kk]]]){ */
 4760: 	/*     fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]); */
 4761: 	/*     /\* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); *\/ */
 4762: 	/*   }else{ */
 4763: 	/*     fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
 4764: 	/*     /\* printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\\/  *\/ */
 4765: 	/*   } */
 4766: 	/* } */
 4767: 	for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
 4768: 	  itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
 4769: 	  ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
 4770: 	  /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
 4771: 	  if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
 4772: 	    /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
 4773: 	    cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
 4774: 	  }else{ /* fixed covariate */
 4775: 	    /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
 4776: 	    /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
 4777: 	    cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
 4778: 	  }
 4779: 	  if(ipos!=iposold){ /* Not a product or first of a product */
 4780: 	    cotvarvold=cotvarv;
 4781: 	  }else{ /* A second product */
 4782: 	    /* printf("DEBUG * \n"); */
 4783: 	    cotvarv=cotvarv*cotvarvold;
 4784: 	  }
 4785: 	  cotvarv=cotvarv*agexact;
 4786: 	  fprintf(ficresilk," %g*age",cotvarv);
 4787: 	  iposold=ipos;
 4788: 	  /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
 4789: 	  cov[ioffset+ipos]=cotvarv;
 4790: 	  /* For products */
 4791: 	}
 4792: 	/* printf("\n"); */
 4793: 	/* } /\*  End debugILK *\/ */
 4794: 	fprintf(ficresilk,"\n");
 4795:       } /* End if globpr */
 4796:     } /* end of wave */
 4797:   } /* end of individual */
 4798:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 4799: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 4800:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 4801:   if(globpr==0){ /* First time we count the contributions and weights */
 4802:     gipmx=ipmx;
 4803:     gsw=sw;
 4804:   }
 4805:   return -l;
 4806: }
 4807: 
 4808: 
 4809: /*************** function likelione ***********/
 4810: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
 4811: {
 4812:   /* This routine should help understanding what is done with 
 4813:      the selection of individuals/waves and
 4814:      to check the exact contribution to the likelihood.
 4815:      Plotting could be done.
 4816:   */
 4817:   void pstamp(FILE *ficres);
 4818:   int k, kf, kk, kvar, ncovv, iposold, ipos;
 4819: 
 4820:   if(*globpri !=0){ /* Just counts and sums, no printings */
 4821:     strcpy(fileresilk,"ILK_"); 
 4822:     strcat(fileresilk,fileresu);
 4823:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
 4824:       printf("Problem with resultfile: %s\n", fileresilk);
 4825:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
 4826:     }
 4827:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
 4828:     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");
 4829:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
 4830:     /* 	i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
 4831:     for(k=1; k<=nlstate; k++) 
 4832:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
 4833:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
 4834: 
 4835:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
 4836:       for(kf=1;kf <= ncovf; kf++){
 4837: 	fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
 4838: 	/* printf("V%d",Tvar[TvarFind[kf]]); */
 4839:       }
 4840:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
 4841: 	ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
 4842: 	if(ipos!=iposold){ /* Not a product or first of a product */
 4843: 	  /* printf(" %d",ipos); */
 4844: 	  fprintf(ficresilk," V%d",TvarVV[ncovv]);
 4845: 	}else{
 4846: 	  /* printf("*"); */
 4847: 	  fprintf(ficresilk,"*");
 4848: 	}
 4849: 	iposold=ipos;
 4850:       }
 4851:       for (kk=1; kk<=cptcovage;kk++) {
 4852: 	if(!FixedV[Tvar[Tage[kk]]]){
 4853: 	  /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
 4854: 	  fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
 4855: 	}else{
 4856: 	  fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
 4857: 	  /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
 4858: 	}
 4859:       }
 4860:     /* } /\* End if debugILK *\/ */
 4861:     /* printf("\n"); */
 4862:     fprintf(ficresilk,"\n");
 4863:   } /* End glogpri */
 4864: 
 4865:   *fretone=(*func)(p);
 4866:   if(*globpri !=0){
 4867:     fclose(ficresilk);
 4868:     if (mle ==0)
 4869:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
 4870:     else if(mle >=1)
 4871:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
 4872:     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));
 4873:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
 4874:       
 4875:     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> \
 4876: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
 4877:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
 4878: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
 4879:     
 4880:     for (k=1; k<= nlstate ; k++) {
 4881:       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>\n \
 4882: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
 4883:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
 4884: 	 kvar=Tvar[TvarFind[kf]];  /* variable */
 4885: 	 fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j with colored covariate V%d. Same dot size of all points but with a different color for transitions with dummy variable V%d=1 at beginning of transition (keeping former color for V%d=0): ",k,k,Tvar[TvarFind[kf]],Tvar[TvarFind[kf]],Tvar[TvarFind[kf]]);
 4886: 	 fprintf(fichtm,"<a href=\"%s-p%dj-%d.png\">%s-p%dj-%d.png</a><br>",subdirf2(optionfilefiname,"ILK_"),k,kvar,subdirf2(optionfilefiname,"ILK_"),k,kvar);
 4887: 	 fprintf(fichtm,"<img src=\"%s-p%dj-%d.png\">",subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]);
 4888:       }
 4889:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
 4890: 	ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
 4891: 	kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
 4892: 	/* printf("DebugILK fichtm ncovv=%d, kvar=TvarVV[ncovv]=V%d, ipos=TvarVVind[ncovv]=%d, Dummy[ipos]=%d, Typevar[ipos]=%d\n", ncovv,kvar,ipos,Dummy[ipos],Typevar[ipos]); */
 4893: 	if(ipos!=iposold){ /* Not a product or first of a product */
 4894: 	  /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
 4895: 	  /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
 4896: 	  if(Dummy[ipos]==0 && Typevar[ipos]==0){ /* Only if dummy time varying: Dummy(0, 1=quant singor prod without age,2 dummy*age, 3quant*age) Typevar (0 single, 1=*age,2=Vn*vm)  */
 4897: 	    fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j with colored time varying dummy covariate V%d. Same dot size of all points but with a different color for transitions with dummy variable V%d=1 at beginning of transition (keeping former color for V%d=0): <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
 4898: <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar);
 4899: 	  } /* End only for dummies time varying (single?) */
 4900: 	}else{ /* Useless product */
 4901: 	  /* printf("*"); */
 4902: 	  /* fprintf(ficresilk,"*"); */ 
 4903: 	}
 4904: 	iposold=ipos;
 4905:       } /* For each time varying covariate */
 4906:     } /* End loop on states */
 4907: 
 4908: /*     if(debugILK){ */
 4909: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
 4910: /* 	/\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
 4911: /* 	for (k=1; k<= nlstate ; k++) { */
 4912: /* 	  fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j with colored covariate V%. Same dot size of all points but with a different color for transitions with dummy variable V%d=1 at beginning of transition (keeping former color for V%d=0): <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \ */
 4913: /* <img src=\"%s-p%dj-%d.png\">",k,k,Tvar[TvarFind[kf]],Tvar[TvarFind[kf]],Tvar[TvarFind[kf]],subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]); */
 4914: /* 	} */
 4915: /*       } */
 4916: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
 4917: /* 	ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
 4918: /* 	kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
 4919: /* 	/\* printf("DebugILK fichtm ncovv=%d, kvar=TvarVV[ncovv]=V%d, ipos=TvarVVind[ncovv]=%d, Dummy[ipos]=%d, Typevar[ipos]=%d\n", ncovv,kvar,ipos,Dummy[ipos],Typevar[ipos]); *\/ */
 4920: /* 	if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
 4921: /* 	  /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
 4922: /* 	  /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
 4923: /* 	  if(Dummy[ipos]==0 && Typevar[ipos]==0){ /\* Only if dummy time varying: Dummy(0, 1=quant singor prod without age,2 dummy*age, 3quant*age) Typevar (0 single, 1=*age,2=Vn*vm)  *\/ */
 4924: /* 	    for (k=1; k<= nlstate ; k++) { */
 4925: /* 	      fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j. Same dot size of all points but with a different color for transitions with dummy variable V%d=1 at beginning of transition (keeping former color for V%d=0): <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \ */
 4926: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
 4927: /* 	    } /\* End state *\/ */
 4928: /* 	  } /\* End only for dummies time varying (single?) *\/ */
 4929: /* 	}else{ /\* Useless product *\/ */
 4930: /* 	  /\* printf("*"); *\/ */
 4931: /* 	  /\* fprintf(ficresilk,"*"); *\/  */
 4932: /* 	} */
 4933: /* 	iposold=ipos; */
 4934: /*       } /\* For each time varying covariate *\/ */
 4935: /*     }/\* End debugILK *\/ */
 4936:     fflush(fichtm);
 4937:   }/* End globpri */
 4938:   return;
 4939: }
 4940: 
 4941: 
 4942: /*********** Maximum Likelihood Estimation ***************/
 4943: 
 4944: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
 4945: {
 4946:   int i,j,k, jk, jkk=0, iter=0;
 4947:   double **xi;
 4948:   double fret;
 4949:   double fretone; /* Only one call to likelihood */
 4950:   /*  char filerespow[FILENAMELENGTH];*/
 4951:   
 4952:   double * p1; /* Shifted parameters from 0 instead of 1 */
 4953: #ifdef NLOPT
 4954:   int creturn;
 4955:   nlopt_opt opt;
 4956:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
 4957:   double *lb;
 4958:   double minf; /* the minimum objective value, upon return */
 4959: 
 4960:   myfunc_data dinst, *d = &dinst;
 4961: #endif
 4962: 
 4963: 
 4964:   xi=matrix(1,npar,1,npar);
 4965:   for (i=1;i<=npar;i++)
 4966:     for (j=1;j<=npar;j++)
 4967:       xi[i][j]=(i==j ? 1.0 : 0.0);
 4968:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
 4969:   strcpy(filerespow,"POW_"); 
 4970:   strcat(filerespow,fileres);
 4971:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
 4972:     printf("Problem with resultfile: %s\n", filerespow);
 4973:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 4974:   }
 4975:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
 4976:   for (i=1;i<=nlstate;i++)
 4977:     for(j=1;j<=nlstate+ndeath;j++)
 4978:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 4979:   fprintf(ficrespow,"\n");
 4980: #ifdef POWELL
 4981: #ifdef LINMINORIGINAL
 4982: #else /* LINMINORIGINAL */
 4983:   
 4984:   flatdir=ivector(1,npar); 
 4985:   for (j=1;j<=npar;j++) flatdir[j]=0; 
 4986: #endif /*LINMINORIGINAL */
 4987: 
 4988: #ifdef FLATSUP
 4989:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
 4990:   /* reorganizing p by suppressing flat directions */
 4991:   for(i=1, jk=1; i <=nlstate; i++){
 4992:     for(k=1; k <=(nlstate+ndeath); k++){
 4993:       if (k != i) {
 4994:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
 4995:         if(flatdir[jk]==1){
 4996:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
 4997:         }
 4998:         for(j=1; j <=ncovmodel; j++){
 4999:           printf("%12.7f ",p[jk]);
 5000:           jk++; 
 5001:         }
 5002:         printf("\n");
 5003:       }
 5004:     }
 5005:   }
 5006: /* skipping */
 5007:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
 5008:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
 5009:     for(k=1; k <=(nlstate+ndeath); k++){
 5010:       if (k != i) {
 5011:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
 5012:         if(flatdir[jk]==1){
 5013:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
 5014:           for(j=1; j <=ncovmodel;  jk++,j++){
 5015:             printf(" p[%d]=%12.7f",jk, p[jk]);
 5016:             /*q[jjk]=p[jk];*/
 5017:           }
 5018:         }else{
 5019:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
 5020:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
 5021:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
 5022:             /*q[jjk]=p[jk];*/
 5023:           }
 5024:         }
 5025:         printf("\n");
 5026:       }
 5027:       fflush(stdout);
 5028:     }
 5029:   }
 5030:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
 5031: #else  /* FLATSUP */
 5032:   powell(p,xi,npar,ftol,&iter,&fret,func);
 5033: #endif  /* FLATSUP */
 5034: 
 5035: #ifdef LINMINORIGINAL
 5036: #else
 5037:       free_ivector(flatdir,1,npar); 
 5038: #endif  /* LINMINORIGINAL*/
 5039: #endif /* POWELL */
 5040: 
 5041: #ifdef NLOPT
 5042: #ifdef NEWUOA
 5043:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
 5044: #else
 5045:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
 5046: #endif
 5047:   lb=vector(0,npar-1);
 5048:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
 5049:   nlopt_set_lower_bounds(opt, lb);
 5050:   nlopt_set_initial_step1(opt, 0.1);
 5051:   
 5052:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
 5053:   d->function = func;
 5054:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
 5055:   nlopt_set_min_objective(opt, myfunc, d);
 5056:   nlopt_set_xtol_rel(opt, ftol);
 5057:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
 5058:     printf("nlopt failed! %d\n",creturn); 
 5059:   }
 5060:   else {
 5061:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
 5062:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
 5063:     iter=1; /* not equal */
 5064:   }
 5065:   nlopt_destroy(opt);
 5066: #endif
 5067: #ifdef FLATSUP
 5068:   /* npared = npar -flatd/ncovmodel; */
 5069:   /* xired= matrix(1,npared,1,npared); */
 5070:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
 5071:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
 5072:   /* free_matrix(xire,1,npared,1,npared); */
 5073: #else  /* FLATSUP */
 5074: #endif /* FLATSUP */
 5075:   free_matrix(xi,1,npar,1,npar);
 5076:   fclose(ficrespow);
 5077:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 5078:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 5079:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 5080: 
 5081: }
 5082: 
 5083: /**** Computes Hessian and covariance matrix ***/
 5084: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
 5085: {
 5086:   double  **a,**y,*x,pd;
 5087:   /* double **hess; */
 5088:   int i, j;
 5089:   int *indx;
 5090: 
 5091:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
 5092:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
 5093:   void lubksb(double **a, int npar, int *indx, double b[]) ;
 5094:   void ludcmp(double **a, int npar, int *indx, double *d) ;
 5095:   double gompertz(double p[]);
 5096:   /* hess=matrix(1,npar,1,npar); */
 5097: 
 5098:   printf("\nCalculation of the hessian matrix. Wait...\n");
 5099:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
 5100:   for (i=1;i<=npar;i++){
 5101:     printf("%d-",i);fflush(stdout);
 5102:     fprintf(ficlog,"%d-",i);fflush(ficlog);
 5103:    
 5104:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
 5105:     
 5106:     /*  printf(" %f ",p[i]);
 5107: 	printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
 5108:   }
 5109:   
 5110:   for (i=1;i<=npar;i++) {
 5111:     for (j=1;j<=npar;j++)  {
 5112:       if (j>i) { 
 5113: 	printf(".%d-%d",i,j);fflush(stdout);
 5114: 	fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
 5115: 	hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
 5116: 	
 5117: 	hess[j][i]=hess[i][j];    
 5118: 	/*printf(" %lf ",hess[i][j]);*/
 5119:       }
 5120:     }
 5121:   }
 5122:   printf("\n");
 5123:   fprintf(ficlog,"\n");
 5124: 
 5125:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
 5126:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
 5127:   
 5128:   a=matrix(1,npar,1,npar);
 5129:   y=matrix(1,npar,1,npar);
 5130:   x=vector(1,npar);
 5131:   indx=ivector(1,npar);
 5132:   for (i=1;i<=npar;i++)
 5133:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
 5134:   ludcmp(a,npar,indx,&pd);
 5135: 
 5136:   for (j=1;j<=npar;j++) {
 5137:     for (i=1;i<=npar;i++) x[i]=0;
 5138:     x[j]=1;
 5139:     lubksb(a,npar,indx,x);
 5140:     for (i=1;i<=npar;i++){ 
 5141:       matcov[i][j]=x[i];
 5142:     }
 5143:   }
 5144: 
 5145:   printf("\n#Hessian matrix#\n");
 5146:   fprintf(ficlog,"\n#Hessian matrix#\n");
 5147:   for (i=1;i<=npar;i++) { 
 5148:     for (j=1;j<=npar;j++) { 
 5149:       printf("%.6e ",hess[i][j]);
 5150:       fprintf(ficlog,"%.6e ",hess[i][j]);
 5151:     }
 5152:     printf("\n");
 5153:     fprintf(ficlog,"\n");
 5154:   }
 5155: 
 5156:   /* printf("\n#Covariance matrix#\n"); */
 5157:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
 5158:   /* for (i=1;i<=npar;i++) {  */
 5159:   /*   for (j=1;j<=npar;j++) {  */
 5160:   /*     printf("%.6e ",matcov[i][j]); */
 5161:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
 5162:   /*   } */
 5163:   /*   printf("\n"); */
 5164:   /*   fprintf(ficlog,"\n"); */
 5165:   /* } */
 5166: 
 5167:   /* Recompute Inverse */
 5168:   /* for (i=1;i<=npar;i++) */
 5169:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
 5170:   /* ludcmp(a,npar,indx,&pd); */
 5171: 
 5172:   /*  printf("\n#Hessian matrix recomputed#\n"); */
 5173: 
 5174:   /* for (j=1;j<=npar;j++) { */
 5175:   /*   for (i=1;i<=npar;i++) x[i]=0; */
 5176:   /*   x[j]=1; */
 5177:   /*   lubksb(a,npar,indx,x); */
 5178:   /*   for (i=1;i<=npar;i++){  */
 5179:   /*     y[i][j]=x[i]; */
 5180:   /*     printf("%.3e ",y[i][j]); */
 5181:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
 5182:   /*   } */
 5183:   /*   printf("\n"); */
 5184:   /*   fprintf(ficlog,"\n"); */
 5185:   /* } */
 5186: 
 5187:   /* Verifying the inverse matrix */
 5188: #ifdef DEBUGHESS
 5189:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
 5190: 
 5191:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
 5192:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
 5193: 
 5194:   for (j=1;j<=npar;j++) {
 5195:     for (i=1;i<=npar;i++){ 
 5196:       printf("%.2f ",y[i][j]);
 5197:       fprintf(ficlog,"%.2f ",y[i][j]);
 5198:     }
 5199:     printf("\n");
 5200:     fprintf(ficlog,"\n");
 5201:   }
 5202: #endif
 5203: 
 5204:   free_matrix(a,1,npar,1,npar);
 5205:   free_matrix(y,1,npar,1,npar);
 5206:   free_vector(x,1,npar);
 5207:   free_ivector(indx,1,npar);
 5208:   /* free_matrix(hess,1,npar,1,npar); */
 5209: 
 5210: 
 5211: }
 5212: 
 5213: /*************** hessian matrix ****************/
 5214: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
 5215: { /* Around values of x, computes the function func and returns the scales delti and hessian */
 5216:   int i;
 5217:   int l=1, lmax=20;
 5218:   double k1,k2, res, fx;
 5219:   double p2[MAXPARM+1]; /* identical to x */
 5220:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 5221:   int k=0,kmax=10;
 5222:   double l1;
 5223: 
 5224:   fx=func(x);
 5225:   for (i=1;i<=npar;i++) p2[i]=x[i];
 5226:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
 5227:     l1=pow(10,l);
 5228:     delts=delt;
 5229:     for(k=1 ; k <kmax; k=k+1){
 5230:       delt = delta*(l1*k);
 5231:       p2[theta]=x[theta] +delt;
 5232:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
 5233:       p2[theta]=x[theta]-delt;
 5234:       k2=func(p2)-fx;
 5235:       /*res= (k1-2.0*fx+k2)/delt/delt; */
 5236:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
 5237:       
 5238: #ifdef DEBUGHESSII
 5239:       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);
 5240:       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);
 5241: #endif
 5242:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
 5243:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 5244: 	k=kmax;
 5245:       }
 5246:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
 5247: 	k=kmax; l=lmax*10;
 5248:       }
 5249:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
 5250: 	delts=delt;
 5251:       }
 5252:     } /* End loop k */
 5253:   }
 5254:   delti[theta]=delts;
 5255:   return res; 
 5256:   
 5257: }
 5258: 
 5259: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
 5260: {
 5261:   int i;
 5262:   int l=1, lmax=20;
 5263:   double k1,k2,k3,k4,res,fx;
 5264:   double p2[MAXPARM+1];
 5265:   int k, kmax=1;
 5266:   double v1, v2, cv12, lc1, lc2;
 5267: 
 5268:   int firstime=0;
 5269:   
 5270:   fx=func(x);
 5271:   for (k=1; k<=kmax; k=k+10) {
 5272:     for (i=1;i<=npar;i++) p2[i]=x[i];
 5273:     p2[thetai]=x[thetai]+delti[thetai]*k;
 5274:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
 5275:     k1=func(p2)-fx;
 5276:   
 5277:     p2[thetai]=x[thetai]+delti[thetai]*k;
 5278:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
 5279:     k2=func(p2)-fx;
 5280:   
 5281:     p2[thetai]=x[thetai]-delti[thetai]*k;
 5282:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
 5283:     k3=func(p2)-fx;
 5284:   
 5285:     p2[thetai]=x[thetai]-delti[thetai]*k;
 5286:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
 5287:     k4=func(p2)-fx;
 5288:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
 5289:     if(k1*k2*k3*k4 <0.){
 5290:       firstime=1;
 5291:       kmax=kmax+10;
 5292:     }
 5293:     if(kmax >=10 || firstime ==1){
 5294:       /* What are the thetai and thetaj? thetai/ncovmodel thetai=(thetai-thetai%ncovmodel)/ncovmodel +thetai%ncovmodel=(line,pos)  */
 5295:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you could increase ftol=%.2e\n",thetai,thetaj, ftol);
 5296:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you could increase ftol=%.2e\n",thetai,thetaj, ftol);
 5297:       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);
 5298:       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);
 5299:     }
 5300: #ifdef DEBUGHESSIJ
 5301:     v1=hess[thetai][thetai];
 5302:     v2=hess[thetaj][thetaj];
 5303:     cv12=res;
 5304:     /* Computing eigen value of Hessian matrix */
 5305:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 5306:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 5307:     if ((lc2 <0) || (lc1 <0) ){
 5308:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
 5309:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
 5310:       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);
 5311:       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);
 5312:     }
 5313: #endif
 5314:   }
 5315:   return res;
 5316: }
 5317: 
 5318:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
 5319: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
 5320: /* { */
 5321: /*   int i; */
 5322: /*   int l=1, lmax=20; */
 5323: /*   double k1,k2,k3,k4,res,fx; */
 5324: /*   double p2[MAXPARM+1]; */
 5325: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
 5326: /*   int k=0,kmax=10; */
 5327: /*   double l1; */
 5328:   
 5329: /*   fx=func(x); */
 5330: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
 5331: /*     l1=pow(10,l); */
 5332: /*     delts=delt; */
 5333: /*     for(k=1 ; k <kmax; k=k+1){ */
 5334: /*       delt = delti*(l1*k); */
 5335: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
 5336: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
 5337: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
 5338: /*       k1=func(p2)-fx; */
 5339:       
 5340: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
 5341: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
 5342: /*       k2=func(p2)-fx; */
 5343:       
 5344: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
 5345: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
 5346: /*       k3=func(p2)-fx; */
 5347:       
 5348: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
 5349: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
 5350: /*       k4=func(p2)-fx; */
 5351: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
 5352: /* #ifdef DEBUGHESSIJ */
 5353: /*       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); */
 5354: /*       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); */
 5355: /* #endif */
 5356: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
 5357: /* 	k=kmax; */
 5358: /*       } */
 5359: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
 5360: /* 	k=kmax; l=lmax*10; */
 5361: /*       } */
 5362: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
 5363: /* 	delts=delt; */
 5364: /*       } */
 5365: /*     } /\* End loop k *\/ */
 5366: /*   } */
 5367: /*   delti[theta]=delts; */
 5368: /*   return res;  */
 5369: /* } */
 5370: 
 5371: 
 5372: /************** Inverse of matrix **************/
 5373: void ludcmp(double **a, int n, int *indx, double *d) 
 5374: { 
 5375:   int i,imax,j,k; 
 5376:   double big,dum,sum,temp; 
 5377:   double *vv; 
 5378:  
 5379:   vv=vector(1,n); 
 5380:   *d=1.0; 
 5381:   for (i=1;i<=n;i++) { 
 5382:     big=0.0; 
 5383:     for (j=1;j<=n;j++) 
 5384:       if ((temp=fabs(a[i][j])) > big) big=temp; 
 5385:     if (big == 0.0){
 5386:       printf(" Singular Hessian matrix at row %d:\n",i);
 5387:       for (j=1;j<=n;j++) {
 5388: 	printf(" a[%d][%d]=%f,",i,j,a[i][j]);
 5389: 	fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
 5390:       }
 5391:       fflush(ficlog);
 5392:       fclose(ficlog);
 5393:       nrerror("Singular matrix in routine ludcmp"); 
 5394:     }
 5395:     vv[i]=1.0/big; 
 5396:   } 
 5397:   for (j=1;j<=n;j++) { 
 5398:     for (i=1;i<j;i++) { 
 5399:       sum=a[i][j]; 
 5400:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
 5401:       a[i][j]=sum; 
 5402:     } 
 5403:     big=0.0; 
 5404:     for (i=j;i<=n;i++) { 
 5405:       sum=a[i][j]; 
 5406:       for (k=1;k<j;k++) 
 5407: 	sum -= a[i][k]*a[k][j]; 
 5408:       a[i][j]=sum; 
 5409:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
 5410: 	big=dum; 
 5411: 	imax=i; 
 5412:       } 
 5413:     } 
 5414:     if (j != imax) { 
 5415:       for (k=1;k<=n;k++) { 
 5416: 	dum=a[imax][k]; 
 5417: 	a[imax][k]=a[j][k]; 
 5418: 	a[j][k]=dum; 
 5419:       } 
 5420:       *d = -(*d); 
 5421:       vv[imax]=vv[j]; 
 5422:     } 
 5423:     indx[j]=imax; 
 5424:     if (a[j][j] == 0.0) a[j][j]=TINY; 
 5425:     if (j != n) { 
 5426:       dum=1.0/(a[j][j]); 
 5427:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
 5428:     } 
 5429:   } 
 5430:   free_vector(vv,1,n);  /* Doesn't work */
 5431: ;
 5432: } 
 5433: 
 5434: void lubksb(double **a, int n, int *indx, double b[]) 
 5435: { 
 5436:   int i,ii=0,ip,j; 
 5437:   double sum; 
 5438:  
 5439:   for (i=1;i<=n;i++) { 
 5440:     ip=indx[i]; 
 5441:     sum=b[ip]; 
 5442:     b[ip]=b[i]; 
 5443:     if (ii) 
 5444:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
 5445:     else if (sum) ii=i; 
 5446:     b[i]=sum; 
 5447:   } 
 5448:   for (i=n;i>=1;i--) { 
 5449:     sum=b[i]; 
 5450:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
 5451:     b[i]=sum/a[i][i]; 
 5452:   } 
 5453: } 
 5454: 
 5455: void pstamp(FILE *fichier)
 5456: {
 5457:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
 5458: }
 5459: 
 5460: void date2dmy(double date,double *day, double *month, double *year){
 5461:   double yp=0., yp1=0., yp2=0.;
 5462:   
 5463:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
 5464: 			fractional in yp1 */
 5465:   *year=yp;
 5466:   yp2=modf((yp1*12),&yp);
 5467:   *month=yp;
 5468:   yp1=modf((yp2*30.5),&yp);
 5469:   *day=yp;
 5470:   if(*day==0) *day=1;
 5471:   if(*month==0) *month=1;
 5472: }
 5473: 
 5474: 
 5475: 
 5476: /************ Frequencies ********************/
 5477: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
 5478: 		  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[],	\
 5479: 		  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
 5480: {  /* Some frequencies as well as proposing some starting values */
 5481:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
 5482:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
 5483:   int iind=0, iage=0;
 5484:   int mi; /* Effective wave */
 5485:   int first;
 5486:   double ***freq; /* Frequencies */
 5487:   double *x, *y, a=0.,b=0.,r=1., sa=0., sb=0.; /* for regression, y=b+m*x and r is the correlation coefficient */
 5488:   int no=0, linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb);
 5489:   double *meanq, *stdq, *idq;
 5490:   double **meanqt;
 5491:   double *pp, **prop, *posprop, *pospropt;
 5492:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
 5493:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
 5494:   double agebegin, ageend;
 5495:     
 5496:   pp=vector(1,nlstate);
 5497:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
 5498:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
 5499:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
 5500:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
 5501:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
 5502:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
 5503:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
 5504:   meanqt=matrix(1,lastpass,1,nqtveff);
 5505:   strcpy(fileresp,"P_");
 5506:   strcat(fileresp,fileresu);
 5507:   /*strcat(fileresphtm,fileresu);*/
 5508:   if((ficresp=fopen(fileresp,"w"))==NULL) {
 5509:     printf("Problem with prevalence resultfile: %s\n", fileresp);
 5510:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
 5511:     exit(0);
 5512:   }
 5513:   
 5514:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
 5515:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
 5516:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
 5517:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
 5518:     fflush(ficlog);
 5519:     exit(70); 
 5520:   }
 5521:   else{
 5522:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 5523: <hr size=\"2\" color=\"#EC5E5E\"> \n					\
 5524: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
 5525: 	    fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 5526:   }
 5527:   fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies (weight=%d) and prevalence by age at begin of transition and dummy covariate value at beginning of transition</h4>\n",fileresphtm, fileresphtm, weightopt);
 5528:   
 5529:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
 5530:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
 5531:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
 5532:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
 5533:     fflush(ficlog);
 5534:     exit(70); 
 5535:   } else{
 5536:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 5537: ,<hr size=\"2\" color=\"#EC5E5E\"> \n					\
 5538: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
 5539: 	    fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 5540:   }
 5541:   fprintf(ficresphtmfr,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>(weight=%d) frequencies of all effective transitions of the model, by age at begin of transition, and covariate value at the begin of transition (if the covariate is a varying covariate) </h4>Unknown status is -1<br/>\n",fileresphtmfr, fileresphtmfr,weightopt);
 5542:   
 5543:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
 5544:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
 5545:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
 5546:   j1=0;
 5547:   
 5548:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
 5549:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
 5550:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
 5551:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 5552:   
 5553:   
 5554:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
 5555:      reference=low_education V1=0,V2=0
 5556:      med_educ                V1=1 V2=0, 
 5557:      high_educ               V1=0 V2=1
 5558:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
 5559:   */
 5560:   dateintsum=0;
 5561:   k2cpt=0;
 5562: 
 5563:   if(cptcoveff == 0 )
 5564:     nl=1;  /* Constant and age model only */
 5565:   else
 5566:     nl=2;
 5567: 
 5568:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
 5569:   /* Loop on nj=1 or 2 if dummy covariates j!=0
 5570:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
 5571:    *     freq[s1][s2][iage] =0.
 5572:    *     Loop on iind
 5573:    *       ++freq[s1][s2][iage] weighted
 5574:    *     end iind
 5575:    *     if covariate and j!0
 5576:    *       headers Variable on one line
 5577:    *     endif cov j!=0
 5578:    *     header of frequency table by age
 5579:    *     Loop on age
 5580:    *       pp[s1]+=freq[s1][s2][iage] weighted
 5581:    *       pos+=freq[s1][s2][iage] weighted
 5582:    *       Loop on s1 initial state
 5583:    *         fprintf(ficresp
 5584:    *       end s1
 5585:    *     end age
 5586:    *     if j!=0 computes starting values
 5587:    *     end compute starting values
 5588:    *   end j1
 5589:    * end nl 
 5590:    */
 5591:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
 5592:     if(nj==1)
 5593:       j=0;  /* First pass for the constant */
 5594:     else{
 5595:       j=cptcoveff; /* Other passes for the covariate values number of simple covariates in the model V2+V1 =2 (simple dummy fixed or time varying) */
 5596:     }
 5597:     first=1;
 5598:     for (j1 = 1; j1 <= (int) pow(2,j); j1++){ /* Loop on all dummy covariates combination of the model, ie excluding quantitatives, V4=0, V3=0 for example, fixed or varying covariates */
 5599:       posproptt=0.;
 5600:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
 5601: 	scanf("%d", i);*/
 5602:       for (i=-5; i<=nlstate+ndeath; i++)  
 5603: 	for (s2=-5; s2<=nlstate+ndeath; s2++)  
 5604: 	  for(m=iagemin; m <= iagemax+3; m++)
 5605: 	    freq[i][s2][m]=0;
 5606:       
 5607:       for (i=1; i<=nlstate; i++)  {
 5608: 	for(m=iagemin; m <= iagemax+3; m++)
 5609: 	  prop[i][m]=0;
 5610: 	posprop[i]=0;
 5611: 	pospropt[i]=0;
 5612:       }
 5613:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
 5614:         idq[z1]=0.;
 5615:         meanq[z1]=0.;
 5616:         stdq[z1]=0.;
 5617:       }
 5618:       /* for (z1=1; z1<= nqtveff; z1++) { */
 5619:       /*   for(m=1;m<=lastpass;m++){ */
 5620:       /* 	  meanqt[m][z1]=0.; */
 5621:       /* 	} */
 5622:       /* }       */
 5623:       /* dateintsum=0; */
 5624:       /* k2cpt=0; */
 5625:       
 5626:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
 5627:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
 5628: 	bool=1;
 5629: 	if(j !=0){
 5630: 	  if(anyvaryingduminmodel==0){ /* If All fixed covariates */
 5631: 	    if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
 5632: 	      for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
 5633: 		/* if(Tvaraff[z1] ==-20){ */
 5634: 		/* 	 /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
 5635: 		/* }else  if(Tvaraff[z1] ==-10){ */
 5636: 		/* 	 /\* sumnew+=coqvar[z1][iind]; *\/ */
 5637: 		/* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
 5638: 		/* if( iind >=imx-3) printf("Searching error iind=%d Tvaraff[z1]=%d covar[Tvaraff[z1]][iind]=%.f TnsdVar[Tvaraff[z1]]=%d, cptcoveff=%d, cptcovs=%d \n",iind, Tvaraff[z1], covar[Tvaraff[z1]][iind],TnsdVar[Tvaraff[z1]],cptcoveff, cptcovs); */
 5639: 		if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
 5640: 		  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
 5641: 		if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
 5642: 		  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
 5643: 		  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
 5644: 		  /* 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", */
 5645: 		  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
 5646:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
 5647: 		  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
 5648: 		} /* Onlyf fixed */
 5649: 	      } /* end z1 */
 5650: 	    } /* cptcoveff > 0 */
 5651: 	  } /* end any */
 5652: 	}/* end j==0 */
 5653: 	if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
 5654: 	  /* for(m=firstpass; m<=lastpass; m++){ */
 5655: 	  for(mi=1; mi<wav[iind];mi++){ /* For each wave */
 5656: 	    m=mw[mi][iind];
 5657: 	    if(j!=0){
 5658: 	      if(anyvaryingduminmodel==1){ /* Some are varying covariates */
 5659: 		for (z1=1; z1<=cptcoveff; z1++) {
 5660: 		  if( Fixed[Tmodelind[z1]]==1){
 5661: 		    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
 5662: 		    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
 5663: 		    if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality. If covariate's 
 5664: 										      value is -1, we don't select. It differs from the 
 5665: 										      constant and age model which counts them. */
 5666: 		      bool=0; /* not selected */
 5667: 		  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
 5668: 		    /* i1=Tvaraff[z1]; */
 5669: 		    /* i2=TnsdVar[i1]; */
 5670: 		    /* i3=nbcode[i1][i2]; */
 5671: 		    /* i4=covar[i1][iind]; */
 5672: 		    /* if(i4 != i3){ */
 5673: 		    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
 5674: 		      bool=0;
 5675: 		    }
 5676: 		  }
 5677: 		}
 5678: 	      }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
 5679: 	    } /* end j==0 */
 5680: 	    /* bool =0 we keep that guy which corresponds to the combination of dummy values */
 5681: 	    if(bool==1){ /*Selected */
 5682: 	      /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
 5683: 		 and mw[mi+1][iind]. dh depends on stepm. */
 5684: 	      agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
 5685: 	      ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
 5686: 	      if(m >=firstpass && m <=lastpass){
 5687: 		k2=anint[m][iind]+(mint[m][iind]/12.);
 5688: 		/*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
 5689: 		if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
 5690: 		if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
 5691: 		if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
 5692: 		  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
 5693: 		if (m<lastpass) {
 5694: 		  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
 5695: 		  /*   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]); */
 5696: 		  if(s[m][iind]==-1)
 5697: 		    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.));
 5698: 		  freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
 5699: 		  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
 5700: 		    if(!isnan(covar[ncovcol+z1][iind])){
 5701: 		      idq[z1]=idq[z1]+weight[iind];
 5702: 		      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
 5703: 		      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
 5704: 		      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
 5705: 		    }
 5706: 		  }
 5707: 		  /* if((int)agev[m][iind] == 55) */
 5708: 		  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
 5709: 		  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
 5710: 		  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 */
 5711: 		}
 5712: 	      } /* end if between passes */  
 5713: 	      if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
 5714: 		dateintsum=dateintsum+k2; /* on all covariates ?*/
 5715: 		k2cpt++;
 5716: 		/* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
 5717: 	      }
 5718: 	    }else{
 5719: 	      bool=1;
 5720: 	    }/* end bool 2 */
 5721: 	  } /* end m */
 5722: 	  /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
 5723: 	  /*   idq[z1]=idq[z1]+weight[iind]; */
 5724: 	  /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
 5725: 	  /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
 5726: 	  /* } */
 5727: 	} /* end bool */
 5728:       } /* end iind = 1 to imx */
 5729:       /* prop[s][age] is fed for any initial and valid live state as well as
 5730: 	 freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
 5731:       
 5732:       
 5733:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 5734:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
 5735:         pstamp(ficresp);
 5736:       if  (cptcoveff>0 && j!=0){
 5737:         pstamp(ficresp);
 5738: 	printf( "\n#********** Variable "); 
 5739: 	fprintf(ficresp, "\n#********** Variable "); 
 5740: 	fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
 5741: 	fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
 5742: 	fprintf(ficlog, "\n#********** Variable "); 
 5743: 	for (z1=1; z1<=cptcoveff; z1++){
 5744: 	  if(!FixedV[Tvaraff[z1]]){
 5745: 	    printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
 5746: 	    fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
 5747: 	    fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
 5748: 	    fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
 5749: 	    fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
 5750: 	  }else{
 5751: 	    printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
 5752: 	    fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
 5753: 	    fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
 5754: 	    fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
 5755: 	    fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
 5756: 	  }
 5757: 	}
 5758: 	printf( "**********\n#");
 5759: 	fprintf(ficresp, "**********\n#");
 5760: 	fprintf(ficresphtm, "**********</h3>\n");
 5761: 	fprintf(ficresphtmfr, "**********</h3>\n");
 5762: 	fprintf(ficlog, "**********\n");
 5763:       }
 5764:       /*
 5765: 	Printing means of quantitative variables if any
 5766:       */
 5767:       for (z1=1; z1<= nqfveff; z1++) {
 5768: 	fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
 5769: 	fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
 5770: 	if(weightopt==1){
 5771: 	  printf(" Weighted mean and standard deviation of");
 5772: 	  fprintf(ficlog," Weighted mean and standard deviation of");
 5773: 	  fprintf(ficresphtmfr," Weighted mean and standard deviation of");
 5774: 	}
 5775: 	/* mu = \frac{w x}{\sum w}
 5776:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
 5777: 	*/
 5778: 	printf(" fixed quantitative variable V%d on  %.3g (weighted) representatives of the population : %8.5g (%8.5g)\n", ncovcol+z1, idq[z1],meanq[z1]/idq[z1], sqrt(stdq[z1]/idq[z1]-meanq[z1]*meanq[z1]/idq[z1]/idq[z1]));
 5779: 	fprintf(ficlog," fixed quantitative variable V%d on  %.3g (weighted) representatives of the population : %8.5g (%8.5g)\n", ncovcol+z1, idq[z1],meanq[z1]/idq[z1], sqrt(stdq[z1]/idq[z1]-meanq[z1]*meanq[z1]/idq[z1]/idq[z1]));
 5780: 	fprintf(ficresphtmfr," fixed quantitative variable V%d on %.3g (weighted) representatives of the population : %8.5g (%8.5g)<p>\n", ncovcol+z1, idq[z1],meanq[z1]/idq[z1], sqrt(stdq[z1]/idq[z1]-meanq[z1]*meanq[z1]/idq[z1]/idq[z1]));
 5781:       }
 5782:       /* for (z1=1; z1<= nqtveff; z1++) { */
 5783:       /* 	for(m=1;m<=lastpass;m++){ */
 5784:       /* 	  fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
 5785:       /*   } */
 5786:       /* } */
 5787: 
 5788:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
 5789:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
 5790:         fprintf(ficresp, " Age");
 5791:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
 5792: 	  printf(" V%d=%d, z1=%d, Tvaraff[z1]=%d, j1=%d, TnsdVar[Tvaraff[%d]]=%d |",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])], z1, Tvaraff[z1], j1,z1,TnsdVar[Tvaraff[z1]]);
 5793: 	  fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
 5794: 	}
 5795:       for(i=1; i<=nlstate;i++) {
 5796: 	if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
 5797: 	fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
 5798:       }
 5799:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
 5800:       fprintf(ficresphtm, "\n");
 5801:       
 5802:       /* Header of frequency table by age */
 5803:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
 5804:       fprintf(ficresphtmfr,"<th>Age</th> ");
 5805:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
 5806: 	for(m=-1; m <=nlstate+ndeath; m++){
 5807: 	  if(s2!=0 && m!=0)
 5808: 	    fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
 5809: 	}
 5810:       }
 5811:       fprintf(ficresphtmfr, "\n");
 5812:     
 5813:       /* For each age */
 5814:       for(iage=iagemin; iage <= iagemax+3; iage++){
 5815: 	fprintf(ficresphtm,"<tr>");
 5816: 	if(iage==iagemax+1){
 5817: 	  fprintf(ficlog,"1");
 5818: 	  fprintf(ficresphtmfr,"<tr><th>0</th> ");
 5819: 	}else if(iage==iagemax+2){
 5820: 	  fprintf(ficlog,"0");
 5821: 	  fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
 5822: 	}else if(iage==iagemax+3){
 5823: 	  fprintf(ficlog,"Total");
 5824: 	  fprintf(ficresphtmfr,"<tr><th>Total</th> ");
 5825: 	}else{
 5826: 	  if(first==1){
 5827: 	    first=0;
 5828: 	    printf("See log file for details...\n");
 5829: 	  }
 5830: 	  fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
 5831: 	  fprintf(ficlog,"Age %d", iage);
 5832: 	}
 5833: 	for(s1=1; s1 <=nlstate ; s1++){
 5834: 	  for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
 5835: 	    pp[s1] += freq[s1][m][iage]; 
 5836: 	}
 5837: 	for(s1=1; s1 <=nlstate ; s1++){
 5838: 	  for(m=-1, pos=0; m <=0 ; m++)
 5839: 	    pos += freq[s1][m][iage];
 5840: 	  if(pp[s1]>=1.e-10){
 5841: 	    if(first==1){
 5842: 	      printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
 5843: 	    }
 5844: 	    fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
 5845: 	  }else{
 5846: 	    if(first==1)
 5847: 	      printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
 5848: 	    fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
 5849: 	  }
 5850: 	}
 5851:       
 5852: 	for(s1=1; s1 <=nlstate ; s1++){ 
 5853: 	  /* posprop[s1]=0; */
 5854: 	  for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
 5855: 	    pp[s1] += freq[s1][m][iage];
 5856: 	}	/* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
 5857:       
 5858: 	for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
 5859: 	  pos += pp[s1]; /* pos is the total number of transitions until this age */
 5860: 	  posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
 5861: 					    from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
 5862: 	  pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
 5863: 					  from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
 5864: 	}
 5865: 	
 5866: 	/* Writing ficresp */
 5867: 	if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
 5868:           if( iage <= iagemax){
 5869: 	    fprintf(ficresp," %d",iage);
 5870:           }
 5871:         }else if( nj==2){
 5872:           if( iage <= iagemax){
 5873: 	    fprintf(ficresp," %d",iage);
 5874:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
 5875:           }
 5876: 	}
 5877: 	for(s1=1; s1 <=nlstate ; s1++){
 5878: 	  if(pos>=1.e-5){
 5879: 	    if(first==1)
 5880: 	      printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
 5881: 	    fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
 5882: 	  }else{
 5883: 	    if(first==1)
 5884: 	      printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
 5885: 	    fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
 5886: 	  }
 5887: 	  if( iage <= iagemax){
 5888: 	    if(pos>=1.e-5){
 5889: 	      if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
 5890: 	        fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
 5891:               }else if( nj==2){
 5892: 	        fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
 5893:               }
 5894: 	      fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
 5895: 	      /*probs[iage][s1][j1]= pp[s1]/pos;*/
 5896: 	      /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
 5897: 	    } else{
 5898: 	      if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
 5899: 	      fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
 5900: 	    }
 5901: 	  }
 5902: 	  pospropt[s1] +=posprop[s1];
 5903: 	} /* end loop s1 */
 5904: 	/* pospropt=0.; */
 5905: 	for(s1=-1; s1 <=nlstate+ndeath; s1++){
 5906: 	  for(m=-1; m <=nlstate+ndeath; m++){
 5907: 	    if(freq[s1][m][iage] !=0 ) { /* minimizing output */
 5908: 	      if(first==1){
 5909: 		printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
 5910: 	      }
 5911: 	      /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
 5912: 	      fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
 5913: 	    }
 5914: 	    if(s1!=0 && m!=0)
 5915: 	      fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
 5916: 	  }
 5917: 	} /* end loop s1 */
 5918: 	posproptt=0.; 
 5919: 	for(s1=1; s1 <=nlstate; s1++){
 5920: 	  posproptt += pospropt[s1];
 5921: 	}
 5922: 	fprintf(ficresphtmfr,"</tr>\n ");
 5923: 	fprintf(ficresphtm,"</tr>\n");
 5924: 	if((cptcoveff==0 && nj==1)|| nj==2 ) {
 5925: 	  if(iage <= iagemax)
 5926:  	    fprintf(ficresp,"\n");
 5927: 	}
 5928: 	if(first==1)
 5929: 	  printf("Others in log...\n");
 5930: 	fprintf(ficlog,"\n");
 5931:       } /* end loop age iage */
 5932:       
 5933:       fprintf(ficresphtm,"<tr><th>Tot</th>");
 5934:       for(s1=1; s1 <=nlstate ; s1++){
 5935: 	if(posproptt < 1.e-5){
 5936: 	  fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt);	
 5937: 	}else{
 5938: 	  fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);	
 5939: 	}
 5940:       }
 5941:       fprintf(ficresphtm,"</tr>\n");
 5942:       fprintf(ficresphtm,"</table>\n");
 5943:       fprintf(ficresphtmfr,"</table>\n");
 5944:       if(posproptt < 1.e-5){
 5945: 	fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
 5946: 	fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
 5947: 	fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
 5948: 	printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
 5949: 	invalidvarcomb[j1]=1;
 5950:       }else{
 5951: 	fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
 5952: 	invalidvarcomb[j1]=0;
 5953:       }
 5954:       fprintf(ficresphtmfr,"</table>\n");
 5955:       fprintf(ficlog,"\n");
 5956:       if(j!=0){
 5957: 	printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
 5958: 	for(i=1,s1=1; i <=nlstate; i++){
 5959: 	  for(k=1; k <=(nlstate+ndeath); k++){
 5960: 	    if (k != i) {
 5961: 	      for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
 5962: 		if(jj==1){  /* Constant case (in fact cste + age) */
 5963: 		  if(j1==1){ /* All dummy covariates to zero */
 5964: 		    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
 5965: 		    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
 5966: 		    printf("%d%d ",i,k);
 5967: 		    fprintf(ficlog,"%d%d ",i,k);
 5968: 		    printf("%12.7f ln(%.0f/%.0f)= %f, OR=%f sd=%f \n",p[s1],freq[i][k][iagemax+3],freq[i][i][iagemax+3], log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]),freq[i][k][iagemax+3]/freq[i][i][iagemax+3], sqrt(1/freq[i][k][iagemax+3]+1/freq[i][i][iagemax+3]));
 5969: 		    fprintf(ficlog,"%12.7f ln(%.0f/%.0f)= %12.7f \n",p[s1],freq[i][k][iagemax+3],freq[i][i][iagemax+3], log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]));
 5970: 		    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
 5971: 		  }
 5972: 		}else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
 5973: 		  for(iage=iagemin; iage <= iagemax+3; iage++){
 5974: 		    x[iage]= (double)iage;
 5975: 		    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
 5976: 		    /* printf("i=%d, k=%d, s1=%d, j1=%d, jj=%d, y[%d]=%f\n",i,k,s1,j1,jj, iage, y[iage]); */
 5977: 		  }
 5978: 		  /* Some are not finite, but linreg will ignore these ages */
 5979: 		  no=0;
 5980: 		  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
 5981: 		  pstart[s1]=b;
 5982: 		  pstart[s1-1]=a;
 5983: 		}else if( j1!=1 && (j1==2 || (log(j1-1.)/log(2.)-(int)(log(j1-1.)/log(2.))) <0.010) && ( TvarsDind[(int)(log(j1-1.)/log(2.))+1]+2+nagesqr == jj)  && Dummy[jj-2-nagesqr]==0){ /* We want only if the position, jj, in model corresponds to unique covariate equal to 1 in j1 combination */ 
 5984: 		  printf("j1=%d, jj=%d, (int)(log(j1-1.)/log(2.))+1=%d, TvarsDind[(int)(log(j1-1.)/log(2.))+1]=%d\n",j1, jj,(int)(log(j1-1.)/log(2.))+1,TvarsDind[(int)(log(j1-1.)/log(2.))+1]);
 5985: 		  printf("j1=%d, jj=%d, (log(j1-1.)/log(2.))+1=%f, TvarsDind[(int)(log(j1-1.)/log(2.))+1]=%d\n",j1, jj,(log(j1-1.)/log(2.))+1,TvarsDind[(int)(log(j1-1.)/log(2.))+1]);
 5986: 		  pstart[s1]= log((freq[i][k][iagemax+3]/freq[i][i][iagemax+3])/(freq[i][k][iagemax+4]/freq[i][i][iagemax+4]));
 5987: 		  printf("%d%d ",i,k);
 5988: 		  fprintf(ficlog,"%d%d ",i,k);
 5989: 		  printf("s1=%d,i=%d,k=%d,p[%d]=%12.7f ln((%.0f/%.0f)/(%.0f/%.0f))= %f, OR=%f sd=%f \n",s1,i,k,s1,p[s1],freq[i][k][iagemax+3],freq[i][i][iagemax+3],freq[i][k][iagemax+4],freq[i][i][iagemax+4], log((freq[i][k][iagemax+3]/freq[i][i][iagemax+3])/(freq[i][k][iagemax+4]/freq[i][i][iagemax+4])),(freq[i][k][iagemax+3]/freq[i][i][iagemax+3])/(freq[i][k][iagemax+4]/freq[i][i][iagemax+4]), sqrt(1/freq[i][k][iagemax+3]+1/freq[i][i][iagemax+3]+1/freq[i][k][iagemax+4]+1/freq[i][i][iagemax+4]));
 5990: 		}else{ /* Other cases, like quantitative fixed or varying covariates */
 5991: 		  ;
 5992: 		}
 5993: 		/* printf("%12.7f )", param[i][jj][k]); */
 5994: 		/* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
 5995: 		s1++; 
 5996: 	      } /* end jj */
 5997: 	    } /* end k!= i */
 5998: 	  } /* end k */
 5999: 	} /* end i, s1 */
 6000:       } /* end j !=0 */
 6001:     } /* end selected combination of covariate j1 */
 6002:     if(j==0){ /* We can estimate starting values from the occurences in each case */
 6003:       printf("#Freqsummary: Starting values for the constants:\n");
 6004:       fprintf(ficlog,"\n");
 6005:       for(i=1,s1=1; i <=nlstate; i++){
 6006: 	for(k=1; k <=(nlstate+ndeath); k++){
 6007: 	  if (k != i) {
 6008: 	    printf("%d%d ",i,k);
 6009: 	    fprintf(ficlog,"%d%d ",i,k);
 6010: 	    for(jj=1; jj <=ncovmodel; jj++){
 6011: 	      pstart[s1]=p[s1]; /* Setting pstart to p values by default */
 6012: 	      if(jj==1){ /* Age has to be done */
 6013: 		pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
 6014: 		printf("%12.7f ln(%.0f/%.0f)= %12.7f ",p[s1],freq[i][k][iagemax+3],freq[i][i][iagemax+3], log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]));
 6015: 		fprintf(ficlog,"%12.7f ln(%.0f/%.0f)= %12.7f ",p[s1],freq[i][k][iagemax+3],freq[i][i][iagemax+3], log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]));
 6016: 	      }
 6017: 	      /* printf("%12.7f )", param[i][jj][k]); */
 6018: 	      /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
 6019: 	      s1++; 
 6020: 	    }
 6021: 	    printf("\n");
 6022: 	    fprintf(ficlog,"\n");
 6023: 	  }
 6024: 	}
 6025:       } /* end of state i */
 6026:       printf("#Freqsummary\n");
 6027:       fprintf(ficlog,"\n");
 6028:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
 6029: 	for(s2=-1; s2 <=nlstate+ndeath; s2++){
 6030: 	  /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
 6031: 	  printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
 6032: 	  fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
 6033: 	  /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
 6034: 	  /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
 6035: 	  /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
 6036: 	  /* } */
 6037: 	}
 6038:       } /* end loop s1 */
 6039:       
 6040:       printf("\n");
 6041:       fprintf(ficlog,"\n");
 6042:     } /* end j=0 */
 6043:   } /* end j */
 6044: 
 6045:   if(mle == -2){  /* We want to use these values as starting values */
 6046:     for(i=1, jk=1; i <=nlstate; i++){
 6047:       for(j=1; j <=nlstate+ndeath; j++){
 6048: 	if(j!=i){
 6049: 	  /*ca[0]= k+'a'-1;ca[1]='\0';*/
 6050: 	  printf("%1d%1d",i,j);
 6051: 	  fprintf(ficparo,"%1d%1d",i,j);
 6052: 	  for(k=1; k<=ncovmodel;k++){
 6053: 	    /* 	  printf(" %lf",param[i][j][k]); */
 6054: 	    /* 	  fprintf(ficparo," %lf",param[i][j][k]); */
 6055: 	    p[jk]=pstart[jk];
 6056: 	    printf(" %f ",pstart[jk]);
 6057: 	    fprintf(ficparo," %f ",pstart[jk]);
 6058: 	    jk++;
 6059: 	  }
 6060: 	  printf("\n");
 6061: 	  fprintf(ficparo,"\n");
 6062: 	}
 6063:       }
 6064:     }
 6065:   } /* end mle=-2 */
 6066:   dateintmean=dateintsum/k2cpt; 
 6067:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
 6068:   
 6069:   fclose(ficresp);
 6070:   fclose(ficresphtm);
 6071:   fclose(ficresphtmfr);
 6072:   free_vector(idq,1,nqfveff);
 6073:   free_vector(meanq,1,nqfveff);
 6074:   free_vector(stdq,1,nqfveff);
 6075:   free_matrix(meanqt,1,lastpass,1,nqtveff);
 6076:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
 6077:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
 6078:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
 6079:   free_vector(pospropt,1,nlstate);
 6080:   free_vector(posprop,1,nlstate);
 6081:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
 6082:   free_vector(pp,1,nlstate);
 6083:   /* End of freqsummary */
 6084: }
 6085: 
 6086: /* Simple linear regression */
 6087: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
 6088: 
 6089:   /* y=a+bx regression */
 6090:   double   sumx = 0.0;                        /* sum of x                      */
 6091:   double   sumx2 = 0.0;                       /* sum of x**2                   */
 6092:   double   sumxy = 0.0;                       /* sum of x * y                  */
 6093:   double   sumy = 0.0;                        /* sum of y                      */
 6094:   double   sumy2 = 0.0;                       /* sum of y**2                   */
 6095:   double   sume2 = 0.0;                       /* sum of square or residuals */
 6096:   double yhat;
 6097:   
 6098:   double denom=0;
 6099:   int i;
 6100:   int ne=*no;
 6101:   
 6102:   for ( i=ifi, ne=0;i<=ila;i++) {
 6103:     if(!isfinite(x[i]) || !isfinite(y[i])){
 6104:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
 6105:       continue;
 6106:     }
 6107:     ne=ne+1;
 6108:     sumx  += x[i];       
 6109:     sumx2 += x[i]*x[i];  
 6110:     sumxy += x[i] * y[i];
 6111:     sumy  += y[i];      
 6112:     sumy2 += y[i]*y[i]; 
 6113:     denom = (ne * sumx2 - sumx*sumx);
 6114:     /* printf("ne=%d, i=%d,x[%d]=%f, y[%d]=%f sumx=%f, sumx2=%f, sumxy=%f, sumy=%f, sumy2=%f, denom=%f\n",ne,i,i,x[i],i,y[i], sumx, sumx2,sumxy, sumy, sumy2,denom); */
 6115:   } 
 6116:   
 6117:   denom = (ne * sumx2 - sumx*sumx);
 6118:   if (denom == 0) {
 6119:     // vertical, slope m is infinity
 6120:     *b = INFINITY;
 6121:     *a = 0;
 6122:     if (r) *r = 0;
 6123:     return 1;
 6124:   }
 6125:   
 6126:   *b = (ne * sumxy  -  sumx * sumy) / denom;
 6127:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
 6128:   if (r!=NULL) {
 6129:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
 6130:       sqrt((sumx2 - sumx*sumx/ne) *
 6131: 	   (sumy2 - sumy*sumy/ne));
 6132:   }
 6133:   *no=ne;
 6134:   for ( i=ifi, ne=0;i<=ila;i++) {
 6135:     if(!isfinite(x[i]) || !isfinite(y[i])){
 6136:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
 6137:       continue;
 6138:     }
 6139:     ne=ne+1;
 6140:     yhat = y[i] - *a -*b* x[i];
 6141:     sume2  += yhat * yhat ;       
 6142:     
 6143:     denom = (ne * sumx2 - sumx*sumx);
 6144:     /* printf("ne=%d, i=%d,x[%d]=%f, y[%d]=%f sumx=%f, sumx2=%f, sumxy=%f, sumy=%f, sumy2=%f, denom=%f\n",ne,i,i,x[i],i,y[i], sumx, sumx2,sumxy, sumy, sumy2,denom); */
 6145:   } 
 6146:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
 6147:   *sa= *sb * sqrt(sumx2/ne);
 6148:   
 6149:   return 0; 
 6150: }
 6151: 
 6152: /************ Prevalence ********************/
 6153: 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)
 6154: {  
 6155:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 6156:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 6157:      We still use firstpass and lastpass as another selection.
 6158:   */
 6159:  
 6160:   int i, m, jk, j1, bool, z1,j, iv;
 6161:   int mi; /* Effective wave */
 6162:   int iage;
 6163:   double agebegin, ageend;
 6164: 
 6165:   double **prop;
 6166:   double posprop; 
 6167:   double  y2; /* in fractional years */
 6168:   int iagemin, iagemax;
 6169:   int first; /** to stop verbosity which is redirected to log file */
 6170: 
 6171:   iagemin= (int) agemin;
 6172:   iagemax= (int) agemax;
 6173:   /*pp=vector(1,nlstate);*/
 6174:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
 6175:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
 6176:   j1=0;
 6177:   
 6178:   /*j=cptcoveff;*/
 6179:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 6180:   
 6181:   first=0;
 6182:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
 6183:     for (i=1; i<=nlstate; i++)  
 6184:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
 6185: 	prop[i][iage]=0.0;
 6186:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
 6187:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
 6188:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
 6189:     
 6190:     for (i=1; i<=imx; i++) { /* Each individual */
 6191:       bool=1;
 6192:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
 6193:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
 6194: 	m=mw[mi][i];
 6195: 	/* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
 6196: 	/* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
 6197: 	for (z1=1; z1<=cptcoveff; z1++){
 6198: 	  if( Fixed[Tmodelind[z1]]==1){
 6199: 	    iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
 6200: 	    if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
 6201: 	      bool=0;
 6202: 	  }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
 6203: 	    if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
 6204: 	      bool=0;
 6205: 	    }
 6206: 	}
 6207: 	if(bool==1){ /* Otherwise we skip that wave/person */
 6208: 	  agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
 6209: 	  /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
 6210: 	  if(m >=firstpass && m <=lastpass){
 6211: 	    y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
 6212: 	    if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
 6213: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 6214: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 6215: 	      if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
 6216: 		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); 
 6217: 		exit(1);
 6218: 	      }
 6219: 	      if (s[m][i]>0 && s[m][i]<=nlstate) { 
 6220: 		/*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]]);*/
 6221: 		prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
 6222: 		prop[s[m][i]][iagemax+3] += weight[i]; 
 6223: 	      } /* end valid statuses */ 
 6224: 	    } /* end selection of dates */
 6225: 	  } /* end selection of waves */
 6226: 	} /* end bool */
 6227:       } /* end wave */
 6228:     } /* end individual */
 6229:     for(i=iagemin; i <= iagemax+3; i++){  
 6230:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
 6231: 	posprop += prop[jk][i]; 
 6232:       } 
 6233:       
 6234:       for(jk=1; jk <=nlstate ; jk++){	    
 6235: 	if( i <=  iagemax){ 
 6236: 	  if(posprop>=1.e-5){ 
 6237: 	    probs[i][jk][j1]= prop[jk][i]/posprop;
 6238: 	  } else{
 6239: 	    if(!first){
 6240: 	      first=1;
 6241: 	      printf("Warning Observed prevalence doesn't sum to 1 for state %d: probs[%d][%d][%d]=%lf because of lack of cases\nSee others in log file...\n",jk,i,jk, j1,probs[i][jk][j1]);
 6242: 	    }else{
 6243: 	      fprintf(ficlog,"Warning Observed prevalence doesn't sum to 1 for state %d: probs[%d][%d][%d]=%lf because of lack of cases.\n",jk,i,jk, j1,probs[i][jk][j1]);
 6244: 	    }
 6245: 	  }
 6246: 	} 
 6247:       }/* end jk */ 
 6248:     }/* end i */ 
 6249:      /*} *//* end i1 */
 6250:   } /* end j1 */
 6251:   
 6252:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
 6253:   /*free_vector(pp,1,nlstate);*/
 6254:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
 6255: }  /* End of prevalence */
 6256: 
 6257: /************* Waves Concatenation ***************/
 6258: 
 6259: 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)
 6260: {
 6261:   /* Concatenates waves: wav[i] is the number of effective (useful waves in the sense that a non interview is useless) of individual i.
 6262:      Death is a valid wave (if date is known).
 6263:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
 6264:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 6265:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
 6266:   */
 6267: 
 6268:   int i=0, mi=0, m=0, mli=0;
 6269:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
 6270:      double sum=0., jmean=0.;*/
 6271:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
 6272:   int j, k=0,jk, ju, jl;
 6273:   double sum=0.;
 6274:   first=0;
 6275:   firstwo=0;
 6276:   firsthree=0;
 6277:   firstfour=0;
 6278:   jmin=100000;
 6279:   jmax=-1;
 6280:   jmean=0.;
 6281: 
 6282: /* Treating live states */
 6283:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
 6284:     mi=0;  /* First valid wave */
 6285:     mli=0; /* Last valid wave */
 6286:     m=firstpass;  /* Loop on waves */
 6287:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
 6288:       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 */
 6289: 	mli=m-1;/* mw[++mi][i]=m-1; */
 6290:       }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 */
 6291: 	mw[++mi][i]=m; /* Valid wave: incrementing mi and updating mi; mw[mi] is the wave number of mi_th valid transition   */
 6292: 	mli=m;
 6293:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
 6294:       if(m < lastpass){ /* m < lastpass, standard case */
 6295: 	m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
 6296:       }
 6297:       else{ /* m = lastpass, eventual special issue with warning */
 6298: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
 6299: 	break;
 6300: #else
 6301: 	if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){ /* no death date and known date of interview, case -2 (vital status unknown is warned later */
 6302: 	  if(firsthree == 0){
 6303: 	    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 1-p_{%d%d} .\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, s[m][i], nlstate+ndeath);
 6304: 	    firsthree=1;
 6305: 	  }else if(firsthree >=1 && firsthree < 10){
 6306: 	    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 1-p_{%d%d} .\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, s[m][i], nlstate+ndeath);
 6307: 	    firsthree++;
 6308: 	  }else if(firsthree == 10){
 6309: 	    printf("Information, too many Information flags: no more reported to log either\n");
 6310: 	    fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
 6311: 	    firsthree++;
 6312: 	  }else{
 6313: 	    firsthree++;
 6314: 	  }
 6315: 	  mw[++mi][i]=m; /* Valid transition with unknown status */
 6316: 	  mli=m;
 6317: 	}
 6318: 	if(s[m][i]==-2){ /* Vital status is really unknown */
 6319: 	  nbwarn++;
 6320: 	  if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
 6321: 	    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);
 6322: 	    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);
 6323: 	  }
 6324: 	  break;
 6325: 	}
 6326: 	break;
 6327: #endif
 6328:       }/* End m >= lastpass */
 6329:     }/* end while */
 6330: 
 6331:     /* mi is the last effective wave, m is lastpass, mw[j][i] gives the # of j-th effective wave for individual i */
 6332:     /* After last pass */
 6333: /* Treating death states */
 6334:     if (s[m][i] > nlstate){  /* In a death state */
 6335:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
 6336:       /* } */
 6337:       mi++;	/* Death is another wave */
 6338:       /* if(mi==0)  never been interviewed correctly before death */
 6339:       /* Only death is a correct wave */
 6340:       mw[mi][i]=m;
 6341:     } /* else not in a death state */
 6342: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
 6343:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
 6344:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
 6345: 	if((andc[i]+moisdc[i]/12.) <=(anint[m][i]+mint[m][i]/12.)){ /* month of death occured before last wave month and status should have been death instead of -1 */
 6346: 	  nbwarn++;
 6347: 	  if(firstfiv==0){
 6348: 	    printf("Warning! Death for individual %ld line=%d occurred at %d/%d before last wave %d, interviewed on %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 );
 6349: 	    firstfiv=1;
 6350: 	  }else{
 6351: 	    fprintf(ficlog,"Warning! Death for individual %ld line=%d occurred at %d/%d before last wave %d, interviewed on %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 );
 6352: 	  }
 6353: 	    s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
 6354: 	}else{ /* Month of Death occured afer last wave month, potential bias */
 6355: 	  nberr++;
 6356: 	  if(firstwo==0){
 6357: 	    printf("Error! Death for individual %ld line=%d occurred at %d/%d after last wave %d interviewed at %d/%d with status %d. Potential bias if other individuals are still alive on this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood. Please add a new fictitious wave at the date of last vital status scan, with a dead status. See documentation\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 );
 6358: 	    firstwo=1;
 6359: 	  }
 6360: 	  fprintf(ficlog,"Error! Death for individual %ld line=%d occurred at %d/%d after last wave %d interviewed at %d/%d with status %d. Potential bias if other individuals are still alive on this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood. Please add a new fictitious wave at the date of last vital status scan, with a dead status. See documentation\n\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], i,m );
 6361: 	}
 6362:       }else{ /* if date of interview is unknown */
 6363: 	/* death is known but not confirmed by death status at any wave */
 6364: 	if(firstfour==0){
 6365: 	  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 with status %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], s[m][i], i,m );
 6366: 	  firstfour=1;
 6367: 	}
 6368: 	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  with status %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], s[m][i], i,m );
 6369:       }
 6370:     } /* end if date of death is known */
 6371: #endif
 6372:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
 6373:     /* wav[i]=mw[mi][i];   */
 6374:     if(mi==0){
 6375:       nbwarn++;
 6376:       if(first==0){
 6377: 	printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
 6378: 	first=1;
 6379:       }
 6380:       if(first==1){
 6381: 	fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
 6382:       }
 6383:     } /* end mi==0 */
 6384:   } /* End individuals */
 6385:   /* wav and mw are no more changed */
 6386: 	
 6387:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
 6388:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
 6389: 
 6390: 
 6391:   for(i=1; i<=imx; i++){
 6392:     for(mi=1; mi<wav[i];mi++){
 6393:       if (stepm <=0)
 6394: 	dh[mi][i]=1;
 6395:       else{
 6396: 	if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
 6397: 	  if (agedc[i] < 2*AGESUP) {
 6398: 	    j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
 6399: 	    if(j==0) j=1;  /* Survives at least one month after exam */
 6400: 	    else if(j<0){
 6401: 	      nberr++;
 6402: 	      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]);
 6403: 	      j=1; /* Temporary Dangerous patch */
 6404: 	      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);
 6405: 	      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]);
 6406: 	      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);
 6407: 	    }
 6408: 	    k=k+1;
 6409: 	    if (j >= jmax){
 6410: 	      jmax=j;
 6411: 	      ijmax=i;
 6412: 	    }
 6413: 	    if (j <= jmin){
 6414: 	      jmin=j;
 6415: 	      ijmin=i;
 6416: 	    }
 6417: 	    sum=sum+j;
 6418: 	    /*if (j<0) printf("j=%d num=%d \n",j,i);*/
 6419: 	    /*	  printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
 6420: 	  }
 6421: 	}
 6422: 	else{
 6423: 	  j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 6424: /* 	  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]); */
 6425: 					
 6426: 	  k=k+1;
 6427: 	  if (j >= jmax) {
 6428: 	    jmax=j;
 6429: 	    ijmax=i;
 6430: 	  }
 6431: 	  else if (j <= jmin){
 6432: 	    jmin=j;
 6433: 	    ijmin=i;
 6434: 	  }
 6435: 	  /*	    if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
 6436: 	  /*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]);*/
 6437: 	  if(j<0){
 6438: 	    nberr++;
 6439: 	    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]);
 6440: 	    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]);
 6441: 	  }
 6442: 	  sum=sum+j;
 6443: 	}
 6444: 	jk= j/stepm;
 6445: 	jl= j -jk*stepm;
 6446: 	ju= j -(jk+1)*stepm;
 6447: 	if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
 6448: 	  if(jl==0){
 6449: 	    dh[mi][i]=jk;
 6450: 	    bh[mi][i]=0;
 6451: 	  }else{ /* We want a negative bias in order to only have interpolation ie
 6452: 		  * to avoid the price of an extra matrix product in likelihood */
 6453: 	    dh[mi][i]=jk+1;
 6454: 	    bh[mi][i]=ju;
 6455: 	  }
 6456: 	}else{
 6457: 	  if(jl <= -ju){
 6458: 	    dh[mi][i]=jk;
 6459: 	    bh[mi][i]=jl;	/* bias is positive if real duration
 6460: 				 * is higher than the multiple of stepm and negative otherwise.
 6461: 				 */
 6462: 	  }
 6463: 	  else{
 6464: 	    dh[mi][i]=jk+1;
 6465: 	    bh[mi][i]=ju;
 6466: 	  }
 6467: 	  if(dh[mi][i]==0){
 6468: 	    dh[mi][i]=1; /* At least one step */
 6469: 	    bh[mi][i]=ju; /* At least one step */
 6470: 	    /*  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);*/
 6471: 	  }
 6472: 	} /* end if mle */
 6473:       }
 6474:     } /* end wave */
 6475:   }
 6476:   jmean=sum/k;
 6477:   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);
 6478:   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);
 6479: }
 6480: 
 6481: /*********** Tricode ****************************/
 6482:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
 6483:  {
 6484:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
 6485:    /*	  Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
 6486:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
 6487:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
 6488:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
 6489:     */
 6490: 
 6491:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
 6492:    int modmaxcovj=0; /* Modality max of covariates j */
 6493:    int cptcode=0; /* Modality max of covariates j */
 6494:    int modmincovj=0; /* Modality min of covariates j */
 6495: 
 6496: 
 6497:    /* cptcoveff=0;  */
 6498:    /* *cptcov=0; */
 6499:  
 6500:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
 6501:    for (k=1; k <= maxncov; k++)
 6502:      for(j=1; j<=2; j++)
 6503:        nbcode[k][j]=0; /* Valgrind */
 6504: 
 6505:    /* Loop on covariates without age and products and no quantitative variable */
 6506:    for (k=1; k<=cptcovt; k++) { /* cptcovt: total number of covariates of the model (2) nbocc(+)+1 = 8 excepting constant and age and age*age */
 6507:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
 6508:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
 6509:      if(Dummy[k]==0 && Typevar[k] !=1 && Typevar[k] != 3  && Typevar[k] != 2){ /* Dummy covariate and not age product nor fixed product */ 
 6510:        switch(Fixed[k]) {
 6511:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
 6512: 	 modmaxcovj=0;
 6513: 	 modmincovj=0;
 6514: 	 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*/
 6515: 	   /* printf("Waiting for error tricode Tvar[%d]=%d i=%d (int)(covar[Tvar[k]][i]=%d\n",k,Tvar[k], i, (int)(covar[Tvar[k]][i])); */
 6516: 	   ij=(int)(covar[Tvar[k]][i]);
 6517: 	   /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
 6518: 	    * If product of Vn*Vm, still boolean *:
 6519: 	    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
 6520: 	    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
 6521: 	   /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
 6522: 	      modality of the nth covariate of individual i. */
 6523: 	   if (ij > modmaxcovj)
 6524: 	     modmaxcovj=ij; 
 6525: 	   else if (ij < modmincovj) 
 6526: 	     modmincovj=ij; 
 6527: 	   if (ij <0 || ij >1 ){
 6528: 	     printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
 6529: 	     fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
 6530: 	     fflush(ficlog);
 6531: 	     exit(1);
 6532: 	   }
 6533: 	   if ((ij < -1) || (ij > NCOVMAX)){
 6534: 	     printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
 6535: 	     exit(1);
 6536: 	   }else
 6537: 	     Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
 6538: 	   /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
 6539: 	   /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
 6540: 	   /* getting the maximum value of the modality of the covariate
 6541: 	      (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
 6542: 	      female ies 1, then modmaxcovj=1.
 6543: 	   */
 6544: 	 } /* end for loop on individuals i */
 6545: 	 printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
 6546: 	 fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
 6547: 	 cptcode=modmaxcovj;
 6548: 	 /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
 6549: 	 /*for (i=0; i<=cptcode; i++) {*/
 6550: 	 for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
 6551: 	   printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
 6552: 	   fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
 6553: 	   if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
 6554: 	     if( j != -1){
 6555: 	       ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
 6556: 				  covariate for which somebody answered excluding 
 6557: 				  undefined. Usually 2: 0 and 1. */
 6558: 	     }
 6559: 	     ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
 6560: 				     covariate for which somebody answered including 
 6561: 				     undefined. Usually 3: -1, 0 and 1. */
 6562: 	   }	/* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
 6563: 		 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
 6564: 	 } /* Ndum[-1] number of undefined modalities */
 6565: 			
 6566: 	 /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
 6567: 	 /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
 6568: 	 /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
 6569: 	 /* modmincovj=3; modmaxcovj = 7; */
 6570: 	 /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
 6571: 	 /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
 6572: 	 /*		 defining two dummy variables: variables V1_1 and V1_2.*/
 6573: 	 /* nbcode[Tvar[j]][ij]=k; */
 6574: 	 /* nbcode[Tvar[j]][1]=0; */
 6575: 	 /* nbcode[Tvar[j]][2]=1; */
 6576: 	 /* nbcode[Tvar[j]][3]=2; */
 6577: 	 /* To be continued (not working yet). */
 6578: 	 ij=0; /* ij is similar to i but can jump over null modalities */
 6579: 
 6580: 	 /* 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*/
 6581: 	 /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
 6582: 	 /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
 6583: 	  * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
 6584: 	 /*, could be restored in the future */
 6585: 	 for (i=0; i<=1; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 or from -1 or 0 to 1 currently*/
 6586: 	   if (Ndum[i] == 0) { /* If nobody responded to this modality k */
 6587: 	     break;
 6588: 	   }
 6589: 	   ij++;
 6590: 	   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 . Could be -1*/
 6591: 	   cptcode = ij; /* New max modality for covar j */
 6592: 	 } /* end of loop on modality i=-1 to 1 or more */
 6593: 	 break;
 6594:        case 1: /* Testing on varying covariate, could be simple and
 6595: 		* should look at waves or product of fixed *
 6596: 		* varying. No time to test -1, assuming 0 and 1 only */
 6597: 	 ij=0;
 6598: 	 for(i=0; i<=1;i++){
 6599: 	   nbcode[Tvar[k]][++ij]=i;
 6600: 	 }
 6601: 	 break;
 6602:        default:
 6603: 	 break;
 6604:        } /* end switch */
 6605:      } /* end dummy test */
 6606:      if(Dummy[k]==1 && Typevar[k] !=1 && Typevar[k] !=3 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
 6607:        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*/
 6608: 	 if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
 6609: 	   printf("Error k=%d \n",k);
 6610: 	   exit(1);
 6611: 	 }
 6612: 	 if(isnan(covar[Tvar[k]][i])){
 6613: 	   printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
 6614: 	   fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
 6615: 	   fflush(ficlog);
 6616: 	   exit(1);
 6617:          }
 6618:        }
 6619:      } /* end Quanti */
 6620:    } /* end of loop on model-covariate k. nbcode[Tvark][1]=-1, nbcode[Tvark][1]=0 and nbcode[Tvark][2]=1 sets the value of covariate k*/  
 6621:   
 6622:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
 6623:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
 6624:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
 6625:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
 6626:      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 */ 
 6627:      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 */
 6628:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
 6629:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
 6630:   
 6631:    ij=0;
 6632:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
 6633:    for (k=1; k<=  cptcovt; k++) { /* cptcovt: total number of covariates of the model (2) nbocc(+)+1 = 8 excepting constant and age and age*age */
 6634:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
 6635:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
 6636:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
 6637:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
 6638:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
 6639:        /* Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product*/
 6640:        /* If product not in single variable we don't print results */
 6641:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
 6642:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
 6643:        /* k=       1    2   3     4       5       6      7       8        9  */
 6644:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
 6645:        /* ij            1    2                                            3  */  
 6646:        /* Tvaraff[ij]=  4    3                                            1  */
 6647:        /* Tmodelind[ij]=2    3                                            9  */
 6648:        /* TmodelInvind[ij]=2 1                                            1  */
 6649:        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*/
 6650:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
 6651:        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 */
 6652:        if(Fixed[k]!=0)
 6653: 	 anyvaryingduminmodel=1;
 6654:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
 6655:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
 6656:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
 6657:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
 6658:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
 6659:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
 6660:      } 
 6661:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
 6662:    /* ij--; */
 6663:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
 6664:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
 6665: 		* because they can be excluded from the model and real
 6666: 		* if in the model but excluded because missing values, but how to get k from ij?*/
 6667:    for(j=ij+1; j<= cptcovt; j++){
 6668:      Tvaraff[j]=0;
 6669:      Tmodelind[j]=0;
 6670:    }
 6671:    for(j=ntveff+1; j<= cptcovt; j++){
 6672:      TmodelInvind[j]=0;
 6673:    }
 6674:    /* To be sorted */
 6675:    ;
 6676:  }
 6677: 
 6678: 
 6679: /*********** Health Expectancies ****************/
 6680: 
 6681:  void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[], int nres )
 6682: 
 6683: {
 6684:   /* Health expectancies, no variances */
 6685:   /* cij is the combination in the list of combination of dummy covariates */
 6686:   /* strstart is a string of time at start of computing */
 6687:   int i, j, nhstepm, hstepm, h, nstepm;
 6688:   int nhstepma, nstepma; /* Decreasing with age */
 6689:   double age, agelim, hf;
 6690:   double ***p3mat;
 6691:   double eip;
 6692: 
 6693:   /* pstamp(ficreseij); */
 6694:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
 6695:   fprintf(ficreseij,"# Age");
 6696:   for(i=1; i<=nlstate;i++){
 6697:     for(j=1; j<=nlstate;j++){
 6698:       fprintf(ficreseij," e%1d%1d ",i,j);
 6699:     }
 6700:     fprintf(ficreseij," e%1d. ",i);
 6701:   }
 6702:   fprintf(ficreseij,"\n");
 6703: 
 6704:   
 6705:   if(estepm < stepm){
 6706:     printf ("Problem %d lower than %d\n",estepm, stepm);
 6707:   }
 6708:   else  hstepm=estepm;   
 6709:   /* We compute the life expectancy from trapezoids spaced every estepm months
 6710:    * This is mainly to measure the difference between two models: for example
 6711:    * if stepm=24 months pijx are given only every 2 years and by summing them
 6712:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 6713:    * progression in between and thus overestimating or underestimating according
 6714:    * to the curvature of the survival function. If, for the same date, we 
 6715:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 6716:    * to compare the new estimate of Life expectancy with the same linear 
 6717:    * hypothesis. A more precise result, taking into account a more precise
 6718:    * curvature will be obtained if estepm is as small as stepm. */
 6719: 
 6720:   /* For example we decided to compute the life expectancy with the smallest unit */
 6721:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 6722:      nhstepm is the number of hstepm from age to agelim 
 6723:      nstepm is the number of stepm from age to agelin. 
 6724:      Look at hpijx to understand the reason which relies in memory size consideration
 6725:      and note for a fixed period like estepm months */
 6726:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 6727:      survival function given by stepm (the optimization length). Unfortunately it
 6728:      means that if the survival funtion is printed only each two years of age and if
 6729:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 6730:      results. So we changed our mind and took the option of the best precision.
 6731:   */
 6732:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 6733: 
 6734:   agelim=AGESUP;
 6735:   /* If stepm=6 months */
 6736:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
 6737:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 6738:     
 6739: /* nhstepm age range expressed in number of stepm */
 6740:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 6741:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 6742:   /* if (stepm >= YEARM) hstepm=1;*/
 6743:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 6744:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6745: 
 6746:   for (age=bage; age<=fage; age ++){ 
 6747:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 6748:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 6749:     /* if (stepm >= YEARM) hstepm=1;*/
 6750:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 6751: 
 6752:     /* If stepm=6 months */
 6753:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 6754:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 6755:     /* printf("HELLO evsij Entering hpxij age=%d cij=%d hstepm=%d x[1]=%f nres=%d\n",(int) age, cij, hstepm, x[1], nres); */
 6756:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
 6757:     
 6758:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 6759:     
 6760:     printf("%d|",(int)age);fflush(stdout);
 6761:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 6762:     
 6763:     /* Computing expectancies */
 6764:     for(i=1; i<=nlstate;i++)
 6765:       for(j=1; j<=nlstate;j++)
 6766: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 6767: 	  eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
 6768: 	  
 6769: 	  /* 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]);*/
 6770: 
 6771: 	}
 6772: 
 6773:     fprintf(ficreseij,"%3.0f",age );
 6774:     for(i=1; i<=nlstate;i++){
 6775:       eip=0;
 6776:       for(j=1; j<=nlstate;j++){
 6777: 	eip +=eij[i][j][(int)age];
 6778: 	fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
 6779:       }
 6780:       fprintf(ficreseij,"%9.4f", eip );
 6781:     }
 6782:     fprintf(ficreseij,"\n");
 6783:     
 6784:   }
 6785:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6786:   printf("\n");
 6787:   fprintf(ficlog,"\n");
 6788:   
 6789: }
 6790: 
 6791:  void cvevsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,double delti[],double **matcov,char strstart[], int nres )
 6792: 
 6793: {
 6794:   /* Covariances of health expectancies eij and of total life expectancies according
 6795:      to initial status i, ei. .
 6796:   */
 6797:   /* Very time consuming function, but already optimized with precov */
 6798:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
 6799:   int nhstepma, nstepma; /* Decreasing with age */
 6800:   double age, agelim, hf;
 6801:   double ***p3matp, ***p3matm, ***varhe;
 6802:   double **dnewm,**doldm;
 6803:   double *xp, *xm;
 6804:   double **gp, **gm;
 6805:   double ***gradg, ***trgradg;
 6806:   int theta;
 6807: 
 6808:   double eip, vip;
 6809: 
 6810:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
 6811:   xp=vector(1,npar);
 6812:   xm=vector(1,npar);
 6813:   dnewm=matrix(1,nlstate*nlstate,1,npar);
 6814:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
 6815:   
 6816:   pstamp(ficresstdeij);
 6817:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
 6818:   fprintf(ficresstdeij,"# Age");
 6819:   for(i=1; i<=nlstate;i++){
 6820:     for(j=1; j<=nlstate;j++)
 6821:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
 6822:     fprintf(ficresstdeij," e%1d. ",i);
 6823:   }
 6824:   fprintf(ficresstdeij,"\n");
 6825: 
 6826:   pstamp(ficrescveij);
 6827:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
 6828:   fprintf(ficrescveij,"# Age");
 6829:   for(i=1; i<=nlstate;i++)
 6830:     for(j=1; j<=nlstate;j++){
 6831:       cptj= (j-1)*nlstate+i;
 6832:       for(i2=1; i2<=nlstate;i2++)
 6833: 	for(j2=1; j2<=nlstate;j2++){
 6834: 	  cptj2= (j2-1)*nlstate+i2;
 6835: 	  if(cptj2 <= cptj)
 6836: 	    fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
 6837: 	}
 6838:     }
 6839:   fprintf(ficrescveij,"\n");
 6840:   
 6841:   if(estepm < stepm){
 6842:     printf ("Problem %d lower than %d\n",estepm, stepm);
 6843:   }
 6844:   else  hstepm=estepm;   
 6845:   /* We compute the life expectancy from trapezoids spaced every estepm months
 6846:    * This is mainly to measure the difference between two models: for example
 6847:    * if stepm=24 months pijx are given only every 2 years and by summing them
 6848:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 6849:    * progression in between and thus overestimating or underestimating according
 6850:    * to the curvature of the survival function. If, for the same date, we 
 6851:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 6852:    * to compare the new estimate of Life expectancy with the same linear 
 6853:    * hypothesis. A more precise result, taking into account a more precise
 6854:    * curvature will be obtained if estepm is as small as stepm. */
 6855: 
 6856:   /* For example we decided to compute the life expectancy with the smallest unit */
 6857:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 6858:      nhstepm is the number of hstepm from age to agelim 
 6859:      nstepm is the number of stepm from age to agelin. 
 6860:      Look at hpijx to understand the reason of that which relies in memory size
 6861:      and note for a fixed period like estepm months */
 6862:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 6863:      survival function given by stepm (the optimization length). Unfortunately it
 6864:      means that if the survival funtion is printed only each two years of age and if
 6865:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 6866:      results. So we changed our mind and took the option of the best precision.
 6867:   */
 6868:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 6869: 
 6870:   /* If stepm=6 months */
 6871:   /* nhstepm age range expressed in number of stepm */
 6872:   agelim=AGESUP;
 6873:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
 6874:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 6875:   /* if (stepm >= YEARM) hstepm=1;*/
 6876:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 6877:   
 6878:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6879:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6880:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
 6881:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
 6882:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
 6883:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
 6884: 
 6885:   for (age=bage; age<=fage; age ++){ 
 6886:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 6887:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 6888:     /* if (stepm >= YEARM) hstepm=1;*/
 6889:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 6890: 		
 6891:     /* If stepm=6 months */
 6892:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 6893:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 6894:     
 6895:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 6896: 		
 6897:     /* Computing  Variances of health expectancies */
 6898:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
 6899:        decrease memory allocation */
 6900:     for(theta=1; theta <=npar; theta++){
 6901:       for(i=1; i<=npar; i++){ 
 6902: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 6903: 	xm[i] = x[i] - (i==theta ?delti[theta]:0);
 6904:       }
 6905:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
 6906:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
 6907: 			
 6908:       for(j=1; j<= nlstate; j++){
 6909: 	for(i=1; i<=nlstate; i++){
 6910: 	  for(h=0; h<=nhstepm-1; h++){
 6911: 	    gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
 6912: 	    gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
 6913: 	  }
 6914: 	}
 6915:       }
 6916: 			
 6917:       for(ij=1; ij<= nlstate*nlstate; ij++)
 6918: 	for(h=0; h<=nhstepm-1; h++){
 6919: 	  gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
 6920: 	}
 6921:     }/* End theta */
 6922:     
 6923:     
 6924:     for(h=0; h<=nhstepm-1; h++)
 6925:       for(j=1; j<=nlstate*nlstate;j++)
 6926: 	for(theta=1; theta <=npar; theta++)
 6927: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 6928:     
 6929: 		
 6930:     for(ij=1;ij<=nlstate*nlstate;ij++)
 6931:       for(ji=1;ji<=nlstate*nlstate;ji++)
 6932: 	varhe[ij][ji][(int)age] =0.;
 6933: 		
 6934:     printf("%d|",(int)age);fflush(stdout);
 6935:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 6936:     for(h=0;h<=nhstepm-1;h++){
 6937:       for(k=0;k<=nhstepm-1;k++){
 6938: 	matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
 6939: 	matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
 6940: 	for(ij=1;ij<=nlstate*nlstate;ij++)
 6941: 	  for(ji=1;ji<=nlstate*nlstate;ji++)
 6942: 	    varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
 6943:       }
 6944:     }
 6945:     /* if((int)age ==50){ */
 6946:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
 6947:     /* } */
 6948:     /* Computing expectancies */
 6949:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
 6950:     for(i=1; i<=nlstate;i++)
 6951:       for(j=1; j<=nlstate;j++)
 6952: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 6953: 	  eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
 6954: 					
 6955: 	  /* 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]);*/
 6956: 					
 6957: 	}
 6958: 
 6959:     /* Standard deviation of expectancies ij */		
 6960:     fprintf(ficresstdeij,"%3.0f",age );
 6961:     for(i=1; i<=nlstate;i++){
 6962:       eip=0.;
 6963:       vip=0.;
 6964:       for(j=1; j<=nlstate;j++){
 6965: 	eip += eij[i][j][(int)age];
 6966: 	for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
 6967: 	  vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
 6968: 	fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
 6969:       }
 6970:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
 6971:     }
 6972:     fprintf(ficresstdeij,"\n");
 6973: 		
 6974:     /* Variance of expectancies ij */		
 6975:     fprintf(ficrescveij,"%3.0f",age );
 6976:     for(i=1; i<=nlstate;i++)
 6977:       for(j=1; j<=nlstate;j++){
 6978: 	cptj= (j-1)*nlstate+i;
 6979: 	for(i2=1; i2<=nlstate;i2++)
 6980: 	  for(j2=1; j2<=nlstate;j2++){
 6981: 	    cptj2= (j2-1)*nlstate+i2;
 6982: 	    if(cptj2 <= cptj)
 6983: 	      fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
 6984: 	  }
 6985:       }
 6986:     fprintf(ficrescveij,"\n");
 6987: 		
 6988:   }
 6989:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
 6990:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
 6991:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
 6992:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
 6993:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6994:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6995:   printf("\n");
 6996:   fprintf(ficlog,"\n");
 6997: 	
 6998:   free_vector(xm,1,npar);
 6999:   free_vector(xp,1,npar);
 7000:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
 7001:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
 7002:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
 7003: }
 7004:  
 7005: /************ Variance ******************/
 7006:  void varevsij(char optionfilefiname[], double ***vareij, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int *ncvyearp, int ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[], int nres)
 7007:  {
 7008:    /** Variance of health expectancies 
 7009:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
 7010:     * double **newm;
 7011:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
 7012:     */
 7013:   
 7014:    /* int movingaverage(); */
 7015:    double **dnewm,**doldm;
 7016:    double **dnewmp,**doldmp;
 7017:    int i, j, nhstepm, hstepm, h, nstepm ;
 7018:    int first=0;
 7019:    int k;
 7020:    double *xp;
 7021:    double **gp, **gm;  /**< for var eij */
 7022:    double ***gradg, ***trgradg; /**< for var eij */
 7023:    double **gradgp, **trgradgp; /**< for var p point j */
 7024:    double *gpp, *gmp; /**< for var p point j */
 7025:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
 7026:    double ***p3mat;
 7027:    double age,agelim, hf;
 7028:    /* double ***mobaverage; */
 7029:    int theta;
 7030:    char digit[4];
 7031:    char digitp[25];
 7032: 
 7033:    char fileresprobmorprev[FILENAMELENGTH];
 7034: 
 7035:    if(popbased==1){
 7036:      if(mobilav!=0)
 7037:        strcpy(digitp,"-POPULBASED-MOBILAV_");
 7038:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
 7039:    }
 7040:    else 
 7041:      strcpy(digitp,"-STABLBASED_");
 7042: 
 7043:    /* if (mobilav!=0) { */
 7044:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 7045:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
 7046:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
 7047:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
 7048:    /*   } */
 7049:    /* } */
 7050: 
 7051:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
 7052:    sprintf(digit,"%-d",ij);
 7053:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
 7054:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
 7055:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
 7056:    strcat(fileresprobmorprev,fileresu);
 7057:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
 7058:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
 7059:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
 7060:    }
 7061:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 7062:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 7063:    pstamp(ficresprobmorprev);
 7064:    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);
 7065:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
 7066: 
 7067:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
 7068:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
 7069:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
 7070:    /* } */
 7071:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
 7072:      /* fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); */
 7073:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
 7074:    }
 7075:    /* for(j=1;j<=cptcoveff;j++)  */
 7076:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
 7077:    fprintf(ficresprobmorprev,"\n");
 7078: 
 7079:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
 7080:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 7081:      fprintf(ficresprobmorprev," p.%-d SE",j);
 7082:      for(i=1; i<=nlstate;i++)
 7083:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 7084:    }  
 7085:    fprintf(ficresprobmorprev,"\n");
 7086:   
 7087:    fprintf(ficgp,"\n# Routine varevsij");
 7088:    fprintf(ficgp,"\nunset title \n");
 7089:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
 7090:    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");
 7091:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
 7092: 
 7093:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 7094:    pstamp(ficresvij);
 7095:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
 7096:    if(popbased==1)
 7097:      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);
 7098:    else
 7099:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
 7100:    fprintf(ficresvij,"# Age");
 7101:    for(i=1; i<=nlstate;i++)
 7102:      for(j=1; j<=nlstate;j++)
 7103:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
 7104:    fprintf(ficresvij,"\n");
 7105: 
 7106:    xp=vector(1,npar);
 7107:    dnewm=matrix(1,nlstate,1,npar);
 7108:    doldm=matrix(1,nlstate,1,nlstate);
 7109:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
 7110:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 7111: 
 7112:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
 7113:    gpp=vector(nlstate+1,nlstate+ndeath);
 7114:    gmp=vector(nlstate+1,nlstate+ndeath);
 7115:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 7116:   
 7117:    if(estepm < stepm){
 7118:      printf ("Problem %d lower than %d\n",estepm, stepm);
 7119:    }
 7120:    else  hstepm=estepm;   
 7121:    /* For example we decided to compute the life expectancy with the smallest unit */
 7122:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 7123:       nhstepm is the number of hstepm from age to agelim 
 7124:       nstepm is the number of stepm from age to agelim. 
 7125:       Look at function hpijx to understand why because of memory size limitations, 
 7126:       we decided (b) to get a life expectancy respecting the most precise curvature of the
 7127:       survival function given by stepm (the optimization length). Unfortunately it
 7128:       means that if the survival funtion is printed every two years of age and if
 7129:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 7130:       results. So we changed our mind and took the option of the best precision.
 7131:    */
 7132:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 7133:    agelim = AGESUP;
 7134:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 7135:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 7136:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 7137:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 7138:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
 7139:      gp=matrix(0,nhstepm,1,nlstate);
 7140:      gm=matrix(0,nhstepm,1,nlstate);
 7141: 		
 7142: 		
 7143:      for(theta=1; theta <=npar; theta++){
 7144:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
 7145: 	 xp[i] = x[i] + (i==theta ?delti[theta]:0);
 7146:        }
 7147:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
 7148: 	* returns into prlim .
 7149: 	*/
 7150:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
 7151: 
 7152:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
 7153:        if (popbased==1) {
 7154: 	 if(mobilav ==0){
 7155: 	   for(i=1; i<=nlstate;i++)
 7156: 	     prlim[i][i]=probs[(int)age][i][ij];
 7157: 	 }else{ /* mobilav */ 
 7158: 	   for(i=1; i<=nlstate;i++)
 7159: 	     prlim[i][i]=mobaverage[(int)age][i][ij];
 7160: 	 }
 7161:        }
 7162:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
 7163: 	*/			
 7164:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  /* Returns p3mat[i][j][h] for h=0 to nhstepm */
 7165:        /**< And for each alive state j, sums over i \f$ w^i_x {}{h}_p^{ij}x\f$, which are the probability
 7166: 	* at horizon h in state j including mortality.
 7167: 	*/
 7168:        for(j=1; j<= nlstate; j++){
 7169: 	 for(h=0; h<=nhstepm; h++){
 7170: 	   for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 7171: 	     gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 7172: 	 }
 7173:        }
 7174:        /* Next for computing shifted+ probability of death (h=1 means
 7175: 	  computed over hstepm matrices product = hstepm*stepm months) 
 7176: 	  as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
 7177:        */
 7178:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
 7179: 	 for(i=1,gpp[j]=0.; i<= nlstate; i++)
 7180: 	   gpp[j] += prlim[i][i]*p3mat[i][j][1];
 7181:        }
 7182:        
 7183:        /* Again with minus shift */
 7184: 			
 7185:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
 7186: 	 xp[i] = x[i] - (i==theta ?delti[theta]:0);
 7187: 
 7188:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
 7189: 			
 7190:        if (popbased==1) {
 7191: 	 if(mobilav ==0){
 7192: 	   for(i=1; i<=nlstate;i++)
 7193: 	     prlim[i][i]=probs[(int)age][i][ij];
 7194: 	 }else{ /* mobilav */ 
 7195: 	   for(i=1; i<=nlstate;i++)
 7196: 	     prlim[i][i]=mobaverage[(int)age][i][ij];
 7197: 	 }
 7198:        }
 7199: 			
 7200:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
 7201: 			
 7202:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
 7203: 	 for(h=0; h<=nhstepm; h++){
 7204: 	   for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 7205: 	     gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 7206: 	 }
 7207:        }
 7208:        /* This for computing probability of death (h=1 means
 7209: 	  computed over hstepm matrices product = hstepm*stepm months) 
 7210: 	  as a weighted average of prlim.
 7211:        */
 7212:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
 7213: 	 for(i=1,gmp[j]=0.; i<= nlstate; i++)
 7214: 	   gmp[j] += prlim[i][i]*p3mat[i][j][1];
 7215:        }    
 7216:        /* end shifting computations */
 7217: 
 7218:        /**< Computing gradient matrix at horizon h 
 7219: 	*/
 7220:        for(j=1; j<= nlstate; j++) /* vareij */
 7221: 	 for(h=0; h<=nhstepm; h++){
 7222: 	   gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 7223: 	 }
 7224:        /**< Gradient of overall mortality p.3 (or p.j) 
 7225: 	*/
 7226:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
 7227: 	 gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
 7228:        }
 7229: 			
 7230:      } /* End theta */
 7231:      
 7232:      /* We got the gradient matrix for each theta and state j */		
 7233:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
 7234: 		
 7235:      for(h=0; h<=nhstepm; h++) /* veij */
 7236:        for(j=1; j<=nlstate;j++)
 7237: 	 for(theta=1; theta <=npar; theta++)
 7238: 	   trgradg[h][j][theta]=gradg[h][theta][j];
 7239: 		
 7240:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
 7241:        for(theta=1; theta <=npar; theta++)
 7242: 	 trgradgp[j][theta]=gradgp[theta][j];
 7243:      /**< as well as its transposed matrix 
 7244:       */		
 7245: 		
 7246:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 7247:      for(i=1;i<=nlstate;i++)
 7248:        for(j=1;j<=nlstate;j++)
 7249: 	 vareij[i][j][(int)age] =0.;
 7250: 
 7251:      /* Computing trgradg by matcov by gradg at age and summing over h
 7252:       * and k (nhstepm) formula 15 of article
 7253:       * Lievre-Brouard-Heathcote
 7254:       */
 7255:      
 7256:      for(h=0;h<=nhstepm;h++){
 7257:        for(k=0;k<=nhstepm;k++){
 7258: 	 matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 7259: 	 matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
 7260: 	 for(i=1;i<=nlstate;i++)
 7261: 	   for(j=1;j<=nlstate;j++)
 7262: 	     vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
 7263:        }
 7264:      }
 7265: 		
 7266:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
 7267:       * p.j overall mortality formula 49 but computed directly because
 7268:       * we compute the grad (wix pijx) instead of grad (pijx),even if
 7269:       * wix is independent of theta.
 7270:       */
 7271:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
 7272:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
 7273:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
 7274:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
 7275: 	 varppt[j][i]=doldmp[j][i];
 7276:      /* end ppptj */
 7277:      /*  x centered again */
 7278: 		
 7279:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
 7280: 		
 7281:      if (popbased==1) {
 7282:        if(mobilav ==0){
 7283: 	 for(i=1; i<=nlstate;i++)
 7284: 	   prlim[i][i]=probs[(int)age][i][ij];
 7285:        }else{ /* mobilav */ 
 7286: 	 for(i=1; i<=nlstate;i++)
 7287: 	   prlim[i][i]=mobaverage[(int)age][i][ij];
 7288:        }
 7289:      }
 7290: 		
 7291:      /* This for computing probability of death (h=1 means
 7292: 	computed over hstepm (estepm) matrices product = hstepm*stepm months) 
 7293: 	as a weighted average of prlim.
 7294:      */
 7295:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
 7296:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
 7297:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
 7298: 	 gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
 7299:      }    
 7300:      /* end probability of death */
 7301: 		
 7302:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
 7303:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 7304:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
 7305:        for(i=1; i<=nlstate;i++){
 7306: 	 fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 7307:        }
 7308:      } 
 7309:      fprintf(ficresprobmorprev,"\n");
 7310: 		
 7311:      fprintf(ficresvij,"%.0f ",age );
 7312:      for(i=1; i<=nlstate;i++)
 7313:        for(j=1; j<=nlstate;j++){
 7314: 	 fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
 7315:        }
 7316:      fprintf(ficresvij,"\n");
 7317:      free_matrix(gp,0,nhstepm,1,nlstate);
 7318:      free_matrix(gm,0,nhstepm,1,nlstate);
 7319:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 7320:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 7321:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 7322:    } /* End age */
 7323:    free_vector(gpp,nlstate+1,nlstate+ndeath);
 7324:    free_vector(gmp,nlstate+1,nlstate+ndeath);
 7325:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
 7326:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 7327:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
 7328:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
 7329:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
 7330:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
 7331:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
 7332:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
 7333:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
 7334:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
 7335:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
 7336:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
 7337:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
 7338:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
 7339:    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);
 7340:    /*  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);
 7341:     */
 7342:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
 7343:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
 7344: 
 7345:    free_vector(xp,1,npar);
 7346:    free_matrix(doldm,1,nlstate,1,nlstate);
 7347:    free_matrix(dnewm,1,nlstate,1,npar);
 7348:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 7349:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
 7350:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 7351:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 7352:    fclose(ficresprobmorprev);
 7353:    fflush(ficgp);
 7354:    fflush(fichtm); 
 7355:  }  /* end varevsij */
 7356: 
 7357: /************ Variance of prevlim ******************/
 7358:  void varprevlim(char fileresvpl[], FILE *ficresvpl, double **varpl, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int *ncvyearp, int ij, char strstart[], int nres)
 7359: {
 7360:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
 7361:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 7362: 
 7363:   double **dnewmpar,**doldm;
 7364:   int i, j, nhstepm, hstepm;
 7365:   double *xp;
 7366:   double *gp, *gm;
 7367:   double **gradg, **trgradg;
 7368:   double **mgm, **mgp;
 7369:   double age,agelim;
 7370:   int theta;
 7371:   
 7372:   pstamp(ficresvpl);
 7373:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
 7374:   fprintf(ficresvpl,"# Age ");
 7375:   if(nresult >=1)
 7376:     fprintf(ficresvpl," Result# ");
 7377:   for(i=1; i<=nlstate;i++)
 7378:       fprintf(ficresvpl," %1d-%1d",i,i);
 7379:   fprintf(ficresvpl,"\n");
 7380: 
 7381:   xp=vector(1,npar);
 7382:   dnewmpar=matrix(1,nlstate,1,npar);
 7383:   doldm=matrix(1,nlstate,1,nlstate);
 7384:   
 7385:   hstepm=1*YEARM; /* Every year of age */
 7386:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 7387:   agelim = AGESUP;
 7388:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 7389:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 7390:     if (stepm >= YEARM) hstepm=1;
 7391:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 7392:     gradg=matrix(1,npar,1,nlstate);
 7393:     mgp=matrix(1,npar,1,nlstate);
 7394:     mgm=matrix(1,npar,1,nlstate);
 7395:     gp=vector(1,nlstate);
 7396:     gm=vector(1,nlstate);
 7397: 
 7398:     for(theta=1; theta <=npar; theta++){
 7399:       for(i=1; i<=npar; i++){ /* Computes gradient */
 7400: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 7401:       }
 7402:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
 7403:       /* 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
 7404:       /* else */
 7405:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
 7406:       for(i=1;i<=nlstate;i++){
 7407: 	gp[i] = prlim[i][i];
 7408: 	mgp[theta][i] = prlim[i][i];
 7409:       }
 7410:       for(i=1; i<=npar; i++) /* Computes gradient */
 7411: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 7412:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
 7413:       /* 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
 7414:       /* else */
 7415:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
 7416:       for(i=1;i<=nlstate;i++){
 7417: 	gm[i] = prlim[i][i];
 7418: 	mgm[theta][i] = prlim[i][i];
 7419:       }
 7420:       for(i=1;i<=nlstate;i++)
 7421: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 7422:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
 7423:     } /* End theta */
 7424: 
 7425:     trgradg =matrix(1,nlstate,1,npar);
 7426: 
 7427:     for(j=1; j<=nlstate;j++)
 7428:       for(theta=1; theta <=npar; theta++)
 7429: 	trgradg[j][theta]=gradg[theta][j];
 7430:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
 7431:     /*   printf("\nmgm mgp %d ",(int)age); */
 7432:     /*   for(j=1; j<=nlstate;j++){ */
 7433:     /* 	printf(" %d ",j); */
 7434:     /* 	for(theta=1; theta <=npar; theta++) */
 7435:     /* 	  printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
 7436:     /* 	printf("\n "); */
 7437:     /*   } */
 7438:     /* } */
 7439:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
 7440:     /*   printf("\n gradg %d ",(int)age); */
 7441:     /*   for(j=1; j<=nlstate;j++){ */
 7442:     /* 	printf("%d ",j); */
 7443:     /* 	for(theta=1; theta <=npar; theta++) */
 7444:     /* 	  printf("%d %lf ",theta,gradg[theta][j]); */
 7445:     /* 	printf("\n "); */
 7446:     /*   } */
 7447:     /* } */
 7448: 
 7449:     for(i=1;i<=nlstate;i++)
 7450:       varpl[i][(int)age] =0.;
 7451:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
 7452:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
 7453:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
 7454:     }else{
 7455:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
 7456:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
 7457:     }
 7458:     for(i=1;i<=nlstate;i++)
 7459:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 7460: 
 7461:     fprintf(ficresvpl,"%.0f ",age );
 7462:     if(nresult >=1)
 7463:       fprintf(ficresvpl,"%d ",nres );
 7464:     for(i=1; i<=nlstate;i++){
 7465:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
 7466:       /* for(j=1;j<=nlstate;j++) */
 7467:       /* 	fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
 7468:     }
 7469:     fprintf(ficresvpl,"\n");
 7470:     free_vector(gp,1,nlstate);
 7471:     free_vector(gm,1,nlstate);
 7472:     free_matrix(mgm,1,npar,1,nlstate);
 7473:     free_matrix(mgp,1,npar,1,nlstate);
 7474:     free_matrix(gradg,1,npar,1,nlstate);
 7475:     free_matrix(trgradg,1,nlstate,1,npar);
 7476:   } /* End age */
 7477: 
 7478:   free_vector(xp,1,npar);
 7479:   free_matrix(doldm,1,nlstate,1,npar);
 7480:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
 7481: 
 7482: }
 7483: 
 7484: 
 7485: /************ Variance of backprevalence limit ******************/
 7486:  void varbrevlim(char fileresvbl[], FILE  *ficresvbl, double **varbpl, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **bprlim, double ftolpl, int mobilavproj, int *ncvyearp, int ij, char strstart[], int nres)
 7487: {
 7488:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
 7489:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 7490: 
 7491:   double **dnewmpar,**doldm;
 7492:   int i, j, nhstepm, hstepm;
 7493:   double *xp;
 7494:   double *gp, *gm;
 7495:   double **gradg, **trgradg;
 7496:   double **mgm, **mgp;
 7497:   double age,agelim;
 7498:   int theta;
 7499:   
 7500:   pstamp(ficresvbl);
 7501:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
 7502:   fprintf(ficresvbl,"# Age ");
 7503:   if(nresult >=1)
 7504:     fprintf(ficresvbl," Result# ");
 7505:   for(i=1; i<=nlstate;i++)
 7506:       fprintf(ficresvbl," %1d-%1d",i,i);
 7507:   fprintf(ficresvbl,"\n");
 7508: 
 7509:   xp=vector(1,npar);
 7510:   dnewmpar=matrix(1,nlstate,1,npar);
 7511:   doldm=matrix(1,nlstate,1,nlstate);
 7512:   
 7513:   hstepm=1*YEARM; /* Every year of age */
 7514:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 7515:   agelim = AGEINF;
 7516:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
 7517:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 7518:     if (stepm >= YEARM) hstepm=1;
 7519:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 7520:     gradg=matrix(1,npar,1,nlstate);
 7521:     mgp=matrix(1,npar,1,nlstate);
 7522:     mgm=matrix(1,npar,1,nlstate);
 7523:     gp=vector(1,nlstate);
 7524:     gm=vector(1,nlstate);
 7525: 
 7526:     for(theta=1; theta <=npar; theta++){
 7527:       for(i=1; i<=npar; i++){ /* Computes gradient */
 7528: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 7529:       }
 7530:       if(mobilavproj > 0 )
 7531: 	bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
 7532:       else
 7533: 	bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
 7534:       for(i=1;i<=nlstate;i++){
 7535: 	gp[i] = bprlim[i][i];
 7536: 	mgp[theta][i] = bprlim[i][i];
 7537:       }
 7538:      for(i=1; i<=npar; i++) /* Computes gradient */
 7539: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 7540:        if(mobilavproj > 0 )
 7541: 	bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
 7542:        else
 7543: 	bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
 7544:       for(i=1;i<=nlstate;i++){
 7545: 	gm[i] = bprlim[i][i];
 7546: 	mgm[theta][i] = bprlim[i][i];
 7547:       }
 7548:       for(i=1;i<=nlstate;i++)
 7549: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 7550:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
 7551:     } /* End theta */
 7552: 
 7553:     trgradg =matrix(1,nlstate,1,npar);
 7554: 
 7555:     for(j=1; j<=nlstate;j++)
 7556:       for(theta=1; theta <=npar; theta++)
 7557: 	trgradg[j][theta]=gradg[theta][j];
 7558:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
 7559:     /*   printf("\nmgm mgp %d ",(int)age); */
 7560:     /*   for(j=1; j<=nlstate;j++){ */
 7561:     /* 	printf(" %d ",j); */
 7562:     /* 	for(theta=1; theta <=npar; theta++) */
 7563:     /* 	  printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
 7564:     /* 	printf("\n "); */
 7565:     /*   } */
 7566:     /* } */
 7567:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
 7568:     /*   printf("\n gradg %d ",(int)age); */
 7569:     /*   for(j=1; j<=nlstate;j++){ */
 7570:     /* 	printf("%d ",j); */
 7571:     /* 	for(theta=1; theta <=npar; theta++) */
 7572:     /* 	  printf("%d %lf ",theta,gradg[theta][j]); */
 7573:     /* 	printf("\n "); */
 7574:     /*   } */
 7575:     /* } */
 7576: 
 7577:     for(i=1;i<=nlstate;i++)
 7578:       varbpl[i][(int)age] =0.;
 7579:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
 7580:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
 7581:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
 7582:     }else{
 7583:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
 7584:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
 7585:     }
 7586:     for(i=1;i<=nlstate;i++)
 7587:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 7588: 
 7589:     fprintf(ficresvbl,"%.0f ",age );
 7590:     if(nresult >=1)
 7591:       fprintf(ficresvbl,"%d ",nres );
 7592:     for(i=1; i<=nlstate;i++)
 7593:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
 7594:     fprintf(ficresvbl,"\n");
 7595:     free_vector(gp,1,nlstate);
 7596:     free_vector(gm,1,nlstate);
 7597:     free_matrix(mgm,1,npar,1,nlstate);
 7598:     free_matrix(mgp,1,npar,1,nlstate);
 7599:     free_matrix(gradg,1,npar,1,nlstate);
 7600:     free_matrix(trgradg,1,nlstate,1,npar);
 7601:   } /* End age */
 7602: 
 7603:   free_vector(xp,1,npar);
 7604:   free_matrix(doldm,1,nlstate,1,npar);
 7605:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
 7606: 
 7607: }
 7608: 
 7609: /************ Variance of one-step probabilities  ******************/
 7610: 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[])
 7611:  {
 7612:    int i, j=0,  k1, l1, tj;
 7613:    int k2, l2, j1,  z1;
 7614:    int k=0, l;
 7615:    int first=1, first1, first2;
 7616:    int nres=0; /* New */
 7617:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
 7618:    double **dnewm,**doldm;
 7619:    double *xp;
 7620:    double *gp, *gm;
 7621:    double **gradg, **trgradg;
 7622:    double **mu;
 7623:    double age, cov[NCOVMAX+1];
 7624:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
 7625:    int theta;
 7626:    char fileresprob[FILENAMELENGTH];
 7627:    char fileresprobcov[FILENAMELENGTH];
 7628:    char fileresprobcor[FILENAMELENGTH];
 7629:    double ***varpij;
 7630: 
 7631:    strcpy(fileresprob,"PROB_"); 
 7632:    strcat(fileresprob,fileres);
 7633:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
 7634:      printf("Problem with resultfile: %s\n", fileresprob);
 7635:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
 7636:    }
 7637:    strcpy(fileresprobcov,"PROBCOV_"); 
 7638:    strcat(fileresprobcov,fileresu);
 7639:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
 7640:      printf("Problem with resultfile: %s\n", fileresprobcov);
 7641:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 7642:    }
 7643:    strcpy(fileresprobcor,"PROBCOR_"); 
 7644:    strcat(fileresprobcor,fileresu);
 7645:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 7646:      printf("Problem with resultfile: %s\n", fileresprobcor);
 7647:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 7648:    }
 7649:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 7650:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 7651:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 7652:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 7653:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 7654:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 7655:    pstamp(ficresprob);
 7656:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
 7657:    fprintf(ficresprob,"# Age");
 7658:    pstamp(ficresprobcov);
 7659:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
 7660:    fprintf(ficresprobcov,"# Age");
 7661:    pstamp(ficresprobcor);
 7662:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 7663:    fprintf(ficresprobcor,"# Age");
 7664: 
 7665: 
 7666:    for(i=1; i<=nlstate;i++)
 7667:      for(j=1; j<=(nlstate+ndeath);j++){
 7668:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
 7669:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
 7670:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
 7671:      }  
 7672:    /* fprintf(ficresprob,"\n");
 7673:       fprintf(ficresprobcov,"\n");
 7674:       fprintf(ficresprobcor,"\n");
 7675:    */
 7676:    xp=vector(1,npar);
 7677:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 7678:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 7679:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
 7680:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 7681:    first=1;
 7682:    fprintf(ficgp,"\n# Routine varprob");
 7683:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
 7684:    fprintf(fichtm,"\n");
 7685: 
 7686:    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. File %s</li>\n",optionfilehtmcov,optionfilehtmcov);
 7687:    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);
 7688:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
 7689: and drawn. It helps understanding how is the covariance between two incidences.\
 7690:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
 7691:    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. \
 7692: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
 7693: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
 7694: standard deviations wide on each axis. <br>\
 7695:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
 7696:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 7697: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
 7698: 
 7699:    cov[1]=1;
 7700:    /* tj=cptcoveff; */
 7701:    tj = (int) pow(2,cptcoveff);
 7702:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
 7703:    j1=0;
 7704: 
 7705:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
 7706:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
 7707:      /* printf("Varprob  TKresult[nres]=%d j1=%d, nres=%d, cptcovn=%d, cptcoveff=%d tj=%d cptcovs=%d\n",  TKresult[nres], j1, nres, cptcovn, cptcoveff, tj, cptcovs); */
 7708:      if(tj != 1 && TKresult[nres]!= j1)
 7709:        continue;
 7710: 
 7711:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
 7712:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
 7713:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
 7714:      if  (cptcovn>0) {
 7715:        fprintf(ficresprob, "\n#********** Variable ");
 7716:        fprintf(ficresprobcov, "\n#********** Variable "); 
 7717:        fprintf(ficgp, "\n#********** Variable ");
 7718:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
 7719:        fprintf(ficresprobcor, "\n#********** Variable ");    
 7720: 
 7721:        /* Including quantitative variables of the resultline to be done */
 7722:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
 7723: 	 /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
 7724: 	 fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
 7725: 	 /* fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s resultline[%d]=%s \n",nres, z1, modelresult[nres][z1], model, nres, resultline[nres]); */
 7726: 	 if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
 7727: 	   if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
 7728: 	     fprintf(ficresprob,"V%d=%d ",Tvresult[nres][z1],Tresult[nres][z1]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
 7729: 	     fprintf(ficresprobcov,"V%d=%d ",Tvresult[nres][z1],Tresult[nres][z1]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
 7730: 	     fprintf(ficgp,"V%d=%d ",Tvresult[nres][z1],Tresult[nres][z1]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
 7731: 	     fprintf(fichtmcov,"V%d=%d ",Tvresult[nres][z1],Tresult[nres][z1]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
 7732: 	     fprintf(ficresprobcor,"V%d=%d ",Tvresult[nres][z1],Tresult[nres][z1]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
 7733: 	     fprintf(ficresprob,"fixed ");
 7734: 	     fprintf(ficresprobcov,"fixed ");
 7735: 	     fprintf(ficgp,"fixed ");
 7736: 	     fprintf(fichtmcov,"fixed ");
 7737: 	     fprintf(ficresprobcor,"fixed ");
 7738: 	   }else{
 7739: 	     fprintf(ficresprob,"varyi ");
 7740: 	     fprintf(ficresprobcov,"varyi ");
 7741: 	     fprintf(ficgp,"varyi ");
 7742: 	     fprintf(fichtmcov,"varyi ");
 7743: 	     fprintf(ficresprobcor,"varyi ");
 7744: 	   }
 7745: 	 }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
 7746: 	   /* For each selected (single) quantitative value */
 7747: 	   fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
 7748: 	   if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
 7749: 	     fprintf(ficresprob,"fixed ");
 7750: 	     fprintf(ficresprobcov,"fixed ");
 7751: 	     fprintf(ficgp,"fixed ");
 7752: 	     fprintf(fichtmcov,"fixed ");
 7753: 	     fprintf(ficresprobcor,"fixed ");
 7754: 	   }else{
 7755: 	     fprintf(ficresprob,"varyi ");
 7756: 	     fprintf(ficresprobcov,"varyi ");
 7757: 	     fprintf(ficgp,"varyi ");
 7758: 	     fprintf(fichtmcov,"varyi ");
 7759: 	     fprintf(ficresprobcor,"varyi ");
 7760: 	   }
 7761: 	 }else{
 7762: 	   printf("Error in varprob() Dummy[modelresult[%d][%d]]=%d, modelresult[%d][%d]=V%d cptcovs=%d, cptcoveff=%d \n", nres, z1, Dummy[modelresult[nres][z1]],nres,z1,modelresult[nres][z1],cptcovs, cptcoveff);  /* end if dummy  or quanti */
 7763: 	   fprintf(ficlog,"Error in varprob() Dummy[modelresult[%d][%d]]=%d, modelresult[%d][%d]=V%d cptcovs=%d, cptcoveff=%d \n", nres, z1, Dummy[modelresult[nres][z1]],nres,z1,modelresult[nres][z1],cptcovs, cptcoveff);  /* end if dummy  or quanti */
 7764: 	   exit(1);
 7765: 	 }
 7766:        } /* End loop on variable of this resultline */
 7767:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
 7768:        fprintf(ficresprob, "**********\n#\n");
 7769:        fprintf(ficresprobcov, "**********\n#\n");
 7770:        fprintf(ficgp, "**********\n#\n");
 7771:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
 7772:        fprintf(ficresprobcor, "**********\n#");    
 7773:        if(invalidvarcomb[j1]){
 7774: 	 fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
 7775: 	 fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
 7776: 	 continue;
 7777:        }
 7778:      }
 7779:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
 7780:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 7781:      gp=vector(1,(nlstate)*(nlstate+ndeath));
 7782:      gm=vector(1,(nlstate)*(nlstate+ndeath));
 7783:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
 7784:        cov[2]=age;
 7785:        if(nagesqr==1)
 7786: 	 cov[3]= age*age;
 7787:        /* New code end of combination but for each resultline */
 7788:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
 7789: 	 if(Typevar[k1]==1 || Typevar[k1] ==3){ /* A product with age */
 7790: 	   cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
 7791: 	 }else{
 7792: 	   cov[2+nagesqr+k1]=precov[nres][k1];
 7793: 	 }
 7794:        }/* End of loop on model equation */
 7795: /* Old code */
 7796:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
 7797:        /* /\* 	 cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
 7798:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
 7799:        /* 	 /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
 7800:        /* 	 cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
 7801:        /* 	 /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
 7802:        /* 								    * 1  1 1 1 1 */
 7803:        /* 								    * 2  2 1 1 1 */
 7804:        /* 								    * 3  1 2 1 1 */
 7805:        /* 								    *\/ */
 7806:        /* 	 /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
 7807:        /* } */
 7808:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
 7809:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
 7810:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
 7811:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
 7812:        /* 	 if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
 7813:        /* 	   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
 7814:        /* 	   /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
 7815:        /* 	 } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
 7816:        /* 	   printf("Internal IMaCh error, don't know which value for quantitative covariate with age, Tage[k]%d, k=%d, Tvar[Tage[k]]=V%d, age=%d\n",Tage[k],k ,Tvar[Tage[k]], (int)cov[2]); */
 7817:        /* 	   /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
 7818:        /* 	   /\* exit(1); *\/ */
 7819:        /* 	   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
 7820:        /* 	 } */
 7821:        /* 	 /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
 7822:        /* } */
 7823:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
 7824:        /* 	 if(Dummy[Tvard[k][1]]==0){ */
 7825:        /* 	   if(Dummy[Tvard[k][2]]==0){ */
 7826:        /* 	     cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])]; */
 7827:        /* 	     /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
 7828:        /* 	   }else{ /\* Should we use the mean of the quantitative variables? *\/ */
 7829:        /* 	     cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
 7830:        /* 	     /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
 7831:        /* 	   } */
 7832:        /* 	 }else{ */
 7833:        /* 	   if(Dummy[Tvard[k][2]]==0){ */
 7834:        /* 	     cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
 7835:        /* 	     /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
 7836:        /* 	   }else{ */
 7837:        /* 	     cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
 7838:        /* 	     /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
 7839:        /* 	   } */
 7840:        /* 	 } */
 7841:        /* 	 /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
 7842:        /* } */			
 7843: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/			
 7844:        for(theta=1; theta <=npar; theta++){
 7845: 	 for(i=1; i<=npar; i++)
 7846: 	   xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
 7847: 				
 7848: 	 pmij(pmmij,cov,ncovmodel,xp,nlstate);
 7849: 				
 7850: 	 k=0;
 7851: 	 for(i=1; i<= (nlstate); i++){
 7852: 	   for(j=1; j<=(nlstate+ndeath);j++){
 7853: 	     k=k+1;
 7854: 	     gp[k]=pmmij[i][j];
 7855: 	   }
 7856: 	 }
 7857: 				
 7858: 	 for(i=1; i<=npar; i++)
 7859: 	   xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
 7860: 				
 7861: 	 pmij(pmmij,cov,ncovmodel,xp,nlstate);
 7862: 	 k=0;
 7863: 	 for(i=1; i<=(nlstate); i++){
 7864: 	   for(j=1; j<=(nlstate+ndeath);j++){
 7865: 	     k=k+1;
 7866: 	     gm[k]=pmmij[i][j];
 7867: 	   }
 7868: 	 }
 7869: 				
 7870: 	 for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
 7871: 	   gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
 7872:        }
 7873: 
 7874:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
 7875: 	 for(theta=1; theta <=npar; theta++)
 7876: 	   trgradg[j][theta]=gradg[theta][j];
 7877: 			
 7878:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
 7879:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
 7880: 			
 7881:        pmij(pmmij,cov,ncovmodel,x,nlstate);
 7882: 			
 7883:        k=0;
 7884:        for(i=1; i<=(nlstate); i++){
 7885: 	 for(j=1; j<=(nlstate+ndeath);j++){
 7886: 	   k=k+1;
 7887: 	   mu[k][(int) age]=pmmij[i][j];
 7888: 	 }
 7889:        }
 7890:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 7891: 	 for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 7892: 	   varpij[i][j][(int)age] = doldm[i][j];
 7893: 			
 7894:        /*printf("\n%d ",(int)age);
 7895: 	 for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 7896: 	 printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 7897: 	 fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 7898: 	 }*/
 7899: 			
 7900:        fprintf(ficresprob,"\n%d ",(int)age);
 7901:        fprintf(ficresprobcov,"\n%d ",(int)age);
 7902:        fprintf(ficresprobcor,"\n%d ",(int)age);
 7903: 			
 7904:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
 7905: 	 fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
 7906:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 7907: 	 fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
 7908: 	 fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
 7909:        }
 7910:        i=0;
 7911:        for (k=1; k<=(nlstate);k++){
 7912: 	 for (l=1; l<=(nlstate+ndeath);l++){ 
 7913: 	   i++;
 7914: 	   fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 7915: 	   fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
 7916: 	   for (j=1; j<=i;j++){
 7917: 	     /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
 7918: 	     fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
 7919: 	     fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
 7920: 	   }
 7921: 	 }
 7922:        }/* end of loop for state */
 7923:      } /* end of loop for age */
 7924:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
 7925:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 7926:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 7927:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 7928:     
 7929:      /* Confidence intervalle of pij  */
 7930:      /*
 7931:        fprintf(ficgp,"\nunset parametric;unset label");
 7932:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
 7933:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 7934:        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);
 7935:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
 7936:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
 7937:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
 7938:      */
 7939: 		
 7940:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
 7941:      first1=1;first2=2;
 7942:      for (k2=1; k2<=(nlstate);k2++){
 7943:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
 7944: 	 if(l2==k2) continue;
 7945: 	 j=(k2-1)*(nlstate+ndeath)+l2;
 7946: 	 for (k1=1; k1<=(nlstate);k1++){
 7947: 	   for (l1=1; l1<=(nlstate+ndeath);l1++){ 
 7948: 	     if(l1==k1) continue;
 7949: 	     i=(k1-1)*(nlstate+ndeath)+l1;
 7950: 	     if(i<=j) continue;
 7951: 	     for (age=bage; age<=fage; age ++){ 
 7952: 	       if ((int)age %5==0){
 7953: 		 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
 7954: 		 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
 7955: 		 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
 7956: 		 mu1=mu[i][(int) age]/stepm*YEARM ;
 7957: 		 mu2=mu[j][(int) age]/stepm*YEARM;
 7958: 		 c12=cv12/sqrt(v1*v2);
 7959: 		 /* Computing eigen value of matrix of covariance */
 7960: 		 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 7961: 		 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 7962: 		 if ((lc2 <0) || (lc1 <0) ){
 7963: 		   if(first2==1){
 7964: 		     first1=0;
 7965: 		     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);
 7966: 		   }
 7967: 		   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);
 7968: 		   /* lc1=fabs(lc1); */ /* If we want to have them positive */
 7969: 		   /* lc2=fabs(lc2); */
 7970: 		 }
 7971: 								
 7972: 		 /* Eigen vectors */
 7973: 		 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
 7974: 		   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
 7975: 		   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
 7976: 		   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
 7977: 		 }else
 7978: 		   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
 7979: 		 /*v21=sqrt(1.-v11*v11); *//* error */
 7980: 		 v21=(lc1-v1)/cv12*v11;
 7981: 		 v12=-v21;
 7982: 		 v22=v11;
 7983: 		 tnalp=v21/v11;
 7984: 		 if(first1==1){
 7985: 		   first1=0;
 7986: 		   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);
 7987: 		 }
 7988: 		 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);
 7989: 		 /*printf(fignu*/
 7990: 		 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
 7991: 		 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
 7992: 		 if(first==1){
 7993: 		   first=0;
 7994: 		   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
 7995: 		   fprintf(ficgp,"\nset parametric;unset label");
 7996: 		   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);
 7997: 		   fprintf(ficgp,"\nset ter svg size 640, 480");
 7998: 		   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
 7999:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">																		\
 8000: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
 8001: 			   subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,	\
 8002: 			   subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 8003: 		   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 8004: 		   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
 8005: 		   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 8006: 		   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 8007: 		   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 8008: 		   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",	\
 8009: 			   mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
 8010: 			   mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
 8011: 		 }else{
 8012: 		   first=0;
 8013: 		   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
 8014: 		   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 8015: 		   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 8016: 		   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", \
 8017: 			   mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),	\
 8018: 			   mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
 8019: 		 }/* if first */
 8020: 	       } /* age mod 5 */
 8021: 	     } /* end loop age */
 8022: 	     fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 8023: 	     first=1;
 8024: 	   } /*l12 */
 8025: 	 } /* k12 */
 8026:        } /*l1 */
 8027:      }/* k1 */
 8028:    }  /* loop on combination of covariates j1 */
 8029:    } /* loop on nres */
 8030:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 8031:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
 8032:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 8033:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
 8034:    free_vector(xp,1,npar);
 8035:    fclose(ficresprob);
 8036:    fclose(ficresprobcov);
 8037:    fclose(ficresprobcor);
 8038:    fflush(ficgp);
 8039:    fflush(fichtmcov);
 8040:  }
 8041: 
 8042: 
 8043: /******************* Printing html file ***********/
 8044: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
 8045: 		  int lastpass, int stepm, int weightopt, char model[],\
 8046: 		  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 8047: 		  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
 8048: 		  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
 8049: 		  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
 8050:   int jj1, k1, i1, cpt, k4, nres;
 8051:   /* In fact some results are already printed in fichtm which is open */
 8052:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
 8053:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
 8054: </ul>");
 8055: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
 8056: /* </ul>", model); */
 8057:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
 8058:    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",
 8059: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
 8060:    fprintf(fichtm,"<li> - Observed prevalence (cross-sectional prevalence) in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> (html file) ",
 8061: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
 8062:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
 8063:    fprintf(fichtm,"\
 8064:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 8065: 	   stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
 8066:    fprintf(fichtm,"\
 8067:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 8068: 	   stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
 8069:    fprintf(fichtm,"\
 8070:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 8071: 	   subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
 8072:    fprintf(fichtm,"\
 8073:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 8074: 	   subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
 8075:    fprintf(fichtm,"\
 8076:  - (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): \
 8077:    <a href=\"%s\">%s</a> <br>\n",
 8078: 	   estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
 8079:    if(prevfcast==1){
 8080:      fprintf(fichtm,"\
 8081:  - Prevalence projections by age and states:				\
 8082:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
 8083:    }
 8084: 
 8085: 
 8086:    m=pow(2,cptcoveff);
 8087:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 8088: 
 8089:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
 8090: 
 8091:    jj1=0;
 8092: 
 8093:    fprintf(fichtm," \n<ul>");
 8094:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 8095:      /* k1=nres; */
 8096:      k1=TKresult[nres];
 8097:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
 8098:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
 8099:    /*   if(m != 1 && TKresult[nres]!= k1) */
 8100:    /*     continue; */
 8101:      jj1++;
 8102:      if (cptcovn > 0) {
 8103:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
 8104:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
 8105: 	 fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
 8106:        }
 8107:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
 8108:        /* 	 fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
 8109:        /* } */
 8110:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 8111:        /* 	 fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
 8112:        /* } */
 8113:        fprintf(fichtm,"\">");
 8114:        
 8115:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
 8116:        fprintf(fichtm,"************ Results for covariates");
 8117:        for (cpt=1; cpt<=cptcovs;cpt++){ 
 8118: 	 fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
 8119:        }
 8120:        /* fprintf(fichtm,"************ Results for covariates"); */
 8121:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
 8122:        /* 	 fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
 8123:        /* } */
 8124:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 8125:        /* 	 fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
 8126:        /* } */
 8127:        if(invalidvarcomb[k1]){
 8128: 	 fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
 8129: 	 continue;
 8130:        }
 8131:        fprintf(fichtm,"</a></li>");
 8132:      } /* cptcovn >0 */
 8133:    }
 8134:    fprintf(fichtm," \n</ul>");
 8135: 
 8136:    jj1=0;
 8137: 
 8138:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 8139:      /* k1=nres; */
 8140:      k1=TKresult[nres];
 8141:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
 8142:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
 8143:    /*   if(m != 1 && TKresult[nres]!= k1) */
 8144:    /*     continue; */
 8145: 
 8146:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
 8147:      jj1++;
 8148:      if (cptcovn > 0) {
 8149:        fprintf(fichtm,"\n<p><a name=\"rescov");
 8150:        for (cpt=1; cpt<=cptcovs;cpt++){ 
 8151: 	 fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
 8152:        }
 8153:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 8154:        /* 	 fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
 8155:        /* } */
 8156:        fprintf(fichtm,"\"</a>");
 8157:  
 8158:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 8159:        for (cpt=1; cpt<=cptcovs;cpt++){ 
 8160: 	 fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
 8161: 	 printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
 8162: 	 /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
 8163: 	 /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
 8164:        }
 8165:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
 8166:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
 8167:        if(invalidvarcomb[k1]){
 8168: 	 fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
 8169: 	 printf("\nCombination (%d) ignored because no cases \n",k1); 
 8170: 	 continue;
 8171:        }
 8172:      }
 8173:      /* aij, bij */
 8174:      fprintf(fichtm,"<br>- Logit model (yours is: logit(pij)=log(pij/pii)= aij+ bij age+%s) as a function of age: <a href=\"%s_%d-1-%d.svg\">%s_%d-1-%d.svg</a><br> \
 8175: <img src=\"%s_%d-1-%d.svg\">",model,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres);
 8176:      /* Pij */
 8177:      fprintf(fichtm,"<br>\n- P<sub>ij</sub> or conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s_%d-2-%d.svg\">%s_%d-2-%d.svg</a><br> \
 8178: <img src=\"%s_%d-2-%d.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres);     
 8179:      /* Quasi-incidences */
 8180:      fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
 8181:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
 8182:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
 8183: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3-%d.svg\">%s_%d-3-%d.svg</a><br> \
 8184: <img src=\"%s_%d-3-%d.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres); 
 8185:      /* Survival functions (period) in state j */
 8186:      for(cpt=1; cpt<=nlstate;cpt++){
 8187:        fprintf(fichtm,"<br>\n- Survival functions in state %d. And probability to be observed in state %d being in state (1 to %d) at different ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br>", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
 8188:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
 8189:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
 8190:      }
 8191:      /* State specific survival functions (period) */
 8192:      for(cpt=1; cpt<=nlstate;cpt++){
 8193:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
 8194:  And probability to be observed in various states (up to %d) being in state %d at different ages.	\
 8195:  <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br> ", cpt, nlstate, cpt, subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
 8196:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
 8197:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
 8198:      }
 8199:      /* Period (forward stable) prevalence in each health state */
 8200:      for(cpt=1; cpt<=nlstate;cpt++){
 8201:        fprintf(fichtm,"<br>\n- Convergence to period (stable) prevalence in state %d. Or probability for a person being in state (1 to %d) at different ages, to be in state %d some years after. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br>", cpt, nlstate, cpt, subdirf2(optionfilefiname,"P_"),cpt,k1,nres,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
 8202:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
 8203:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
 8204:      }
 8205:      if(prevbcast==1){
 8206:        /* Backward prevalence in each health state */
 8207:        for(cpt=1; cpt<=nlstate;cpt++){
 8208: 	 fprintf(fichtm,"<br>\n- Convergence to mixed (stable) back prevalence in state %d. Or probability for a person to be in state %d at a younger age, knowing that she/he was in state (1 to %d) at different older ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br>", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,k1,nres,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
 8209: 	 fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
 8210: 	 fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
 8211:        }
 8212:      }
 8213:      if(prevfcast==1){
 8214:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
 8215:        for(cpt=1; cpt<=nlstate;cpt++){
 8216: 	 fprintf(fichtm,"<br>\n- Projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), from year %.1f up to year %.1f tending to period (stable) forward prevalence in state %d. Or probability to be in state %d being in an observed weighted state (from 1 to %d). <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a>", dateprev1, dateprev2, mobilavproj, dateprojd, dateprojf, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
 8217: 	 fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
 8218: 	 fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
 8219: 		 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
 8220:        }
 8221:      }
 8222:      if(prevbcast==1){
 8223:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
 8224:        for(cpt=1; cpt<=nlstate;cpt++){
 8225: 	 fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
 8226:  from year %.1f up to year %.1f (probably close to stable [mixed] back prevalence in state %d (randomness in cross-sectional prevalence is not taken into \
 8227:  account but can visually be appreciated). Or probability to have been in an state %d, knowing that the person was in either state (1 or %d) \
 8228: with weights corresponding to observed prevalence at different ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a>", dateprev1, dateprev2, mobilavproj, dateback1, dateback2, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
 8229: 	 fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
 8230: 	 fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
 8231:        }
 8232:      }
 8233: 	 
 8234:      for(cpt=1; cpt<=nlstate;cpt++) {
 8235:        fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies in each alive state (1 to %d) (or area under each survival functions): <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a>",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
 8236:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
 8237:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
 8238:      }
 8239:      /* } /\* end i1 *\/ */
 8240:    }/* End k1=nres */
 8241:    fprintf(fichtm,"</ul>");
 8242: 
 8243:    fprintf(fichtm,"\
 8244: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
 8245:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
 8246:  - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
 8247: But because parameters are usually highly correlated (a higher incidence of disability \
 8248: and a higher incidence of recovery can give very close observed transition) it might \
 8249: be very useful to look not only at linear confidence intervals estimated from the \
 8250: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
 8251: (parameters) of the logistic regression, it might be more meaningful to visualize the \
 8252: covariance matrix of the one-step probabilities. \
 8253: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
 8254: 
 8255:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 8256: 	   subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
 8257:    fprintf(fichtm,"\
 8258:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 8259: 	   subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
 8260: 
 8261:    fprintf(fichtm,"\
 8262:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 8263: 	   subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
 8264:    fprintf(fichtm,"\
 8265:  - 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): \
 8266:    <a href=\"%s\">%s</a> <br>\n</li>",
 8267: 	   estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
 8268:    fprintf(fichtm,"\
 8269:  - (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): \
 8270:    <a href=\"%s\">%s</a> <br>\n</li>",
 8271: 	   estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
 8272:    fprintf(fichtm,"\
 8273:  - Variances and covariances of health expectancies by age. Status (i) based health expectancies (in state j), e<sup>ij</sup> are weighted by the forward (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",
 8274: 	   estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
 8275:    fprintf(fichtm,"\
 8276:  - 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",
 8277: 	   estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
 8278:    fprintf(fichtm,"\
 8279:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
 8280: 	   subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
 8281: 
 8282: /*  if(popforecast==1) fprintf(fichtm,"\n */
 8283: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
 8284: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
 8285: /* 	<br>",fileres,fileres,fileres,fileres); */
 8286: /*  else  */
 8287: /*    fprintf(fichtm,"\n No population forecast: popforecast = %d (instead of 1) or stepm = %d (instead of 1) or model=1+age+%s (instead of .)<br><br></li>\n",popforecast, stepm, model); */
 8288:    fflush(fichtm);
 8289: 
 8290:    m=pow(2,cptcoveff);
 8291:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 8292: 
 8293:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
 8294: 
 8295:   jj1=0;
 8296: 
 8297:    fprintf(fichtm," \n<ul>");
 8298:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 8299:      /* k1=nres; */
 8300:      k1=TKresult[nres];
 8301:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
 8302:      /* if(m != 1 && TKresult[nres]!= k1) */
 8303:      /*   continue; */
 8304:      jj1++;
 8305:      if (cptcovn > 0) {
 8306:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
 8307:        for (cpt=1; cpt<=cptcovs;cpt++){ 
 8308: 	 fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
 8309:        }
 8310:        fprintf(fichtm,"\">");
 8311:        
 8312:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
 8313:        fprintf(fichtm,"************ Results for covariates");
 8314:        for (cpt=1; cpt<=cptcovs;cpt++){ 
 8315: 	 fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
 8316:        }
 8317:        if(invalidvarcomb[k1]){
 8318: 	 fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
 8319: 	 continue;
 8320:        }
 8321:        fprintf(fichtm,"</a></li>");
 8322:      } /* cptcovn >0 */
 8323:    } /* End nres */
 8324:    fprintf(fichtm," \n</ul>");
 8325: 
 8326:    jj1=0;
 8327: 
 8328:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 8329:      /* k1=nres; */
 8330:      k1=TKresult[nres];
 8331:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
 8332:      /* for(k1=1; k1<=m;k1++){ */
 8333:      /* if(m != 1 && TKresult[nres]!= k1) */
 8334:      /*   continue; */
 8335:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
 8336:      jj1++;
 8337:      if (cptcovn > 0) {
 8338:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
 8339:        for (cpt=1; cpt<=cptcovs;cpt++){ 
 8340: 	 fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
 8341:        }
 8342:        fprintf(fichtm,"\"</a>");
 8343:        
 8344:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 8345:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
 8346: 	 fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
 8347: 	 printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
 8348: 	 /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
 8349:        }
 8350: 
 8351:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
 8352: 
 8353:        if(invalidvarcomb[k1]){
 8354: 	 fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
 8355: 	 continue;
 8356:        }
 8357:      } /* If cptcovn >0 */
 8358:      for(cpt=1; cpt<=nlstate;cpt++) {
 8359:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
 8360: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d-%d.svg\"> %s_%d-%d-%d.svg</a>",mobilav,cpt,subdirf2(optionfilefiname,"V_"),cpt,k1,nres,subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
 8361:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
 8362:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
 8363:      }
 8364:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
 8365: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
 8366: true period expectancies (those weighted with period prevalences are also\
 8367:  drawn in addition to the population based expectancies computed using\
 8368:  observed and cahotic prevalences:  <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a>",nlstate, subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres);
 8369:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
 8370:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
 8371:      /* } /\* end i1 *\/ */
 8372:   }/* End nres */
 8373:    fprintf(fichtm,"</ul>");
 8374:    fflush(fichtm);
 8375: }
 8376: 
 8377: /******************* Gnuplot file **************/
 8378: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double bage, double fage , int prevfcast, int prevbcast, char pathc[], double p[], int offyear, int offbyear){
 8379: 
 8380:   char dirfileres[256],optfileres[256];
 8381:   char gplotcondition[256], gplotlabel[256];
 8382:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,k4=0,kf=0,kvar=0,kk=0,ipos=0,iposold=0,ij=0, ijp=0, l=0;
 8383:   int lv=0, vlv=0, kl=0;
 8384:   int ng=0;
 8385:   int vpopbased;
 8386:   int ioffset; /* variable offset for columns */
 8387:   int iyearc=1; /* variable column for year of projection  */
 8388:   int iagec=1; /* variable column for age of projection  */
 8389:   int nres=0; /* Index of resultline */
 8390:   int istart=1; /* For starting graphs in projections */
 8391: 
 8392: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
 8393: /*     printf("Problem with file %s",optionfilegnuplot); */
 8394: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
 8395: /*   } */
 8396: 
 8397:   /*#ifdef windows */
 8398:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 8399:   /*#endif */
 8400:   m=pow(2,cptcoveff);
 8401: 
 8402:   /* diagram of the model */
 8403:   fprintf(ficgp,"\n#Diagram of the model \n");
 8404:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
 8405:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
 8406:   fprintf(ficgp,"\n#Peripheral arrows\nset for [i=1:%d] for [j=1:%d] arrow i*10+j from cos(pi*((1-(%d/2)*2./%d)/2+(i-1)*2./%d))-(i!=j?(i-j)/abs(i-j)*delta:0), yoff +sin(pi*((1-(%d/2)*2./%d)/2+(i-1)*2./%d)) + (i!=j?(i-j)/abs(i-j)*delta:0) rto -0.95*(cos(pi*((1-(%d/2)*2./%d)/2+(i-1)*2./%d))+(i!=j?(i-j)/abs(i-j)*delta:0) - cos(pi*((1-(%d/2)*2./%d)/2+(j-1)*2./%d)) + (i!=j?(i-j)/abs(i-j)*delta2:0)), -0.95*(sin(pi*((1-(%d/2)*2./%d)/2+(i-1)*2./%d)) + (i!=j?(i-j)/abs(i-j)*delta:0) - sin(pi*((1-(%d/2)*2./%d)/2+(j-1)*2./%d))+( i!=j?(i-j)/abs(i-j)*delta2:0)) ls (i < j? 1:2)\n",nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate);
 8407: 
 8408:   fprintf(ficgp,"\n#Centripete arrows (turning in other direction (1-i) instead of (i-1)) \nset for [i=1:%d] for [j=1:%d] arrow (%d+1)*10+i from cos(pi*((1-(%d/2)*2./%d)/2+(1-i)*2./%d))-(i!=j?(i-j)/abs(i-j)*delta:0), yoff +sin(pi*((1-(%d/2)*2./%d)/2+(1-i)*2./%d)) + (i!=j?(i-j)/abs(i-j)*delta:0) rto -0.80*(cos(pi*((1-(%d/2)*2./%d)/2+(1-i)*2./%d))+(i!=j?(i-j)/abs(i-j)*delta:0)  ), -0.80*(sin(pi*((1-(%d/2)*2./%d)/2+(1-i)*2./%d)) + (i!=j?(i-j)/abs(i-j)*delta:0) + yoff ) ls 4\n",nlstate, nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate);
 8409:   fprintf(ficgp,"\n#show arrow\nunset label\n");
 8410:   fprintf(ficgp,"\n#States labels, starting from 2 (2-i) instead of (1-i), was (i-1)\nset for [i=1:%d] label i sprintf(\"State %%d\",i) center at cos(pi*((1-(%d/2)*2./%d)/2+(2-i)*2./%d)), yoff+sin(pi*((1-(%d/2)*2./%d)/2+(2-i)*2./%d)) font \"helvetica, 16\" tc rgbcolor \"blue\"\n",nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate);
 8411:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
 8412:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
 8413:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
 8414:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
 8415: 
 8416:   /* Contribution to likelihood */
 8417:   /* Plot the probability implied in the likelihood */
 8418:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
 8419:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
 8420:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
 8421:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
 8422: /* nice for mle=4 plot by number of matrix products.
 8423:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
 8424: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
 8425:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
 8426:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
 8427:   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));
 8428:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
 8429:   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));
 8430:   for (i=1; i<= nlstate ; i ++) {
 8431:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
 8432:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
 8433:     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);
 8434:     for (j=2; j<= nlstate+ndeath ; j ++) {
 8435:       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);
 8436:     }
 8437:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
 8438:   }
 8439:   /* 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 */		 
 8440:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
 8441:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
 8442:   fprintf(ficgp,"\nset out;unset log\n");
 8443:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
 8444: 
 8445:   /* Plot the probability implied in the likelihood by covariate value */
 8446:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
 8447:   /* if(debugILK==1){ */
 8448:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
 8449:     kvar=Tvar[TvarFind[kf]]; /* variable name */
 8450:     /* k=18+Tvar[TvarFind[kf]];/\*offset because there are 18 columns in the ILK_ file but could be placed else where *\/ */
 8451:     /* k=18+kf;/\*offset because there are 18 columns in the ILK_ file *\/ */
 8452:     /* k=19+nlstate+kf;/\*offset because there are 19 columns in the ILK_ file *\/ */
 8453:     k=16+nlstate+kf;/*offset because there are 19 columns in the ILK_ file, first cov Vn on col 21 with 4 living states */
 8454:     for (i=1; i<= nlstate ; i ++) {
 8455:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
 8456:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
 8457:       if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
 8458: 	fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? 7 : 9):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt variable ps 0.4 lc variable \\\n",i,1,k,k,i,1,kvar);
 8459: 	for (j=2; j<= nlstate+ndeath ; j ++) {
 8460: 	  fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? 7 : 9):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt variable ps 0.4 lc variable ",i,j,k,k,i,j,kvar);
 8461: 	}
 8462:       }else{
 8463: 	fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt 7 ps 0.4 lc variable \\\n",i,1,k,i,1,kvar);
 8464: 	for (j=2; j<= nlstate+ndeath ; j ++) {
 8465: 	  fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt 7 ps 0.4 lc variable ",i,j,k,i,j,kvar);
 8466: 	}
 8467:       }
 8468:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
 8469:     }
 8470:   } /* End of each covariate dummy */
 8471:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
 8472:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
 8473:      *     kmodel       =     1   2     3     4         5        6        7       8        9
 8474:      *  varying                   1     2                                 3       4        5
 8475:      *  ncovv                     1     2                                3 4     5 6      7 8
 8476:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
 8477:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
 8478:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
 8479:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
 8480:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
 8481:      */
 8482:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
 8483:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
 8484:     /* printf("DebugILK ficgp ncovv=%d, kvar=TvarVV[ncovv]=%d, ipos=TvarVVind[ncovv]=%d, Dummy[ipos]=%d, Typevar[ipos]=%d\n", ncovv,kvar,ipos,Dummy[ipos],Typevar[ipos]); */
 8485:     if(ipos!=iposold){ /* Not a product or first of a product */
 8486:       /* printf(" %d",ipos); */
 8487:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
 8488:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
 8489:       kk++; /* Position of the ncovv column in ILK_ */
 8490:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
 8491:       if(Dummy[ipos]==0 && Typevar[ipos]==0){ /* Only if dummy time varying: Dummy(0, 1=quant singor prod without age,2 dummy*age, 3quant*age) Typevar (0 single, 1=*age,2=Vn*vm)  */
 8492: 	for (i=1; i<= nlstate ; i ++) {
 8493: 	  fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
 8494: 	  fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
 8495: 
 8496: 	    /* printf("Before DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
 8497: 	  if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
 8498: 	    /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
 8499: 	    fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? 7 : 9):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt variable ps 0.4 lc variable \\\n",i,1,k,k,i,1,kvar);
 8500: 	    for (j=2; j<= nlstate+ndeath ; j ++) {
 8501: 	      fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? 7 : 9):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt variable ps 0.4 lc variable ",i,j,k,k,i,j,kvar);
 8502: 	    }
 8503: 	  }else{
 8504: 	    /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
 8505: 	    fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt 7 ps 0.4 lc variable \\\n",i,1,k,i,1,kvar);
 8506: 	    for (j=2; j<= nlstate+ndeath ; j ++) {
 8507: 	      fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt 7 ps 0.4 lc variable ",i,j,k,i,j,kvar);
 8508: 	    }
 8509: 	  }
 8510: 	  fprintf(ficgp,";\nset out; unset ylabel;\n"); 
 8511: 	}
 8512:       }/* End if dummy varying */
 8513:     }else{ /*Product */
 8514:       /* printf("*"); */
 8515:       /* fprintf(ficresilk,"*"); */
 8516:     }
 8517:     iposold=ipos;
 8518:   } /* For each time varying covariate */
 8519:   /* } /\* debugILK==1 *\/ */
 8520:   /* 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 */		 
 8521:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
 8522:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
 8523:   fprintf(ficgp,"\nset out;unset log\n");
 8524:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
 8525: 
 8526: 
 8527:   
 8528:   strcpy(dirfileres,optionfilefiname);
 8529:   strcpy(optfileres,"vpl");
 8530:   /* 1eme*/
 8531:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
 8532:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
 8533:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 8534: 	k1=TKresult[nres];
 8535: 	if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
 8536: 	/* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
 8537: 	/* if(m != 1 && TKresult[nres]!= k1) */
 8538: 	/*   continue; */
 8539: 	/* We are interested in selected combination by the resultline */
 8540: 	/* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
 8541: 	fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
 8542: 	strcpy(gplotlabel,"(");
 8543: 	for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 8544: 	  fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 8545: 	  sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 8546: 
 8547: 	/* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
 8548: 	/*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
 8549: 	/*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
 8550: 	/*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
 8551: 	/*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
 8552: 	/*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
 8553: 	/*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
 8554: 	/*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
 8555: 	/*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
 8556: 	/*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
 8557: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
 8558: 	/* } */
 8559: 	/* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 8560: 	/*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
 8561: 	/*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
 8562: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
 8563: 	}
 8564: 	strcpy(gplotlabel+strlen(gplotlabel),")");
 8565: 	/* printf("\n#\n"); */
 8566: 	fprintf(ficgp,"\n#\n");
 8567: 	if(invalidvarcomb[k1]){
 8568:           /*k1=k1-1;*/ /* To be checked */
 8569: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 8570: 	  continue;
 8571: 	}
 8572:       
 8573: 	fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
 8574: 	fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
 8575: 	/* fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel); */
 8576: 	fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
 8577: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nset ter svg size 640, 480\nplot [%.f:%.f] \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),nres-1,nres-1,nres);
 8578: 	/* fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nset ter svg size 640, 480\nplot [%.f:%.f] \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1,nres); */
 8579:       /* k1-1 error should be nres-1*/
 8580: 	for (i=1; i<= nlstate ; i ++) {
 8581: 	  if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 8582: 	  else        fprintf(ficgp," %%*lf (%%*lf)");
 8583: 	}
 8584: 	fprintf(ficgp,"\" t\"Forward prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2==%d ? $3+1.96*$4 : 1/0) \"%%lf %%lf",subdirf2(fileresu,"VPL_"),nres-1,nres-1,nres);
 8585: 	for (i=1; i<= nlstate ; i ++) {
 8586: 	  if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 8587: 	  else fprintf(ficgp," %%*lf (%%*lf)");
 8588: 	} 
 8589: 	fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2==%d ? $3-1.96*$4 : 1/0) \"%%lf %%lf",subdirf2(fileresu,"VPL_"),nres-1,nres-1,nres); 
 8590: 	for (i=1; i<= nlstate ; i ++) {
 8591: 	  if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 8592: 	  else fprintf(ficgp," %%*lf (%%*lf)");
 8593: 	}  
 8594: 	/* 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)); */
 8595: 	
 8596: 	fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
 8597:         if(cptcoveff ==0){
 8598: 	  fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",	 2+3*(cpt-1),  cpt );
 8599: 	}else{
 8600: 	  kl=0;
 8601: 	  for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
 8602: 	    /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
 8603: 	    lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
 8604: 	    /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 8605: 	    /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 8606: 	    /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 8607: 	    vlv= nbcode[Tvaraff[k]][lv];
 8608: 	    kl++;
 8609: 	    /* 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 *\/ */
 8610: 	    /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
 8611: 	    /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
 8612: 	    /* ''  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*/
 8613: 	    if(k==cptcoveff){
 8614: 	      fprintf(ficgp,"$%d==%d && $%d==%d)? $%d : 1/0) t 'Observed prevalence in state %d' w l lt 2",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv], \
 8615: 		      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
 8616: 	    }else{
 8617: 	      fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
 8618: 	      kl++;
 8619: 	    }
 8620: 	  } /* end covariate */
 8621: 	} /* end if no covariate */
 8622: 
 8623: 	if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
 8624: 	  /* 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); */
 8625: 	  fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
 8626: 	  if(cptcoveff ==0){
 8627: 	    fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",	 2+(cpt-1),  cpt );
 8628: 	  }else{
 8629: 	    kl=0;
 8630: 	    for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
 8631: 	      /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
 8632: 	      lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
 8633: 	      /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 8634: 	      /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 8635: 	      /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 8636: 	      /* vlv= nbcode[Tvaraff[k]][lv]; */
 8637: 	      vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
 8638: 	      kl++;
 8639: 	      /* 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 *\/ */
 8640: 	      /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
 8641: 	      /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
 8642: 	      /* ''  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*/
 8643: 	      if(k==cptcoveff){
 8644: 		fprintf(ficgp,"$%d==%d && $%d==%d)? $%d : 1/0) t 'Backward prevalence in state %d' w l lt 3",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv], \
 8645: 			2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
 8646: 	      }else{
 8647: 		fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
 8648: 		kl++;
 8649: 	      }
 8650: 	    } /* end covariate */
 8651: 	  } /* end if no covariate */
 8652: 	  if(prevbcast == 1){
 8653: 	    fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
 8654: 	    /* k1-1 error should be nres-1*/
 8655: 	    for (i=1; i<= nlstate ; i ++) {
 8656: 	      if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 8657: 	      else        fprintf(ficgp," %%*lf (%%*lf)");
 8658: 	    }
 8659: 	    fprintf(ficgp,"\" t\"Backward (stable) prevalence\" w l lt 6 dt 3,\"%s\" every :::%d::%d u 1:($2==%d ? $3+1.96*$4 : 1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
 8660: 	    for (i=1; i<= nlstate ; i ++) {
 8661: 	      if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 8662: 	      else fprintf(ficgp," %%*lf (%%*lf)");
 8663: 	    } 
 8664: 	    fprintf(ficgp,"\" t\"95%% CI\" w l lt 4,\"%s\" every :::%d::%d u 1:($2==%d ? $3-1.96*$4 : 1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres); 
 8665: 	    for (i=1; i<= nlstate ; i ++) {
 8666: 	      if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 8667: 	      else fprintf(ficgp," %%*lf (%%*lf)");
 8668: 	    } 
 8669: 	    fprintf(ficgp,"\" t\"\" w l lt 4");
 8670: 	  } /* end if backprojcast */
 8671: 	} /* end if prevbcast */
 8672: 	/* fprintf(ficgp,"\nset out ;unset label;\n"); */
 8673: 	fprintf(ficgp,"\nset out ;unset title;\n");
 8674:       } /* nres */
 8675:     /* } /\* k1 *\/ */
 8676:   } /* cpt */
 8677: 
 8678:   
 8679:   /*2 eme*/
 8680:   /* for (k1=1; k1<= m ; k1 ++){   */
 8681:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 8682:       k1=TKresult[nres];
 8683:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
 8684:       /* if(m != 1 && TKresult[nres]!= k1) */
 8685:       /* 	continue; */
 8686:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
 8687:       strcpy(gplotlabel,"(");
 8688:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 8689: 	fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 8690: 	sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 8691:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
 8692:       /* 	/\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
 8693:       /* 	lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
 8694:       /* 	/\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
 8695:       /* 	/\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
 8696:       /* 	/\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
 8697:       /* 	/\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
 8698:       /* 	vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
 8699:       /* 	fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
 8700:       /* 	sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
 8701:       /* } */
 8702:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
 8703:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 8704:       /* 	printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
 8705:       /* 	fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
 8706:       /* 	sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
 8707:       }
 8708:       strcpy(gplotlabel+strlen(gplotlabel),")");
 8709:       fprintf(ficgp,"\n#\n");
 8710:       if(invalidvarcomb[k1]){
 8711: 	fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 8712: 	continue;
 8713:       }
 8714: 			
 8715:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
 8716:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 8717: 	fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
 8718: 	if(vpopbased==0){
 8719: 	  fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
 8720: 	}else
 8721: 	  fprintf(ficgp,"\nreplot ");
 8722: 	for (i=1; i<= nlstate+1 ; i ++) {
 8723: 	  k=2*i;
 8724: 	  fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ?$4 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),nres-1,nres-1, vpopbased);
 8725: 	  for (j=1; j<= nlstate+1 ; j ++) {
 8726: 	    if (j==i) fprintf(ficgp," %%lf (%%lf)");
 8727: 	    else fprintf(ficgp," %%*lf (%%*lf)");
 8728: 	  }   
 8729: 	  if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
 8730: 	  else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
 8731: 	  fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ? $4-$5*2 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),nres-1,nres-1,vpopbased);
 8732: 	  for (j=1; j<= nlstate+1 ; j ++) {
 8733: 	    if (j==i) fprintf(ficgp," %%lf (%%lf)");
 8734: 	    else fprintf(ficgp," %%*lf (%%*lf)");
 8735: 	  }   
 8736: 	  fprintf(ficgp,"\" t\"\" w l lt 0,");
 8737: 	  fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ? $4+$5*2 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),nres-1,nres-1,vpopbased);
 8738: 	  for (j=1; j<= nlstate+1 ; j ++) {
 8739: 	    if (j==i) fprintf(ficgp," %%lf (%%lf)");
 8740: 	    else fprintf(ficgp," %%*lf (%%*lf)");
 8741: 	  }   
 8742: 	  if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
 8743: 	  else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
 8744: 	} /* state */
 8745:       } /* vpopbased */
 8746:       fprintf(ficgp,"\nset out;set out \"%s_%d-%d.svg\"; replot; set out; unset label;\n",subdirf2(optionfilefiname,"E_"),k1,nres); /* Buggy gnuplot */
 8747:     } /* end nres */
 8748:   /* } /\* k1 end 2 eme*\/ */
 8749: 	
 8750: 	
 8751:   /*3eme*/
 8752:   /* for (k1=1; k1<= m ; k1 ++){ */
 8753:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 8754:       k1=TKresult[nres];
 8755:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
 8756:       /* if(m != 1 && TKresult[nres]!= k1) */
 8757:       /* 	continue; */
 8758: 
 8759:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
 8760: 	fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
 8761: 	strcpy(gplotlabel,"(");
 8762: 	for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 8763: 	  fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 8764: 	  sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 8765: 	/* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
 8766: 	/*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
 8767: 	/*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
 8768: 	/*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
 8769: 	/*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
 8770: 	/*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
 8771: 	/*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
 8772: 	/*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
 8773: 	/*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
 8774: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
 8775: 	/* } */
 8776: 	/* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 8777: 	/*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
 8778: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
 8779: 	}
 8780: 	strcpy(gplotlabel+strlen(gplotlabel),")");
 8781: 	fprintf(ficgp,"\n#\n");
 8782: 	if(invalidvarcomb[k1]){
 8783: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 8784: 	  continue;
 8785: 	}
 8786: 			
 8787: 	/*       k=2+nlstate*(2*cpt-2); */
 8788: 	k=2+(nlstate+1)*(cpt-1);
 8789: 	fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
 8790: 	fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
 8791: 	fprintf(ficgp,"set ter svg size 640, 480\n\
 8792: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileresu,"E_"),nres-1,nres-1,k,cpt);
 8793: 	/*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 8794: 	  for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 8795: 	  fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 8796: 	  fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 8797: 	  for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 8798: 	  fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 8799: 				
 8800: 	*/
 8801: 	for (i=1; i< nlstate ; i ++) {
 8802: 	  fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileresu,"E_"),nres-1,nres-1,k+i,cpt,i+1);
 8803: 	  /*	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);*/
 8804: 				
 8805: 	} 
 8806: 	fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),nres-1,nres-1,k+nlstate,cpt);
 8807:       }
 8808:       fprintf(ficgp,"\nunset label;\n");
 8809:     } /* end nres */
 8810:   /* } /\* end kl 3eme *\/ */
 8811:   
 8812:   /* 4eme */
 8813:   /* Survival functions (period) from state i in state j by initial state i */
 8814:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
 8815:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 8816:       k1=TKresult[nres];
 8817:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
 8818:       /* if(m != 1 && TKresult[nres]!= k1) */
 8819:       /* 	continue; */
 8820:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
 8821: 	strcpy(gplotlabel,"(");
 8822: 	fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
 8823: 	for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 8824: 	  fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 8825: 	  sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 8826: 	/* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
 8827: 	/*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
 8828: 	/*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
 8829: 	/*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
 8830: 	/*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
 8831: 	/*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
 8832: 	/*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
 8833: 	/*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
 8834: 	/*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
 8835: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
 8836: 	/* } */
 8837: 	/* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 8838: 	/*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 8839: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 8840: 	}	
 8841: 	strcpy(gplotlabel+strlen(gplotlabel),")");
 8842: 	fprintf(ficgp,"\n#\n");
 8843: 	if(invalidvarcomb[k1]){
 8844: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 8845: 	  continue;
 8846: 	}
 8847:       
 8848: 	fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
 8849: 	fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
 8850: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
 8851: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
 8852: 	k=3;
 8853: 	for (i=1; i<= nlstate ; i ++){
 8854: 	  if(i==1){
 8855: 	    fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 8856: 	  }else{
 8857: 	    fprintf(ficgp,", '' ");
 8858: 	  }
 8859: 	  l=(nlstate+ndeath)*(i-1)+1;
 8860: 	  fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 8861: 	  for (j=2; j<= nlstate+ndeath ; j ++)
 8862: 	    fprintf(ficgp,"+$%d",k+l+j-1);
 8863: 	  fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
 8864: 	} /* nlstate */
 8865: 	fprintf(ficgp,"\nset out; unset label;\n");
 8866:       } /* end cpt state*/ 
 8867:     } /* end nres */
 8868:   /* } /\* end covariate k1 *\/   */
 8869: 
 8870: /* 5eme */
 8871:   /* Survival functions (period) from state i in state j by final state j */
 8872:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
 8873:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 8874:       k1=TKresult[nres];
 8875:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
 8876:       /* if(m != 1 && TKresult[nres]!= k1) */
 8877:       /* 	continue; */
 8878:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
 8879: 	strcpy(gplotlabel,"(");
 8880: 	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);
 8881: 	for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 8882: 	  fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 8883: 	  sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 8884: 	/* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
 8885: 	/*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
 8886: 	/*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
 8887: 	/*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
 8888: 	/*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
 8889: 	/*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
 8890: 	/*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
 8891: 	/*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
 8892: 	/*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
 8893: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
 8894: 	/* } */
 8895: 	/* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 8896: 	/*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 8897: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 8898: 	}	
 8899: 	strcpy(gplotlabel+strlen(gplotlabel),")");
 8900: 	fprintf(ficgp,"\n#\n");
 8901: 	if(invalidvarcomb[k1]){
 8902: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 8903: 	  continue;
 8904: 	}
 8905:       
 8906: 	fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
 8907: 	fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
 8908: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
 8909: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
 8910: 	k=3;
 8911: 	for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
 8912: 	  if(j==1)
 8913: 	    fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 8914: 	  else
 8915: 	    fprintf(ficgp,", '' ");
 8916: 	  l=(nlstate+ndeath)*(cpt-1) +j;
 8917: 	  fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
 8918: 	  /* for (i=2; i<= nlstate+ndeath ; i ++) */
 8919: 	  /*   fprintf(ficgp,"+$%d",k+l+i-1); */
 8920: 	  fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
 8921: 	} /* nlstate */
 8922: 	fprintf(ficgp,", '' ");
 8923: 	fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
 8924: 	for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
 8925: 	  l=(nlstate+ndeath)*(cpt-1) +j;
 8926: 	  if(j < nlstate)
 8927: 	    fprintf(ficgp,"$%d +",k+l);
 8928: 	  else
 8929: 	    fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
 8930: 	}
 8931: 	fprintf(ficgp,"\nset out; unset label;\n");
 8932:       } /* end cpt state*/ 
 8933:     /* } /\* end covariate *\/   */
 8934:   } /* end nres */
 8935:   
 8936: /* 6eme */
 8937:   /* CV preval stable (period) for each covariate */
 8938:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
 8939:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 8940:      k1=TKresult[nres];
 8941:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
 8942:      /* if(m != 1 && TKresult[nres]!= k1) */
 8943:      /*  continue; */
 8944:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
 8945:       strcpy(gplotlabel,"(");      
 8946:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
 8947:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 8948: 	fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 8949: 	sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 8950:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
 8951:       /* 	/\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
 8952:       /* 	lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
 8953:       /* 	/\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
 8954:       /* 	/\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
 8955:       /* 	/\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
 8956:       /* 	/\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
 8957:       /* 	vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
 8958:       /* 	fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
 8959:       /* 	sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
 8960:       /* } */
 8961:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 8962:       /* 	fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 8963:       /* 	sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 8964:       }	
 8965:       strcpy(gplotlabel+strlen(gplotlabel),")");
 8966:       fprintf(ficgp,"\n#\n");
 8967:       if(invalidvarcomb[k1]){
 8968: 	fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 8969: 	continue;
 8970:       }
 8971:       
 8972:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
 8973:       fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
 8974:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 8975: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
 8976:       k=3; /* Offset */
 8977:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
 8978: 	if(i==1)
 8979: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 8980: 	else
 8981: 	  fprintf(ficgp,", '' ");
 8982: 	l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
 8983: 	fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 8984: 	for (j=2; j<= nlstate ; j ++)
 8985: 	  fprintf(ficgp,"+$%d",k+l+j-1);
 8986: 	fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
 8987:       } /* nlstate */
 8988:       fprintf(ficgp,"\nset out; unset label;\n");
 8989:     } /* end cpt state*/ 
 8990:   } /* end covariate */  
 8991:   
 8992:   
 8993: /* 7eme */
 8994:   if(prevbcast == 1){
 8995:     /* CV backward prevalence  for each covariate */
 8996:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
 8997:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 8998:       k1=TKresult[nres];
 8999:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
 9000:       /* if(m != 1 && TKresult[nres]!= k1) */
 9001:       /* 	continue; */
 9002:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
 9003: 	strcpy(gplotlabel,"(");      
 9004:  	fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
 9005: 	for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 9006: 	  fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 9007: 	  sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 9008: 	/* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
 9009: 	/*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
 9010: 	/*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
 9011: 	/*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
 9012: 	/*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
 9013: 	/*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
 9014: 	/*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
 9015: 	/*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
 9016: 	/*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
 9017: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
 9018: 	/* } */
 9019: 	/* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 9020: 	/*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 9021: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 9022: 	}	
 9023: 	strcpy(gplotlabel+strlen(gplotlabel),")");
 9024: 	fprintf(ficgp,"\n#\n");
 9025: 	if(invalidvarcomb[k1]){
 9026: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 9027: 	  continue;
 9028: 	}
 9029: 	
 9030: 	fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
 9031: 	fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
 9032: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 9033: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
 9034: 	k=3; /* Offset */
 9035: 	for (i=1; i<= nlstate ; i ++){ /* State of arrival */
 9036: 	  if(i==1)
 9037: 	    fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
 9038: 	  else
 9039: 	    fprintf(ficgp,", '' ");
 9040: 	  /* l=(nlstate+ndeath)*(i-1)+1; */
 9041: 	  l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
 9042: 	  /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
 9043: 	  /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
 9044: 	  fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
 9045: 	  /* for (j=2; j<= nlstate ; j ++) */
 9046: 	  /* 	fprintf(ficgp,"+$%d",k+l+j-1); */
 9047: 	  /* 	/\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
 9048: 	  fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
 9049: 	} /* nlstate */
 9050: 	fprintf(ficgp,"\nset out; unset label;\n");
 9051:       } /* end cpt state*/ 
 9052:     } /* end covariate */  
 9053:   } /* End if prevbcast */
 9054:   
 9055:   /* 8eme */
 9056:   if(prevfcast==1){
 9057:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
 9058:     
 9059:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
 9060:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 9061:       k1=TKresult[nres];
 9062:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
 9063:       /* if(m != 1 && TKresult[nres]!= k1) */
 9064:       /* 	continue; */
 9065:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 9066: 	strcpy(gplotlabel,"(");      
 9067: 	fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
 9068: 	for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 9069: 	  fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 9070: 	  sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 9071: 	/* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
 9072: 	/*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
 9073: 	/*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
 9074: 	/*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
 9075: 	/*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
 9076: 	/*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
 9077: 	/*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
 9078: 	/*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
 9079: 	/*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
 9080: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
 9081: 	/* } */
 9082: 	/* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 9083: 	/*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 9084: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 9085: 	}	
 9086: 	strcpy(gplotlabel+strlen(gplotlabel),")");
 9087: 	fprintf(ficgp,"\n#\n");
 9088: 	if(invalidvarcomb[k1]){
 9089: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 9090: 	  continue;
 9091: 	}
 9092: 	
 9093: 	fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
 9094: 	fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
 9095: 	fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
 9096: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
 9097: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
 9098: 
 9099: 	/* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
 9100: 	istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
 9101: 	/*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
 9102: 	for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
 9103: 	  /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 9104: 	  /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 9105: 	  /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 9106: 	  /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 9107: 	  if(i==istart){
 9108: 	    fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
 9109: 	  }else{
 9110: 	    fprintf(ficgp,",\\\n '' ");
 9111: 	  }
 9112: 	  if(cptcoveff ==0){ /* No covariate */
 9113: 	    ioffset=2; /* Age is in 2 */
 9114: 	    /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
 9115: 	    /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
 9116: 	    /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
 9117: 	    /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
 9118: 	    fprintf(ficgp," u %d:(", ioffset); 
 9119: 	    if(i==nlstate+1){
 9120: 	      fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",	\
 9121: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
 9122: 	      fprintf(ficgp,",\\\n '' ");
 9123: 	      fprintf(ficgp," u %d:(",ioffset); 
 9124: 	      fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
 9125: 		     offyear,				\
 9126: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
 9127: 	    }else
 9128: 	      fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",	\
 9129: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
 9130: 	  }else{ /* more than 2 covariates */
 9131: 	    ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
 9132: 	    /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 9133: 	    /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
 9134: 	    iyearc=ioffset-1;
 9135: 	    iagec=ioffset;
 9136: 	    fprintf(ficgp," u %d:(",ioffset); 
 9137: 	    kl=0;
 9138: 	    strcpy(gplotcondition,"(");
 9139: 	    /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
 9140: 	      /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
 9141: 	    for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 9142: 	      /* lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
 9143: 	      lv=Tvresult[nres][k];
 9144: 	      vlv=TinvDoQresult[nres][Tvresult[nres][k]];
 9145: 	      /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 9146: 	      /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 9147: 	      /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 9148: 	      /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
 9149: 	      /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
 9150: 	      kl++;
 9151: 	      /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
 9152: 	      sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,lv, kl+1, vlv );
 9153: 	      kl++;
 9154: 	      if(k <cptcovs && cptcovs>1)
 9155: 		sprintf(gplotcondition+strlen(gplotcondition)," && ");
 9156: 	    }
 9157: 	    strcpy(gplotcondition+strlen(gplotcondition),")");
 9158: 	    /* 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 *\/ */
 9159: 	    /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
 9160: 	    /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
 9161: 	    /* ''  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*/
 9162: 	    if(i==nlstate+1){
 9163: 	      fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
 9164: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
 9165: 	      fprintf(ficgp,",\\\n '' ");
 9166: 	      fprintf(ficgp," u %d:(",iagec); 
 9167: 	      fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
 9168: 		      iyearc, iagec, offyear,				\
 9169: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
 9170: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
 9171: 	    }else{
 9172: 	      fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
 9173: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
 9174: 	    }
 9175: 	  } /* end if covariate */
 9176: 	} /* nlstate */
 9177: 	fprintf(ficgp,"\nset out; unset label;\n");
 9178:       } /* end cpt state*/
 9179:     } /* end covariate */
 9180:   } /* End if prevfcast */
 9181:   
 9182:   if(prevbcast==1){
 9183:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
 9184:     
 9185:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
 9186:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 9187:      k1=TKresult[nres];
 9188:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
 9189:        /* if(m != 1 && TKresult[nres]!= k1) */
 9190:        /* 	continue; */
 9191:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 9192: 	strcpy(gplotlabel,"(");      
 9193: 	fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
 9194: 	for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 9195: 	  fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 9196: 	  sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 9197: 	/* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
 9198: 	/*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
 9199: 	/*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
 9200: 	/*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
 9201: 	/*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
 9202: 	/*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
 9203: 	/*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
 9204: 	/*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
 9205: 	/*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
 9206: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
 9207: 	/* } */
 9208: 	/* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 9209: 	/*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 9210: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 9211: 	}	
 9212: 	strcpy(gplotlabel+strlen(gplotlabel),")");
 9213: 	fprintf(ficgp,"\n#\n");
 9214: 	if(invalidvarcomb[k1]){
 9215: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 9216: 	  continue;
 9217: 	}
 9218: 	
 9219: 	fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
 9220: 	fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
 9221: 	fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
 9222: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
 9223: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
 9224: 
 9225: 	/* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
 9226: 	istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
 9227: 	/*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
 9228: 	for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
 9229: 	  /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 9230: 	  /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 9231: 	  /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 9232: 	  /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 9233: 	  if(i==istart){
 9234: 	    fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
 9235: 	  }else{
 9236: 	    fprintf(ficgp,",\\\n '' ");
 9237: 	  }
 9238: 	  /* if(cptcoveff ==0){ /\* No covariate *\/ */
 9239: 	  if(cptcovs ==0){ /* No covariate */
 9240: 	    ioffset=2; /* Age is in 2 */
 9241: 	    /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
 9242: 	    /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
 9243: 	    /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
 9244: 	    /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
 9245: 	    fprintf(ficgp," u %d:(", ioffset); 
 9246: 	    if(i==nlstate+1){
 9247: 	      fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ",	\
 9248: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
 9249: 	      fprintf(ficgp,",\\\n '' ");
 9250: 	      fprintf(ficgp," u %d:(",ioffset); 
 9251: 	      fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
 9252: 		     offbyear,				\
 9253: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
 9254: 	    }else
 9255: 	      fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",	\
 9256: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
 9257: 	  }else{ /* more than 2 covariates */
 9258: 	    ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
 9259: 	    /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 9260: 	    /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
 9261: 	    iyearc=ioffset-1;
 9262: 	    iagec=ioffset;
 9263: 	    fprintf(ficgp," u %d:(",ioffset); 
 9264: 	    kl=0;
 9265: 	    strcpy(gplotcondition,"(");
 9266: 	    for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
 9267: 	      if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
 9268: 		/* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
 9269: 		/* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
 9270: 		/* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
 9271: 		lv=Tvresult[nres][k];
 9272: 		vlv=TinvDoQresult[nres][Tvresult[nres][k]];
 9273: 		/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 9274: 		/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 9275: 		/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 9276: 		/* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
 9277: 		/* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
 9278: 		kl++;
 9279: 		/* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
 9280: 		sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
 9281: 		kl++;
 9282: 		if(k <cptcovs && cptcovs>1)
 9283: 		  sprintf(gplotcondition+strlen(gplotcondition)," && ");
 9284: 	      }
 9285: 	    }
 9286: 	    strcpy(gplotcondition+strlen(gplotcondition),")");
 9287: 	    /* 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 *\/ */
 9288: 	    /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
 9289: 	    /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
 9290: 	    /* ''  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*/
 9291: 	    if(i==nlstate+1){
 9292: 	      fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
 9293: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
 9294: 	      fprintf(ficgp,",\\\n '' ");
 9295: 	      fprintf(ficgp," u %d:(",iagec); 
 9296: 	      /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
 9297: 	      fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
 9298: 		      iyearc,iagec,offbyear,				\
 9299: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
 9300: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
 9301: 	    }else{
 9302: 	      /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
 9303: 	      fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
 9304: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
 9305: 	    }
 9306: 	  } /* end if covariate */
 9307: 	} /* nlstate */
 9308: 	fprintf(ficgp,"\nset out; unset label;\n");
 9309:       } /* end cpt state*/
 9310:     } /* end covariate */
 9311:   } /* End if prevbcast */
 9312:   
 9313:   
 9314:   /* 9eme writing MLE parameters */
 9315:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
 9316:   for(i=1,jk=1; i <=nlstate; i++){
 9317:     fprintf(ficgp,"# initial state %d\n",i);
 9318:     for(k=1; k <=(nlstate+ndeath); k++){
 9319:       if (k != i) {
 9320: 	fprintf(ficgp,"#   current state %d\n",k);
 9321: 	for(j=1; j <=ncovmodel; j++){
 9322: 	  fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
 9323: 	  jk++; 
 9324: 	}
 9325: 	fprintf(ficgp,"\n");
 9326:       }
 9327:     }
 9328:   }
 9329:   fprintf(ficgp,"##############\n#\n");
 9330:   
 9331:   /*goto avoid;*/
 9332:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
 9333:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
 9334:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
 9335:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
 9336:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
 9337:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
 9338:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 9339:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 9340:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 9341:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 9342:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
 9343:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 9344:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
 9345:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
 9346:   fprintf(ficgp,"#\n");
 9347:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
 9348:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
 9349:     fprintf(ficgp,"#model=1+age+%s \n",model);
 9350:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
 9351:     /* fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/\* to be checked *\/ */
 9352:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcovs,m);/* to be checked */
 9353:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
 9354:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 9355:      /* k1=nres; */
 9356:       k1=TKresult[nres];
 9357:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
 9358:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
 9359:       strcpy(gplotlabel,"(");
 9360:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
 9361:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
 9362: 	/* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
 9363: 	   TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
 9364: 	fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 9365: 	sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 9366:       }
 9367:       /* if(m != 1 && TKresult[nres]!= k1) */
 9368:       /* 	continue; */
 9369:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
 9370:       /* strcpy(gplotlabel,"("); */
 9371:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
 9372:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
 9373:       /* 	/\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
 9374:       /* 	lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
 9375:       /* 	/\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
 9376:       /* 	/\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
 9377:       /* 	/\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
 9378:       /* 	/\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
 9379:       /* 	vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
 9380:       /* 	fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
 9381:       /* 	sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
 9382:       /* } */
 9383:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 9384:       /* 	fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 9385:       /* 	sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 9386:       /* }	 */
 9387:       strcpy(gplotlabel+strlen(gplotlabel),")");
 9388:       fprintf(ficgp,"\n#\n");
 9389:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
 9390:       fprintf(ficgp,"\nset key outside ");
 9391:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
 9392:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
 9393:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
 9394:       if (ng==1){
 9395: 	fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
 9396: 	fprintf(ficgp,"\nunset log y");
 9397:       }else if (ng==2){
 9398: 	fprintf(ficgp,"\nset ylabel \"Probability\"\n");
 9399: 	fprintf(ficgp,"\nset log y");
 9400:       }else if (ng==3){
 9401: 	fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
 9402: 	fprintf(ficgp,"\nset log y");
 9403:       }else
 9404: 	fprintf(ficgp,"\nunset title ");
 9405:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
 9406:       i=1;
 9407:       for(k2=1; k2<=nlstate; k2++) {
 9408: 	k3=i;
 9409: 	for(k=1; k<=(nlstate+ndeath); k++) {
 9410: 	  if (k != k2){
 9411: 	    switch( ng) {
 9412: 	    case 1:
 9413: 	      if(nagesqr==0)
 9414: 		fprintf(ficgp," p%d+p%d*x",i,i+1);
 9415: 	      else /* nagesqr =1 */
 9416: 		fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
 9417: 	      break;
 9418: 	    case 2: /* ng=2 */
 9419: 	      if(nagesqr==0)
 9420: 		fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
 9421: 	      else /* nagesqr =1 */
 9422: 		fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
 9423: 	      break;
 9424: 	    case 3:
 9425: 	      if(nagesqr==0)
 9426: 		fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
 9427: 	      else /* nagesqr =1 */
 9428: 		fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
 9429: 	      break;
 9430: 	    }
 9431: 	    ij=1;/* To be checked else nbcode[0][0] wrong */
 9432: 	    ijp=1; /* product no age */
 9433: 	    /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
 9434: 	    for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
 9435: 	      /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
 9436: 	      switch(Typevar[j]){
 9437: 	      case 1:
 9438: 		if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
 9439: 		  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
 9440: 		    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
 9441: 		      if(DummyV[j]==0){/* Bug valgrind */
 9442: 			fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
 9443: 		      }else{ /* quantitative */
 9444: 			fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
 9445: 			/* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
 9446: 		      }
 9447: 		      ij++;
 9448: 		    }
 9449: 		  }
 9450: 		}
 9451: 		break;
 9452: 	      case 2:
 9453: 		if(cptcovprod >0){
 9454: 		  if(j==Tprod[ijp]) { /* */ 
 9455: 		    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
 9456: 		    if(ijp <=cptcovprod) { /* Product */
 9457: 		      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
 9458: 			if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
 9459: 			  /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],nbcode[Tvard[ijp][2]][codtabm(k1,j)]); */
 9460: 			  fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
 9461: 			}else{ /* Vn is dummy and Vm is quanti */
 9462: 			  /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
 9463: 			  fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
 9464: 			}
 9465: 		      }else{ /* Vn*Vm Vn is quanti */
 9466: 			if(DummyV[Tvard[ijp][2]]==0){
 9467: 			  fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
 9468: 			}else{ /* Both quanti */
 9469: 			  fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
 9470: 			}
 9471: 		      }
 9472: 		      ijp++;
 9473: 		    }
 9474: 		  } /* end Tprod */
 9475: 		}
 9476: 		break;
 9477: 	      case 3:
 9478: 		if(cptcovdageprod >0){
 9479: 		  /* if(j==Tprod[ijp]) { */ /* not necessary */ 
 9480: 		    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
 9481: 		    if(ijp <=cptcovprod) { /* Product Vn*Vm and age*VN*Vm*/
 9482: 		      if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
 9483: 			if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
 9484: 			  /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],nbcode[Tvard[ijp][2]][codtabm(k1,j)]); */
 9485: 			  fprintf(ficgp,"+p%d*%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
 9486: 			}else{ /* Vn is dummy and Vm is quanti */
 9487: 			  /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
 9488: 			  fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
 9489: 			}
 9490: 		      }else{ /* age* Vn*Vm Vn is quanti HERE */
 9491: 			if(DummyV[Tvard[ijp][2]]==0){
 9492: 			  fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvardk[ijp][2]],Tqinvresult[nres][Tvardk[ijp][1]]);
 9493: 			}else{ /* Both quanti */
 9494: 			  fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
 9495: 			}
 9496: 		      }
 9497: 		      ijp++;
 9498: 		    }
 9499: 		    /* } */ /* end Tprod */
 9500: 		}
 9501: 		break;
 9502: 	      case 0:
 9503: 		/* simple covariate */
 9504: 		/* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
 9505: 		if(Dummy[j]==0){
 9506: 		  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
 9507: 		}else{ /* quantitative */
 9508: 		  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
 9509: 		  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
 9510: 		}
 9511: 	       /* end simple */
 9512: 		break;
 9513: 	      default:
 9514: 		break;
 9515: 	      } /* end switch */
 9516: 	    } /* end j */
 9517: 	  }else{ /* k=k2 */
 9518: 	    if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
 9519: 	      fprintf(ficgp," (1.");i=i-ncovmodel;
 9520: 	    }else
 9521: 	      i=i-ncovmodel;
 9522: 	  }
 9523: 	  
 9524: 	  if(ng != 1){
 9525: 	    fprintf(ficgp,")/(1");
 9526: 	    
 9527: 	    for(cpt=1; cpt <=nlstate; cpt++){ 
 9528: 	      if(nagesqr==0)
 9529: 		fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
 9530: 	      else /* nagesqr =1 */
 9531: 		fprintf(ficgp,"+exp(p%d+p%d*x+p%d*x*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1,k3+(cpt-1)*ncovmodel+1+nagesqr);
 9532: 	       
 9533: 	      ij=1;
 9534: 	      ijp=1;
 9535: 	      /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
 9536: 	      for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
 9537: 		switch(Typevar[j]){
 9538: 		case 1:
 9539: 		  if(cptcovage >0){ 
 9540: 		    if(j==Tage[ij]) { /* Bug valgrind */
 9541: 		      if(ij <=cptcovage) { /* Bug valgrind */
 9542: 			if(DummyV[j]==0){/* Bug valgrind */
 9543: 			  /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
 9544: 			  /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
 9545: 			  fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
 9546: 			  /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
 9547: 			  /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
 9548: 			}else{ /* quantitative */
 9549: 			  /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
 9550: 			  fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
 9551: 			  /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
 9552: 			  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
 9553: 			}
 9554: 			ij++;
 9555: 		      }
 9556: 		    }
 9557: 		  }
 9558: 		  break;
 9559: 		case 2:
 9560: 		  if(cptcovprod >0){
 9561: 		    if(j==Tprod[ijp]) { /* */ 
 9562: 		      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
 9563: 		      if(ijp <=cptcovprod) { /* Product */
 9564: 			if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
 9565: 			  if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
 9566: 			    /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],nbcode[Tvard[ijp][2]][codtabm(k1,j)]); */
 9567: 			    fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
 9568: 			    /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
 9569: 			  }else{ /* Vn is dummy and Vm is quanti */
 9570: 			    /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
 9571: 			    fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
 9572: 			    /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
 9573: 			  }
 9574: 			}else{ /* Vn*Vm Vn is quanti */
 9575: 			  if(DummyV[Tvard[ijp][2]]==0){
 9576: 			    fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
 9577: 			    /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
 9578: 			  }else{ /* Both quanti */
 9579: 			    fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
 9580: 			    /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
 9581: 			  } 
 9582: 			}
 9583: 			ijp++;
 9584: 		      }
 9585: 		    } /* end Tprod */
 9586: 		  } /* end if */
 9587: 		  break;
 9588: 		case 3:
 9589: 		  if(cptcovdageprod >0){
 9590: 		    /* if(j==Tprod[ijp]) { /\* *\/  */
 9591: 		      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
 9592: 		      if(ijp <=cptcovprod) { /* Product */
 9593: 			if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
 9594: 			  if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
 9595: 			    /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],nbcode[Tvard[ijp][2]][codtabm(k1,j)]); */
 9596: 			    fprintf(ficgp,"+p%d*%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvardk[ijp][1]],Tinvresult[nres][Tvardk[ijp][2]]);
 9597: 			    /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
 9598: 			  }else{ /* Vn is dummy and Vm is quanti */
 9599: 			    /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
 9600: 			    fprintf(ficgp,"+p%d*%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
 9601: 			    /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
 9602: 			  }
 9603: 			}else{ /* Vn*Vm Vn is quanti */
 9604: 			  if(DummyV[Tvardk[ijp][2]]==0){
 9605: 			    fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvardk[ijp][2]],Tqinvresult[nres][Tvardk[ijp][1]]);
 9606: 			    /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
 9607: 			  }else{ /* Both quanti */
 9608: 			    fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
 9609: 			    /* fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
 9610: 			  } 
 9611: 			}
 9612: 			ijp++;
 9613: 		      }
 9614: 		    /* } /\* end Tprod *\/ */
 9615: 		  } /* end if */
 9616: 		  break;
 9617: 		case 0: 
 9618: 		  /* simple covariate */
 9619: 		  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
 9620: 		  if(Dummy[j]==0){
 9621: 		    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
 9622: 		    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
 9623: 		    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
 9624: 		  }else{ /* quantitative */
 9625: 		    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
 9626: 		    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
 9627: 		    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
 9628: 		  }
 9629: 		  /* end simple */
 9630: 		  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
 9631: 		  break;
 9632: 		default:
 9633: 		  break;
 9634: 		} /* end switch */
 9635: 	      }
 9636: 	      fprintf(ficgp,")");
 9637: 	    }
 9638: 	    fprintf(ficgp,")");
 9639: 	    if(ng ==2)
 9640: 	      fprintf(ficgp," w l lw 2 lt (%d*%d+%d)%%%d+1 dt %d t \"p%d%d\" ", nlstate+ndeath, k2, k, nlstate+ndeath, k2, k2,k);
 9641: 	    else /* ng= 3 */
 9642: 	      fprintf(ficgp," w l lw 2 lt (%d*%d+%d)%%%d+1 dt %d t \"i%d%d\" ",  nlstate+ndeath, k2, k, nlstate+ndeath, k2, k2,k);
 9643:           }else{ /* end ng <> 1 */
 9644: 	    if( k !=k2) /* logit p11 is hard to draw */
 9645: 	      fprintf(ficgp," w l lw 2 lt (%d*%d+%d)%%%d+1 dt %d t \"logit(p%d%d)\" ",  nlstate+ndeath, k2, k, nlstate+ndeath, k2, k2,k);
 9646: 	  }
 9647: 	  if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
 9648: 	    fprintf(ficgp,",");
 9649: 	  if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
 9650: 	    fprintf(ficgp,",");
 9651: 	  i=i+ncovmodel;
 9652: 	} /* end k */
 9653:       } /* end k2 */
 9654:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
 9655:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
 9656:     } /* end resultline */
 9657:   } /* end ng */
 9658:   /* avoid: */
 9659:   fflush(ficgp); 
 9660: }  /* end gnuplot */
 9661: 
 9662: 
 9663: /*************** Moving average **************/
 9664: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
 9665:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
 9666:    
 9667:    int i, cpt, cptcod;
 9668:    int modcovmax =1;
 9669:    int mobilavrange, mob;
 9670:    int iage=0;
 9671:    int firstA1=0, firstA2=0;
 9672: 
 9673:    double sum=0., sumr=0.;
 9674:    double age;
 9675:    double *sumnewp, *sumnewm, *sumnewmr;
 9676:    double *agemingood, *agemaxgood; 
 9677:    double *agemingoodr, *agemaxgoodr; 
 9678:   
 9679:   
 9680:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
 9681:    /* 		   a covariate has 2 modalities, should be equal to ncovcombmax   */
 9682: 
 9683:    sumnewp = vector(1,ncovcombmax);
 9684:    sumnewm = vector(1,ncovcombmax);
 9685:    sumnewmr = vector(1,ncovcombmax);
 9686:    agemingood = vector(1,ncovcombmax);	
 9687:    agemingoodr = vector(1,ncovcombmax);	
 9688:    agemaxgood = vector(1,ncovcombmax);
 9689:    agemaxgoodr = vector(1,ncovcombmax);
 9690: 
 9691:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
 9692:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
 9693:      sumnewp[cptcod]=0.;
 9694:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
 9695:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
 9696:    }
 9697:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
 9698:   
 9699:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
 9700:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
 9701:      else mobilavrange=mobilav;
 9702:      for (age=bage; age<=fage; age++)
 9703:        for (i=1; i<=nlstate;i++)
 9704: 	 for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
 9705: 	   mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 9706:      /* We keep the original values on the extreme ages bage, fage and for 
 9707: 	fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
 9708: 	we use a 5 terms etc. until the borders are no more concerned. 
 9709:      */ 
 9710:      for (mob=3;mob <=mobilavrange;mob=mob+2){
 9711:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
 9712: 	 for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
 9713: 	   sumnewm[cptcod]=0.;
 9714: 	   for (i=1; i<=nlstate;i++){
 9715: 	     mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
 9716: 	     for (cpt=1;cpt<=(mob-1)/2;cpt++){
 9717: 	       mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
 9718: 	       mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
 9719: 	     }
 9720: 	     mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
 9721: 	     sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 9722: 	   } /* end i */
 9723: 	   if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
 9724: 	 } /* end cptcod */
 9725:        }/* end age */
 9726:      }/* end mob */
 9727:    }else{
 9728:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
 9729:      return -1;
 9730:    }
 9731: 
 9732:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
 9733:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
 9734:      if(invalidvarcomb[cptcod]){
 9735:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
 9736:        continue;
 9737:      }
 9738: 
 9739:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
 9740:        sumnewm[cptcod]=0.;
 9741:        sumnewmr[cptcod]=0.;
 9742:        for (i=1; i<=nlstate;i++){
 9743: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 9744: 	 sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
 9745:        }
 9746:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
 9747: 	 agemingoodr[cptcod]=age;
 9748:        }
 9749:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
 9750: 	   agemingood[cptcod]=age;
 9751:        }
 9752:      } /* age */
 9753:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
 9754:        sumnewm[cptcod]=0.;
 9755:        sumnewmr[cptcod]=0.;
 9756:        for (i=1; i<=nlstate;i++){
 9757: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 9758: 	 sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
 9759:        }
 9760:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
 9761: 	 agemaxgoodr[cptcod]=age;
 9762:        }
 9763:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
 9764: 	 agemaxgood[cptcod]=age;
 9765:        }
 9766:      } /* age */
 9767:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
 9768:      /* but they will change */
 9769:      firstA1=0;firstA2=0;
 9770:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
 9771:        sumnewm[cptcod]=0.;
 9772:        sumnewmr[cptcod]=0.;
 9773:        for (i=1; i<=nlstate;i++){
 9774: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 9775: 	 sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
 9776:        }
 9777:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
 9778: 	 if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
 9779: 	   agemaxgoodr[cptcod]=age;  /* age min */
 9780: 	   for (i=1; i<=nlstate;i++)
 9781: 	     mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 9782: 	 }else{ /* bad we change the value with the values of good ages */
 9783: 	   for (i=1; i<=nlstate;i++){
 9784: 	     mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
 9785: 	   } /* i */
 9786: 	 } /* end bad */
 9787:        }else{
 9788: 	 if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
 9789: 	   agemaxgood[cptcod]=age;
 9790: 	 }else{ /* bad we change the value with the values of good ages */
 9791: 	   for (i=1; i<=nlstate;i++){
 9792: 	     mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
 9793: 	   } /* i */
 9794: 	 } /* end bad */
 9795:        }/* end else */
 9796:        sum=0.;sumr=0.;
 9797:        for (i=1; i<=nlstate;i++){
 9798: 	 sum+=mobaverage[(int)age][i][cptcod];
 9799: 	 sumr+=probs[(int)age][i][cptcod];
 9800:        }
 9801:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
 9802: 	 if(!firstA1){
 9803: 	   firstA1=1;
 9804: 	   printf("Moving average A1: For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one (%f) at any descending age! age=%d, could you increase bage=%d. Others in log file...\n",cptcod,sumr, (int)age, (int)bage);
 9805: 	 }
 9806: 	 fprintf(ficlog,"Moving average A1: For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one (%f) at any descending age! age=%d, could you increase bage=%d\n",cptcod,sumr, (int)age, (int)bage);
 9807:        } /* end bad */
 9808:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
 9809:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
 9810: 	 if(!firstA2){
 9811: 	   firstA2=1;
 9812: 	   printf("Moving average A2: For this combination of covariate cptcod=%d, the raw prevalence doesn't sums to one (%f) even with smoothed values at young ages! age=%d, could you increase bage=%d. Others in log file...\n",cptcod,sumr, (int)age, (int)bage);
 9813: 	 }
 9814: 	 fprintf(ficlog,"Moving average A2: For this combination of covariate cptcod=%d, the raw prevalence doesn't sums to one (%f) even with smoothed values at young ages! age=%d, could you increase bage=%d\n",cptcod,sumr, (int)age, (int)bage);
 9815:        } /* end bad */
 9816:      }/* age */
 9817: 
 9818:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
 9819:        sumnewm[cptcod]=0.;
 9820:        sumnewmr[cptcod]=0.;
 9821:        for (i=1; i<=nlstate;i++){
 9822: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 9823: 	 sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
 9824:        } 
 9825:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
 9826: 	 if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
 9827: 	   agemingoodr[cptcod]=age;
 9828: 	   for (i=1; i<=nlstate;i++)
 9829: 	     mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 9830: 	 }else{ /* bad we change the value with the values of good ages */
 9831: 	   for (i=1; i<=nlstate;i++){
 9832: 	     mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
 9833: 	   } /* i */
 9834: 	 } /* end bad */
 9835:        }else{
 9836: 	 if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
 9837: 	   agemingood[cptcod]=age;
 9838: 	 }else{ /* bad */
 9839: 	   for (i=1; i<=nlstate;i++){
 9840: 	     mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
 9841: 	   } /* i */
 9842: 	 } /* end bad */
 9843:        }/* end else */
 9844:        sum=0.;sumr=0.;
 9845:        for (i=1; i<=nlstate;i++){
 9846: 	 sum+=mobaverage[(int)age][i][cptcod];
 9847: 	 sumr+=mobaverage[(int)age][i][cptcod];
 9848:        }
 9849:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
 9850: 	 printf("Moving average B1: For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one (%f) at any descending age! age=%d, could you decrease fage=%d?\n",cptcod, sum, (int) age, (int)fage);
 9851:        } /* end bad */
 9852:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
 9853:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
 9854: 	 printf("Moving average B2: For this combination of covariate cptcod=%d, the raw prevalence doesn't sums to one (%f) even with smoothed values at young ages! age=%d, could you increase fage=%d\n",cptcod,sumr, (int)age, (int)fage);
 9855:        } /* end bad */
 9856:      }/* age */
 9857: 
 9858: 		
 9859:      for (age=bage; age<=fage; age++){
 9860:        /* printf("%d %d ", cptcod, (int)age); */
 9861:        sumnewp[cptcod]=0.;
 9862:        sumnewm[cptcod]=0.;
 9863:        for (i=1; i<=nlstate;i++){
 9864: 	 sumnewp[cptcod]+=probs[(int)age][i][cptcod];
 9865: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 9866: 	 /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
 9867:        }
 9868:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
 9869:      }
 9870:      /* printf("\n"); */
 9871:      /* } */
 9872: 
 9873:      /* brutal averaging */
 9874:      /* for (i=1; i<=nlstate;i++){ */
 9875:      /*   for (age=1; age<=bage; age++){ */
 9876:      /* 	 mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
 9877:      /* 	 /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
 9878:      /*   }	 */
 9879:      /*   for (age=fage; age<=AGESUP; age++){ */
 9880:      /* 	 mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
 9881:      /* 	 /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
 9882:      /*   } */
 9883:      /* } /\* end i status *\/ */
 9884:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
 9885:      /*   for (age=1; age<=AGESUP; age++){ */
 9886:      /* 	 /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
 9887:      /* 	 mobaverage[(int)age][i][cptcod]=0.; */
 9888:      /*   } */
 9889:      /* } */
 9890:    }/* end cptcod */
 9891:    free_vector(agemaxgoodr,1, ncovcombmax);
 9892:    free_vector(agemaxgood,1, ncovcombmax);
 9893:    free_vector(agemingood,1, ncovcombmax);
 9894:    free_vector(agemingoodr,1, ncovcombmax);
 9895:    free_vector(sumnewmr,1, ncovcombmax);
 9896:    free_vector(sumnewm,1, ncovcombmax);
 9897:    free_vector(sumnewp,1, ncovcombmax);
 9898:    return 0;
 9899:  }/* End movingaverage */
 9900:  
 9901: 
 9902:  
 9903: /************** Forecasting ******************/
 9904: /* void prevforecast(char fileres[], double dateintmean, double anprojd, double mprojd, double jprojd, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double ***prev, double bage, double fage, int firstpass, int lastpass, double anprojf, double p[], int cptcoveff)*/
 9905: void prevforecast(char fileres[], double dateintmean, double dateprojd, double dateprojf, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double ***prev, double bage, double fage, int firstpass, int lastpass, double p[], int cptcoveff){
 9906:   /* dateintemean, mean date of interviews
 9907:      dateprojd, year, month, day of starting projection 
 9908:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
 9909:      agemin, agemax range of age
 9910:      dateprev1 dateprev2 range of dates during which prevalence is computed
 9911:   */
 9912:   /* double anprojd, mprojd, jprojd; */
 9913:   /* double anprojf, mprojf, jprojf; */
 9914:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
 9915:   double agec; /* generic age */
 9916:   double agelim, ppij, yp,yp1,yp2;
 9917:   double *popeffectif,*popcount;
 9918:   double ***p3mat;
 9919:   /* double ***mobaverage; */
 9920:   char fileresf[FILENAMELENGTH];
 9921: 
 9922:   agelim=AGESUP;
 9923:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 9924:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 9925:      We still use firstpass and lastpass as another selection.
 9926:   */
 9927:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
 9928:   /* 	      firstpass, lastpass,  stepm,  weightopt, model); */
 9929:  
 9930:   strcpy(fileresf,"F_"); 
 9931:   strcat(fileresf,fileresu);
 9932:   if((ficresf=fopen(fileresf,"w"))==NULL) {
 9933:     printf("Problem with forecast resultfile: %s\n", fileresf);
 9934:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
 9935:   }
 9936:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
 9937:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
 9938: 
 9939:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 9940: 
 9941: 
 9942:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 9943:   if (stepm<=12) stepsize=1;
 9944:   if(estepm < stepm){
 9945:     printf ("Problem %d lower than %d\n",estepm, stepm);
 9946:   }
 9947:   else{
 9948:     hstepm=estepm;   
 9949:   }
 9950:   if(estepm > stepm){ /* Yes every two year */
 9951:     stepsize=2;
 9952:   }
 9953:   hstepm=hstepm/stepm;
 9954: 
 9955:   
 9956:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
 9957:   /*                              fractional in yp1 *\/ */
 9958:   /* aintmean=yp; */
 9959:   /* yp2=modf((yp1*12),&yp); */
 9960:   /* mintmean=yp; */
 9961:   /* yp1=modf((yp2*30.5),&yp); */
 9962:   /* jintmean=yp; */
 9963:   /* if(jintmean==0) jintmean=1; */
 9964:   /* if(mintmean==0) mintmean=1; */
 9965: 
 9966: 
 9967:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
 9968:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
 9969:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
 9970:   /* i1=pow(2,cptcoveff); */
 9971:   /* if (cptcovn < 1){i1=1;} */
 9972:   
 9973:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
 9974:   
 9975:   fprintf(ficresf,"#****** Routine prevforecast **\n");
 9976:   
 9977: /* 	      if (h==(int)(YEARM*yearp)){ */
 9978:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 9979:     k=TKresult[nres];
 9980:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
 9981:     /*  for(k=1; k<=i1;k++){ /\* We want to find the combination k corresponding to the values of the dummies given in this resut line (to be cleaned one day) *\/ */
 9982:     /* if(i1 != 1 && TKresult[nres]!= k) */
 9983:     /*   continue; */
 9984:     /* if(invalidvarcomb[k]){ */
 9985:     /*   printf("\nCombination (%d) projection ignored because no cases \n",k);  */
 9986:     /*   continue; */
 9987:     /* } */
 9988:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
 9989:     for(j=1;j<=cptcovs;j++){
 9990:       /* for(j=1;j<=cptcoveff;j++) { */
 9991:     /*   /\* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); *\/ */
 9992:     /*   fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
 9993:     /* } */
 9994:     /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 9995:     /*   fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
 9996:     /* } */
 9997:       fprintf(ficresf," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
 9998:     }
 9999:  
10000:     fprintf(ficresf," yearproj age");
10001:     for(j=1; j<=nlstate+ndeath;j++){ 
10002:       for(i=1; i<=nlstate;i++) 	      
10003: 	fprintf(ficresf," p%d%d",i,j);
10004:       fprintf(ficresf," wp.%d",j);
10005:     }
10006:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
10007:       fprintf(ficresf,"\n");
10008:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
10009:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
10010:       for (agec=fage; agec>=(bage); agec--){ 
10011: 	nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
10012: 	nhstepm = nhstepm/hstepm; 
10013: 	p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
10014: 	oldm=oldms;savm=savms;
10015: 	/* We compute pii at age agec over nhstepm);*/
10016: 	hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
10017: 	/* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
10018: 	for (h=0; h<=nhstepm; h++){
10019: 	  if (h*hstepm/YEARM*stepm ==yearp) {
10020: 	    break;
10021: 	  }
10022: 	}
10023: 	fprintf(ficresf,"\n");
10024: 	/* for(j=1;j<=cptcoveff;j++)  */
10025: 	for(j=1;j<=cptcovs;j++) 
10026: 	  fprintf(ficresf,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
10027: 	  /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
10028: 	  /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* TnsdVar[Tvaraff]  correct *\/ */
10029: 	fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
10030: 	
10031: 	for(j=1; j<=nlstate+ndeath;j++) {
10032: 	  ppij=0.;
10033: 	  for(i=1; i<=nlstate;i++) {
10034: 	    if (mobilav>=1)
10035: 	     ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
10036: 	    else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
10037: 	    	ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
10038: 	    }
10039: 	    fprintf(ficresf," %.3f", p3mat[i][j][h]);
10040: 	  } /* end i */
10041: 	  fprintf(ficresf," %.3f", ppij);
10042: 	}/* end j */
10043: 	free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
10044:       } /* end agec */
10045:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
10046:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
10047:     } /* end yearp */
10048:   } /* end  k */
10049: 	
10050:   fclose(ficresf);
10051:   printf("End of Computing forecasting \n");
10052:   fprintf(ficlog,"End of Computing forecasting\n");
10053: 
10054: }
10055: 
10056: /************** Back Forecasting ******************/
10057:  /* void prevbackforecast(char fileres[], double ***prevacurrent, 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){ */
10058:  void prevbackforecast(char fileres[], double ***prevacurrent, double dateintmean, double dateprojd, double dateprojf, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double p[], int cptcoveff){
10059:   /* back1, year, month, day of starting backprojection
10060:      agemin, agemax range of age
10061:      dateprev1 dateprev2 range of dates during which prevalence is computed
10062:      anback2 year of end of backprojection (same day and month as back1).
10063:      prevacurrent and prev are prevalences.
10064:   */
10065:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
10066:   double agec; /* generic age */
10067:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
10068:   double *popeffectif,*popcount;
10069:   double ***p3mat;
10070:   /* double ***mobaverage; */
10071:   char fileresfb[FILENAMELENGTH];
10072:  
10073:   agelim=AGEINF;
10074:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
10075:      in each health status at the date of interview (if between dateprev1 and dateprev2).
10076:      We still use firstpass and lastpass as another selection.
10077:   */
10078:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
10079:   /* 	      firstpass, lastpass,  stepm,  weightopt, model); */
10080: 
10081:   /*Do we need to compute prevalence again?*/
10082: 
10083:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
10084:   
10085:   strcpy(fileresfb,"FB_");
10086:   strcat(fileresfb,fileresu);
10087:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
10088:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
10089:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
10090:   }
10091:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
10092:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
10093:   
10094:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
10095:   
10096:    
10097:   stepsize=(int) (stepm+YEARM-1)/YEARM;
10098:   if (stepm<=12) stepsize=1;
10099:   if(estepm < stepm){
10100:     printf ("Problem %d lower than %d\n",estepm, stepm);
10101:   }
10102:   else{
10103:     hstepm=estepm;   
10104:   }
10105:   if(estepm >= stepm){ /* Yes every two year */
10106:     stepsize=2;
10107:   }
10108:   
10109:   hstepm=hstepm/stepm;
10110:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
10111:   /*                              fractional in yp1 *\/ */
10112:   /* aintmean=yp; */
10113:   /* yp2=modf((yp1*12),&yp); */
10114:   /* mintmean=yp; */
10115:   /* yp1=modf((yp2*30.5),&yp); */
10116:   /* jintmean=yp; */
10117:   /* if(jintmean==0) jintmean=1; */
10118:   /* if(mintmean==0) jintmean=1; */
10119:   
10120:   /* i1=pow(2,cptcoveff); */
10121:   /* if (cptcovn < 1){i1=1;} */
10122:   
10123:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
10124:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
10125:   
10126:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
10127:   
10128:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
10129:     k=TKresult[nres];
10130:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
10131:   /* for(k=1; k<=i1;k++){ */
10132:   /*   if(i1 != 1 && TKresult[nres]!= k) */
10133:   /*     continue; */
10134:   /*   if(invalidvarcomb[k]){ */
10135:   /*     printf("\nCombination (%d) projection ignored because no cases \n",k);  */
10136:   /*     continue; */
10137:   /*   } */
10138:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
10139:     for(j=1;j<=cptcovs;j++){
10140:     /* for(j=1;j<=cptcoveff;j++) { */
10141:     /*   fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
10142:     /* } */
10143:       fprintf(ficresfb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
10144:     }
10145:    /*  fprintf(ficrespij,"******\n"); */
10146:    /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
10147:    /*    fprintf(ficresfb," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
10148:    /*  } */
10149:     fprintf(ficresfb," yearbproj age");
10150:     for(j=1; j<=nlstate+ndeath;j++){
10151:       for(i=1; i<=nlstate;i++)
10152: 	fprintf(ficresfb," b%d%d",i,j);
10153:       fprintf(ficresfb," b.%d",j);
10154:     }
10155:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
10156:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
10157:       fprintf(ficresfb,"\n");
10158:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
10159:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
10160:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
10161:       for (agec=bage; agec<=fage; agec++){  /* testing */
10162: 	/* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
10163: 	nhstepm=(int) (agec-agelim) *YEARM/stepm;/*	nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
10164: 	nhstepm = nhstepm/hstepm;
10165: 	p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
10166: 	oldm=oldms;savm=savms;
10167: 	/* computes hbxij at age agec over 1 to nhstepm */
10168: 	/* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
10169: 	hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
10170: 	/* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
10171: 	/* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
10172: 	/* printf(" agec=%.2f\n",agec);fflush(stdout); */
10173: 	for (h=0; h<=nhstepm; h++){
10174: 	  if (h*hstepm/YEARM*stepm ==-yearp) {
10175: 	    break;
10176: 	  }
10177: 	}
10178: 	fprintf(ficresfb,"\n");
10179: 	/* for(j=1;j<=cptcoveff;j++) */
10180: 	for(j=1;j<=cptcovs;j++)
10181: 	  fprintf(ficresfb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
10182: 	  /* fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
10183: 	fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
10184: 	for(i=1; i<=nlstate+ndeath;i++) {
10185: 	  ppij=0.;ppi=0.;
10186: 	  for(j=1; j<=nlstate;j++) {
10187: 	    /* if (mobilav==1) */
10188: 	    ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
10189: 	    ppi=ppi+prevacurrent[(int)agec][j][k];
10190: 	    /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
10191: 	    /* ppi=ppi+mobaverage[(int)agec][j][k]; */
10192: 	      /* else { */
10193: 	      /* 	ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
10194: 	      /* } */
10195: 	    fprintf(ficresfb," %.3f", p3mat[i][j][h]);
10196: 	  } /* end j */
10197: 	  if(ppi <0.99){
10198: 	    printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
10199: 	    fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
10200: 	  }
10201: 	  fprintf(ficresfb," %.3f", ppij);
10202: 	}/* end j */
10203: 	free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
10204:       } /* end agec */
10205:     } /* end yearp */
10206:   } /* end k */
10207:   
10208:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
10209:   
10210:   fclose(ficresfb);
10211:   printf("End of Computing Back forecasting \n");
10212:   fprintf(ficlog,"End of Computing Back forecasting\n");
10213: 	
10214: }
10215: 
10216: /* Variance of prevalence limit: varprlim */
10217:  void varprlim(char fileresu[], int nresult, double ***prevacurrent, int mobilavproj, double bage, double fage, double **prlim, int *ncvyearp, double ftolpl, double p[], double **matcov, double *delti, int stepm, int cptcoveff){
10218:     /*------- Variance of forward period (stable) prevalence------*/   
10219:  
10220:    char fileresvpl[FILENAMELENGTH];  
10221:    FILE *ficresvpl;
10222:    double **oldm, **savm;
10223:    double **varpl; /* Variances of prevalence limits by age */   
10224:    int i1, k, nres, j ;
10225:    
10226:     strcpy(fileresvpl,"VPL_");
10227:     strcat(fileresvpl,fileresu);
10228:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
10229:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
10230:       exit(0);
10231:     }
10232:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
10233:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
10234:     
10235:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
10236:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
10237:     
10238:     i1=pow(2,cptcoveff);
10239:     if (cptcovn < 1){i1=1;}
10240: 
10241:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
10242:        k=TKresult[nres];
10243:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
10244:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
10245:       if(i1 != 1 && TKresult[nres]!= k)
10246: 	continue;
10247:       fprintf(ficresvpl,"\n#****** ");
10248:       printf("\n#****** ");
10249:       fprintf(ficlog,"\n#****** ");
10250:       for(j=1;j<=cptcovs;j++) {
10251: 	fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
10252: 	fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
10253: 	printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
10254: 	/* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
10255: 	/* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
10256:       }
10257:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
10258:       /* 	printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
10259:       /* 	fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
10260:       /* 	fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
10261:       /* }	 */
10262:       fprintf(ficresvpl,"******\n");
10263:       printf("******\n");
10264:       fprintf(ficlog,"******\n");
10265:       
10266:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
10267:       oldm=oldms;savm=savms;
10268:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
10269:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
10270:       /*}*/
10271:     }
10272:     
10273:     fclose(ficresvpl);
10274:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
10275:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
10276: 
10277:  }
10278: /* Variance of back prevalence: varbprlim */
10279:  void varbprlim(char fileresu[], int nresult, double ***prevacurrent, int mobilavproj, double bage, double fage, double **bprlim, int *ncvyearp, double ftolpl, double p[], double **matcov, double *delti, int stepm, int cptcoveff){
10280:       /*------- Variance of back (stable) prevalence------*/
10281: 
10282:    char fileresvbl[FILENAMELENGTH];  
10283:    FILE  *ficresvbl;
10284: 
10285:    double **oldm, **savm;
10286:    double **varbpl; /* Variances of back prevalence limits by age */   
10287:    int i1, k, nres, j ;
10288: 
10289:    strcpy(fileresvbl,"VBL_");
10290:    strcat(fileresvbl,fileresu);
10291:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
10292:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
10293:      exit(0);
10294:    }
10295:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
10296:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
10297:    
10298:    
10299:    i1=pow(2,cptcoveff);
10300:    if (cptcovn < 1){i1=1;}
10301:    
10302:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
10303:      k=TKresult[nres];
10304:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
10305:     /* for(k=1; k<=i1;k++){ */
10306:     /*    if(i1 != 1 && TKresult[nres]!= k) */
10307:     /* 	 continue; */
10308:        fprintf(ficresvbl,"\n#****** ");
10309:        printf("\n#****** ");
10310:        fprintf(ficlog,"\n#****** ");
10311:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
10312: 	 printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
10313: 	 fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
10314: 	 fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
10315:        /* for(j=1;j<=cptcoveff;j++) { */
10316:        /* 	 fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
10317:        /* 	 fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
10318:        /* 	 printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
10319:        /* } */
10320:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
10321:        /* 	 printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
10322:        /* 	 fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
10323:        /* 	 fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
10324:        }
10325:        fprintf(ficresvbl,"******\n");
10326:        printf("******\n");
10327:        fprintf(ficlog,"******\n");
10328:        
10329:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
10330:        oldm=oldms;savm=savms;
10331:        
10332:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
10333:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
10334:        /*}*/
10335:      }
10336:    
10337:    fclose(ficresvbl);
10338:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
10339:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
10340: 
10341:  } /* End of varbprlim */
10342: 
10343: /************** Forecasting *****not tested NB*************/
10344: /* 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){ */
10345:   
10346: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
10347: /*   int *popage; */
10348: /*   double calagedatem, agelim, kk1, kk2; */
10349: /*   double *popeffectif,*popcount; */
10350: /*   double ***p3mat,***tabpop,***tabpopprev; */
10351: /*   /\* double ***mobaverage; *\/ */
10352: /*   char filerespop[FILENAMELENGTH]; */
10353: 
10354: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
10355: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
10356: /*   agelim=AGESUP; */
10357: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
10358:   
10359: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
10360:   
10361:   
10362: /*   strcpy(filerespop,"POP_");  */
10363: /*   strcat(filerespop,fileresu); */
10364: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
10365: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
10366: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
10367: /*   } */
10368: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
10369: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
10370: 
10371: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
10372: 
10373: /*   /\* if (mobilav!=0) { *\/ */
10374: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
10375: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
10376: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
10377: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
10378: /*   /\*   } *\/ */
10379: /*   /\* } *\/ */
10380: 
10381: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
10382: /*   if (stepm<=12) stepsize=1; */
10383:   
10384: /*   agelim=AGESUP; */
10385:   
10386: /*   hstepm=1; */
10387: /*   hstepm=hstepm/stepm;  */
10388: 	
10389: /*   if (popforecast==1) { */
10390: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
10391: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
10392: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
10393: /*     }  */
10394: /*     popage=ivector(0,AGESUP); */
10395: /*     popeffectif=vector(0,AGESUP); */
10396: /*     popcount=vector(0,AGESUP); */
10397:     
10398: /*     i=1;    */
10399: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
10400:     
10401: /*     imx=i; */
10402: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
10403: /*   } */
10404:   
10405: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
10406: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
10407: /*       k=k+1; */
10408: /*       fprintf(ficrespop,"\n#******"); */
10409: /*       for(j=1;j<=cptcoveff;j++) { */
10410: /* 	fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
10411: /*       } */
10412: /*       fprintf(ficrespop,"******\n"); */
10413: /*       fprintf(ficrespop,"# Age"); */
10414: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
10415: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
10416:       
10417: /*       for (cpt=0; cpt<=0;cpt++) {  */
10418: /* 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
10419: 	
10420: /* 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
10421: /* 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
10422: /* 	  nhstepm = nhstepm/hstepm;  */
10423: 	  
10424: /* 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
10425: /* 	  oldm=oldms;savm=savms; */
10426: /* 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
10427: 	  
10428: /* 	  for (h=0; h<=nhstepm; h++){ */
10429: /* 	    if (h==(int) (calagedatem+YEARM*cpt)) { */
10430: /* 	      fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
10431: /* 	    }  */
10432: /* 	    for(j=1; j<=nlstate+ndeath;j++) { */
10433: /* 	      kk1=0.;kk2=0; */
10434: /* 	      for(i=1; i<=nlstate;i++) {	       */
10435: /* 		if (mobilav==1)  */
10436: /* 		  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
10437: /* 		else { */
10438: /* 		  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
10439: /* 		} */
10440: /* 	      } */
10441: /* 	      if (h==(int)(calagedatem+12*cpt)){ */
10442: /* 		tabpop[(int)(agedeb)][j][cptcod]=kk1; */
10443: /* 		/\*fprintf(ficrespop," %.3f", kk1); */
10444: /* 		  if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
10445: /* 	      } */
10446: /* 	    } */
10447: /* 	    for(i=1; i<=nlstate;i++){ */
10448: /* 	      kk1=0.; */
10449: /* 	      for(j=1; j<=nlstate;j++){ */
10450: /* 		kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
10451: /* 	      } */
10452: /* 	      tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
10453: /* 	    } */
10454: 	    
10455: /* 	    if (h==(int)(calagedatem+12*cpt)) */
10456: /* 	      for(j=1; j<=nlstate;j++)  */
10457: /* 		fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
10458: /* 	  } */
10459: /* 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
10460: /* 	} */
10461: /*       } */
10462:       
10463: /*       /\******\/ */
10464:       
10465: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
10466: /* 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
10467: /* 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
10468: /* 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
10469: /* 	  nhstepm = nhstepm/hstepm;  */
10470: 	  
10471: /* 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
10472: /* 	  oldm=oldms;savm=savms; */
10473: /* 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
10474: /* 	  for (h=0; h<=nhstepm; h++){ */
10475: /* 	    if (h==(int) (calagedatem+YEARM*cpt)) { */
10476: /* 	      fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
10477: /* 	    }  */
10478: /* 	    for(j=1; j<=nlstate+ndeath;j++) { */
10479: /* 	      kk1=0.;kk2=0; */
10480: /* 	      for(i=1; i<=nlstate;i++) {	       */
10481: /* 		kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];	 */
10482: /* 	      } */
10483: /* 	      if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);	 */
10484: /* 	    } */
10485: /* 	  } */
10486: /* 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
10487: /* 	} */
10488: /*       } */
10489: /*     }  */
10490: /*   } */
10491:   
10492: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
10493:   
10494: /*   if (popforecast==1) { */
10495: /*     free_ivector(popage,0,AGESUP); */
10496: /*     free_vector(popeffectif,0,AGESUP); */
10497: /*     free_vector(popcount,0,AGESUP); */
10498: /*   } */
10499: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
10500: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
10501: /*   fclose(ficrespop); */
10502: /* } /\* End of popforecast *\/ */
10503:  
10504: int fileappend(FILE *fichier, char *optionfich)
10505: {
10506:   if((fichier=fopen(optionfich,"a"))==NULL) {
10507:     printf("Problem with file: %s\n", optionfich);
10508:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
10509:     return (0);
10510:   }
10511:   fflush(fichier);
10512:   return (1);
10513: }
10514: 
10515: 
10516: /**************** function prwizard **********************/
10517: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
10518: {
10519: 
10520:   /* Wizard to print covariance matrix template */
10521: 
10522:   char ca[32], cb[32];
10523:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
10524:   int numlinepar;
10525: 
10526:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
10527:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
10528:   for(i=1; i <=nlstate; i++){
10529:     jj=0;
10530:     for(j=1; j <=nlstate+ndeath; j++){
10531:       if(j==i) continue;
10532:       jj++;
10533:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
10534:       printf("%1d%1d",i,j);
10535:       fprintf(ficparo,"%1d%1d",i,j);
10536:       for(k=1; k<=ncovmodel;k++){
10537: 	/* 	  printf(" %lf",param[i][j][k]); */
10538: 	/* 	  fprintf(ficparo," %lf",param[i][j][k]); */
10539: 	printf(" 0.");
10540: 	fprintf(ficparo," 0.");
10541:       }
10542:       printf("\n");
10543:       fprintf(ficparo,"\n");
10544:     }
10545:   }
10546:   printf("# Scales (for hessian or gradient estimation)\n");
10547:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
10548:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
10549:   for(i=1; i <=nlstate; i++){
10550:     jj=0;
10551:     for(j=1; j <=nlstate+ndeath; j++){
10552:       if(j==i) continue;
10553:       jj++;
10554:       fprintf(ficparo,"%1d%1d",i,j);
10555:       printf("%1d%1d",i,j);
10556:       fflush(stdout);
10557:       for(k=1; k<=ncovmodel;k++){
10558: 	/* 	printf(" %le",delti3[i][j][k]); */
10559: 	/* 	fprintf(ficparo," %le",delti3[i][j][k]); */
10560: 	printf(" 0.");
10561: 	fprintf(ficparo," 0.");
10562:       }
10563:       numlinepar++;
10564:       printf("\n");
10565:       fprintf(ficparo,"\n");
10566:     }
10567:   }
10568:   printf("# Covariance matrix\n");
10569: /* # 121 Var(a12)\n\ */
10570: /* # 122 Cov(b12,a12) Var(b12)\n\ */
10571: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
10572: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
10573: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
10574: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
10575: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
10576: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
10577:   fflush(stdout);
10578:   fprintf(ficparo,"# Covariance matrix\n");
10579:   /* # 121 Var(a12)\n\ */
10580:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
10581:   /* #   ...\n\ */
10582:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
10583:   
10584:   for(itimes=1;itimes<=2;itimes++){
10585:     jj=0;
10586:     for(i=1; i <=nlstate; i++){
10587:       for(j=1; j <=nlstate+ndeath; j++){
10588: 	if(j==i) continue;
10589: 	for(k=1; k<=ncovmodel;k++){
10590: 	  jj++;
10591: 	  ca[0]= k+'a'-1;ca[1]='\0';
10592: 	  if(itimes==1){
10593: 	    printf("#%1d%1d%d",i,j,k);
10594: 	    fprintf(ficparo,"#%1d%1d%d",i,j,k);
10595: 	  }else{
10596: 	    printf("%1d%1d%d",i,j,k);
10597: 	    fprintf(ficparo,"%1d%1d%d",i,j,k);
10598: 	    /* 	printf(" %.5le",matcov[i][j]); */
10599: 	  }
10600: 	  ll=0;
10601: 	  for(li=1;li <=nlstate; li++){
10602: 	    for(lj=1;lj <=nlstate+ndeath; lj++){
10603: 	      if(lj==li) continue;
10604: 	      for(lk=1;lk<=ncovmodel;lk++){
10605: 		ll++;
10606: 		if(ll<=jj){
10607: 		  cb[0]= lk +'a'-1;cb[1]='\0';
10608: 		  if(ll<jj){
10609: 		    if(itimes==1){
10610: 		      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
10611: 		      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
10612: 		    }else{
10613: 		      printf(" 0.");
10614: 		      fprintf(ficparo," 0.");
10615: 		    }
10616: 		  }else{
10617: 		    if(itimes==1){
10618: 		      printf(" Var(%s%1d%1d)",ca,i,j);
10619: 		      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
10620: 		    }else{
10621: 		      printf(" 0.");
10622: 		      fprintf(ficparo," 0.");
10623: 		    }
10624: 		  }
10625: 		}
10626: 	      } /* end lk */
10627: 	    } /* end lj */
10628: 	  } /* end li */
10629: 	  printf("\n");
10630: 	  fprintf(ficparo,"\n");
10631: 	  numlinepar++;
10632: 	} /* end k*/
10633:       } /*end j */
10634:     } /* end i */
10635:   } /* end itimes */
10636: 
10637: } /* end of prwizard */
10638: /******************* Gompertz Likelihood ******************************/
10639: double gompertz(double x[])
10640: { 
10641:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
10642:   int i,n=0; /* n is the size of the sample */
10643: 
10644:   for (i=1;i<=imx ; i++) {
10645:     sump=sump+weight[i];
10646:     /*    sump=sump+1;*/
10647:     num=num+1;
10648:   }
10649:   L=0.0;
10650:   /* agegomp=AGEGOMP; */
10651:   /* for (i=0; i<=imx; i++) 
10652:      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]);*/
10653: 
10654:   for (i=1;i<=imx ; i++) {
10655:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
10656:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
10657:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
10658:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
10659:      * +
10660:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
10661:      */
10662:      if (wav[i] > 1 || agedc[i] < AGESUP) {
10663:        if (cens[i] == 1){
10664: 	 A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
10665:        } else if (cens[i] == 0){
10666: 	A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
10667: 	  +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
10668:       } else
10669: 	 printf("Gompertz cens[%d] neither 1 nor 0\n",i);
10670:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
10671:        L=L+A*weight[i];
10672: 	/* 	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]);*/
10673:      }
10674:   }
10675: 
10676:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
10677:  
10678:   return -2*L*num/sump;
10679: }
10680: 
10681: #ifdef GSL
10682: /******************* Gompertz_f Likelihood ******************************/
10683: double gompertz_f(const gsl_vector *v, void *params)
10684: { 
10685:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
10686:   double *x= (double *) v->data;
10687:   int i,n=0; /* n is the size of the sample */
10688: 
10689:   for (i=0;i<=imx-1 ; i++) {
10690:     sump=sump+weight[i];
10691:     /*    sump=sump+1;*/
10692:     num=num+1;
10693:   }
10694:  
10695:  
10696:   /* for (i=0; i<=imx; i++) 
10697:      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]);*/
10698:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
10699:   for (i=1;i<=imx ; i++)
10700:     {
10701:       if (cens[i] == 1 && wav[i]>1)
10702: 	A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
10703:       
10704:       if (cens[i] == 0 && wav[i]>1)
10705: 	A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
10706: 	     +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
10707:       
10708:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
10709:       if (wav[i] > 1 ) { /* ??? */
10710: 	LL=LL+A*weight[i];
10711: 	/* 	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]);*/
10712:       }
10713:     }
10714: 
10715:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
10716:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
10717:  
10718:   return -2*LL*num/sump;
10719: }
10720: #endif
10721: 
10722: /******************* Printing html file ***********/
10723: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
10724: 		  int lastpass, int stepm, int weightopt, char model[],\
10725: 		  int imx,  double p[],double **matcov,double agemortsup){
10726:   int i,k;
10727: 
10728:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
10729:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
10730:   for (i=1;i<=2;i++) 
10731:     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]));
10732:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
10733:   fprintf(fichtm,"</ul>");
10734: 
10735: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
10736: 
10737:  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>");
10738: 
10739:  for (k=agegomp;k<(agemortsup-2);k++) 
10740:    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]);
10741: 
10742:  
10743:   fflush(fichtm);
10744: }
10745: 
10746: /******************* Gnuplot file **************/
10747: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
10748: 
10749:   char dirfileres[132],optfileres[132];
10750: 
10751:   int ng;
10752: 
10753: 
10754:   /*#ifdef windows */
10755:   fprintf(ficgp,"cd \"%s\" \n",pathc);
10756:     /*#endif */
10757: 
10758: 
10759:   strcpy(dirfileres,optionfilefiname);
10760:   strcpy(optfileres,"vpl");
10761:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
10762:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
10763:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
10764:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
10765:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
10766: 
10767: } 
10768: 
10769: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
10770: {
10771: 
10772:   /*-------- data file ----------*/
10773:   FILE *fic;
10774:   char dummy[]="                         ";
10775:   int i=0, j=0, n=0, iv=0, v;
10776:   int lstra;
10777:   int linei, month, year,iout;
10778:   int noffset=0; /* This is the offset if BOM data file */
10779:   char line[MAXLINE], linetmp[MAXLINE];
10780:   char stra[MAXLINE], strb[MAXLINE];
10781:   char *stratrunc;
10782: 
10783:   /* DummyV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
10784:   /* FixedV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
10785:   
10786:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
10787:   
10788:   if((fic=fopen(datafile,"r"))==NULL)    {
10789:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
10790:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
10791:   }
10792: 
10793:     /* Is it a BOM UTF-8 Windows file? */
10794:   /* First data line */
10795:   linei=0;
10796:   while(fgets(line, MAXLINE, fic)) {
10797:     noffset=0;
10798:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
10799:     {
10800:       noffset=noffset+3;
10801:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
10802:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
10803:       fflush(ficlog); return 1;
10804:     }
10805:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
10806:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
10807:     {
10808:       noffset=noffset+2;
10809:       printf("# Error Data file '%s'  is a huge UTF16BE BOM file, please convert to UTF8 or ascii file (for example with dos2unix) and rerun.\n",datafile);fflush(stdout);
10810:       fprintf(ficlog,"# Error Data file '%s'  is a huge UTF16BE BOM file, please convert to UTF8 or ascii file (for example with dos2unix) and rerun.\n",datafile);
10811:       fflush(ficlog); return 1;
10812:     }
10813:     else if( line[0] == 0 && line[1] == 0)
10814:     {
10815:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
10816: 	noffset=noffset+4;
10817: 	printf("# Error Data file '%s'  is a huge UTF16BE BOM file, please convert to UTF8 or ascii file (for example with dos2unix) and rerun.\n",datafile);fflush(stdout);
10818: 	fprintf(ficlog,"# Error Data file '%s'  is a huge UTF16BE BOM file, please convert to UTF8 or ascii file (for example with dos2unix) and rerun.\n",datafile);
10819: 	fflush(ficlog); return 1;
10820:       }
10821:     } else{
10822:       ;/*printf(" Not a BOM file\n");*/
10823:     }
10824:         /* If line starts with a # it is a comment */
10825:     if (line[noffset] == '#') {
10826:       linei=linei+1;
10827:       break;
10828:     }else{
10829:       break;
10830:     }
10831:   }
10832:   fclose(fic);
10833:   if((fic=fopen(datafile,"r"))==NULL)    {
10834:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
10835:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
10836:   }
10837:   /* Not a Bom file */
10838:   
10839:   i=1;
10840:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
10841:     linei=linei+1;
10842:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
10843:       if(line[j] == '\t')
10844: 	line[j] = ' ';
10845:     }
10846:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
10847:       ;
10848:     };
10849:     line[j+1]=0;  /* Trims blanks at end of line */
10850:     if(line[0]=='#'){
10851:       fprintf(ficlog,"Comment line\n%s\n",line);
10852:       printf("Comment line\n%s\n",line);
10853:       continue;
10854:     }
10855:     trimbb(linetmp,line); /* Trims multiple blanks in line */
10856:     strcpy(line, linetmp);
10857:     
10858:     /* Loops on waves */
10859:     for (j=maxwav;j>=1;j--){
10860:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
10861: 	cutv(stra, strb, line, ' '); 
10862: 	if(strb[0]=='.') { /* Missing value */
10863: 	  lval=-1;
10864: 	  cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
10865: 	  cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
10866: 	  if(isalpha(strb[1])) { /* .m or .d Really Missing value */
10867: 	    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);
10868: 	    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);
10869: 	    return 1;
10870: 	  }
10871: 	}else{
10872: 	  errno=0;
10873: 	  /* what_kind_of_number(strb); */
10874: 	  dval=strtod(strb,&endptr); 
10875: 	  /* if( strb[0]=='\0' || (*endptr != '\0')){ */
10876: 	  /* if(strb != endptr && *endptr == '\0') */
10877: 	  /*    dval=dlval; */
10878: 	  /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
10879: 	  if( strb[0]=='\0' || (*endptr != '\0')){
10880: 	    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);
10881: 	    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);
10882: 	    return 1;
10883: 	  }
10884: 	  cotqvar[j][iv][i]=dval; 
10885: 	  cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
10886: 	}
10887: 	strcpy(line,stra);
10888:       }/* end loop ntqv */
10889:       
10890:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
10891: 	cutv(stra, strb, line, ' '); 
10892: 	if(strb[0]=='.') { /* Missing value */
10893: 	  lval=-1;
10894: 	}else{
10895: 	  errno=0;
10896: 	  lval=strtol(strb,&endptr,10); 
10897: 	  /*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
10898: 	  if( strb[0]=='\0' || (*endptr != '\0')){
10899: 	    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);
10900: 	    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);
10901: 	    return 1;
10902: 	  }
10903: 	}
10904: 	if(lval <-1 || lval >1){
10905: 	  printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
10906:  Should be a value of %d(nth) covariate of wave %d (0 should be the value for the reference and 1\n \
10907:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
10908:  For example, for multinomial values like 1, 2 and 3,\n			\
10909:  build V1=0 V2=0 for the reference value (1),\n				\
10910:         V1=1 V2=0 for (2) \n						\
10911:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
10912:  output of IMaCh is often meaningless.\n				\
10913:  Exiting.\n",lval,linei, i,line,iv,j);
10914: 	  fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
10915:  Should be a value of %d(nth) covariate of wave %d (0 should be the value for the reference and 1\n \
10916:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
10917:  For example, for multinomial values like 1, 2 and 3,\n			\
10918:  build V1=0 V2=0 for the reference value (1),\n				\
10919:         V1=1 V2=0 for (2) \n						\
10920:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
10921:  output of IMaCh is often meaningless.\n				\
10922:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
10923: 	  return 1;
10924: 	}
10925: 	cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
10926: 	strcpy(line,stra);
10927:       }/* end loop ntv */
10928:       
10929:       /* Statuses  at wave */
10930:       cutv(stra, strb, line, ' '); 
10931:       if(strb[0]=='.') { /* Missing value */
10932: 	lval=-1;
10933:       }else{
10934: 	errno=0;
10935: 	lval=strtol(strb,&endptr,10); 
10936: 	/*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
10937: 	if( strb[0]=='\0' || (*endptr != '\0' )){
10938: 	  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);
10939: 	  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);
10940: 	  return 1;
10941: 	}else if( lval==0 || lval > nlstate+ndeath){
10942: 	  printf("Error in data around '%s' at line number %d for individual %d, '%s'\n Should be a state at wave %d. A state should be 1 to %d and not %ld.\n Fix your data file '%s'!  Exiting.\n", strb, linei,i,line,j,nlstate+ndeath, lval, datafile);fflush(stdout);
10943: 	  fprintf(ficlog,"Error in data around '%s' at line number %d for individual %d, '%s'\n Should be a state at wave %d. A state should be 1 to %d and not %ld.\n Fix your data file '%s'!  Exiting.\n", strb, linei,i,line,j,nlstate+ndeath, lval, datafile); fflush(ficlog);
10944: 	  return 1;
10945: 	}
10946:       }
10947:       
10948:       s[j][i]=lval;
10949:       
10950:       /* Date of Interview */
10951:       strcpy(line,stra);
10952:       cutv(stra, strb,line,' ');
10953:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
10954:       }
10955:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
10956: 	month=99;
10957: 	year=9999;
10958:       }else{
10959: 	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);
10960: 	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);
10961: 	return 1;
10962:       }
10963:       anint[j][i]= (double) year; 
10964:       mint[j][i]= (double)month;
10965:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
10966:       /* 	printf("Warning reading data around '%s' at line number %d for individual %d, '%s'\nThe date of interview (%2d/%4d) at wave %d occurred before the date of birth (%2d/%4d).\n",strb, linei,i, line, mint[j][i],anint[j][i], moisnais[i],annais[i]); */
10967:       /* 	fprintf(ficlog,"Warning reading data around '%s' at line number %d for individual %d, '%s'\nThe date of interview (%2d/%4d) at wave %d occurred before the date of birth (%2d/%4d).\n",strb, linei,i, line, mint[j][i],anint[j][i], moisnais[i],annais[i]); */
10968:       /* } */
10969:       strcpy(line,stra);
10970:     } /* End loop on waves */
10971:     
10972:     /* Date of death */
10973:     cutv(stra, strb,line,' '); 
10974:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
10975:     }
10976:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
10977:       month=99;
10978:       year=9999;
10979:     }else{
10980:       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);
10981:       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);
10982:       return 1;
10983:     }
10984:     andc[i]=(double) year; 
10985:     moisdc[i]=(double) month; 
10986:     strcpy(line,stra);
10987:     
10988:     /* Date of birth */
10989:     cutv(stra, strb,line,' '); 
10990:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
10991:     }
10992:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
10993:       month=99;
10994:       year=9999;
10995:     }else{
10996:       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);
10997:       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);
10998:       return 1;
10999:     }
11000:     if (year==9999) {
11001:       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);
11002:       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);
11003:       return 1;
11004:       
11005:     }
11006:     annais[i]=(double)(year);
11007:     moisnais[i]=(double)(month);
11008:     for (j=1;j<=maxwav;j++){
11009:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
11010: 	printf("Warning reading data around '%s' at line number %d for individual %d, '%s'\nThe date of interview (%2d/%4d) at wave %d occurred before the date of birth (%2d/%4d).\n",strb, linei,i, line, (int)mint[j][i],(int)anint[j][i], j,(int)moisnais[i],(int)annais[i]);
11011: 	fprintf(ficlog,"Warning reading data around '%s' at line number %d for individual %d, '%s'\nThe date of interview (%2d/%4d) at wave %d occurred before the date of birth (%2d/%4d).\n",strb, linei,i, line, (int)mint[j][i],(int)anint[j][i], j, (int)moisnais[i],(int)annais[i]);
11012:       }
11013:     }
11014: 
11015:     strcpy(line,stra);
11016:     
11017:     /* Sample weight */
11018:     cutv(stra, strb,line,' '); 
11019:     errno=0;
11020:     dval=strtod(strb,&endptr); 
11021:     if( strb[0]=='\0' || (*endptr != '\0')){
11022:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
11023:       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);
11024:       fflush(ficlog);
11025:       return 1;
11026:     }
11027:     weight[i]=dval; 
11028:     strcpy(line,stra);
11029:     
11030:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
11031:       cutv(stra, strb, line, ' '); 
11032:       if(strb[0]=='.') { /* Missing value */
11033: 	lval=-1;
11034: 	coqvar[iv][i]=NAN; 
11035: 	covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
11036:       }else{
11037: 	errno=0;
11038: 	/* what_kind_of_number(strb); */
11039: 	dval=strtod(strb,&endptr);
11040: 	/* if(strb != endptr && *endptr == '\0') */
11041: 	/*   dval=dlval; */
11042: 	/* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
11043: 	if( strb[0]=='\0' || (*endptr != '\0')){
11044: 	  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);
11045: 	  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);
11046: 	  return 1;
11047: 	}
11048: 	coqvar[iv][i]=dval; 
11049: 	covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
11050:       }
11051:       strcpy(line,stra);
11052:     }/* end loop nqv */
11053:     
11054:     /* Covariate values */
11055:     for (j=ncovcol;j>=1;j--){
11056:       cutv(stra, strb,line,' '); 
11057:       if(strb[0]=='.') { /* Missing covariate value */
11058: 	lval=-1;
11059:       }else{
11060: 	errno=0;
11061: 	lval=strtol(strb,&endptr,10); 
11062: 	if( strb[0]=='\0' || (*endptr != '\0')){
11063: 	  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);
11064: 	  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);
11065: 	  return 1;
11066: 	}
11067:       }
11068:       if(lval <-1 || lval >1){
11069: 	printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
11070:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
11071:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
11072:  For example, for multinomial values like 1, 2 and 3,\n			\
11073:  build V1=0 V2=0 for the reference value (1),\n				\
11074:         V1=1 V2=0 for (2) \n						\
11075:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
11076:  output of IMaCh is often meaningless.\n				\
11077:  Exiting.\n",lval,linei, i,line,j);
11078: 	fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
11079:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
11080:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
11081:  For example, for multinomial values like 1, 2 and 3,\n			\
11082:  build V1=0 V2=0 for the reference value (1),\n				\
11083:         V1=1 V2=0 for (2) \n						\
11084:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
11085:  output of IMaCh is often meaningless.\n				\
11086:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
11087: 	return 1;
11088:       }
11089:       covar[j][i]=(double)(lval);
11090:       strcpy(line,stra);
11091:     }  
11092:     lstra=strlen(stra);
11093:     
11094:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
11095:       stratrunc = &(stra[lstra-9]);
11096:       num[i]=atol(stratrunc);
11097:     }
11098:     else
11099:       num[i]=atol(stra);
11100:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
11101:       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;}*/
11102:     
11103:     i=i+1;
11104:   } /* End loop reading  data */
11105:   
11106:   *imax=i-1; /* Number of individuals */
11107:   fclose(fic);
11108:   
11109:   return (0);
11110:   /* endread: */
11111:   printf("Exiting readdata: ");
11112:   fclose(fic);
11113:   return (1);
11114: }
11115: 
11116: void removefirstspace(char **stri){/*, char stro[]) {*/
11117:   char *p1 = *stri, *p2 = *stri;
11118:   while (*p2 == ' ')
11119:     p2++; 
11120:   /* while ((*p1++ = *p2++) !=0) */
11121:   /*   ; */
11122:   /* do */
11123:   /*   while (*p2 == ' ') */
11124:   /*     p2++; */
11125:   /* while (*p1++ == *p2++); */
11126:   *stri=p2; 
11127: }
11128: 
11129: int decoderesult( char resultline[], int nres)
11130: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
11131: {
11132:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
11133:   char resultsav[MAXLINE];
11134:   /* int resultmodel[MAXLINE]; */
11135:   /* int modelresult[MAXLINE]; */
11136:   char stra[80], strb[80], strc[80], strd[80],stre[80];
11137: 
11138:   removefirstspace(&resultline);
11139:   printf("decoderesult:%s\n",resultline);
11140: 
11141:   strcpy(resultsav,resultline);
11142:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
11143:   if (strlen(resultsav) >1){
11144:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
11145:   }
11146:   if(j == 0 && cptcovs== 0){ /* Resultline but no =  and no covariate in the model */
11147:     TKresult[nres]=0; /* Combination for the nresult and the model */
11148:     return (0);
11149:   }
11150:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
11151:     fprintf(ficlog,"ERROR: the number of variables in the resultline which is %d, differs from the number %d of single variables used in the model line, 1+age+%s.\n",j, cptcovs, model);fflush(ficlog);
11152:     printf("ERROR: the number of variables in the resultline which is %d, differs from the number %d of single variables used in the model line, 1+age+%s.\n",j, cptcovs, model);fflush(stdout);
11153:     if(j==0)
11154:       return 1;
11155:   }
11156:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
11157:     if(nbocc(resultsav,'=') >1){
11158:       cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' (stra is the rest of the resultline to be analyzed in the next loop *//*     resultsav= "V4=1 V5=25.1 V3=0" stra= "V5=25.1 V3=0" strb= "V4=1" */
11159:       /* If resultsav= "V4= 1 V5=25.1 V3=0" with a blank then strb="V4=" and stra="1 V5=25.1 V3=0" */
11160:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
11161:       /* If a blank, then strc="V4=" and strd='\0' */
11162:       if(strc[0]=='\0'){
11163:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
11164: 	fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
11165: 	return 1;
11166:       }
11167:     }else
11168:       cutl(strc,strd,resultsav,'=');
11169:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
11170:     
11171:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
11172:     Tvarsel[k]=atoi(strc);  /* 4 */ /* Tvarsel is the id of the kth covariate in the result line Tvarsel[1] in "V4=1.." is 4.*/
11173:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
11174:     /* cptcovsel++;     */
11175:     if (nbocc(stra,'=') >0)
11176:       strcpy(resultsav,stra); /* and analyzes it */
11177:   }
11178:   /* Checking for missing or useless values in comparison of current model needs */
11179:   /* Feeds resultmodel[nres][k1]=k2 for k1th product covariate with age in the model equation fed by the index k2 of the resutline*/
11180:   for(k1=1; k1<= cptcovt ;k1++){ /* Loop on MODEL LINE V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
11181:     if(Typevar[k1]==0){ /* Single covariate in model */
11182:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
11183:       match=0;
11184:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
11185: 	if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
11186: 	  modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
11187: 	  match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
11188: 	  break;
11189: 	}
11190:       }
11191:       if(match == 0){
11192: 	printf("Error in result line (Dummy single): V%d is missing in result: %s according to model=1+age+%s. Tvar[k1=%d]=%d is different from Tvarsel[k2=%d]=%d.\n",Tvar[k1], resultline, model,k1, Tvar[k1], k2, Tvarsel[k2]);
11193: 	fprintf(ficlog,"Error in result line (Dummy single): V%d is missing in result: %s according to model=1+age+%s\n",Tvar[k1], resultline, model);
11194: 	return 1;
11195:       }
11196:     }else if(Typevar[k1]==1){ /* Product with age We want to get the position k2 in the resultline of the product k1 in the model line*/
11197:       /* We feed resultmodel[k1]=k2; */
11198:       match=0;
11199:       for(k2=1; k2 <=j;k2++){/* Loop on resultline.  jth occurence of = signs in the result line. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
11200: 	if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
11201: 	  modelresult[nres][k2]=k1;/* we found a Vn=1 corrresponding to Vn*age in the model modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
11202: 	  resultmodel[nres][k1]=k2; /* Added here */
11203: 	  /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
11204: 	  match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
11205: 	  break;
11206: 	}
11207:       }
11208:       if(match == 0){
11209: 	printf("Error in result line (Product with age): V%d is missing in result: %s according to model=1+age+%s (Tvarsel[k2=%d]=%d)\n",Tvar[k1], resultline, model, k2, Tvarsel[k2]);
11210: 	fprintf(ficlog,"Error in result line (Product with age): V%d is missing in result: %s according to model=1+age+%s (Tvarsel[k2=%d]=%d)\n",Tvar[k1], resultline, model, k2, Tvarsel[k2]);
11211:       return 1;
11212:       }
11213:     }else if(Typevar[k1]==2 || Typevar[k1]==3){ /* Product with or without age. We want to get the position in the resultline of the product in the model line*/
11214:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
11215:       match=0;
11216:       /* printf("Decoderesult very first Product Tvardk[k1=%d][1]=%d Tvardk[k1=%d][2]=%d V%d * V%d\n",k1,Tvardk[k1][1],k1,Tvardk[k1][2],Tvardk[k1][1],Tvardk[k1][2]); */
11217:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
11218: 	if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
11219: 	  /* modelresult[k2]=k1; */
11220: 	  /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
11221: 	  match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
11222: 	}
11223:       }
11224:       if(match == 0){
11225: 	printf("Error in result line (Product without age first variable or double product with age): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][1], resultline, model);
11226: 	fprintf(ficlog,"Error in result line (Product without age first variable or double product with age): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][1], resultline, model);
11227: 	return 1;
11228:       }
11229:       match=0;
11230:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
11231: 	if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
11232: 	  /* modelresult[k2]=k1;*/
11233: 	  /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
11234: 	  match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
11235: 	  break;
11236: 	}
11237:       }
11238:       if(match == 0){
11239: 	printf("Error in result line (Product without age second variable or double product with age): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][2], resultline, model);
11240: 	fprintf(ficlog,"Error in result line (Product without age second variable or double product with age): V%d is missing in result : %s according to model=1+age+%s\n",Tvardk[k1][2], resultline, model);
11241: 	return 1;
11242:       }
11243:     }/* End of testing */
11244:   }/* End loop cptcovt */
11245:   /* Checking for missing or useless values in comparison of current model needs */
11246:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
11247:   for(k2=1; k2 <=j;k2++){ /* j or cptcovs is the number of single covariates used either in the model line as well as in the result line (dummy or quantitative)
11248: 			   * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
11249:     match=0;
11250:     for(k1=1; k1<= cptcovt ;k1++){ /* loop on model: model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
11251:       if(Typevar[k1]==0){ /* Single only */
11252: 	if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4  What if a product?  */
11253: 	  resultmodel[nres][k1]=k2;  /* k1th position in the model equation corresponds to k2th position in the result line. resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
11254: 	  modelresult[nres][k2]=k1; /* k1th position in the model equation corresponds to k2th position in the result line. modelresult[1]=2 modelresult[2]=1  modelresult[3]=3  remodelresult[4]=6 modelresult[5]=9 */
11255: 	  ++match;
11256: 	}
11257:       }
11258:     }
11259:     if(match == 0){
11260:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
11261:       fprintf(ficlog,"Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
11262:       return 1;
11263:     }else if(match > 1){
11264:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
11265:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
11266:       return 1;
11267:     }
11268:   }
11269:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
11270:   /* We need to deduce which combination number is chosen and save quantitative values */
11271:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
11272:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
11273:   /* should correspond to the combination 6 of dummy: V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 1*1 + 0*2 + 1*4 = 5 + (1offset) = 6*/
11274:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
11275:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
11276:   /*    1 0 0 0 */
11277:   /*    2 1 0 0 */
11278:   /*    3 0 1 0 */ 
11279:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
11280:   /*    5 0 0 1 */
11281:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
11282:   /*    7 0 1 1 */
11283:   /*    8 1 1 1 */
11284:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
11285:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
11286:   /* V5*age V5 known which value for nres?  */
11287:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
11288:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* cptcovt number of covariates (excluding 1 and age or age*age) in the MODEL equation.
11289: 						   * loop on position k1 in the MODEL LINE */
11290:     /* k counting number of combination of single dummies in the equation model */
11291:     /* k4 counting single dummies in the equation model */
11292:     /* k4q counting single quantitatives in the equation model */
11293:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Dummy and Single, fixed or timevarying, k1 is sorting according to MODEL, but k3 to resultline */
11294:        /* k4+1= (not always if quant in model) position in the resultline V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) */
11295:       /* modelresult[k3]=k1: k3th position in the result line corresponds to the k1 position in the model line (doesn't work with products)*/
11296:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
11297:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
11298:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
11299:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
11300:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
11301:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
11302:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
11303:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
11304:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
11305:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
11306:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
11307:       k2=(int)Tvarsel[k3]; /* from position k3 in resultline get name k2: nres=1 k1=2=>k3=1 Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 (V4); k1=3=>k3=2 Tvarsel[2]=3 (V3)*/
11308:       k+=Tvalsel[k3]*pow(2,k4);  /* nres=1 k1=2 Tvalsel[1]=1 (V4=1); k1=3 k3=2 Tvalsel[2]=0 (V3=0) */
11309:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
11310:       /* Tinvresult[nres][4]=1 */
11311:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
11312:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
11313:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
11314:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
11315:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
11316:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
11317:       /* printf("Decoderesult Dummy k=%d, k1=%d precov[nres=%d][k1=%d]=%.f V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k1, nres, k1,precov[nres][k1], k2, k3, (int)Tvalsel[k3], k4); */
11318:       k4++;;
11319:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
11320:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
11321:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
11322:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
11323:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
11324:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
11325:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
11326:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
11327:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
11328:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
11329:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
11330:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
11331:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
11332:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
11333:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
11334:       precov[nres][k1]=Tvalsel[k3q];
11335:       /* printf("Decoderesult Quantitative nres=%d,precov[nres=%d][k1=%d]=%.f V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, nres, k1,precov[nres][k1], k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]); */
11336:       k4q++;;
11337:     }else if( Dummy[k1]==2 ){ /* For dummy with age product "V2+V3+V4+V6+V7+V6*V2+V7*V2+V6*V3+V7*V3+V6*V4+V7*V4+age*V2+age*V3+age*V4+age*V6+age*V7+age*V6*V2+age*V6*V3+age*V7*V3+age*V6*V4+age*V7*V4\r"*/
11338:       /* Tvar[k1]; */ /* Age variable */ /* 17 age*V6*V2 ?*/
11339:       /* Wrong we want the value of variable name Tvar[k1] */
11340:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
11341: 	precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
11342:       /* printf("Decoderesult Quantitative or Dummy (not with age) nres=%d k1=%d precov[nres=%d][k1=%d]=%.f V%d(=%.f) * V%d(=%.f) \n",nres, k1, nres, k1,precov[nres][k1], Tvardk[k1][1], TinvDoQresult[nres][Tvardk[k1][1]], Tvardk[k1][2], TinvDoQresult[nres][Tvardk[k1][2]]); */
11343:       }else{
11344: 	k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
11345: 	k2=(int)Tvarsel[k3]; /* nres=1 k1=2=>k3=1 Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 (V4); k1=3=>k3=2 Tvarsel[2]=3 (V3)*/
11346: 	TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
11347: 	precov[nres][k1]=Tvalsel[k3];
11348:       }
11349:       /* printf("Decoderesult Dummy with age k=%d, k1=%d precov[nres=%d][k1=%d]=%.f Tvar[%d]=V%d k2=Tvarsel[%d]=%d Tvalsel[%d]=%d\n",k, k1, nres, k1,precov[nres][k1], k1, Tvar[k1], k3,(int)Tvarsel[k3], k3, (int)Tvalsel[k3]); */
11350:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
11351:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
11352: 	precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
11353:       /* printf("Decoderesult Quantitative or Dummy (not with age) nres=%d k1=%d precov[nres=%d][k1=%d]=%.f V%d(=%.f) * V%d(=%.f) \n",nres, k1, nres, k1,precov[nres][k1], Tvardk[k1][1], TinvDoQresult[nres][Tvardk[k1][1]], Tvardk[k1][2], TinvDoQresult[nres][Tvardk[k1][2]]); */
11354:       }else{
11355: 	k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
11356: 	k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
11357: 	TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
11358: 	precov[nres][k1]=Tvalsel[k3q];
11359:       }
11360:       /* printf("Decoderesult Quantitative with age nres=%d, k1=%d, precov[nres=%d][k1=%d]=%f Tvar[%d]=V%d V(k2q=%d)= Tvarsel[%d]=%d, Tvalsel[%d]=%f\n",nres, k1, nres, k1,precov[nres][k1], k1,  Tvar[k1], k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]); */
11361:     }else if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
11362:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
11363:       /* printf("Decoderesult Quantitative or Dummy (not with age) nres=%d k1=%d precov[nres=%d][k1=%d]=%.f V%d(=%.f) * V%d(=%.f) \n",nres, k1, nres, k1,precov[nres][k1], Tvardk[k1][1], TinvDoQresult[nres][Tvardk[k1][1]], Tvardk[k1][2], TinvDoQresult[nres][Tvardk[k1][2]]); */
11364:     }else{
11365:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
11366:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
11367:     }
11368:   }
11369:   
11370:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
11371:   return (0);
11372: }
11373: 
11374: int decodemodel( char model[], int lastobs)
11375:  /**< This routine decodes the model and returns:
11376: 	* Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
11377: 	* - nagesqr = 1 if age*age in the model, otherwise 0.
11378: 	* - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
11379: 	* - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
11380: 	* - cptcovage number of covariates with age*products =2
11381: 	* - cptcovs number of simple covariates
11382: 	* ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
11383: 	* - 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
11384: 	*     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
11385: 	* - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
11386: 	* - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
11387: 	*    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
11388: 	* - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
11389: 	*/
11390: /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 */
11391: {
11392:   int i, j, k, ks, v;
11393:   int n,m;
11394:   int  j1, k1, k11, k12, k2, k3, k4;
11395:   char modelsav[300];
11396:   char stra[300], strb[300], strc[300], strd[300],stre[300],strf[300];
11397:   char *strpt;
11398:   int  **existcomb;
11399:   
11400:   existcomb=imatrix(1,NCOVMAX,1,NCOVMAX);
11401:   for(i=1;i<=NCOVMAX;i++)
11402:     for(j=1;j<=NCOVMAX;j++)
11403:       existcomb[i][j]=0;
11404:     
11405:   /*removespace(model);*/
11406:   if (strlen(model) >1){ /* If there is at least 1 covariate */
11407:     j=0, j1=0, k1=0, k12=0, k2=-1, ks=0, cptcovn=0;
11408:     if (strstr(model,"AGE") !=0){
11409:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
11410:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
11411:       return 1;
11412:     }
11413:     if (strstr(model,"v") !=0){
11414:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
11415:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
11416:       return 1;
11417:     }
11418:     strcpy(modelsav,model); 
11419:     if ((strpt=strstr(model,"age*age")) !=0){
11420:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
11421:       if(strpt != model){
11422: 	printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
11423:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
11424:  corresponding column of parameters.\n",model);
11425: 	fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
11426:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
11427:  corresponding column of parameters.\n",model); fflush(ficlog);
11428: 	return 1;
11429:       }
11430:       nagesqr=1;
11431:       if (strstr(model,"+age*age") !=0)
11432: 	substrchaine(modelsav, model, "+age*age");
11433:       else if (strstr(model,"age*age+") !=0)
11434: 	substrchaine(modelsav, model, "age*age+");
11435:       else 
11436: 	substrchaine(modelsav, model, "age*age");
11437:     }else
11438:       nagesqr=0;
11439:     if (strlen(modelsav) >1){ /* V2 +V3 +V4 +V6 +V7 +V6*V2 +V7*V2 +V6*V3 +V7*V3 +V6*V4 +V7*V4 +age*V2 +age*V3 +age*V4 +age*V6 +age*V7 +age*V6*V2 +V7*V2 +age*V6*V3 +age*V7*V3 +age*V6*V4 +age*V7*V4 */
11440:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
11441:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
11442:       cptcovs=0; /**<  Number of simple covariates V1 +V1*age +V3 +V3*V4 +age*age => V1 + V3 =4+1-3=2  Wrong */
11443:       cptcovt= j+1; /* Number of total covariates in the model, not including
11444: 		     * cst, age and age*age 
11445: 		     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
11446:       /* including age products which are counted in cptcovage.
11447:        * but the covariates which are products must be treated 
11448:        * separately: ncovn=4- 2=2 (V1+V3). */
11449:       cptcovprod=0; /**< Number of products  V1*V2 +v3*age = 2 */
11450:       cptcovdageprod=0; /* Number of doouble products with age age*Vn*VM or Vn*age*Vm or Vn*Vm*age */
11451:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
11452:       cptcovprodage=0;
11453:       /* cptcovprodage=nboccstr(modelsav,"age");*/
11454:       
11455:       /*   Design
11456:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
11457:        *  <          ncovcol=8                >
11458:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
11459:        *   k=  1    2      3       4     5       6      7        8
11460:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
11461:        *  covar[k,i], are for fixed covariates, value of kth covariate if not including age for individual i:
11462:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
11463:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
11464:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
11465:        *  Tage[++cptcovage]=k
11466:        *       if products, new covar are created after ncovcol + nqv (quanti fixed) with k1
11467:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
11468:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
11469:        *  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
11470:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
11471:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
11472:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
11473:        *  <          ncovcol=8  8 fixed covariate. Additional starts at 9 (V5*V6) and 10(V7*V8)              >
11474:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
11475:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
11476:        *     Tvard[k]= 2    1      3       3    10      11      8        8    5    6    7   8
11477:        * p Tvar[1]@12={2,   1,     3,      3,   9,     10,     8,       8}
11478:        * p Tprod[1]@2={                         6, 5}
11479:        *p Tvard[1][1]@4= {7, 8, 5, 6}
11480:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
11481:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
11482:        *How to reorganize? Tvars(orted)
11483:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
11484:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
11485:        *       {2,   1,     4,      8,    5,      6,     3,       7}
11486:        * Struct []
11487:        */
11488:       
11489:       /* This loop fills the array Tvar from the string 'model'.*/
11490:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
11491:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
11492:       /* 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
11493:       /* 	k=3 V4 Tvar[k=3]= 4 (from V4) */
11494:       /* 	k=2 V1 Tvar[k=2]= 1 (from V1) */
11495:       /* 	k=1 Tvar[1]=2 (from V2) */
11496:       /* 	k=5 Tvar[5] */
11497:       /* for (k=1; k<=cptcovn;k++) { */
11498:       /* 	cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
11499:       /* 	} */
11500:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
11501:       /*
11502:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
11503:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
11504:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
11505:       }
11506:       cptcovage=0;
11507: 
11508:       /* First loop in order to calculate */
11509:       /* for age*VN*Vm
11510:        * Provides, Typevar[k], Tage[cptcovage], existcomb[n][m], FixedV[ncovcolt+k12]
11511:        * Tprod[k1]=k  Tposprod[k]=k1;    Tvard[k1][1] =m;
11512:       */
11513:       /* Needs  FixedV[Tvardk[k][1]] */
11514:       /* For others:
11515:        * Sets 	Typevar[k];
11516:        * Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
11517:        *	Tposprod[k]=k11;
11518:        *	Tprod[k11]=k;
11519:        *	Tvardk[k][1] =m;
11520:        * Needs FixedV[Tvardk[k][1]] == 0
11521:       */
11522:       
11523:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
11524: 	cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
11525: 					 modelsav==V2+V1+V5*age+V4+V3*age strb=V3*age stra=V2+V1V5*age+V4 */	/* <model> "V5+V4+V3+V4*V3+V5*age+V1*age+V1" strb="V5" stra="V4+V3+V4*V3+V5*age+V1*age+V1" */
11526: 	if (nbocc(modelsav,'+')==0)
11527: 	  strcpy(strb,modelsav); /* and analyzes it */
11528: 	/*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
11529: 	/*scanf("%d",i);*/
11530: 	if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age OR double product with age strb=age*V6*V2 or V6*V2*age or V6*age*V2 */
11531: 	  cutl(strc,strd,strb,'*'); /**< k=1 strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 OR strb=age*V6*V2 strc=V6*V2 strd=age OR c=V2*age OR c=age*V2  */
11532: 	  if(strchr(strc,'*')) { /**< Model with age and DOUBLE product: allowed since 0.99r44, strc=V6*V2 or V2*age or age*V2, strd=age or V6 or V6   */
11533: 	    Typevar[k]=3;  /* 3 for age and double product age*Vn*Vm varying of fixed */
11534:             if(strstr(strc,"age")!=0) { /* It means that strc=V2*age or age*V2 and thus that strd=Vn */
11535:               cutl(stre,strf,strc,'*') ; /* strf=age or Vm, stre=Vm or age. If strc=V6*V2 then strf=V6 and stre=V2 */
11536: 	      strcpy(strc,strb); /* save strb(=age*Vn*Vm) into strc */
11537: 	      /* We want strb=Vn*Vm */
11538:               if(strcmp(strf,"age")==0){ /* strf is "age" so that stre=Vm =V2 . */
11539:                 strcpy(strb,strd);
11540:                 strcat(strb,"*");
11541:                 strcat(strb,stre);
11542:               }else{  /* strf=Vm  If strf=V6 then stre=V2 */
11543:                 strcpy(strb,strf);
11544:                 strcat(strb,"*");
11545:                 strcat(strb,stre);
11546:                 strcpy(strd,strb); /* in order for strd to not be "age"  for next test (will be Vn*Vm */
11547:               }
11548: 	      /* printf("DEBUG FIXED k=%d, Tage[k]=%d, Tvar[Tage[k]=%d,FixedV[Tvar[Tage[k]]]=%d\n",k,Tage[k],Tvar[Tage[k]],FixedV[Tvar[Tage[k]]]); */
11549: 	      /* FixedV[Tvar[Tage[k]]]=0; /\* HERY not sure if V7*V4*age Fixed might not exist  yet*\/ */
11550:             }else{  /* strc=Vn*Vm (and strd=age) and should be strb=Vn*Vm but want to keep original strb double product  */
11551: 	      strcpy(stre,strb); /* save full b in stre */
11552: 	      strcpy(strb,strc); /* save short c in new short b for next block strb=Vn*Vm*/
11553: 	      strcpy(strf,strc); /* save short c in new short f */
11554:               cutl(strc,strd,strf,'*'); /* We get strd=Vn and strc=Vm for next block (strb=Vn*Vm)*/
11555: 	      /* strcpy(strc,stre);*/ /* save full e in c for future */
11556:             }
11557:             cptcovdageprod++; /* double product with age  Which product is it? */
11558:             /* strcpy(strb,strc);  /\* strb was age*V6*V2 or V6*V2*age or V6*age*V2 IS now V6*V2 or V2*age or age*V2 *\/ */
11559:             /* cutl(strc,strd,strb,'*'); /\* strd=  V6    or   V2     or    age and  strc=  V2 or    age or    V2 *\/ */
11560: 	    cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
11561: 	    n=atoi(stre);
11562: 	    cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
11563: 	    m=atoi(strc);
11564: 	    cptcovage++; /* Counts the number of covariates which include age as a product */
11565: 	    Tage[cptcovage]=k; /* For age*V3*V2 gives the position in model of covariates associated with age Tage[1]=6 HERY too*/
11566: 	    if(existcomb[n][m] == 0){
11567: 	      /*  r /home/brouard/Documents/Recherches/REVES/Zachary/Zach-2022/Feinuo_Sun/Feinuo-threeway/femV12V15_3wayintNBe.imach */
11568: 	      printf("Warning in model combination V%d*V%d should exist in the model before adding V%d*V%d*age !\n",n,m,n,m);
11569: 	      fprintf(ficlog,"Warning in model combination V%d*V%d should exist in the model before adding V%d*V%d*age !\n",n,m,n,m);
11570: 	      fflush(ficlog);
11571: 	      k1++;  /* The combination Vn*Vm will be in the model so we create it at k1 */
11572: 	      k12++;
11573: 	      existcomb[n][m]=k1;
11574: 	      existcomb[m][n]=k1;
11575: 	      Tvar[k]=ncovcol+nqv+ntv+nqtv+k1;
11576: 	      Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2+ age*V6*V3 Gives the k position of the k1 double product Vn*Vm or age*Vn*Vm*/
11577: 	      Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 Gives the k1 double product  Vn*Vm or age*Vn*Vm at the k position */
11578: 	      Tvard[k1][1] =m; /* m 1 for V1*/
11579: 	      Tvardk[k][1] =m; /* m 1 for V1*/
11580: 	      Tvard[k1][2] =n; /* n 4 for V4*/
11581: 	      Tvardk[k][2] =n; /* n 4 for V4*/
11582: /*	      Tvar[Tage[cptcovage]]=k1;*/ /* Tvar[6=age*V3*V2]=9 (new fixed covariate) */ /* We don't know about Fixed yet HERE */
11583: 	      if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){ /* If the product is a fixed covariate then we feed the new column with Vn*Vm */
11584: 		for (i=1; i<=lastobs;i++){/* For fixed product */
11585: 		  /* Computes the new covariate which is a product of
11586: 		     covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
11587: 		  covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
11588: 		}
11589: 		cptcovprodage++; /* Counting the number of fixed covariate with age */
11590: 		FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
11591: 		k12++;
11592: 		FixedV[ncovcolt+k12]=0;
11593: 	      }else{ /*End of FixedV */
11594: 		cptcovprodvage++; /* Counting the number of varying covariate with age */
11595: 		FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
11596: 		k12++;
11597: 		FixedV[ncovcolt+k12]=1;
11598: 	      }
11599: 	    }else{  /* k1 Vn*Vm already exists */
11600: 	      k11=existcomb[n][m];
11601: 	      Tposprod[k]=k11; /* OK */
11602: 	      Tvar[k]=Tvar[Tprod[k11]]; /* HERY */
11603: 	      Tvardk[k][1]=m;
11604: 	      Tvardk[k][2]=n;
11605: 	      if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){ /* If the product is a fixed covariate then we feed the new column with Vn*Vm */
11606: 		/*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
11607: 		cptcovprodage++; /* Counting the number of fixed covariate with age */
11608: 		/*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
11609: 		Tvar[Tage[cptcovage]]=k1;
11610: 		FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
11611: 		k12++;
11612: 		FixedV[ncovcolt+k12]=0;
11613: 	      }else{ /* Already exists but time varying (and age) */
11614: 		/*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
11615: 		/*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
11616: 		/* Tvar[Tage[cptcovage]]=k1; */
11617: 		cptcovprodvage++;
11618: 		FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
11619: 		k12++;
11620: 		FixedV[ncovcolt+k12]=1;
11621: 	      }
11622: 	    }
11623: 	    /* Tage[cptcovage]=k;  /\*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
11624: 	    /* Tvar[k]=k11; /\* HERY *\/ */
11625: 	  } else {/* simple product strb=age*Vn so that c=Vn and d=age, or strb=Vn*age so that c=age and d=Vn, or b=Vn*Vm so that c=Vm and d=Vn */
11626:             cptcovprod++;
11627:             if (strcmp(strc,"age")==0) { /**< Model includes age: strb= Vn*age c=age d=Vn*/
11628:               /* covar is not filled and then is empty */
11629:               cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
11630:               Tvar[k]=atoi(stre);  /* V2+V1+V5*age+V4+V3*age Tvar[5]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
11631:               Typevar[k]=1;  /* 1 for age product */
11632:               cptcovage++; /* Counts the number of covariates which include age as a product */
11633:               Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
11634: 	      if( FixedV[Tvar[k]] == 0){
11635: 		cptcovprodage++; /* Counting the number of fixed covariate with age */
11636: 	      }else{
11637: 		cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
11638: 	      }
11639:               /*printf("stre=%s ", stre);*/
11640:             } else if (strcmp(strd,"age")==0) { /* strb= age*Vn c=Vn */
11641:               cutl(stre,strb,strc,'V');
11642:               Tvar[k]=atoi(stre);
11643:               Typevar[k]=1;  /* 1 for age product */
11644:               cptcovage++;
11645:               Tage[cptcovage]=k;
11646: 	      if( FixedV[Tvar[k]] == 0){
11647: 		cptcovprodage++; /* Counting the number of fixed covariate with age */
11648: 	      }else{
11649: 		cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
11650: 	      }
11651:             }else{ /*  for product Vn*Vm */
11652: 	      Typevar[k]=2;  /* 2 for product Vn*Vm */
11653: 	      cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
11654: 	      n=atoi(stre);
11655: 	      cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
11656: 	      m=atoi(strc);
11657: 	      k1++;
11658: 	      cptcovprodnoage++;
11659: 	      if(existcomb[n][m] != 0 || existcomb[m][n] != 0){
11660: 		printf("Warning in model combination V%d*V%d already exists in the model in position k1=%d!\n",n,m,existcomb[n][m]);
11661: 		fprintf(ficlog,"Warning in model combination V%d*V%d already exists in the model in position k1=%d!\n",n,m,existcomb[n][m]);
11662: 		fflush(ficlog);
11663: 		k11=existcomb[n][m];
11664: 		Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
11665: 		Tposprod[k]=k11;
11666: 		Tprod[k11]=k;
11667: 		Tvardk[k][1] =m; /* m 1 for V1*/
11668: 		/* Tvard[k11][1] =m; /\* n 4 for V4*\/ */
11669: 		Tvardk[k][2] =n; /* n 4 for V4*/		
11670: 		/* Tvard[k11][2] =n; /\* n 4 for V4*\/ */
11671: 	      }else{ /* combination Vn*Vm doesn't exist we create it (no age)*/
11672: 		existcomb[n][m]=k1;
11673: 		existcomb[m][n]=k1;
11674: 		Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
11675: 						    because this model-covariate is a construction we invent a new column
11676: 						    which is after existing variables ncovcol+nqv+ntv+nqtv + k1
11677: 						    If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
11678: 						    thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
11679: 						    Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
11680: 		/* Please remark that the new variables are model dependent */
11681: 		/* If we have 4 variable but the model uses only 3, like in
11682: 		 * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
11683: 		 *  k=     1     2      3   4     5        6        7       8
11684: 		 * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
11685: 		 * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
11686: 		 * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
11687: 		 */
11688: 		/* We need to feed some variables like TvarVV, but later on next loop because of ncovv (k2) is not correct */
11689: 		Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 +V6*V2*age  */
11690: 		Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
11691: 		Tvard[k1][1] =m; /* m 1 for V1*/
11692: 		Tvardk[k][1] =m; /* m 1 for V1*/
11693: 		Tvard[k1][2] =n; /* n 4 for V4*/
11694: 		Tvardk[k][2] =n; /* n 4 for V4*/
11695: 		k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
11696: 		/* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
11697: 		/* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
11698: 		/*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
11699: 		/*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
11700: 		if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){ /* If the product is a fixed covariate then we feed the new column with Vn*Vm */
11701: 		  for (i=1; i<=lastobs;i++){/* For fixed product */
11702: 		    /* Computes the new covariate which is a product of
11703: 		       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
11704: 		    covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
11705: 		  }
11706: 		  /* TvarVV[k2]=n; */
11707: 		  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
11708: 		  /* TvarVV[k2+1]=m; */
11709: 		  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
11710: 		}else{ /* not FixedV */
11711: 		  /* TvarVV[k2]=n; */
11712: 		  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
11713: 		  /* TvarVV[k2+1]=m; */
11714: 		  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
11715: 		}		  
11716: 	      }  /* End of creation of Vn*Vm if not created by age*Vn*Vm earlier  */
11717: 	    } /*  End of product Vn*Vm */
11718:           } /* End of age*double product or simple product */
11719: 	}else { /* not a product */
11720: 	  /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
11721: 	  /*  scanf("%d",i);*/
11722: 	  cutl(strd,strc,strb,'V');
11723: 	  ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
11724: 	  cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
11725: 	  Tvar[k]=atoi(strd);
11726: 	  Typevar[k]=0;  /* 0 for simple covariates */
11727: 	}
11728: 	strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
11729: 				/*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
11730: 				  scanf("%d",i);*/
11731:       } /* end of loop + on total covariates */
11732: 
11733:       
11734:     } /* end if strlen(modelsave == 0) age*age might exist */
11735:   } /* end if strlen(model == 0) */
11736:   cptcovs=cptcovt - cptcovdageprod - cptcovprod;/**<  Number of simple covariates V1 +V1*age +V3 +V3*V4 +age*age + age*v4*V3=> V1 + V3 =4+1-3=2  */
11737: 
11738:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
11739:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
11740:   
11741:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
11742:      printf("cptcovprod=%d ", cptcovprod);
11743:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
11744:      scanf("%d ",i);*/
11745: 
11746: 
11747: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
11748:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
11749: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
11750:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
11751:    k =           1    2   3     4       5       6      7      8        9
11752:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
11753:    Typevar[k]=   0    0   0     2       1       0      2      1        0
11754:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
11755:    Dummy[k]      1    0   0     0       3       1      1      2        3
11756: 	  Tmodelind[combination of covar]=k;
11757: */  
11758: /* Dispatching between quantitative and time varying covariates */
11759:   /* If Tvar[k] >ncovcol it is a product */
11760:   /* Tvar[k] is the value n of Vn with n varying for 1 to nvcol, or p  Vp=Vn*Vm for product */
11761: 	/* Computing effective variables, ie used by the model, that is from the cptcovt variables */
11762:   printf("Model=1+age+%s\n\
11763: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product, 3 for double product with age \n\
11764: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
11765: 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);
11766:   fprintf(ficlog,"Model=1+age+%s\n\
11767: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product, 3 for double product with age  \n\
11768: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
11769: 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);
11770:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
11771:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
11772: 
11773: 
11774:   /* Second loop for calculating  Fixed[k], Dummy[k]*/
11775: 
11776:   
11777:   for(k=1, ncovf=0, nsd=0, nsq=0, ncovv=0,ncovva=0,ncovvta=0, ncova=0, ncoveff=0, nqfveff=0, ntveff=0, nqtveff=0, ncovvt=0;k<=cptcovt; k++){ /* or cptocvt loop on k from model */
11778:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
11779:       Fixed[k]= 0;
11780:       Dummy[k]= 0;
11781:       ncoveff++;
11782:       ncovf++;
11783:       nsd++;
11784:       modell[k].maintype= FTYPE;
11785:       TvarsD[nsd]=Tvar[k];
11786:       TvarsDind[nsd]=k;
11787:       TnsdVar[Tvar[k]]=nsd;
11788:       TvarF[ncovf]=Tvar[k];
11789:       TvarFind[ncovf]=k;
11790:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
11791:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
11792:     /* }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /\* Product of fixed dummy (<=ncovcol) covariates For a fixed product k is higher than ncovcol *\/ */
11793:     }else if( Tvar[k] <=ncovcol+nqv && Typevar[k]==0){/* Remind that product Vn*Vm are added in k Only simple fixed quantitative variable */
11794:       Fixed[k]= 0;
11795:       Dummy[k]= 1;
11796:       nqfveff++;
11797:       modell[k].maintype= FTYPE;
11798:       modell[k].subtype= FQ;
11799:       nsq++;
11800:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
11801:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
11802:       ncovf++;
11803:       TvarF[ncovf]=Tvar[k];
11804:       TvarFind[ncovf]=k;
11805:       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 */
11806:       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 */
11807:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
11808:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
11809:       /* model V1+V3+age*V1+age*V3+V1*V3 */
11810:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
11811:       ncovvt++;
11812:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
11813:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
11814: 
11815:       Fixed[k]= 1;
11816:       Dummy[k]= 0;
11817:       ntveff++; /* Only simple time varying dummy variable */
11818:       modell[k].maintype= VTYPE;
11819:       modell[k].subtype= VD;
11820:       nsd++;
11821:       TvarsD[nsd]=Tvar[k];
11822:       TvarsDind[nsd]=k;
11823:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
11824:       ncovv++; /* Only simple time varying variables */
11825:       TvarV[ncovv]=Tvar[k];
11826:       TvarVind[ncovv]=k; /* TvarVind[2]=2  TvarVind[3]=3 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Any time varying singele */
11827:       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 */
11828:       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 */
11829:       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);
11830:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
11831:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
11832:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
11833:       /* model V1+V3+age*V1+age*V3+V1*V3 */
11834:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
11835:       ncovvt++;
11836:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
11837:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
11838:       
11839:       Fixed[k]= 1;
11840:       Dummy[k]= 1;
11841:       nqtveff++;
11842:       modell[k].maintype= VTYPE;
11843:       modell[k].subtype= VQ;
11844:       ncovv++; /* Only simple time varying variables */
11845:       nsq++;
11846:       TvarsQ[nsq]=Tvar[k]; /* k=1 Tvar=5 nsq=1 TvarsQ[1]=5 */ /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary here) */
11847:       TvarsQind[nsq]=k; /* For single quantitative covariate gives the model position of each single quantitative covariate *//* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
11848:       TvarV[ncovv]=Tvar[k];
11849:       TvarVind[ncovv]=k; /* TvarVind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Any time varying singele */
11850:       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 */
11851:       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 */
11852:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
11853:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
11854:       /* printf("Quasi TmodelQind[%d]=%d,Tvar[TmodelQind[%d]]=V%d, ncovcol=%d, nqv=%d, ntv=%Ad,Tvar[k]- ncovcol-nqv-ntv=%d\n",nqtveff,k,nqtveff,Tvar[k], ncovcol, nqv, ntv, Tvar[k]- ncovcol-nqv-ntv); */
11855:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
11856:     }else if (Typevar[k] == 1) {  /* product with age */
11857:       ncova++;
11858:       TvarA[ncova]=Tvar[k];
11859:       TvarAind[ncova]=k;
11860:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
11861:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
11862:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
11863:       	Fixed[k]= 2;
11864:       	Dummy[k]= 2;
11865:       	modell[k].maintype= ATYPE;
11866:       	modell[k].subtype= APFD;
11867: 	ncovta++;
11868: 	TvarAVVA[ncovta]=Tvar[k]; /*  (2)age*V3 */
11869: 	TvarAVVAind[ncovta]=k;
11870:       	/* ncoveff++; */
11871:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
11872:       	Fixed[k]= 2;
11873:       	Dummy[k]= 3;
11874:       	modell[k].maintype= ATYPE;
11875:       	modell[k].subtype= APFQ;		/*	Product age * fixed quantitative */
11876: 	ncovta++;
11877: 	TvarAVVA[ncovta]=Tvar[k]; /*   */
11878: 	TvarAVVAind[ncovta]=k;
11879:       	/* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
11880:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
11881:       	Fixed[k]= 3;
11882:       	Dummy[k]= 2;
11883:       	modell[k].maintype= ATYPE;
11884:       	modell[k].subtype= APVD;		/*	Product age * varying dummy */
11885: 	ncovva++;
11886: 	TvarVVA[ncovva]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
11887: 	TvarVVAind[ncovva]=k;
11888: 	ncovta++;
11889: 	TvarAVVA[ncovta]=Tvar[k]; /*   */
11890: 	TvarAVVAind[ncovta]=k;
11891:       	/* ntveff++; /\* Only simple time varying dummy variable *\/ */
11892:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
11893:       	Fixed[k]= 3;
11894:       	Dummy[k]= 3;
11895:       	modell[k].maintype= ATYPE;
11896:       	modell[k].subtype= APVQ;		/*	Product age * varying quantitative */
11897: 	ncovva++;
11898: 	TvarVVA[ncovva]=Tvar[k]; /*   */
11899: 	TvarVVAind[ncovva]=k;
11900: 	ncovta++;
11901: 	TvarAVVA[ncovta]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
11902: 	TvarAVVAind[ncovta]=k;
11903:       	/* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
11904:       }
11905:     }else if( Tposprod[k]>0  &&  Typevar[k]==2){  /* Detects if fixed product no age Vm*Vn */
11906:       printf("MEMORY ERRORR k=%d  Tposprod[k]=%d, Typevar[k]=%d\n ",k, Tposprod[k], Typevar[k]);
11907:       if(FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){ /* Needs a fixed product Product of fixed dummy (<=ncovcol) covariates For a fixed product k is higher than ncovcol V3*V2 */
11908:       printf("MEMORY ERRORR k=%d Tvardk[k][1]=%d, Tvardk[k][2]=%d, FixedV[Tvardk[k][1]]=%d,FixedV[Tvardk[k][2]]=%d\n ",k,Tvardk[k][1],Tvardk[k][2],FixedV[Tvardk[k][1]],FixedV[Tvardk[k][2]]);
11909: 	Fixed[k]= 0;
11910: 	Dummy[k]= 0;
11911: 	ncoveff++;
11912: 	ncovf++;
11913: 	/* ncovv++; */
11914: 	/* TvarVV[ncovv]=Tvardk[k][1]; */
11915: 	/* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
11916: 	/* ncovv++; */
11917: 	/* TvarVV[ncovv]=Tvardk[k][2]; */
11918: 	/* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
11919: 	modell[k].maintype= FTYPE;
11920: 	TvarF[ncovf]=Tvar[k];
11921: 	/* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
11922: 	TvarFind[ncovf]=k;
11923: 	TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
11924: 	TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
11925:       }else{/* product varying Vn * Vm without age, V1+V3+age*V1+age*V3+V1*V3 looking at V1*V3, Typevar={0, 0, 1, 1, 2}, k=5, V1 is fixed, V3 is timevary, V5 is a product  */
11926: 	/*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
11927: 	/* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
11928: 	/*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
11929: 	k1=Tposprod[k];  /* Position in the products of product k, Tposprod={0, 0, 0, 0, 1, 1} k1=1 first product but second time varying because of V3 */
11930: 	ncovvt++;
11931: 	TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
11932: 	TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
11933: 	ncovvt++;
11934: 	TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
11935: 	TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
11936: 	
11937: 	/** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
11938: 	/** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
11939: 	
11940: 	if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
11941: 	  if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
11942: 	    Fixed[k]= 1;
11943: 	    Dummy[k]= 0;
11944: 	    modell[k].maintype= FTYPE;
11945: 	    modell[k].subtype= FPDD;		/*	Product fixed dummy * fixed dummy */
11946: 	    ncovf++; /* Fixed variables without age */
11947: 	    TvarF[ncovf]=Tvar[k];
11948: 	    TvarFind[ncovf]=k;
11949: 	  }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
11950: 	    Fixed[k]= 0;  /* Fixed product */
11951: 	    Dummy[k]= 1;
11952: 	    modell[k].maintype= FTYPE;
11953: 	    modell[k].subtype= FPDQ;		/*	Product fixed dummy * fixed quantitative */
11954: 	    ncovf++; /* Varying variables without age */
11955: 	    TvarF[ncovf]=Tvar[k];
11956: 	    TvarFind[ncovf]=k;
11957: 	  }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
11958: 	    Fixed[k]= 1;
11959: 	    Dummy[k]= 0;
11960: 	    modell[k].maintype= VTYPE;
11961: 	    modell[k].subtype= VPDD;		/*	Product fixed dummy * varying dummy */
11962: 	    ncovv++; /* Varying variables without age */
11963: 	    TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
11964: 	    TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
11965: 	  }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
11966: 	    Fixed[k]= 1;
11967: 	    Dummy[k]= 1;
11968: 	    modell[k].maintype= VTYPE;
11969: 	    modell[k].subtype= VPDQ;		/*	Product fixed dummy * varying quantitative */
11970: 	    ncovv++; /* Varying variables without age */
11971: 	    TvarV[ncovv]=Tvar[k];
11972: 	    TvarVind[ncovv]=k;
11973: 	  }
11974: 	}else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
11975: 	  if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
11976: 	    Fixed[k]= 0;  /*  Fixed product */
11977: 	    Dummy[k]= 1;
11978: 	    modell[k].maintype= FTYPE;
11979: 	    modell[k].subtype= FPDQ;		/*	Product fixed quantitative * fixed dummy */
11980: 	    ncovf++; /* Fixed variables without age */
11981: 	    TvarF[ncovf]=Tvar[k];
11982: 	    TvarFind[ncovf]=k;
11983: 	  }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
11984: 	    Fixed[k]= 1;
11985: 	    Dummy[k]= 1;
11986: 	    modell[k].maintype= VTYPE;
11987: 	    modell[k].subtype= VPDQ;		/*	Product fixed quantitative * varying dummy */
11988: 	    ncovv++; /* Varying variables without age */
11989: 	    TvarV[ncovv]=Tvar[k];
11990: 	    TvarVind[ncovv]=k;
11991: 	  }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
11992: 	    Fixed[k]= 1;
11993: 	    Dummy[k]= 1;
11994: 	    modell[k].maintype= VTYPE;
11995: 	    modell[k].subtype= VPQQ;		/*	Product fixed quantitative * varying quantitative */
11996: 	    ncovv++; /* Varying variables without age */
11997: 	    TvarV[ncovv]=Tvar[k];
11998: 	    TvarVind[ncovv]=k;
11999: 	    ncovv++; /* Varying variables without age */
12000: 	    TvarV[ncovv]=Tvar[k];
12001: 	    TvarVind[ncovv]=k;
12002: 	  }
12003: 	}else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
12004: 	  if(Tvard[k1][2] <=ncovcol){
12005: 	    Fixed[k]= 1;
12006: 	    Dummy[k]= 1;
12007: 	    modell[k].maintype= VTYPE;
12008: 	    modell[k].subtype= VPDD;		/*	Product time varying dummy * fixed dummy */
12009: 	    ncovv++; /* Varying variables without age */
12010: 	    TvarV[ncovv]=Tvar[k];
12011: 	    TvarVind[ncovv]=k;
12012: 	  }else if(Tvard[k1][2] <=ncovcol+nqv){
12013: 	    Fixed[k]= 1;
12014: 	    Dummy[k]= 1;
12015: 	    modell[k].maintype= VTYPE;
12016: 	    modell[k].subtype= VPDQ;		/*	Product time varying dummy * fixed quantitative */
12017: 	    ncovv++; /* Varying variables without age */
12018: 	    TvarV[ncovv]=Tvar[k];
12019: 	    TvarVind[ncovv]=k;
12020: 	  }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
12021: 	    Fixed[k]= 1;
12022: 	    Dummy[k]= 0;
12023: 	    modell[k].maintype= VTYPE;
12024: 	    modell[k].subtype= VPDD;		/*	Product time varying dummy * time varying dummy */
12025: 	    ncovv++; /* Varying variables without age */
12026: 	    TvarV[ncovv]=Tvar[k];
12027: 	    TvarVind[ncovv]=k;
12028: 	  }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
12029: 	    Fixed[k]= 1;
12030: 	    Dummy[k]= 1;
12031: 	    modell[k].maintype= VTYPE;
12032: 	    modell[k].subtype= VPDQ;		/*	Product time varying dummy * time varying quantitative */
12033: 	    ncovv++; /* Varying variables without age */
12034: 	    TvarV[ncovv]=Tvar[k];
12035: 	    TvarVind[ncovv]=k;
12036: 	  }
12037: 	}else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
12038: 	  if(Tvard[k1][2] <=ncovcol){
12039: 	    Fixed[k]= 1;
12040: 	    Dummy[k]= 1;
12041: 	    modell[k].maintype= VTYPE;
12042: 	    modell[k].subtype= VPDQ;		/*	Product time varying quantitative * fixed dummy */
12043: 	    ncovv++; /* Varying variables without age */
12044: 	    TvarV[ncovv]=Tvar[k];
12045: 	    TvarVind[ncovv]=k;
12046: 	  }else if(Tvard[k1][2] <=ncovcol+nqv){
12047: 	    Fixed[k]= 1;
12048: 	    Dummy[k]= 1;
12049: 	    modell[k].maintype= VTYPE;
12050: 	    modell[k].subtype= VPQQ;		/*	Product time varying quantitative * fixed quantitative */
12051: 	    ncovv++; /* Varying variables without age */
12052: 	    TvarV[ncovv]=Tvar[k];
12053: 	    TvarVind[ncovv]=k;
12054: 	  }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
12055: 	    Fixed[k]= 1;
12056: 	    Dummy[k]= 1;
12057: 	    modell[k].maintype= VTYPE;
12058: 	    modell[k].subtype= VPDQ;		/*	Product time varying quantitative * time varying dummy */
12059: 	    ncovv++; /* Varying variables without age */
12060: 	    TvarV[ncovv]=Tvar[k];
12061: 	    TvarVind[ncovv]=k;
12062: 	  }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
12063: 	    Fixed[k]= 1;
12064: 	    Dummy[k]= 1;
12065: 	    modell[k].maintype= VTYPE;
12066: 	    modell[k].subtype= VPQQ;		/*	Product time varying quantitative * time varying quantitative */
12067: 	    ncovv++; /* Varying variables without age */
12068: 	    TvarV[ncovv]=Tvar[k];
12069: 	    TvarVind[ncovv]=k;
12070: 	  }
12071: 	}else{
12072: 	  printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
12073: 	  fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
12074: 	} /*end k1*/
12075:       }
12076:     }else if(Typevar[k] == 3){  /* product Vn * Vm with age, V1+V3+age*V1+age*V3+V1*V3 looking at V1*V3, Typevar={0, 0, 1, 1, 2}, k=5, V1 is fixed, V3 is timevary, V5 is a product  */
12077:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
12078:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
12079:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
12080:       k1=Tposprod[k];  /* Position in the products of product k, Tposprod={0, 0, 0, 0, 1, 1} k1=1 first product but second time varying because of V3 */
12081:       ncova++;
12082:       TvarA[ncova]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
12083:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
12084:       ncova++;
12085:       TvarA[ncova]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
12086:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
12087: 
12088:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
12089:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
12090:       if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){
12091: 	ncovta++;
12092: 	TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
12093: 	TvarAVVAind[ncovta]=k;
12094: 	ncovta++;
12095: 	TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
12096: 	TvarAVVAind[ncovta]=k;
12097:       }else{
12098: 	ncovva++;  /* HERY  reached */
12099: 	TvarVVA[ncovva]=Tvard[k1][1]; /*  age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4  */
12100: 	TvarVVAind[ncovva]=k;
12101: 	ncovva++;
12102: 	TvarVVA[ncovva]=Tvard[k1][2]; /*   */
12103: 	TvarVVAind[ncovva]=k;
12104: 	ncovta++;
12105: 	TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
12106: 	TvarAVVAind[ncovta]=k;
12107: 	ncovta++;
12108: 	TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
12109: 	TvarAVVAind[ncovta]=k;
12110:       }
12111:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
12112:     	if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
12113:     	  Fixed[k]= 2;
12114:     	  Dummy[k]= 2;
12115:     	  modell[k].maintype= FTYPE;
12116:     	  modell[k].subtype= FPDD;		/*	Product fixed dummy * fixed dummy */
12117:     	  /* TvarF[ncova]=Tvar[k];   /\* Problem to solve *\/ */
12118:     	  /* TvarFind[ncova]=k; */
12119:     	}else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
12120:     	  Fixed[k]= 2;  /* Fixed product */
12121:     	  Dummy[k]= 3;
12122:     	  modell[k].maintype= FTYPE;
12123:     	  modell[k].subtype= FPDQ;		/*	Product fixed dummy * fixed quantitative */
12124:     	  /* TvarF[ncova]=Tvar[k]; */
12125:     	  /* TvarFind[ncova]=k; */
12126:     	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
12127:     	  Fixed[k]= 3;
12128:     	  Dummy[k]= 2;
12129:     	  modell[k].maintype= VTYPE;
12130:     	  modell[k].subtype= VPDD;		/*	Product fixed dummy * varying dummy */
12131:     	  TvarV[ncova]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
12132:     	  TvarVind[ncova]=k;/* TvarVind[1]=5 */ 
12133:     	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
12134:     	  Fixed[k]= 3;
12135:     	  Dummy[k]= 3;
12136:     	  modell[k].maintype= VTYPE;
12137:     	  modell[k].subtype= VPDQ;		/*	Product fixed dummy * varying quantitative */
12138:     	  /* ncovv++; /\* Varying variables without age *\/ */
12139:     	  /* TvarV[ncovv]=Tvar[k]; */
12140:     	  /* TvarVind[ncovv]=k; */
12141:     	}
12142:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
12143:     	if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
12144:     	  Fixed[k]= 2;  /*  Fixed product */
12145:     	  Dummy[k]= 2;
12146:     	  modell[k].maintype= FTYPE;
12147:     	  modell[k].subtype= FPDQ;		/*	Product fixed quantitative * fixed dummy */
12148:     	  /* ncova++; /\* Fixed variables with age *\/ */
12149:     	  /* TvarF[ncovf]=Tvar[k]; */
12150:     	  /* TvarFind[ncovf]=k; */
12151:     	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
12152:     	  Fixed[k]= 2;
12153:     	  Dummy[k]= 3;
12154:     	  modell[k].maintype= VTYPE;
12155:     	  modell[k].subtype= VPDQ;		/*	Product fixed quantitative * varying dummy */
12156:     	  /* ncova++; /\* Varying variables with age *\/ */
12157:     	  /* TvarV[ncova]=Tvar[k]; */
12158:     	  /* TvarVind[ncova]=k; */
12159:     	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
12160:     	  Fixed[k]= 3;
12161:     	  Dummy[k]= 2;
12162:     	  modell[k].maintype= VTYPE;
12163:     	  modell[k].subtype= VPQQ;		/*	Product fixed quantitative * varying quantitative */
12164:     	  ncova++; /* Varying variables without age */
12165:     	  TvarV[ncova]=Tvar[k];
12166:     	  TvarVind[ncova]=k;
12167:     	  /* ncova++; /\* Varying variables without age *\/ */
12168:     	  /* TvarV[ncova]=Tvar[k]; */
12169:     	  /* TvarVind[ncova]=k; */
12170:     	}
12171:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
12172:     	if(Tvard[k1][2] <=ncovcol){
12173:     	  Fixed[k]= 2;
12174:     	  Dummy[k]= 2;
12175:     	  modell[k].maintype= VTYPE;
12176:     	  modell[k].subtype= VPDD;		/*	Product time varying dummy * fixed dummy */
12177:     	  /* ncova++; /\* Varying variables with age *\/ */
12178:     	  /* TvarV[ncova]=Tvar[k]; */
12179:     	  /* TvarVind[ncova]=k; */
12180:     	}else if(Tvard[k1][2] <=ncovcol+nqv){
12181:     	  Fixed[k]= 2;
12182:     	  Dummy[k]= 3;
12183:     	  modell[k].maintype= VTYPE;
12184:     	  modell[k].subtype= VPDQ;		/*	Product time varying dummy * fixed quantitative */
12185:     	  /* ncova++; /\* Varying variables with age *\/ */
12186:     	  /* TvarV[ncova]=Tvar[k]; */
12187:     	  /* TvarVind[ncova]=k; */
12188:     	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
12189:     	  Fixed[k]= 3;
12190:     	  Dummy[k]= 2;
12191:     	  modell[k].maintype= VTYPE;
12192:     	  modell[k].subtype= VPDD;		/*	Product time varying dummy * time varying dummy */
12193:     	  /* ncova++; /\* Varying variables with age *\/ */
12194:     	  /* TvarV[ncova]=Tvar[k]; */
12195:     	  /* TvarVind[ncova]=k; */
12196:     	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
12197:     	  Fixed[k]= 3;
12198:     	  Dummy[k]= 3;
12199:     	  modell[k].maintype= VTYPE;
12200:     	  modell[k].subtype= VPDQ;		/*	Product time varying dummy * time varying quantitative */
12201:     	  /* ncova++; /\* Varying variables with age *\/ */
12202:     	  /* TvarV[ncova]=Tvar[k]; */
12203:     	  /* TvarVind[ncova]=k; */
12204:     	}
12205:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
12206:     	if(Tvard[k1][2] <=ncovcol){
12207:     	  Fixed[k]= 2;
12208:     	  Dummy[k]= 2;
12209:     	  modell[k].maintype= VTYPE;
12210:     	  modell[k].subtype= VPDQ;		/*	Product time varying quantitative * fixed dummy */
12211:     	  /* ncova++; /\* Varying variables with age *\/ */
12212:     	  /* TvarV[ncova]=Tvar[k]; */
12213:     	  /* TvarVind[ncova]=k; */
12214:     	}else if(Tvard[k1][2] <=ncovcol+nqv){
12215:     	  Fixed[k]= 2;
12216:     	  Dummy[k]= 3;
12217:     	  modell[k].maintype= VTYPE;
12218:     	  modell[k].subtype= VPQQ;		/*	Product time varying quantitative * fixed quantitative */
12219:     	  /* ncova++; /\* Varying variables with age *\/ */
12220:     	  /* TvarV[ncova]=Tvar[k]; */
12221:     	  /* TvarVind[ncova]=k; */
12222:     	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
12223:     	  Fixed[k]= 3;
12224:     	  Dummy[k]= 2;
12225:     	  modell[k].maintype= VTYPE;
12226:     	  modell[k].subtype= VPDQ;		/*	Product time varying quantitative * time varying dummy */
12227:     	  /* ncova++; /\* Varying variables with age *\/ */
12228:     	  /* TvarV[ncova]=Tvar[k]; */
12229:     	  /* TvarVind[ncova]=k; */
12230:     	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
12231:     	  Fixed[k]= 3;
12232:     	  Dummy[k]= 3;
12233:     	  modell[k].maintype= VTYPE;
12234:     	  modell[k].subtype= VPQQ;		/*	Product time varying quantitative * time varying quantitative */
12235:     	  /* ncova++; /\* Varying variables with age *\/ */
12236:     	  /* TvarV[ncova]=Tvar[k]; */
12237:     	  /* TvarVind[ncova]=k; */
12238:     	}
12239:       }else{
12240:     	printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
12241:     	fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
12242:       } /*end k1*/
12243:     } else{
12244:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
12245:       fprintf(ficlog,"Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
12246:     }
12247:     /* 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]); */
12248:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
12249:     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]);
12250:   }
12251:   ncovvta=ncovva;
12252:   /* Searching for doublons in the model */
12253:   for(k1=1; k1<= cptcovt;k1++){
12254:     for(k2=1; k2 <k1;k2++){
12255:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
12256:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
12257: 	if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
12258: 	  if(Tvar[k1]==Tvar[k2]){
12259: 	    printf("Error duplication in the model=1+age+%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[k1],Dummy[k1]);
12260: 	    fprintf(ficlog,"Error duplication in the model=1+age+%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[k1],Dummy[k1]); fflush(ficlog);
12261: 	    return(1);
12262: 	  }
12263: 	}else if (Typevar[k1] ==2){
12264: 	  k3=Tposprod[k1];
12265: 	  k4=Tposprod[k2];
12266: 	  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])) ){
12267: 	    printf("Error duplication in the model=1+age+%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]]);
12268: 	    fprintf(ficlog,"Error duplication in the model=1+age+%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);
12269: 	    return(1);
12270: 	  }
12271: 	}
12272:       }
12273:     }
12274:   }
12275:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
12276:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
12277:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
12278:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
12279: 
12280:   free_imatrix(existcomb,1,NCOVMAX,1,NCOVMAX);
12281:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
12282:   /*endread:*/
12283:   printf("Exiting decodemodel: ");
12284:   return (1);
12285: }
12286: 
12287: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
12288: {/* Check ages at death */
12289:   int i, m;
12290:   int firstone=0;
12291:   
12292:   for (i=1; i<=imx; i++) {
12293:     for(m=2; (m<= maxwav); m++) {
12294:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
12295: 	anint[m][i]=9999;
12296: 	if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
12297: 	  s[m][i]=-1;
12298:       }
12299:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
12300: 	*nberr = *nberr + 1;
12301: 	if(firstone == 0){
12302: 	  firstone=1;
12303: 	printf("Warning (#%d)! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown but status is a death state %d at wave %d. If you don't know the vital status, please enter -2. If he/she is still alive but don't know the state, please code with '-1 or '.'. Here, we do not believe in a death, skipped.\nOther similar cases in log file\n", *nberr,(int)moisdc[i],(int)andc[i],num[i],i,s[m][i],m);
12304: 	}
12305: 	fprintf(ficlog,"Warning (#%d)! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown but status is a death state %d at wave %d. If you don't know the vital status, please enter -2. If he/she is still alive but don't know the state, please code with '-1 or '.'. Here, we do not believe in a death, skipped.\n", *nberr,(int)moisdc[i],(int)andc[i],num[i],i,s[m][i],m);
12306: 	s[m][i]=-1;  /* Droping the death status */
12307:       }
12308:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
12309: 	(*nberr)++;
12310: 	printf("Error (#%d)! Month of death of individual %ld on line %d was unknown (%2d) (year of death is %4d) and status is a death state %d at wave %d. Please impute an arbitrary (or not) month and rerun. Currently this transition to death will be skipped (status is set to -2).\nOther similar cases in log file\n", *nberr, num[i],i,(int)moisdc[i],(int)andc[i],s[m][i],m);
12311: 	fprintf(ficlog,"Error (#%d)! Month of death of individual %ld on line %d was unknown (%2d) (year of death is %4d) and status is a death state %d at wave %d. Please impute an arbitrary (or not) month and rerun. Currently this transition to death will be skipped (status is set to -2).\n", *nberr, num[i],i,(int)moisdc[i],(int)andc[i],s[m][i],m);
12312: 	s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
12313:       }
12314:     }
12315:   }
12316: 
12317:   for (i=1; i<=imx; i++)  {
12318:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
12319:     for(m=firstpass; (m<= lastpass); m++){
12320:       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 */
12321: 	if (s[m][i] >= nlstate+1) {
12322: 	  if(agedc[i]>0){
12323: 	    if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
12324: 	      agev[m][i]=agedc[i];
12325: 	      /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
12326: 	    }else {
12327: 	      if ((int)andc[i]!=9999){
12328: 		nbwarn++;
12329: 		printf("Warning negative age at death: %ld line:%d\n",num[i],i);
12330: 		fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
12331: 		agev[m][i]=-1;
12332: 	      }
12333: 	    }
12334: 	  } /* agedc > 0 */
12335: 	} /* end if */
12336: 	else if(s[m][i] !=9){ /* Standard case, age in fractional
12337: 				 years but with the precision of a month */
12338: 	  agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
12339: 	  if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
12340: 	    agev[m][i]=1;
12341: 	  else if(agev[m][i] < *agemin){ 
12342: 	    *agemin=agev[m][i];
12343: 	    printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
12344: 	  }
12345: 	  else if(agev[m][i] >*agemax){
12346: 	    *agemax=agev[m][i];
12347: 	    /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
12348: 	  }
12349: 	  /*agev[m][i]=anint[m][i]-annais[i];*/
12350: 	  /*	 agev[m][i] = age[i]+2*m;*/
12351: 	} /* en if 9*/
12352: 	else { /* =9 */
12353: 	  /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
12354: 	  agev[m][i]=1;
12355: 	  s[m][i]=-1;
12356: 	}
12357:       }
12358:       else if(s[m][i]==0) /*= 0 Unknown */
12359: 	agev[m][i]=1;
12360:       else{
12361: 	printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
12362: 	fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
12363: 	agev[m][i]=0;
12364:       }
12365:     } /* End for lastpass */
12366:   }
12367:     
12368:   for (i=1; i<=imx; i++)  {
12369:     for(m=firstpass; (m<=lastpass); m++){
12370:       if (s[m][i] > (nlstate+ndeath)) {
12371: 	(*nberr)++;
12372: 	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);	
12373: 	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);	
12374: 	return 1;
12375:       }
12376:     }
12377:   }
12378: 
12379:   /*for (i=1; i<=imx; i++){
12380:   for (m=firstpass; (m<lastpass); m++){
12381:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
12382: }
12383: 
12384: }*/
12385: 
12386: 
12387:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
12388:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
12389: 
12390:   return (0);
12391:  /* endread:*/
12392:     printf("Exiting calandcheckages: ");
12393:     return (1);
12394: }
12395: 
12396: #if defined(_MSC_VER)
12397: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
12398: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
12399: //#include "stdafx.h"
12400: //#include <stdio.h>
12401: //#include <tchar.h>
12402: //#include <windows.h>
12403: //#include <iostream>
12404: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
12405: 
12406: LPFN_ISWOW64PROCESS fnIsWow64Process;
12407: 
12408: BOOL IsWow64()
12409: {
12410: 	BOOL bIsWow64 = FALSE;
12411: 
12412: 	//typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
12413: 	//  (HANDLE, PBOOL);
12414: 
12415: 	//LPFN_ISWOW64PROCESS fnIsWow64Process;
12416: 
12417: 	HMODULE module = GetModuleHandle(_T("kernel32"));
12418: 	const char funcName[] = "IsWow64Process";
12419: 	fnIsWow64Process = (LPFN_ISWOW64PROCESS)
12420: 		GetProcAddress(module, funcName);
12421: 
12422: 	if (NULL != fnIsWow64Process)
12423: 	{
12424: 		if (!fnIsWow64Process(GetCurrentProcess(),
12425: 			&bIsWow64))
12426: 			//throw std::exception("Unknown error");
12427: 			printf("Unknown error\n");
12428: 	}
12429: 	return bIsWow64 != FALSE;
12430: }
12431: #endif
12432: 
12433: void syscompilerinfo(int logged)
12434: {
12435: #include <stdint.h>
12436: 
12437:   /* #include "syscompilerinfo.h"*/
12438:    /* command line Intel compiler 32bit windows, XP compatible:*/
12439:    /* /GS /W3 /Gy
12440:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
12441:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
12442:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
12443:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
12444:    */ 
12445:    /* 64 bits */
12446:    /*
12447:      /GS /W3 /Gy
12448:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
12449:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
12450:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
12451:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
12452:    /* Optimization are useless and O3 is slower than O2 */
12453:    /*
12454:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
12455:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
12456:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
12457:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
12458:    */
12459:    /* Link is */ /* /OUT:"visual studio
12460:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
12461:       /PDB:"visual studio
12462:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
12463:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
12464:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
12465:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
12466:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
12467:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
12468:       uiAccess='false'"
12469:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
12470:       /NOLOGO /TLBID:1
12471:    */
12472: 
12473: 
12474: #if defined __INTEL_COMPILER
12475: #if defined(__GNUC__)
12476: 	struct utsname sysInfo;  /* For Intel on Linux and OS/X */
12477: #endif
12478: #elif defined(__GNUC__) 
12479: #ifndef  __APPLE__
12480: #include <gnu/libc-version.h>  /* Only on gnu */
12481: #endif
12482:    struct utsname sysInfo;
12483:    int cross = CROSS;
12484:    if (cross){
12485: 	   printf("Cross-");
12486: 	   if(logged) fprintf(ficlog, "Cross-");
12487:    }
12488: #endif
12489: 
12490:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
12491: #if defined(__clang__)
12492:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");	/* Clang/LLVM. ---------------------------------------------- */
12493: #endif
12494: #if defined(__ICC) || defined(__INTEL_COMPILER)
12495:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
12496: #endif
12497: #if defined(__GNUC__) || defined(__GNUG__)
12498:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
12499: #endif
12500: #if defined(__HP_cc) || defined(__HP_aCC)
12501:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
12502: #endif
12503: #if defined(__IBMC__) || defined(__IBMCPP__)
12504:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
12505: #endif
12506: #if defined(_MSC_VER)
12507:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
12508: #endif
12509: #if defined(__PGI)
12510:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
12511: #endif
12512: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
12513:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
12514: #endif
12515:    printf(" for "); if (logged) fprintf(ficlog, " for ");
12516:    
12517: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
12518: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
12519:     // Windows (x64 and x86)
12520:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
12521: #elif __unix__ // all unices, not all compilers
12522:     // Unix
12523:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
12524: #elif __linux__
12525:     // linux
12526:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
12527: #elif __APPLE__
12528:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
12529:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
12530: #endif
12531: 
12532: /*  __MINGW32__	  */
12533: /*  __CYGWIN__	 */
12534: /* __MINGW64__  */
12535: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
12536: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
12537: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
12538: /* _WIN64  // Defined for applications for Win64. */
12539: /* _M_X64 // Defined for compilations that target x64 processors. */
12540: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
12541: 
12542: #if UINTPTR_MAX == 0xffffffff
12543:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
12544: #elif UINTPTR_MAX == 0xffffffffffffffff
12545:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
12546: #else
12547:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
12548: #endif
12549: 
12550: #if defined(__GNUC__)
12551: # if defined(__GNUC_PATCHLEVEL__)
12552: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
12553:                             + __GNUC_MINOR__ * 100 \
12554:                             + __GNUC_PATCHLEVEL__)
12555: # else
12556: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
12557:                             + __GNUC_MINOR__ * 100)
12558: # endif
12559:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
12560:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
12561: 
12562:    if (uname(&sysInfo) != -1) {
12563:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
12564: 	 if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
12565:    }
12566:    else
12567:       perror("uname() error");
12568:    //#ifndef __INTEL_COMPILER 
12569: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
12570:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
12571:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
12572: #endif
12573: #endif
12574: 
12575:    //   void main ()
12576:    //   {
12577: #if defined(_MSC_VER)
12578:    if (IsWow64()){
12579: 	   printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
12580: 	   if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
12581:    }
12582:    else{
12583: 	   printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
12584: 	   if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
12585:    }
12586:    //	   printf("\nPress Enter to continue...");
12587:    //	   getchar();
12588:    //   }
12589: 
12590: #endif
12591:    
12592: 
12593: }
12594: 
12595: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
12596:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
12597:   /* Computes the prevalence limit for each combination of the dummy covariates */
12598:   int i, j, k, i1, k4=0, nres=0 ;
12599:   /* double ftolpl = 1.e-10; */
12600:   double age, agebase, agelim;
12601:   double tot;
12602: 
12603:   strcpy(filerespl,"PL_");
12604:   strcat(filerespl,fileresu);
12605:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
12606:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
12607:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
12608:   }
12609:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
12610:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
12611:   pstamp(ficrespl);
12612:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
12613:   fprintf(ficrespl,"#Age ");
12614:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
12615:   fprintf(ficrespl,"\n");
12616:   
12617:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
12618: 
12619:   agebase=ageminpar;
12620:   agelim=agemaxpar;
12621: 
12622:   /* i1=pow(2,ncoveff); */
12623:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
12624:   if (cptcovn < 1){i1=1;}
12625: 
12626:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
12627:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
12628:       k=TKresult[nres];
12629:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
12630:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
12631:       /* 	continue; */
12632: 
12633:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
12634:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
12635:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
12636:       /* k=k+1; */
12637:       /* to clean */
12638:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
12639:       fprintf(ficrespl,"#******");
12640:       printf("#******");
12641:       fprintf(ficlog,"#******");
12642:       for(j=1;j<=cptcovs ;j++) {/**< cptcovs number of SIMPLE covariates in the model or resultline V2+V1 =2 (dummy or quantit or time varying) */
12643: 	/* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
12644: 	/* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
12645: 	/* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
12646: 	fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
12647: 	printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
12648: 	fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
12649:       }
12650:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
12651:       /* 	printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
12652:       /* 	fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
12653:       /* 	fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
12654:       /* } */
12655:       fprintf(ficrespl,"******\n");
12656:       printf("******\n");
12657:       fprintf(ficlog,"******\n");
12658:       if(invalidvarcomb[k]){
12659: 	printf("\nCombination (%d) ignored because no case \n",k); 
12660: 	fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
12661: 	fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
12662: 	continue;
12663:       }
12664: 
12665:       fprintf(ficrespl,"#Age ");
12666:       /* for(j=1;j<=cptcoveff;j++) { */
12667:       /* 	fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
12668:       /* } */
12669:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
12670: 	fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
12671:       }
12672:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
12673:       fprintf(ficrespl,"Total Years_to_converge\n");
12674:     
12675:       for (age=agebase; age<=agelim; age++){
12676: 	/* for (age=agebase; age<=agebase; age++){ */
12677: 	/**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
12678: 	prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
12679: 	fprintf(ficrespl,"%.0f ",age );
12680: 	/* for(j=1;j<=cptcoveff;j++) */
12681: 	/*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
12682: 	for(j=1;j<=cptcovs;j++)
12683: 	  fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
12684: 	tot=0.;
12685: 	for(i=1; i<=nlstate;i++){
12686: 	  tot +=  prlim[i][i];
12687: 	  fprintf(ficrespl," %.5f", prlim[i][i]);
12688: 	}
12689: 	fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
12690:       } /* Age */
12691:       /* was end of cptcod */
12692:     } /* nres */
12693:   /* } /\* for each combination *\/ */
12694:   return 0;
12695: }
12696: 
12697: 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){
12698: 	/*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
12699: 	
12700: 	/* Computes the back prevalence limit  for any combination	of covariate values 
12701:    * at any age between ageminpar and agemaxpar
12702: 	 */
12703:   int i, j, k, i1, nres=0 ;
12704:   /* double ftolpl = 1.e-10; */
12705:   double age, agebase, agelim;
12706:   double tot;
12707:   /* double ***mobaverage; */
12708:   /* double	 **dnewm, **doldm, **dsavm;  /\* for use *\/ */
12709: 
12710:   strcpy(fileresplb,"PLB_");
12711:   strcat(fileresplb,fileresu);
12712:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
12713:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
12714:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
12715:   }
12716:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
12717:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
12718:   pstamp(ficresplb);
12719:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
12720:   fprintf(ficresplb,"#Age ");
12721:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
12722:   fprintf(ficresplb,"\n");
12723:   
12724:   
12725:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
12726:   
12727:   agebase=ageminpar;
12728:   agelim=agemaxpar;
12729:   
12730:   
12731:   i1=pow(2,cptcoveff);
12732:   if (cptcovn < 1){i1=1;}
12733:   
12734:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
12735:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
12736:       k=TKresult[nres];
12737:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
12738:      /* if(i1 != 1 && TKresult[nres]!= k) */
12739:      /* 	continue; */
12740:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
12741:       fprintf(ficresplb,"#******");
12742:       printf("#******");
12743:       fprintf(ficlog,"#******");
12744:       for(j=1;j<=cptcovs ;j++) {/**< cptcovs number of SIMPLE covariates in the model or resultline V2+V1 =2 (dummy or quantit or time varying) */
12745: 	printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
12746: 	fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
12747: 	fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
12748:       }
12749:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
12750:       /* 	fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
12751:       /* 	printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
12752:       /* 	fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
12753:       /* } */
12754:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
12755:       /* 	printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
12756:       /* 	fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
12757:       /* 	fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
12758:       /* } */
12759:       fprintf(ficresplb,"******\n");
12760:       printf("******\n");
12761:       fprintf(ficlog,"******\n");
12762:       if(invalidvarcomb[k]){
12763: 	printf("\nCombination (%d) ignored because no cases \n",k); 
12764: 	fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
12765: 	fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
12766: 	continue;
12767:       }
12768:     
12769:       fprintf(ficresplb,"#Age ");
12770:       for(j=1;j<=cptcovs;j++) {
12771: 	fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
12772:       }
12773:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
12774:       fprintf(ficresplb,"Total Years_to_converge\n");
12775:     
12776:     
12777:       for (age=agebase; age<=agelim; age++){
12778: 	/* for (age=agebase; age<=agebase; age++){ */
12779: 	if(mobilavproj > 0){
12780: 	  /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
12781: 	  /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
12782: 	  bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
12783: 	}else if (mobilavproj == 0){
12784: 	  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);
12785: 	  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);
12786: 	  exit(1);
12787: 	}else{
12788: 	  /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
12789: 	  bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
12790: 	  /* printf("TOTOT\n"); */
12791:           /* exit(1); */
12792: 	}
12793: 	fprintf(ficresplb,"%.0f ",age );
12794: 	for(j=1;j<=cptcovs;j++)
12795: 	  fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
12796: 	tot=0.;
12797: 	for(i=1; i<=nlstate;i++){
12798: 	  tot +=  bprlim[i][i];
12799: 	  fprintf(ficresplb," %.5f", bprlim[i][i]);
12800: 	}
12801: 	fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
12802:       } /* Age */
12803:       /* was end of cptcod */
12804:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
12805:     /* } /\* end of any combination *\/ */
12806:   } /* end of nres */  
12807:   /* hBijx(p, bage, fage); */
12808:   /* fclose(ficrespijb); */
12809:   
12810:   return 0;
12811: }
12812:  
12813: int hPijx(double *p, int bage, int fage){
12814:     /*------------- h Pij x at various ages ------------*/
12815:   /* to be optimized with precov */
12816:   int stepsize;
12817:   int agelim;
12818:   int hstepm;
12819:   int nhstepm;
12820:   int h, i, i1, j, k, k4, nres=0;
12821: 
12822:   double agedeb;
12823:   double ***p3mat;
12824: 
12825:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
12826:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
12827:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
12828:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
12829:   }
12830:   printf("Computing pij: result on file '%s' \n", filerespij);
12831:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
12832:   
12833:   stepsize=(int) (stepm+YEARM-1)/YEARM;
12834:   /*if (stepm<=24) stepsize=2;*/
12835:   
12836:   agelim=AGESUP;
12837:   hstepm=stepsize*YEARM; /* Every year of age */
12838:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
12839:   
12840:   /* hstepm=1;   aff par mois*/
12841:   pstamp(ficrespij);
12842:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
12843:   i1= pow(2,cptcoveff);
12844:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
12845:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
12846:   /*  	k=k+1;  */
12847:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
12848:     k=TKresult[nres];
12849:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
12850:     /* for(k=1; k<=i1;k++){ */
12851:     /* if(i1 != 1 && TKresult[nres]!= k) */
12852:     /* 	continue; */
12853:     fprintf(ficrespij,"\n#****** ");
12854:     for(j=1;j<=cptcovs;j++){
12855:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
12856:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
12857:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
12858:       /* 	printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
12859:       /* 	fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
12860:     }
12861:     fprintf(ficrespij,"******\n");
12862:     
12863:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
12864:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
12865:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
12866:       
12867:       /*	  nhstepm=nhstepm*YEARM; aff par mois*/
12868:       
12869:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
12870:       oldm=oldms;savm=savms;
12871:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
12872:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
12873:       for(i=1; i<=nlstate;i++)
12874: 	for(j=1; j<=nlstate+ndeath;j++)
12875: 	  fprintf(ficrespij," %1d-%1d",i,j);
12876:       fprintf(ficrespij,"\n");
12877:       for (h=0; h<=nhstepm; h++){
12878: 	/*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
12879: 	fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
12880: 	for(i=1; i<=nlstate;i++)
12881: 	  for(j=1; j<=nlstate+ndeath;j++)
12882: 	    fprintf(ficrespij," %.5f", p3mat[i][j][h]);
12883: 	fprintf(ficrespij,"\n");
12884:       }
12885:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
12886:       fprintf(ficrespij,"\n");
12887:     }
12888:   }
12889:   /*}*/
12890:   return 0;
12891: }
12892:  
12893:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
12894:     /*------------- h Bij x at various ages ------------*/
12895:     /* To be optimized with precov */
12896:   int stepsize;
12897:   /* int agelim; */
12898: 	int ageminl;
12899:   int hstepm;
12900:   int nhstepm;
12901:   int h, i, i1, j, k, nres;
12902: 	
12903:   double agedeb;
12904:   double ***p3mat;
12905: 	
12906:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
12907:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
12908:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
12909:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
12910:   }
12911:   printf("Computing pij back: result on file '%s' \n", filerespijb);
12912:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
12913:   
12914:   stepsize=(int) (stepm+YEARM-1)/YEARM;
12915:   /*if (stepm<=24) stepsize=2;*/
12916:   
12917:   /* agelim=AGESUP; */
12918:   ageminl=AGEINF; /* was 30 */
12919:   hstepm=stepsize*YEARM; /* Every year of age */
12920:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
12921:   
12922:   /* hstepm=1;   aff par mois*/
12923:   pstamp(ficrespijb);
12924:   fprintf(ficrespijb,"#****** h Bij x Back probability to be in state i at age x-h being in j at x: B1j+B2j+...=1 ");
12925:   i1= pow(2,cptcoveff);
12926:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
12927:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
12928:   /*  	k=k+1;  */
12929:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
12930:     k=TKresult[nres];
12931:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
12932:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
12933:     /*    if(i1 != 1 && TKresult[nres]!= k) */
12934:     /* 	continue; */
12935:     fprintf(ficrespijb,"\n#****** ");
12936:     for(j=1;j<=cptcovs;j++){
12937:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
12938:       /* for(j=1;j<=cptcoveff;j++) */
12939:       /* 	fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
12940:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
12941:       /* 	fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
12942:     }
12943:     fprintf(ficrespijb,"******\n");
12944:     if(invalidvarcomb[k]){  /* Is it necessary here? */
12945:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
12946:       continue;
12947:     }
12948:     
12949:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
12950:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
12951:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
12952:       nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm+0.1)-1; /* Typically 20 years = 20*12/6=40 or 55*12/24=27.5-1.1=>27 */
12953:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
12954:       
12955:       /*	  nhstepm=nhstepm*YEARM; aff par mois*/
12956:       
12957:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
12958:       /* and memory limitations if stepm is small */
12959:       
12960:       /* oldm=oldms;savm=savms; */
12961:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
12962:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
12963:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
12964:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
12965:       for(i=1; i<=nlstate;i++)
12966: 	for(j=1; j<=nlstate+ndeath;j++)
12967: 	  fprintf(ficrespijb," %1d-%1d",i,j);
12968:       fprintf(ficrespijb,"\n");
12969:       for (h=0; h<=nhstepm; h++){
12970: 	/*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
12971: 	fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
12972: 	/* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
12973: 	for(i=1; i<=nlstate;i++)
12974: 	  for(j=1; j<=nlstate+ndeath;j++)
12975: 	    fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
12976: 	fprintf(ficrespijb,"\n");
12977:       }
12978:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
12979:       fprintf(ficrespijb,"\n");
12980:     } /* end age deb */
12981:     /* } /\* end combination *\/ */
12982:   } /* end nres */
12983:   return 0;
12984:  } /*  hBijx */
12985: 
12986: 
12987: /***********************************************/
12988: /**************** Main Program *****************/
12989: /***********************************************/
12990: 
12991: int main(int argc, char *argv[])
12992: {
12993: #ifdef GSL
12994:   const gsl_multimin_fminimizer_type *T;
12995:   size_t iteri = 0, it;
12996:   int rval = GSL_CONTINUE;
12997:   int status = GSL_SUCCESS;
12998:   double ssval;
12999: #endif
13000:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
13001:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
13002:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
13003:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
13004:   int jj, ll, li, lj, lk;
13005:   int numlinepar=0; /* Current linenumber of parameter file */
13006:   int num_filled;
13007:   int itimes;
13008:   int NDIM=2;
13009:   int vpopbased=0;
13010:   int nres=0;
13011:   int endishere=0;
13012:   int noffset=0;
13013:   int ncurrv=0; /* Temporary variable */
13014:   
13015:   char ca[32], cb[32];
13016:   /*  FILE *fichtm; *//* Html File */
13017:   /* FILE *ficgp;*/ /*Gnuplot File */
13018:   struct stat info;
13019:   double agedeb=0.;
13020: 
13021:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
13022:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
13023: 
13024:   double fret;
13025:   double dum=0.; /* Dummy variable */
13026:   double ***p3mat;
13027:   /* double ***mobaverage; */
13028:   double wald;
13029: 
13030:   char line[MAXLINE], linetmp[MAXLINE];
13031:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
13032: 
13033:   char  modeltemp[MAXLINE];
13034:   char resultline[MAXLINE], resultlineori[MAXLINE];
13035:   
13036:   char pathr[MAXLINE], pathimach[MAXLINE]; 
13037:   char *tok, *val; /* pathtot */
13038:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
13039:   int c,  h , cpt, c2;
13040:   int jl=0;
13041:   int i1, j1, jk, stepsize=0;
13042:   int count=0;
13043: 
13044:   int *tab; 
13045:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
13046:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
13047:   /* double anprojf, mprojf, jprojf; */
13048:   /* double jintmean,mintmean,aintmean;   */
13049:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
13050:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
13051:   double yrfproj= 10.0; /* Number of years of forward projections */
13052:   double yrbproj= 10.0; /* Number of years of backward projections */
13053:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
13054:   int mobilav=0,popforecast=0;
13055:   int hstepm=0, nhstepm=0;
13056:   int agemortsup;
13057:   float  sumlpop=0.;
13058:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
13059:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
13060: 
13061:   double bage=0, fage=110., age, agelim=0., agebase=0.;
13062:   double ftolpl=FTOL;
13063:   double **prlim;
13064:   double **bprlim;
13065:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
13066:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
13067:   double ***paramstart; /* Matrix of starting parameter values */
13068:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
13069:   double **matcov; /* Matrix of covariance */
13070:   double **hess; /* Hessian matrix */
13071:   double ***delti3; /* Scale */
13072:   double *delti; /* Scale */
13073:   double ***eij, ***vareij;
13074:   double **varpl; /* Variances of prevalence limits by age */
13075: 
13076:   double *epj, vepp;
13077: 
13078:   double dateprev1, dateprev2;
13079:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
13080:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
13081: 
13082: 
13083:   double **ximort;
13084:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
13085:   int *dcwave;
13086: 
13087:   char z[1]="c";
13088: 
13089:   /*char  *strt;*/
13090:   char strtend[80];
13091: 
13092: 
13093: /*   setlocale (LC_ALL, ""); */
13094: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
13095: /*   textdomain (PACKAGE); */
13096: /*   setlocale (LC_CTYPE, ""); */
13097: /*   setlocale (LC_MESSAGES, ""); */
13098: 
13099:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
13100:   rstart_time = time(NULL);  
13101:   /*  (void) gettimeofday(&start_time,&tzp);*/
13102:   start_time = *localtime(&rstart_time);
13103:   curr_time=start_time;
13104:   /*tml = *localtime(&start_time.tm_sec);*/
13105:   /* strcpy(strstart,asctime(&tml)); */
13106:   strcpy(strstart,asctime(&start_time));
13107: 
13108: /*  printf("Localtime (at start)=%s",strstart); */
13109: /*  tp.tm_sec = tp.tm_sec +86400; */
13110: /*  tm = *localtime(&start_time.tm_sec); */
13111: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
13112: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
13113: /*   tmg.tm_hour=tmg.tm_hour + 1; */
13114: /*   tp.tm_sec = mktime(&tmg); */
13115: /*   strt=asctime(&tmg); */
13116: /*   printf("Time(after) =%s",strstart);  */
13117: /*  (void) time (&time_value);
13118: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
13119: *  tm = *localtime(&time_value);
13120: *  strstart=asctime(&tm);
13121: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
13122: */
13123: 
13124:   nberr=0; /* Number of errors and warnings */
13125:   nbwarn=0;
13126: #ifdef WIN32
13127:   _getcwd(pathcd, size);
13128: #else
13129:   getcwd(pathcd, size);
13130: #endif
13131:   syscompilerinfo(0);
13132:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
13133:   if(argc <=1){
13134:     printf("\nEnter the parameter file name: ");
13135:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
13136:       printf("ERROR Empty parameter file name\n");
13137:       goto end;
13138:     }
13139:     i=strlen(pathr);
13140:     if(pathr[i-1]=='\n')
13141:       pathr[i-1]='\0';
13142:     i=strlen(pathr);
13143:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
13144:       pathr[i-1]='\0';
13145:     }
13146:     i=strlen(pathr);
13147:     if( i==0 ){
13148:       printf("ERROR Empty parameter file name\n");
13149:       goto end;
13150:     }
13151:     for (tok = pathr; tok != NULL; ){
13152:       printf("Pathr |%s|\n",pathr);
13153:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
13154:       printf("val= |%s| pathr=%s\n",val,pathr);
13155:       strcpy (pathtot, val);
13156:       if(pathr[0] == '\0') break; /* Dirty */
13157:     }
13158:   }
13159:   else if (argc<=2){
13160:     strcpy(pathtot,argv[1]);
13161:   }
13162:   else{
13163:     strcpy(pathtot,argv[1]);
13164:     strcpy(z,argv[2]);
13165:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
13166:   }
13167:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
13168:   /*cygwin_split_path(pathtot,path,optionfile);
13169:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
13170:   /* cutv(path,optionfile,pathtot,'\\');*/
13171: 
13172:   /* Split argv[0], imach program to get pathimach */
13173:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
13174:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
13175:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
13176:  /*   strcpy(pathimach,argv[0]); */
13177:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
13178:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
13179:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
13180: #ifdef WIN32
13181:   _chdir(path); /* Can be a relative path */
13182:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
13183: #else
13184:   chdir(path); /* Can be a relative path */
13185:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
13186: #endif
13187:   printf("Current directory %s!\n",pathcd);
13188:   strcpy(command,"mkdir ");
13189:   strcat(command,optionfilefiname);
13190:   if((outcmd=system(command)) != 0){
13191:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
13192:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
13193:     /* fclose(ficlog); */
13194: /*     exit(1); */
13195:   }
13196: /*   if((imk=mkdir(optionfilefiname))<0){ */
13197: /*     perror("mkdir"); */
13198: /*   } */
13199: 
13200:   /*-------- arguments in the command line --------*/
13201: 
13202:   /* Main Log file */
13203:   strcat(filelog, optionfilefiname);
13204:   strcat(filelog,".log");    /* */
13205:   if((ficlog=fopen(filelog,"w"))==NULL)    {
13206:     printf("Problem with logfile %s\n",filelog);
13207:     goto end;
13208:   }
13209:   fprintf(ficlog,"Log filename:%s\n",filelog);
13210:   fprintf(ficlog,"Version %s %s",version,fullversion);
13211:   fprintf(ficlog,"\nEnter the parameter file name: \n");
13212:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
13213:  path=%s \n\
13214:  optionfile=%s\n\
13215:  optionfilext=%s\n\
13216:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
13217: 
13218:   syscompilerinfo(1);
13219: 
13220:   printf("Local time (at start):%s",strstart);
13221:   fprintf(ficlog,"Local time (at start): %s",strstart);
13222:   fflush(ficlog);
13223: /*   (void) gettimeofday(&curr_time,&tzp); */
13224: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
13225: 
13226:   /* */
13227:   strcpy(fileres,"r");
13228:   strcat(fileres, optionfilefiname);
13229:   strcat(fileresu, optionfilefiname); /* Without r in front */
13230:   strcat(fileres,".txt");    /* Other files have txt extension */
13231:   strcat(fileresu,".txt");    /* Other files have txt extension */
13232: 
13233:   /* Main ---------arguments file --------*/
13234: 
13235:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
13236:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
13237:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
13238:     fflush(ficlog);
13239:     /* goto end; */
13240:     exit(70); 
13241:   }
13242: 
13243:   strcpy(filereso,"o");
13244:   strcat(filereso,fileresu);
13245:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
13246:     printf("Problem with Output resultfile: %s\n", filereso);
13247:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
13248:     fflush(ficlog);
13249:     goto end;
13250:   }
13251:       /*-------- Rewriting parameter file ----------*/
13252:   strcpy(rfileres,"r");    /* "Rparameterfile */
13253:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
13254:   strcat(rfileres,".");    /* */
13255:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
13256:   if((ficres =fopen(rfileres,"w"))==NULL) {
13257:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
13258:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
13259:     fflush(ficlog);
13260:     goto end;
13261:   }
13262:   fprintf(ficres,"#IMaCh %s\n",version);
13263: 
13264: 				      
13265:   /* Reads comments: lines beginning with '#' */
13266:   numlinepar=0;
13267:   /* Is it a BOM UTF-8 Windows file? */
13268:   /* First parameter line */
13269:   while(fgets(line, MAXLINE, ficpar)) {
13270:     noffset=0;
13271:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
13272:     {
13273:       noffset=noffset+3;
13274:       printf("# File is an UTF8 Bom.\n"); // 0xBF
13275:     }
13276: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
13277:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
13278:     {
13279:       noffset=noffset+2;
13280:       printf("# File is an UTF16BE BOM file\n");
13281:     }
13282:     else if( line[0] == 0 && line[1] == 0)
13283:     {
13284:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
13285: 	noffset=noffset+4;
13286: 	printf("# File is an UTF16BE BOM file\n");
13287:       }
13288:     } else{
13289:       ;/*printf(" Not a BOM file\n");*/
13290:     }
13291:   
13292:     /* If line starts with a # it is a comment */
13293:     if (line[noffset] == '#') {
13294:       numlinepar++;
13295:       fputs(line,stdout);
13296:       fputs(line,ficparo);
13297:       fputs(line,ficres);
13298:       fputs(line,ficlog);
13299:       continue;
13300:     }else
13301:       break;
13302:   }
13303:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
13304: 			title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
13305:     if (num_filled != 5) {
13306:       printf("Should be 5 parameters\n");
13307:       fprintf(ficlog,"Should be 5 parameters\n");
13308:     }
13309:     numlinepar++;
13310:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
13311:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
13312:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
13313:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
13314:   }
13315:   /* Second parameter line */
13316:   while(fgets(line, MAXLINE, ficpar)) {
13317:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
13318:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
13319:     if (line[0] == '#') {
13320:       numlinepar++;
13321:       printf("%s",line);
13322:       fprintf(ficres,"%s",line);
13323:       fprintf(ficparo,"%s",line);
13324:       fprintf(ficlog,"%s",line);
13325:       continue;
13326:     }else
13327:       break;
13328:   }
13329:   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", \
13330: 			&ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
13331:     if (num_filled != 11) {
13332:       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");
13333:       printf("but line=%s\n",line);
13334:       fprintf(ficlog,"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");
13335:       fprintf(ficlog,"but line=%s\n",line);
13336:     }
13337:     if( lastpass > maxwav){
13338:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
13339:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
13340:       fflush(ficlog);
13341:       goto end;
13342:     }
13343:       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);
13344:     fprintf(ficparo,"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);
13345:     fprintf(ficres,"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, 0, weightopt);
13346:     fprintf(ficlog,"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);
13347:   }
13348:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
13349:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
13350:   /* Third parameter line */
13351:   while(fgets(line, MAXLINE, ficpar)) {
13352:     /* If line starts with a # it is a comment */
13353:     if (line[0] == '#') {
13354:       numlinepar++;
13355:       printf("%s",line);
13356:       fprintf(ficres,"%s",line);
13357:       fprintf(ficparo,"%s",line);
13358:       fprintf(ficlog,"%s",line);
13359:       continue;
13360:     }else
13361:       break;
13362:   }
13363:   if((num_filled=sscanf(line,"model=%[^.\n]", model)) !=EOF){ /* Every character after model but dot and  return */
13364:     if (num_filled != 1){
13365:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
13366:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
13367:       model[0]='\0';
13368:       goto end;
13369:     }else{
13370:       trimbtab(linetmp,line); /* Trims multiple blanks in line */
13371:       strcpy(line, linetmp);
13372:     }
13373:   }
13374:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){ /* Every character after 1+age but dot and  return */
13375:     if (num_filled != 1){
13376:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
13377:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
13378:       model[0]='\0';
13379:       goto end;
13380:     }
13381:     else{
13382:       if (model[0]=='+'){
13383: 	for(i=1; i<=strlen(model);i++)
13384: 	  modeltemp[i-1]=model[i];
13385: 	strcpy(model,modeltemp); 
13386:       }
13387:     }
13388:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
13389:     printf("model=1+age+%s\n",model);fflush(stdout);
13390:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
13391:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
13392:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
13393:   }
13394:   /* 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); */
13395:   /* numlinepar=numlinepar+3; /\* In general *\/ */
13396:   /* 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); */
13397:   /* 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); */
13398:   /* 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); */
13399:   fflush(ficlog);
13400:   /* if(model[0]=='#'|| model[0]== '\0'){ */
13401:   if(model[0]=='#'){
13402:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
13403:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
13404:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");		\
13405:     if(mle != -1){
13406:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter vectors and subdiagonal covariance matrix.\n");
13407:       exit(1);
13408:     }
13409:   }
13410:   while((c=getc(ficpar))=='#' && c!= EOF){
13411:     ungetc(c,ficpar);
13412:     fgets(line, MAXLINE, ficpar);
13413:     numlinepar++;
13414:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
13415:       z[0]=line[1];
13416:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
13417:       debugILK=1;printf("DebugILK\n");
13418:     }
13419:     /* printf("****line [1] = %c \n",line[1]); */
13420:     fputs(line, stdout);
13421:     //puts(line);
13422:     fputs(line,ficparo);
13423:     fputs(line,ficlog);
13424:   }
13425:   ungetc(c,ficpar);
13426: 
13427:    
13428:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
13429:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
13430:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
13431:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
13432:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
13433:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
13434:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
13435:      v1+v2*age+v2*v3 makes cptcovn = 3
13436:   */
13437:   if (strlen(model)>1) 
13438:     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*/
13439:   else
13440:     ncovmodel=2; /* Constant and age */
13441:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
13442:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
13443:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
13444:     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);
13445:     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);
13446:     fflush(stdout);
13447:     fclose (ficlog);
13448:     goto end;
13449:   }
13450:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
13451:   delti=delti3[1][1];
13452:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
13453:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
13454: /* We could also provide initial parameters values giving by simple logistic regression 
13455:  * only one way, that is without matrix product. We will have nlstate maximizations */
13456:       /* for(i=1;i<nlstate;i++){ */
13457:       /* 	/\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
13458:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
13459:       /* } */
13460:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
13461:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
13462:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
13463:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
13464:     fclose (ficparo);
13465:     fclose (ficlog);
13466:     goto end;
13467:     exit(0);
13468:   }  else if(mle==-5) { /* Main Wizard */
13469:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
13470:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
13471:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
13472:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
13473:     matcov=matrix(1,npar,1,npar);
13474:     hess=matrix(1,npar,1,npar);
13475:   }  else{ /* Begin of mle != -1 or -5 */
13476:     /* Read guessed parameters */
13477:     /* Reads comments: lines beginning with '#' */
13478:     while((c=getc(ficpar))=='#' && c!= EOF){
13479:       ungetc(c,ficpar);
13480:       fgets(line, MAXLINE, ficpar);
13481:       numlinepar++;
13482:       fputs(line,stdout);
13483:       fputs(line,ficparo);
13484:       fputs(line,ficlog);
13485:     }
13486:     ungetc(c,ficpar);
13487:     
13488:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
13489:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
13490:     for(i=1; i <=nlstate; i++){
13491:       j=0;
13492:       for(jj=1; jj <=nlstate+ndeath; jj++){
13493: 	if(jj==i) continue;
13494: 	j++;
13495: 	while((c=getc(ficpar))=='#' && c!= EOF){
13496: 	  ungetc(c,ficpar);
13497: 	  fgets(line, MAXLINE, ficpar);
13498: 	  numlinepar++;
13499: 	  fputs(line,stdout);
13500: 	  fputs(line,ficparo);
13501: 	  fputs(line,ficlog);
13502: 	}
13503: 	ungetc(c,ficpar);
13504: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
13505: 	if ((i1 != i) || (j1 != jj)){
13506: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
13507: It might be a problem of design; if ncovcol and the model are correct\n \
13508: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
13509: 	  exit(1);
13510: 	}
13511: 	fprintf(ficparo,"%1d%1d",i1,j1);
13512: 	if(mle==1)
13513: 	  printf("%1d%1d",i,jj);
13514: 	fprintf(ficlog,"%1d%1d",i,jj);
13515: 	for(k=1; k<=ncovmodel;k++){
13516: 	  fscanf(ficpar," %lf",&param[i][j][k]);
13517: 	  if(mle==1){
13518: 	    printf(" %lf",param[i][j][k]);
13519: 	    fprintf(ficlog," %lf",param[i][j][k]);
13520: 	  }
13521: 	  else
13522: 	    fprintf(ficlog," %lf",param[i][j][k]);
13523: 	  fprintf(ficparo," %lf",param[i][j][k]);
13524: 	}
13525: 	fscanf(ficpar,"\n");
13526: 	numlinepar++;
13527: 	if(mle==1)
13528: 	  printf("\n");
13529: 	fprintf(ficlog,"\n");
13530: 	fprintf(ficparo,"\n");
13531:       }
13532:     }  
13533:     fflush(ficlog);
13534:     
13535:     /* Reads parameters values */
13536:     p=param[1][1];
13537:     pstart=paramstart[1][1];
13538:     
13539:     /* Reads comments: lines beginning with '#' */
13540:     while((c=getc(ficpar))=='#' && c!= EOF){
13541:       ungetc(c,ficpar);
13542:       fgets(line, MAXLINE, ficpar);
13543:       numlinepar++;
13544:       fputs(line,stdout);
13545:       fputs(line,ficparo);
13546:       fputs(line,ficlog);
13547:     }
13548:     ungetc(c,ficpar);
13549: 
13550:     for(i=1; i <=nlstate; i++){
13551:       for(j=1; j <=nlstate+ndeath-1; j++){
13552: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
13553: 	if ( (i1-i) * (j1-j) != 0){
13554: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
13555: 	  exit(1);
13556: 	}
13557: 	printf("%1d%1d",i,j);
13558: 	fprintf(ficparo,"%1d%1d",i1,j1);
13559: 	fprintf(ficlog,"%1d%1d",i1,j1);
13560: 	for(k=1; k<=ncovmodel;k++){
13561: 	  fscanf(ficpar,"%le",&delti3[i][j][k]);
13562: 	  printf(" %le",delti3[i][j][k]);
13563: 	  fprintf(ficparo," %le",delti3[i][j][k]);
13564: 	  fprintf(ficlog," %le",delti3[i][j][k]);
13565: 	}
13566: 	fscanf(ficpar,"\n");
13567: 	numlinepar++;
13568: 	printf("\n");
13569: 	fprintf(ficparo,"\n");
13570: 	fprintf(ficlog,"\n");
13571:       }
13572:     }
13573:     fflush(ficlog);
13574:     
13575:     /* Reads covariance matrix */
13576:     delti=delti3[1][1];
13577: 		
13578: 		
13579:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
13580: 		
13581:     /* Reads comments: lines beginning with '#' */
13582:     while((c=getc(ficpar))=='#' && c!= EOF){
13583:       ungetc(c,ficpar);
13584:       fgets(line, MAXLINE, ficpar);
13585:       numlinepar++;
13586:       fputs(line,stdout);
13587:       fputs(line,ficparo);
13588:       fputs(line,ficlog);
13589:     }
13590:     ungetc(c,ficpar);
13591: 		
13592:     matcov=matrix(1,npar,1,npar);
13593:     hess=matrix(1,npar,1,npar);
13594:     for(i=1; i <=npar; i++)
13595:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
13596: 		
13597:     /* Scans npar lines */
13598:     for(i=1; i <=npar; i++){
13599:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
13600:       if(count != 3){
13601: 	printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
13602: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
13603: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
13604: 	fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
13605: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
13606: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
13607: 	exit(1);
13608:       }else{
13609: 	if(mle==1)
13610: 	  printf("%1d%1d%d",i1,j1,jk);
13611:       }
13612:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
13613:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
13614:       for(j=1; j <=i; j++){
13615: 	fscanf(ficpar," %le",&matcov[i][j]);
13616: 	if(mle==1){
13617: 	  printf(" %.5le",matcov[i][j]);
13618: 	}
13619: 	fprintf(ficlog," %.5le",matcov[i][j]);
13620: 	fprintf(ficparo," %.5le",matcov[i][j]);
13621:       }
13622:       fscanf(ficpar,"\n");
13623:       numlinepar++;
13624:       if(mle==1)
13625: 				printf("\n");
13626:       fprintf(ficlog,"\n");
13627:       fprintf(ficparo,"\n");
13628:     }
13629:     /* End of read covariance matrix npar lines */
13630:     for(i=1; i <=npar; i++)
13631:       for(j=i+1;j<=npar;j++)
13632: 	matcov[i][j]=matcov[j][i];
13633:     
13634:     if(mle==1)
13635:       printf("\n");
13636:     fprintf(ficlog,"\n");
13637:     
13638:     fflush(ficlog);
13639:     
13640:   }    /* End of mle != -3 */
13641:   
13642:   /*  Main data
13643:    */
13644:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
13645:   /* num=lvector(1,n); */
13646:   /* moisnais=vector(1,n); */
13647:   /* annais=vector(1,n); */
13648:   /* moisdc=vector(1,n); */
13649:   /* andc=vector(1,n); */
13650:   /* weight=vector(1,n); */
13651:   /* agedc=vector(1,n); */
13652:   /* cod=ivector(1,n); */
13653:   /* for(i=1;i<=n;i++){ */
13654:   num=lvector(firstobs,lastobs);
13655:   moisnais=vector(firstobs,lastobs);
13656:   annais=vector(firstobs,lastobs);
13657:   moisdc=vector(firstobs,lastobs);
13658:   andc=vector(firstobs,lastobs);
13659:   weight=vector(firstobs,lastobs);
13660:   agedc=vector(firstobs,lastobs);
13661:   cod=ivector(firstobs,lastobs);
13662:   for(i=firstobs;i<=lastobs;i++){
13663:     num[i]=0;
13664:     moisnais[i]=0;
13665:     annais[i]=0;
13666:     moisdc[i]=0;
13667:     andc[i]=0;
13668:     agedc[i]=0;
13669:     cod[i]=0;
13670:     weight[i]=1.0; /* Equal weights, 1 by default */
13671:   }
13672:   mint=matrix(1,maxwav,firstobs,lastobs);
13673:   anint=matrix(1,maxwav,firstobs,lastobs);
13674:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
13675:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
13676:   tab=ivector(1,NCOVMAX);
13677:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
13678:   ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
13679: 
13680:   /* Reads data from file datafile */
13681:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
13682:     goto end;
13683: 
13684:   /* Calculation of the number of parameters from char model */
13685:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
13686: 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
13687: 	k=3 V4 Tvar[k=3]= 4 (from V4)
13688: 	k=2 V1 Tvar[k=2]= 1 (from V1)
13689: 	k=1 Tvar[1]=2 (from V2)
13690:   */
13691:   
13692:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
13693:   TvarsDind=ivector(1,NCOVMAX); /*  */
13694:   TnsdVar=ivector(1,NCOVMAX); /*  */
13695:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
13696:   TvarsD=ivector(1,NCOVMAX); /*  */
13697:   TvarsQind=ivector(1,NCOVMAX); /*  */
13698:   TvarsQ=ivector(1,NCOVMAX); /*  */
13699:   TvarF=ivector(1,NCOVMAX); /*  */
13700:   TvarFind=ivector(1,NCOVMAX); /*  */
13701:   TvarV=ivector(1,NCOVMAX); /*  */
13702:   TvarVind=ivector(1,NCOVMAX); /*  */
13703:   TvarA=ivector(1,NCOVMAX); /*  */
13704:   TvarAind=ivector(1,NCOVMAX); /*  */
13705:   TvarFD=ivector(1,NCOVMAX); /*  */
13706:   TvarFDind=ivector(1,NCOVMAX); /*  */
13707:   TvarFQ=ivector(1,NCOVMAX); /*  */
13708:   TvarFQind=ivector(1,NCOVMAX); /*  */
13709:   TvarVD=ivector(1,NCOVMAX); /*  */
13710:   TvarVDind=ivector(1,NCOVMAX); /*  */
13711:   TvarVQ=ivector(1,NCOVMAX); /*  */
13712:   TvarVQind=ivector(1,NCOVMAX); /*  */
13713:   TvarVV=ivector(1,NCOVMAX); /*  */
13714:   TvarVVind=ivector(1,NCOVMAX); /*  */
13715:   TvarVVA=ivector(1,NCOVMAX); /*  */
13716:   TvarVVAind=ivector(1,NCOVMAX); /*  */
13717:   TvarAVVA=ivector(1,NCOVMAX); /*  */
13718:   TvarAVVAind=ivector(1,NCOVMAX); /*  */
13719: 
13720:   Tvalsel=vector(1,NCOVMAX); /*  */
13721:   Tvarsel=ivector(1,NCOVMAX); /*  */
13722:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
13723:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
13724:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
13725:   DummyV=ivector(-1,NCOVMAX); /* 1 to 3 */
13726:   FixedV=ivector(-1,NCOVMAX); /* 1 to 3 */
13727: 
13728:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
13729:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
13730:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
13731:   */
13732:   /* For model-covariate k tells which data-covariate to use but
13733:     because this model-covariate is a construction we invent a new column
13734:     ncovcol + k1
13735:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
13736:     Tvar[3=V1*V4]=4+1 etc */
13737:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
13738:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
13739:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
13740:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
13741:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
13742:   */
13743:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
13744:   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
13745: 			    * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
13746: 			    * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
13747:   Tvardk=imatrix(0,NCOVMAX,1,2);
13748:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
13749: 			 4 covariates (3 plus signs)
13750: 			 Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
13751: 			   */  
13752:   for(i=1;i<NCOVMAX;i++)
13753:     Tage[i]=0;
13754:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
13755: 				* individual dummy, fixed or varying:
13756: 				* Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
13757: 				* 3, 1, 0, 0, 0, 0, 0, 0},
13758: 				* model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
13759: 				* V1 df, V2 qf, V3 & V4 dv, V5 qv
13760: 				* Tmodelind[1]@9={9,0,3,2,}*/
13761:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
13762:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
13763: 				* individual quantitative, fixed or varying:
13764: 				* Tmodelqind[1]=1,Tvaraff[1]@9={4,
13765: 				* 3, 1, 0, 0, 0, 0, 0, 0},
13766: 				* model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
13767: 
13768: /* Probably useless zeroes */
13769:   for(i=1;i<NCOVMAX;i++){
13770:     DummyV[i]=0;
13771:     FixedV[i]=0;
13772:   }
13773: 
13774:   for(i=1; i <=ncovcol;i++){
13775:     DummyV[i]=0;
13776:     FixedV[i]=0;
13777:   }
13778:   for(i=ncovcol+1; i <=ncovcol+nqv;i++){
13779:     DummyV[i]=1;
13780:     FixedV[i]=0;
13781:   }
13782:   for(i=ncovcol+nqv+1; i <=ncovcol+nqv+ntv;i++){
13783:     DummyV[i]=0;
13784:     FixedV[i]=1;
13785:   }
13786:   for(i=ncovcol+nqv+ntv+1; i <=ncovcol+nqv+ntv+nqtv;i++){
13787:     DummyV[i]=1;
13788:     FixedV[i]=1;
13789:   }
13790:   for(i=1; i <=ncovcol+nqv+ntv+nqtv;i++){
13791:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",i,i,DummyV[i],i,FixedV[i]);
13792:     fprintf(ficlog,"Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",i,i,DummyV[i],i,FixedV[i]);
13793:   }
13794: 
13795: 
13796: 
13797: /* Main decodemodel */
13798: 
13799: 
13800:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
13801:     goto end;
13802: 
13803:   if((double)(lastobs-imx)/(double)imx > 1.10){
13804:     nbwarn++;
13805:     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); 
13806:     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); 
13807:   }
13808:     /*  if(mle==1){*/
13809:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
13810:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
13811:   }
13812: 
13813:     /*-calculation of age at interview from date of interview and age at death -*/
13814:   agev=matrix(1,maxwav,1,imx);
13815: 
13816:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
13817:     goto end;
13818: 
13819: 
13820:   agegomp=(int)agemin;
13821:   free_vector(moisnais,firstobs,lastobs);
13822:   free_vector(annais,firstobs,lastobs);
13823:   /* free_matrix(mint,1,maxwav,1,n);
13824:      free_matrix(anint,1,maxwav,1,n);*/
13825:   /* free_vector(moisdc,1,n); */
13826:   /* free_vector(andc,1,n); */
13827:   /* */
13828:   
13829:   wav=ivector(1,imx);
13830:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
13831:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
13832:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
13833:   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.*/
13834:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
13835:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
13836:    
13837:   /* Concatenates waves */
13838:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
13839:      Death is a valid wave (if date is known).
13840:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
13841:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
13842:      and mw[mi+1][i]. dh depends on stepm.
13843:   */
13844: 
13845:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
13846:   /* Concatenates waves */
13847:  
13848:   free_vector(moisdc,firstobs,lastobs);
13849:   free_vector(andc,firstobs,lastobs);
13850: 
13851:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
13852:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
13853:   ncodemax[1]=1;
13854:   Ndum =ivector(-1,NCOVMAX);  
13855:   cptcoveff=0;
13856:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
13857:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; as well as calculate cptcoveff or number of total effective dummy covariates*/
13858:   }
13859:   
13860:   ncovcombmax=pow(2,cptcoveff);
13861:   invalidvarcomb=ivector(0, ncovcombmax); 
13862:   for(i=0;i<ncovcombmax;i++)
13863:     invalidvarcomb[i]=0;
13864:   
13865:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
13866:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
13867:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
13868:   
13869:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
13870:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
13871:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
13872:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
13873:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
13874:    * (currently 0 or 1) in the data.
13875:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
13876:    * corresponding modality (h,j).
13877:    */
13878: 
13879:   h=0;
13880:   /*if (cptcovn > 0) */
13881:   m=pow(2,cptcoveff);
13882:  
13883: 	  /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
13884: 	   * For k=4 covariates, h goes from 1 to m=2**k
13885: 	   * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
13886:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
13887: 	   *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
13888: 	   *______________________________   *______________________
13889: 	   *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
13890: 	   *     2     2     1     1     1   *     1     0  0  0  1 
13891: 	   *     3 i=2 1     2     1     1   *     2     0  0  1  0 
13892: 	   *     4     2     2     1     1   *     3     0  0  1  1 
13893: 	   *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
13894: 	   *     6     2     1     2     1   *     5     0  1  0  1 
13895: 	   *     7 i=4 1     2     2     1   *     6     0  1  1  0 
13896: 	   *     8     2     2     2     1   *     7     0  1  1  1 
13897: 	   *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
13898: 	   *    10     2     1     1     2   *     9     1  0  0  1 
13899: 	   *    11 i=6 1     2     1     2   *    10     1  0  1  0 
13900: 	   *    12     2     2     1     2   *    11     1  0  1  1 
13901: 	   *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
13902: 	   *    14     2     1     2     2   *    13     1  1  0  1 
13903: 	   *    15 i=8 1     2     2     2   *    14     1  1  1  0 
13904: 	   *    16     2     2     2     2   *    15     1  1  1  1          
13905: 	   */					  
13906:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
13907:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
13908:      * and the value of each covariate?
13909:      * V1=1, V2=1, V3=2, V4=1 ?
13910:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
13911:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
13912:      * In order to get the real value in the data, we use nbcode
13913:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
13914:      * We are keeping this crazy system in order to be able (in the future?) 
13915:      * to have more than 2 values (0 or 1) for a covariate.
13916:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
13917:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
13918:      *              bbbbbbbb
13919:      *              76543210     
13920:      *   h-1        00000101 (6-1=5)
13921:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
13922:      *           &
13923:      *     1        00000001 (1)
13924:      *              00000000        = 1 & ((h-1) >> (k-1))
13925:      *          +1= 00000001 =1 
13926:      *
13927:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
13928:      *          h'      1101 =2^3+2^2+0x2^1+2^0
13929:      *    >>k'            11
13930:      *          &   00000001
13931:      *            = 00000001
13932:      *      +1    = 00000010=2    =  codtabm(14,3)   
13933:      * Reverse h=6 and m=16?
13934:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
13935:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
13936:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
13937:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
13938:      * V3=decodtabm(14,3,2**4)=2
13939:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
13940:      *(h-1) >> (j-1)    0011 =13 >> 2
13941:      *          &1 000000001
13942:      *           = 000000001
13943:      *         +1= 000000010 =2
13944:      *                  2211
13945:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
13946:      *                  V3=2
13947: 		 * codtabm and decodtabm are identical
13948:      */
13949: 
13950: 
13951:  free_ivector(Ndum,-1,NCOVMAX);
13952: 
13953: 
13954:     
13955:   /* Initialisation of ----------- gnuplot -------------*/
13956:   strcpy(optionfilegnuplot,optionfilefiname);
13957:   if(mle==-3)
13958:     strcat(optionfilegnuplot,"-MORT_");
13959:   strcat(optionfilegnuplot,".gp");
13960: 
13961:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
13962:     printf("Problem with file %s",optionfilegnuplot);
13963:   }
13964:   else{
13965:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
13966:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
13967:     //fprintf(ficgp,"set missing 'NaNq'\n");
13968:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
13969:   }
13970:   /*  fclose(ficgp);*/
13971: 
13972: 
13973:   /* Initialisation of --------- index.htm --------*/
13974: 
13975:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
13976:   if(mle==-3)
13977:     strcat(optionfilehtm,"-MORT_");
13978:   strcat(optionfilehtm,".htm");
13979:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
13980:     printf("Problem with %s \n",optionfilehtm);
13981:     exit(0);
13982:   }
13983: 
13984:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
13985:   strcat(optionfilehtmcov,"-cov.htm");
13986:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
13987:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
13988:   }
13989:   else{
13990:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
13991: <hr size=\"2\" color=\"#EC5E5E\"> \n\
13992: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
13993: 	  optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
13994:   }
13995: 
13996:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
13997: <title>IMaCh %s</title></head>\n\
13998:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
13999: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
14000: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
14001: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
14002: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
14003:   
14004:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
14005: <font size=\"2\">IMaCh-%s <br> %s</font> \
14006: <hr size=\"2\" color=\"#EC5E5E\"> \n\
14007: This file: <a href=\"%s\">%s</a></br>Title=%s <br>Datafile=<a href=\"%s\">%s</a> Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
14008: \n\
14009: <hr  size=\"2\" color=\"#EC5E5E\">\
14010:  <ul><li><h4>Parameter files</h4>\n\
14011:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
14012:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
14013:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
14014:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
14015:  - Date and time at start: %s</ul>\n",\
14016: 	  version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
14017: 	  optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
14018: 	  fileres,fileres,\
14019: 	  filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
14020:   fflush(fichtm);
14021: 
14022:   strcpy(pathr,path);
14023:   strcat(pathr,optionfilefiname);
14024: #ifdef WIN32
14025:   _chdir(optionfilefiname); /* Move to directory named optionfile */
14026: #else
14027:   chdir(optionfilefiname); /* Move to directory named optionfile */
14028: #endif
14029: 	  
14030:   
14031:   /* Calculates basic frequencies. Computes observed prevalence at single age 
14032: 		 and for any valid combination of covariates
14033:      and prints on file fileres'p'. */
14034:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
14035: 	      firstpass, lastpass,  stepm,  weightopt, model);
14036: 
14037:   fprintf(fichtm,"\n");
14038:   fprintf(fichtm,"<h4>Parameter line 2</h4><ul><li>Tolerance for the convergence of the likelihood: ftol=%g \n<li>Interval for the elementary matrix (in month): stepm=%d",\
14039: 	  ftol, stepm);
14040:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
14041:   ncurrv=1;
14042:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
14043:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
14044:   ncurrv=i;
14045:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
14046:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
14047:   ncurrv=i;
14048:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
14049:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
14050:   ncurrv=i;
14051:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
14052:   fprintf(fichtm,"\n<li>Weights column \n<br>Number of alive states: nlstate=%d <br>Number of death states (not really implemented): ndeath=%d \n<li>Number of waves: maxwav=%d \n<li>Parameter for maximization (1), using parameter values (0), for design of parameters and variance-covariance matrix: mle=%d \n<li>Does the weight column be taken into account (1), or not (0): weight=%d</ul>\n", \
14053: 	   nlstate, ndeath, maxwav, mle, weightopt);
14054: 
14055:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
14056: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
14057: 
14058:   
14059:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
14060: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
14061: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
14062:   imx,agemin,agemax,jmin,jmax,jmean);
14063:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
14064:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
14065:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
14066:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
14067:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
14068: 
14069:   /* For Powell, parameters are in a vector p[] starting at p[1]
14070:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
14071:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
14072: 
14073:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
14074:   /* For mortality only */
14075:   if (mle==-3){
14076:     ximort=matrix(1,NDIM,1,NDIM); 
14077:     for(i=1;i<=NDIM;i++)
14078:       for(j=1;j<=NDIM;j++)
14079: 	ximort[i][j]=0.;
14080:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
14081:     cens=ivector(firstobs,lastobs);
14082:     ageexmed=vector(firstobs,lastobs);
14083:     agecens=vector(firstobs,lastobs);
14084:     dcwave=ivector(firstobs,lastobs);
14085: 		
14086:     for (i=1; i<=imx; i++){
14087:       dcwave[i]=-1;
14088:       for (m=firstpass; m<=lastpass; m++)
14089: 	if (s[m][i]>nlstate) {
14090: 	  dcwave[i]=m;
14091: 	  /*	printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
14092: 	  break;
14093: 	}
14094:     }
14095:     
14096:     for (i=1; i<=imx; i++) {
14097:       if (wav[i]>0){
14098: 	ageexmed[i]=agev[mw[1][i]][i];
14099: 	j=wav[i];
14100: 	agecens[i]=1.; 
14101: 	
14102: 	if (ageexmed[i]> 1 && wav[i] > 0){
14103: 	  agecens[i]=agev[mw[j][i]][i];
14104: 	  cens[i]= 1;
14105: 	}else if (ageexmed[i]< 1) 
14106: 	  cens[i]= -1;
14107: 	if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
14108: 	  cens[i]=0 ;
14109:       }
14110:       else cens[i]=-1;
14111:     }
14112:     
14113:     for (i=1;i<=NDIM;i++) {
14114:       for (j=1;j<=NDIM;j++)
14115: 	ximort[i][j]=(i == j ? 1.0 : 0.0);
14116:     }
14117:     
14118:     p[1]=0.0268; p[NDIM]=0.083;
14119:     /* printf("%lf %lf", p[1], p[2]); */
14120:     
14121:     
14122: #ifdef GSL
14123:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
14124: #else
14125:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
14126: #endif
14127:     strcpy(filerespow,"POW-MORT_"); 
14128:     strcat(filerespow,fileresu);
14129:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
14130:       printf("Problem with resultfile: %s\n", filerespow);
14131:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
14132:     }
14133: #ifdef GSL
14134:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
14135: #else
14136:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
14137: #endif
14138:     /*  for (i=1;i<=nlstate;i++)
14139: 	for(j=1;j<=nlstate+ndeath;j++)
14140: 	if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
14141:     */
14142:     fprintf(ficrespow,"\n");
14143: #ifdef GSL
14144:     /* gsl starts here */ 
14145:     T = gsl_multimin_fminimizer_nmsimplex;
14146:     gsl_multimin_fminimizer *sfm = NULL;
14147:     gsl_vector *ss, *x;
14148:     gsl_multimin_function minex_func;
14149: 
14150:     /* Initial vertex size vector */
14151:     ss = gsl_vector_alloc (NDIM);
14152:     
14153:     if (ss == NULL){
14154:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
14155:     }
14156:     /* Set all step sizes to 1 */
14157:     gsl_vector_set_all (ss, 0.001);
14158: 
14159:     /* Starting point */
14160:     
14161:     x = gsl_vector_alloc (NDIM);
14162:     
14163:     if (x == NULL){
14164:       gsl_vector_free(ss);
14165:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
14166:     }
14167:   
14168:     /* Initialize method and iterate */
14169:     /*     p[1]=0.0268; p[NDIM]=0.083; */
14170:     /*     gsl_vector_set(x, 0, 0.0268); */
14171:     /*     gsl_vector_set(x, 1, 0.083); */
14172:     gsl_vector_set(x, 0, p[1]);
14173:     gsl_vector_set(x, 1, p[2]);
14174: 
14175:     minex_func.f = &gompertz_f;
14176:     minex_func.n = NDIM;
14177:     minex_func.params = (void *)&p; /* ??? */
14178:     
14179:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
14180:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
14181:     
14182:     printf("Iterations beginning .....\n\n");
14183:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
14184: 
14185:     iteri=0;
14186:     while (rval == GSL_CONTINUE){
14187:       iteri++;
14188:       status = gsl_multimin_fminimizer_iterate(sfm);
14189:       
14190:       if (status) printf("error: %s\n", gsl_strerror (status));
14191:       fflush(0);
14192:       
14193:       if (status) 
14194:         break;
14195:       
14196:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
14197:       ssval = gsl_multimin_fminimizer_size (sfm);
14198:       
14199:       if (rval == GSL_SUCCESS)
14200:         printf ("converged to a local maximum at\n");
14201:       
14202:       printf("%5d ", iteri);
14203:       for (it = 0; it < NDIM; it++){
14204: 	printf ("%10.5f ", gsl_vector_get (sfm->x, it));
14205:       }
14206:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
14207:     }
14208:     
14209:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
14210:     
14211:     gsl_vector_free(x); /* initial values */
14212:     gsl_vector_free(ss); /* inital step size */
14213:     for (it=0; it<NDIM; it++){
14214:       p[it+1]=gsl_vector_get(sfm->x,it);
14215:       fprintf(ficrespow," %.12lf", p[it]);
14216:     }
14217:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
14218: #endif
14219: #ifdef POWELL
14220:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
14221: #endif  
14222:     fclose(ficrespow);
14223:     
14224:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
14225: 
14226:     for(i=1; i <=NDIM; i++)
14227:       for(j=i+1;j<=NDIM;j++)
14228: 				matcov[i][j]=matcov[j][i];
14229:     
14230:     printf("\nCovariance matrix\n ");
14231:     fprintf(ficlog,"\nCovariance matrix\n ");
14232:     for(i=1; i <=NDIM; i++) {
14233:       for(j=1;j<=NDIM;j++){ 
14234: 				printf("%f ",matcov[i][j]);
14235: 				fprintf(ficlog,"%f ",matcov[i][j]);
14236:       }
14237:       printf("\n ");  fprintf(ficlog,"\n ");
14238:     }
14239:     
14240:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
14241:     for (i=1;i<=NDIM;i++) {
14242:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
14243:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
14244:     }
14245:     lsurv=vector(agegomp,AGESUP);
14246:     lpop=vector(agegomp,AGESUP);
14247:     tpop=vector(agegomp,AGESUP);
14248:     lsurv[agegomp]=100000;
14249:     
14250:     for (k=agegomp;k<=AGESUP;k++) {
14251:       agemortsup=k;
14252:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
14253:     }
14254:     
14255:     for (k=agegomp;k<agemortsup;k++)
14256:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
14257:     
14258:     for (k=agegomp;k<agemortsup;k++){
14259:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
14260:       sumlpop=sumlpop+lpop[k];
14261:     }
14262:     
14263:     tpop[agegomp]=sumlpop;
14264:     for (k=agegomp;k<(agemortsup-3);k++){
14265:       /*  tpop[k+1]=2;*/
14266:       tpop[k+1]=tpop[k]-lpop[k];
14267:     }
14268:     
14269:     
14270:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
14271:     for (k=agegomp;k<(agemortsup-2);k++) 
14272:       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]);
14273:     
14274:     
14275:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
14276: 		ageminpar=50;
14277: 		agemaxpar=100;
14278:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
14279:       	printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
14280: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
14281: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
14282:       	fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
14283: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
14284: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
14285:     }else{
14286: 			printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
14287: 			fprintf(ficlog,"Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
14288:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
14289: 		}
14290:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
14291: 		     stepm, weightopt,\
14292: 		     model,imx,p,matcov,agemortsup);
14293:     
14294:     free_vector(lsurv,agegomp,AGESUP);
14295:     free_vector(lpop,agegomp,AGESUP);
14296:     free_vector(tpop,agegomp,AGESUP);
14297:     free_matrix(ximort,1,NDIM,1,NDIM);
14298:     free_ivector(dcwave,firstobs,lastobs);
14299:     free_vector(agecens,firstobs,lastobs);
14300:     free_vector(ageexmed,firstobs,lastobs);
14301:     free_ivector(cens,firstobs,lastobs);
14302: #ifdef GSL
14303: #endif
14304:   } /* Endof if mle==-3 mortality only */
14305:   /* Standard  */
14306:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
14307:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
14308:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
14309:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
14310:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
14311:     for (k=1; k<=npar;k++)
14312:       printf(" %d %8.5f",k,p[k]);
14313:     printf("\n");
14314:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
14315:       /* mlikeli uses func not funcone */
14316:       /* for(i=1;i<nlstate;i++){ */
14317:       /* 	/\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
14318:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
14319:       /* } */
14320:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
14321:     }
14322:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
14323:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
14324:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
14325:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
14326:     }
14327:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
14328:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
14329:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
14330:           /* exit(0); */
14331:     for (k=1; k<=npar;k++)
14332:       printf(" %d %8.5f",k,p[k]);
14333:     printf("\n");
14334:     
14335:     /*--------- results files --------------*/
14336:     /* 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); */
14337:     
14338:     
14339:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
14340:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
14341:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
14342: 
14343:     printf("#model=  1      +     age ");
14344:     fprintf(ficres,"#model=  1      +     age ");
14345:     fprintf(ficlog,"#model=  1      +     age ");
14346:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
14347: </ul>", model);
14348: 
14349:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
14350:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
14351:     if(nagesqr==1){
14352:       printf("  + age*age  ");
14353:       fprintf(ficres,"  + age*age  ");
14354:       fprintf(ficlog,"  + age*age  ");
14355:       fprintf(fichtm, "<th>+ age*age</th>");
14356:     }
14357:     for(j=1;j <=ncovmodel-2;j++){
14358:       if(Typevar[j]==0) {
14359: 	printf("  +      V%d  ",Tvar[j]);
14360: 	fprintf(ficres,"  +      V%d  ",Tvar[j]);
14361: 	fprintf(ficlog,"  +      V%d  ",Tvar[j]);
14362: 	fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
14363:       }else if(Typevar[j]==1) {
14364: 	printf("  +    V%d*age ",Tvar[j]);
14365: 	fprintf(ficres,"  +    V%d*age ",Tvar[j]);
14366: 	fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
14367: 	fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
14368:       }else if(Typevar[j]==2) {
14369: 	printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
14370: 	fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
14371: 	fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
14372: 	fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
14373:       }else if(Typevar[j]==3) { /* TO VERIFY */
14374: 	printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
14375: 	fprintf(ficres,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
14376: 	fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
14377: 	fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
14378:       }
14379:     }
14380:     printf("\n");
14381:     fprintf(ficres,"\n");
14382:     fprintf(ficlog,"\n");
14383:     fprintf(fichtm, "</tr>");
14384:     fprintf(fichtm, "\n");
14385:     
14386:     
14387:     for(i=1,jk=1; i <=nlstate; i++){
14388:       for(k=1; k <=(nlstate+ndeath); k++){
14389: 	if (k != i) {
14390: 	  fprintf(fichtm, "<tr>");
14391: 	  printf("%d%d ",i,k);
14392: 	  fprintf(ficlog,"%d%d ",i,k);
14393: 	  fprintf(ficres,"%1d%1d ",i,k);
14394: 	  fprintf(fichtm, "<td>%1d%1d</td>",i,k);
14395: 	  for(j=1; j <=ncovmodel; j++){
14396: 	    printf("%12.7f ",p[jk]);
14397: 	    fprintf(ficlog,"%12.7f ",p[jk]);
14398: 	    fprintf(ficres,"%12.7f ",p[jk]);
14399: 	    fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
14400: 	    jk++; 
14401: 	  }
14402: 	  printf("\n");
14403: 	  fprintf(ficlog,"\n");
14404: 	  fprintf(ficres,"\n");
14405: 	  fprintf(fichtm, "</tr>\n");
14406: 	}
14407:       }
14408:     }
14409:     /* fprintf(fichtm,"</tr>\n"); */
14410:     fprintf(fichtm,"</table>\n");
14411:     fprintf(fichtm, "\n");
14412: 
14413:     if(mle != 0){
14414:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
14415:       ftolhess=ftol; /* Usually correct */
14416:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
14417:       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");
14418:       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");
14419:       fprintf(fichtm, "\n<p>The Wald test results are output only if the maximimzation of the Likelihood is performed (mle=1)\n</br>Parameters, Wald tests and Wald-based confidence intervals\n</br> W is simply the result of the division of the parameter by the square root of covariance of the parameter.\n</br> And Wald-based confidence intervals plus and minus 1.96 * W \n </br> It might be better to visualize the covariance matrix. See the page '<a href=\"%s\">Matrix of variance-covariance of one-step probabilities and its graphs</a>'.\n</br>",optionfilehtmcov);
14420:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
14421:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
14422:       if(nagesqr==1){
14423: 	printf("  + age*age  ");
14424: 	fprintf(ficres,"  + age*age  ");
14425: 	fprintf(ficlog,"  + age*age  ");
14426: 	fprintf(fichtm, "<th>+ age*age</th>");
14427:       }
14428:       for(j=1;j <=ncovmodel-2;j++){
14429: 	if(Typevar[j]==0) {
14430: 	  printf("  +      V%d  ",Tvar[j]);
14431: 	  fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
14432: 	}else if(Typevar[j]==1) {
14433: 	  printf("  +    V%d*age ",Tvar[j]);
14434: 	  fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
14435: 	}else if(Typevar[j]==2) {
14436: 	  fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
14437: 	}else if(Typevar[j]==3) { /* TO VERIFY */
14438: 	  fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
14439: 	}
14440:       }
14441:       fprintf(fichtm, "</tr>\n");
14442:  
14443:       for(i=1,jk=1; i <=nlstate; i++){
14444: 	for(k=1; k <=(nlstate+ndeath); k++){
14445: 	  if (k != i) {
14446: 	    fprintf(fichtm, "<tr valign=top>");
14447: 	    printf("%d%d ",i,k);
14448: 	    fprintf(ficlog,"%d%d ",i,k);
14449: 	    fprintf(fichtm, "<td>%1d%1d</td>",i,k);
14450: 	    for(j=1; j <=ncovmodel; j++){
14451: 	      wald=p[jk]/sqrt(matcov[jk][jk]);
14452: 	      printf("%12.7f(%12.7f) W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk],sqrt(matcov[jk][jk]), p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
14453: 	      fprintf(ficlog,"%12.7f(%12.7f) W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk],sqrt(matcov[jk][jk]), p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
14454: 	      if(fabs(wald) > 1.96){
14455: 		fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
14456: 	      }else{
14457: 		fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
14458: 	      }
14459: 	      fprintf(fichtm,"W=%8.3f</br>",wald);
14460: 	      fprintf(fichtm,"[%12.7f;%12.7f]</br></td>", p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
14461: 	      jk++; 
14462: 	    }
14463: 	    printf("\n");
14464: 	    fprintf(ficlog,"\n");
14465: 	    fprintf(fichtm, "</tr>\n");
14466: 	  }
14467: 	}
14468:       }
14469:     } /* end of hesscov and Wald tests */
14470:     fprintf(fichtm,"</table>\n");
14471:     
14472:     /*  */
14473:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
14474:     printf("# Scales (for hessian or gradient estimation)\n");
14475:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
14476:     for(i=1,jk=1; i <=nlstate; i++){
14477:       for(j=1; j <=nlstate+ndeath; j++){
14478: 	if (j!=i) {
14479: 	  fprintf(ficres,"%1d%1d",i,j);
14480: 	  printf("%1d%1d",i,j);
14481: 	  fprintf(ficlog,"%1d%1d",i,j);
14482: 	  for(k=1; k<=ncovmodel;k++){
14483: 	    printf(" %.5e",delti[jk]);
14484: 	    fprintf(ficlog," %.5e",delti[jk]);
14485: 	    fprintf(ficres," %.5e",delti[jk]);
14486: 	    jk++;
14487: 	  }
14488: 	  printf("\n");
14489: 	  fprintf(ficlog,"\n");
14490: 	  fprintf(ficres,"\n");
14491: 	}
14492:       }
14493:     }
14494:     
14495:     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");
14496:     if(mle >= 1) /* Too big for the screen */
14497:       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");
14498:     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");
14499:     /* # 121 Var(a12)\n\ */
14500:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
14501:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
14502:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
14503:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
14504:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
14505:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
14506:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
14507:     
14508:     
14509:     /* Just to have a covariance matrix which will be more understandable
14510:        even is we still don't want to manage dictionary of variables
14511:     */
14512:     for(itimes=1;itimes<=2;itimes++){
14513:       jj=0;
14514:       for(i=1; i <=nlstate; i++){
14515: 	for(j=1; j <=nlstate+ndeath; j++){
14516: 	  if(j==i) continue;
14517: 	  for(k=1; k<=ncovmodel;k++){
14518: 	    jj++;
14519: 	    ca[0]= k+'a'-1;ca[1]='\0';
14520: 	    if(itimes==1){
14521: 	      if(mle>=1)
14522: 		printf("#%1d%1d%d",i,j,k);
14523: 	      fprintf(ficlog,"#%1d%1d%d",i,j,k);
14524: 	      fprintf(ficres,"#%1d%1d%d",i,j,k);
14525: 	    }else{
14526: 	      if(mle>=1)
14527: 		printf("%1d%1d%d",i,j,k);
14528: 	      fprintf(ficlog,"%1d%1d%d",i,j,k);
14529: 	      fprintf(ficres,"%1d%1d%d",i,j,k);
14530: 	    }
14531: 	    ll=0;
14532: 	    for(li=1;li <=nlstate; li++){
14533: 	      for(lj=1;lj <=nlstate+ndeath; lj++){
14534: 		if(lj==li) continue;
14535: 		for(lk=1;lk<=ncovmodel;lk++){
14536: 		  ll++;
14537: 		  if(ll<=jj){
14538: 		    cb[0]= lk +'a'-1;cb[1]='\0';
14539: 		    if(ll<jj){
14540: 		      if(itimes==1){
14541: 			if(mle>=1)
14542: 			  printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
14543: 			fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
14544: 			fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
14545: 		      }else{
14546: 			if(mle>=1)
14547: 			  printf(" %.5e",matcov[jj][ll]); 
14548: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
14549: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
14550: 		      }
14551: 		    }else{
14552: 		      if(itimes==1){
14553: 			if(mle>=1)
14554: 			  printf(" Var(%s%1d%1d)",ca,i,j);
14555: 			fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
14556: 			fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
14557: 		      }else{
14558: 			if(mle>=1)
14559: 			  printf(" %.7e",matcov[jj][ll]); 
14560: 			fprintf(ficlog," %.7e",matcov[jj][ll]); 
14561: 			fprintf(ficres," %.7e",matcov[jj][ll]); 
14562: 		      }
14563: 		    }
14564: 		  }
14565: 		} /* end lk */
14566: 	      } /* end lj */
14567: 	    } /* end li */
14568: 	    if(mle>=1)
14569: 	      printf("\n");
14570: 	    fprintf(ficlog,"\n");
14571: 	    fprintf(ficres,"\n");
14572: 	    numlinepar++;
14573: 	  } /* end k*/
14574: 	} /*end j */
14575:       } /* end i */
14576:     } /* end itimes */
14577:     
14578:     fflush(ficlog);
14579:     fflush(ficres);
14580:     while(fgets(line, MAXLINE, ficpar)) {
14581:       /* If line starts with a # it is a comment */
14582:       if (line[0] == '#') {
14583: 	numlinepar++;
14584: 	fputs(line,stdout);
14585: 	fputs(line,ficparo);
14586: 	fputs(line,ficlog);
14587: 	fputs(line,ficres);
14588: 	continue;
14589:       }else
14590: 	break;
14591:     }
14592:     
14593:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
14594:     /*   ungetc(c,ficpar); */
14595:     /*   fgets(line, MAXLINE, ficpar); */
14596:     /*   fputs(line,stdout); */
14597:     /*   fputs(line,ficparo); */
14598:     /* } */
14599:     /* ungetc(c,ficpar); */
14600:     
14601:     estepm=0;
14602:     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){
14603:       
14604:       if (num_filled != 6) {
14605: 	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);
14606: 	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);
14607: 	goto end;
14608:       }
14609:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
14610:     }
14611:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
14612:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
14613:     
14614:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
14615:     if (estepm==0 || estepm < stepm) estepm=stepm;
14616:     if (fage <= 2) {
14617:       bage = ageminpar;
14618:       fage = agemaxpar;
14619:     }
14620:     
14621:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
14622:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
14623:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
14624: 		
14625:     /* Other stuffs, more or less useful */    
14626:     while(fgets(line, MAXLINE, ficpar)) {
14627:       /* If line starts with a # it is a comment */
14628:       if (line[0] == '#') {
14629: 	numlinepar++;
14630: 	fputs(line,stdout);
14631: 	fputs(line,ficparo);
14632: 	fputs(line,ficlog);
14633: 	fputs(line,ficres);
14634: 	continue;
14635:       }else
14636: 	break;
14637:     }
14638: 
14639:     if((num_filled=sscanf(line,"begin-prev-date=%lf/%lf/%lf end-prev-date=%lf/%lf/%lf mov_average=%d\n",&jprev1, &mprev1,&anprev1,&jprev2, &mprev2,&anprev2,&mobilav)) !=EOF){
14640:       
14641:       if (num_filled != 7) {
14642: 	printf("Error: Not 7 (data)parameters in line but %d, for example:begin-prev-date=1/1/1990 end-prev-date=1/6/2004  mov_average=0\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
14643: 	fprintf(ficlog,"Error: Not 7 (data)parameters in line but %d, for example:begin-prev-date=1/1/1990 end-prev-date=1/6/2004  mov_average=0\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
14644: 	goto end;
14645:       }
14646:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
14647:       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);
14648:       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);
14649:       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);
14650:     }
14651: 
14652:     while(fgets(line, MAXLINE, ficpar)) {
14653:       /* If line starts with a # it is a comment */
14654:       if (line[0] == '#') {
14655: 	numlinepar++;
14656: 	fputs(line,stdout);
14657: 	fputs(line,ficparo);
14658: 	fputs(line,ficlog);
14659: 	fputs(line,ficres);
14660: 	continue;
14661:       }else
14662: 	break;
14663:     }
14664:     
14665:     
14666:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
14667:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
14668:     
14669:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
14670:       if (num_filled != 1) {
14671: 	printf("Error: Not 1 (data)parameters in line but %d, for example:pop_based=0\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
14672: 	fprintf(ficlog,"Error: Not 1 (data)parameters in line but %d, for example: pop_based=1\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
14673: 	goto end;
14674:       }
14675:       printf("pop_based=%d\n",popbased);
14676:       fprintf(ficlog,"pop_based=%d\n",popbased);
14677:       fprintf(ficparo,"pop_based=%d\n",popbased);   
14678:       fprintf(ficres,"pop_based=%d\n",popbased);   
14679:     }
14680:      
14681:     /* Results */
14682:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
14683:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
14684:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
14685:     endishere=0;
14686:     nresult=0;
14687:     parameterline=0;
14688:     do{
14689:       if(!fgets(line, MAXLINE, ficpar)){
14690: 	endishere=1;
14691: 	parameterline=15;
14692:       }else if (line[0] == '#') {
14693: 	/* If line starts with a # it is a comment */
14694: 	numlinepar++;
14695: 	fputs(line,stdout);
14696: 	fputs(line,ficparo);
14697: 	fputs(line,ficlog);
14698: 	fputs(line,ficres);
14699: 	continue;
14700:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
14701: 	parameterline=11;
14702:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
14703: 	parameterline=12;
14704:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
14705: 	parameterline=13;
14706:       }
14707:       else{
14708: 	parameterline=14;
14709:       }
14710:       switch (parameterline){ /* =0 only if only comments */
14711:       case 11:
14712: 	if((num_filled=sscanf(line,"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)) !=EOF && (num_filled == 8)){
14713: 	  	  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);
14714: 	  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);
14715: 	  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);
14716: 	  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);
14717: 	  /* day and month of proj2 are not used but only year anproj2.*/
14718: 	  dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
14719: 	  dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
14720:           prvforecast = 1;
14721: 	} 
14722: 	else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
14723: 	  printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
14724: 	  fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
14725: 	  fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
14726:           prvforecast = 2;
14727: 	}
14728: 	else {
14729: 	  printf("Error: Not 8 (data)parameters in line but %d, for example:prevforecast=1 starting-proj-date=1/1/1990 final-proj-date=1/1/2000 mobil_average=0\nnor 3 (data)parameters, for example:prevforecast=1 yearsfproj=10 mobil_average=0. Your line=%s . You are running probably an older format.\n, ",num_filled,line);
14730: 	  fprintf(ficlog,"Error: Not 8 (data)parameters in line but %d, for example:prevforecast=1 starting-proj-date=1/1/1990 final-proj-date=1/1/2000 mobil_average=0\nnor 3 (data)parameters, for example:prevforecast=1 yearproj=10 mobil_average=0. Your line=%s . You are running probably an older format.\n, ",num_filled,line);
14731: 	  goto end;
14732: 	}
14733: 	break;
14734:       case 12:
14735: 	if((num_filled=sscanf(line,"prevbackcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",&prevbcast,&jback1,&mback1,&anback1,&jback2,&mback2,&anback2,&mobilavproj)) !=EOF && (num_filled == 8)){
14736:           fprintf(ficparo,"prevbackcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevbcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
14737: 	  printf("prevbackcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevbcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
14738: 	  fprintf(ficlog,"prevbackcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevbcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
14739: 	  fprintf(ficres,"prevbackcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevbcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
14740: 	  /* day and month of back2 are not used but only year anback2.*/
14741: 	  dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
14742: 	  dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
14743:           prvbackcast = 1;
14744: 	} 
14745: 	else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
14746: 	  printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
14747: 	  fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
14748: 	  fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
14749:           prvbackcast = 2;
14750: 	}
14751: 	else {
14752: 	  printf("Error: Not 8 (data)parameters in line but %d, for example:prevbackcast=1 starting-back-date=1/1/1990 final-back-date=1/1/2000 mobil_average=0\nnor 3 (data)parameters, for example:prevbackcast=1 yearsbproj=10 mobil_average=0. Your line=%s . You are running probably an older format.\n, ",num_filled,line);
14753: 	  fprintf(ficlog,"Error: Not 8 (data)parameters in line but %d, for example:prevbackcast=1 starting-back-date=1/1/1990 final-back-date=1/1/2000 mobil_average=0\nnor 3 (data)parameters, for example:prevbackcast=1 yearbproj=10 mobil_average=0. Your line=%s . You are running probably an older format.\n, ",num_filled,line);
14754: 	  goto end;
14755: 	}
14756: 	break;
14757:       case 13:
14758: 	num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
14759: 	nresult++; /* Sum of resultlines */
14760: 	/* printf("Result %d: result:%s\n",nresult, resultlineori); */
14761: 	/* removefirstspace(&resultlineori); */
14762: 	
14763: 	if(strstr(resultlineori,"v") !=0){
14764: 	  printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
14765: 	  fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
14766: 	  return 1;
14767: 	}
14768: 	trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
14769: 	/* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
14770: 	if(nresult > MAXRESULTLINESPONE-1){
14771: 	  printf("ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\nYou can use the 'r' parameter file '%s' which uses option mle=0 to get other results. ",MAXRESULTLINESPONE-1,nresult,rfileres);
14772: 	  fprintf(ficlog,"ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\nYou can use the 'r' parameter file '%s' which uses option mle=0 to get other results. ",MAXRESULTLINESPONE-1,nresult,rfileres);
14773: 	  goto end;
14774: 	}
14775: 	
14776: 	if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
14777: 	  fprintf(ficparo,"result: %s\n",resultline);
14778: 	  fprintf(ficres,"result: %s\n",resultline);
14779: 	  fprintf(ficlog,"result: %s\n",resultline);
14780: 	} else
14781: 	  goto end;
14782: 	break;
14783:       case 14:
14784: 	printf("Error: Unknown command '%s'\n",line);
14785: 	fprintf(ficlog,"Error: Unknown command '%s'\n",line);
14786: 	if(line[0] == ' ' || line[0] == '\n'){
14787: 	  printf("It should not be an empty line '%s'\n",line);
14788: 	  fprintf(ficlog,"It should not be an empty line '%s'\n",line);
14789: 	}	  
14790: 	if(ncovmodel >=2 && nresult==0 ){
14791: 	  printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
14792: 	  fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
14793: 	}
14794: 	/* goto end; */
14795: 	break;
14796:       case 15:
14797: 	printf("End of resultlines.\n");
14798: 	fprintf(ficlog,"End of resultlines.\n");
14799: 	break;
14800:       default: /* parameterline =0 */
14801: 	nresult=1;
14802: 	decoderesult(".",nresult ); /* No covariate */
14803:       } /* End switch parameterline */
14804:     }while(endishere==0); /* End do */
14805:     
14806:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
14807:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
14808:     
14809:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
14810:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
14811:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
14812: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
14813: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
14814:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
14815: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
14816: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
14817:     }else{
14818:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
14819:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
14820:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
14821:       if(prvforecast==1){
14822:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
14823:         jprojd=jproj1;
14824:         mprojd=mproj1;
14825:         anprojd=anproj1;
14826:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
14827:         jprojf=jproj2;
14828:         mprojf=mproj2;
14829:         anprojf=anproj2;
14830:       } else if(prvforecast == 2){
14831:         dateprojd=dateintmean;
14832:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
14833:         dateprojf=dateintmean+yrfproj;
14834:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
14835:       }
14836:       if(prvbackcast==1){
14837:         datebackd=(jback1+12*mback1+365*anback1)/365;
14838:         jbackd=jback1;
14839:         mbackd=mback1;
14840:         anbackd=anback1;
14841:         datebackf=(jback2+12*mback2+365*anback2)/365;
14842:         jbackf=jback2;
14843:         mbackf=mback2;
14844:         anbackf=anback2;
14845:       } else if(prvbackcast == 2){
14846:         datebackd=dateintmean;
14847:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
14848:         datebackf=dateintmean-yrbproj;
14849:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
14850:       }
14851:       
14852:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);/* HERE valgrind Tvard*/
14853:     }
14854:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
14855: 		 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
14856: 		 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
14857: 		
14858:     /*------------ free_vector  -------------*/
14859:     /*  chdir(path); */
14860: 		
14861:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
14862:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
14863:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
14864:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
14865:     free_lvector(num,firstobs,lastobs);
14866:     free_vector(agedc,firstobs,lastobs);
14867:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
14868:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
14869:     fclose(ficparo);
14870:     fclose(ficres);
14871: 		
14872: 		
14873:     /* Other results (useful)*/
14874: 		
14875: 		
14876:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
14877:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
14878:     prlim=matrix(1,nlstate,1,nlstate);
14879:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
14880:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
14881:     fclose(ficrespl);
14882: 
14883:     /*------------- h Pij x at various ages ------------*/
14884:     /*#include "hpijx.h"*/
14885:     /** h Pij x Probability to be in state j at age x+h being in i at x, for each combination k of dummies in the model line or to nres?*/
14886:     /* calls hpxij with combination k */
14887:     hPijx(p, bage, fage);
14888:     fclose(ficrespij);
14889:     
14890:     /* ncovcombmax=  pow(2,cptcoveff); */
14891:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
14892:     k=1;
14893:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
14894:     
14895:     /* Prevalence for each covariate combination in probs[age][status][cov] */
14896:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
14897:     for(i=AGEINF;i<=AGESUP;i++)
14898:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
14899: 	for(k=1;k<=ncovcombmax;k++)
14900: 	  probs[i][j][k]=0.;
14901:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
14902: 	       ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
14903:     if (mobilav!=0 ||mobilavproj !=0 ) {
14904:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
14905:       for(i=AGEINF;i<=AGESUP;i++)
14906: 	for(j=1;j<=nlstate+ndeath;j++)
14907: 	  for(k=1;k<=ncovcombmax;k++)
14908: 	    mobaverages[i][j][k]=0.;
14909:       mobaverage=mobaverages;
14910:       if (mobilav!=0) {
14911: 	printf("Movingaveraging observed prevalence\n");
14912: 	fprintf(ficlog,"Movingaveraging observed prevalence\n");
14913: 	if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
14914: 	  fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
14915: 	  printf(" Error in movingaverage mobilav=%d\n",mobilav);
14916: 	}
14917:       } else if (mobilavproj !=0) {
14918: 	printf("Movingaveraging projected observed prevalence\n");
14919: 	fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
14920: 	if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
14921: 	  fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
14922: 	  printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
14923: 	}
14924:       }else{
14925: 	printf("Internal error moving average\n");
14926: 	fflush(stdout);
14927: 	exit(1);
14928:       }
14929:     }/* end if moving average */
14930:     
14931:     /*---------- Forecasting ------------------*/
14932:     if(prevfcast==1){ 
14933:       /*   /\*    if(stepm ==1){*\/ */
14934:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
14935:       /*This done previously after freqsummary.*/
14936:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
14937:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
14938:       
14939:       /* } else if (prvforecast==2){ */
14940:       /*   /\*    if(stepm ==1){*\/ */
14941:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
14942:       /* } */
14943:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
14944:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
14945:     }
14946: 
14947:     /* Prevbcasting */
14948:     if(prevbcast==1){
14949:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath); 	
14950:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath); 	
14951:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
14952: 
14953:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
14954: 
14955:       bprlim=matrix(1,nlstate,1,nlstate);
14956: 
14957:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
14958:       fclose(ficresplb);
14959: 
14960:       hBijx(p, bage, fage, mobaverage);
14961:       fclose(ficrespijb);
14962: 
14963:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
14964:       /* /\* 		       mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
14965:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
14966:       /* 		       mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
14967:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
14968:       		       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
14969: 
14970:       
14971:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
14972: 
14973:       
14974:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
14975:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
14976:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
14977:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
14978:     }    /* end  Prevbcasting */
14979:  
14980:  
14981:     /* ------ Other prevalence ratios------------ */
14982: 
14983:     free_ivector(wav,1,imx);
14984:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
14985:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
14986:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
14987: 		
14988: 		
14989:     /*---------- Health expectancies, no variances ------------*/
14990: 		
14991:     strcpy(filerese,"E_");
14992:     strcat(filerese,fileresu);
14993:     if((ficreseij=fopen(filerese,"w"))==NULL) {
14994:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
14995:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
14996:     }
14997:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
14998:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
14999: 
15000:     pstamp(ficreseij);
15001:  		
15002:     /* i1=pow(2,cptcoveff); /\* Number of combination of dummy covariates *\/ */
15003:     /* if (cptcovn < 1){i1=1;} */
15004:     
15005:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
15006:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
15007:       /* if(i1 != 1 && TKresult[nres]!= k) */
15008:       /* 	continue; */
15009:       fprintf(ficreseij,"\n#****** ");
15010:       printf("\n#****** ");
15011:       for(j=1;j<=cptcovs;j++){
15012:       /* for(j=1;j<=cptcoveff;j++) { */
15013: 	/* fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
15014: 	fprintf(ficreseij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
15015: 	printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
15016: 	/* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
15017:       }
15018:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
15019: 	printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
15020: 	fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
15021:       }
15022:       fprintf(ficreseij,"******\n");
15023:       printf("******\n");
15024:       
15025:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
15026:       oldm=oldms;savm=savms;
15027:       /* printf("HELLO Entering evsij bage=%d fage=%d k=%d estepm=%d nres=%d\n",(int) bage, (int)fage, k, estepm, nres); */
15028:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
15029:       
15030:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
15031:     }
15032:     fclose(ficreseij);
15033:     printf("done evsij\n");fflush(stdout);
15034:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
15035: 
15036: 		
15037:     /*---------- State-specific expectancies and variances ------------*/
15038:     /* Should be moved in a function */		
15039:     strcpy(filerest,"T_");
15040:     strcat(filerest,fileresu);
15041:     if((ficrest=fopen(filerest,"w"))==NULL) {
15042:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
15043:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
15044:     }
15045:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
15046:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
15047:     strcpy(fileresstde,"STDE_");
15048:     strcat(fileresstde,fileresu);
15049:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
15050:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
15051:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
15052:     }
15053:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
15054:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
15055: 
15056:     strcpy(filerescve,"CVE_");
15057:     strcat(filerescve,fileresu);
15058:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
15059:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
15060:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
15061:     }
15062:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
15063:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
15064: 
15065:     strcpy(fileresv,"V_");
15066:     strcat(fileresv,fileresu);
15067:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
15068:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
15069:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
15070:     }
15071:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
15072:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
15073: 
15074:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
15075:     if (cptcovn < 1){i1=1;}
15076:     
15077:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
15078:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
15079: 			  * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
15080: 			  * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
15081: 			  * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
15082:       /* */
15083:       if(i1 != 1 && TKresult[nres]!= k) /* TKresult[nres] is the combination of this nres resultline. All the i1 combinations are not output */
15084: 	continue;
15085:       printf("\n# model %s \n#****** Result for:", model);  /* HERE model is empty */
15086:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
15087:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
15088:       /* It might not be a good idea to mix dummies and quantitative */
15089:       /* for(j=1;j<=cptcoveff;j++){ /\* j=resultpos. Could be a loop on cptcovs: number of single dummy covariate in the result line as well as in the model *\/ */
15090:       for(j=1;j<=cptcovs;j++){ /* j=resultpos. Could be a loop on cptcovs: number of single covariate (dummy or quantitative) in the result line as well as in the model */
15091: 	/* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
15092: 	/* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
15093: 	 * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
15094: 	 * (V5 is quanti) V4 and V3 are dummies
15095: 	 * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
15096: 	 *                                                              l=1 l=2
15097: 	 *                                                           k=1  1   1   0   0
15098: 	 *                                                           k=2  2   1   1   0
15099: 	 *                                                           k=3 [1] [2]  0   1
15100: 	 *                                                           k=4  2   2   1   1
15101: 	 * If nres=1 result: V3=1 V4=0 then k=3 and outputs
15102: 	 * If nres=2 result: V4=1 V3=0 then k=2 and outputs
15103: 	 * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
15104: 	 * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
15105: 	 */
15106: 	/* Tvresult[nres][j] Name of the variable at position j in this resultline */
15107: 	/* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
15108: /* We give up with the combinations!! */
15109: 	/* if(debugILK) */
15110: 	/*   printf("\n j=%d In computing T_ Dummy[modelresult[%d][%d]]=%d, modelresult[%d][%d]=%d cptcovs=%d, cptcoveff=%d Fixed[modelresult[nres][j]]=%d\n", j, nres, j, Dummy[modelresult[nres][j]],nres,j,modelresult[nres][j],cptcovs, cptcoveff,Fixed[modelresult[nres][j]]);  /\* end if dummy  or quanti *\/ */
15111: 
15112: 	if(Dummy[modelresult[nres][j]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to j in resultline  */
15113: 	  /* printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][j]); /\* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  *\/ */ /* TinvDoQresult[nres][Name of the variable] */
15114: 	  printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); /* Output of each value for the combination TKresult[nres], ordered by the covariate values in the resultline  */
15115: 	  fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
15116: 	  fprintf(ficrest,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
15117: 	  if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
15118: 	    printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
15119: 	  }else{
15120: 	    printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
15121: 	  }
15122: 	  /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
15123: 	  /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
15124: 	}else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
15125: 	  /* For each selected (single) quantitative value */
15126: 	  printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
15127: 	  fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
15128: 	  fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
15129: 	  if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
15130: 	    printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
15131: 	  }else{
15132: 	    printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
15133: 	  }
15134: 	}else{
15135: 	  printf("Error in computing T_ Dummy[modelresult[%d][%d]]=%d, modelresult[%d][%d]=%d cptcovs=%d, cptcoveff=%d \n", nres, j, Dummy[modelresult[nres][j]],nres,j,modelresult[nres][j],cptcovs, cptcoveff);  /* end if dummy  or quanti */
15136: 	  fprintf(ficlog,"Error in computing T_ Dummy[modelresult[%d][%d]]=%d, modelresult[%d][%d]=%d cptcovs=%d, cptcoveff=%d \n", nres, j, Dummy[modelresult[nres][j]],nres,j,modelresult[nres][j],cptcovs, cptcoveff);  /* end if dummy  or quanti */
15137: 	  exit(1);
15138: 	}
15139:       } /* End loop for each variable in the resultline */
15140:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
15141:       /* 	printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
15142:       /* 	fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
15143:       /* 	fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
15144:       /* }	 */
15145:       fprintf(ficrest,"******\n");
15146:       fprintf(ficlog,"******\n");
15147:       printf("******\n");
15148:       
15149:       fprintf(ficresstdeij,"\n#****** ");
15150:       fprintf(ficrescveij,"\n#****** ");
15151:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
15152:       /* But it won't be sorted and depends on how the resultline is ordered */
15153:       for(j=1;j<=cptcoveff;j++) {
15154: 	fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
15155: 	/* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
15156: 	/* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
15157:       }
15158:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value, TvarsQind gives the position of a quantitative in model equation  */
15159: 	fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
15160: 	fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
15161:       }	
15162:       fprintf(ficresstdeij,"******\n");
15163:       fprintf(ficrescveij,"******\n");
15164:       
15165:       fprintf(ficresvij,"\n#****** ");
15166:       /* pstamp(ficresvij); */
15167:       for(j=1;j<=cptcoveff;j++) 
15168: 	fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
15169: 	/* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
15170:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
15171: 	/* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
15172: 	fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
15173:       }	
15174:       fprintf(ficresvij,"******\n");
15175:       
15176:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
15177:       oldm=oldms;savm=savms;
15178:       printf(" cvevsij ");
15179:       fprintf(ficlog, " cvevsij ");
15180:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
15181:       printf(" end cvevsij \n ");
15182:       fprintf(ficlog, " end cvevsij \n ");
15183:       
15184:       /*
15185:        */
15186:       /* goto endfree; */
15187:       
15188:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
15189:       pstamp(ficrest);
15190:       
15191:       epj=vector(1,nlstate+1);
15192:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
15193: 	oldm=oldms;savm=savms; /* ZZ Segmentation fault */
15194: 	cptcod= 0; /* To be deleted */
15195: 	printf("varevsij vpopbased=%d \n",vpopbased);
15196: 	fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
15197: 	varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart, nres); /* cptcod not initialized Intel */
15198: 	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 ");
15199: 	if(vpopbased==1)
15200: 	  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);
15201: 	else
15202: 	  fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
15203: 	fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
15204: 	for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
15205: 	fprintf(ficrest,"\n");
15206: 	/* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
15207: 	printf("Computing age specific forward period (stable) prevalences in each health state \n");
15208: 	fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
15209: 	for(age=bage; age <=fage ;age++){
15210: 	  prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
15211: 	  if (vpopbased==1) {
15212: 	    if(mobilav ==0){
15213: 	      for(i=1; i<=nlstate;i++)
15214: 		prlim[i][i]=probs[(int)age][i][k];
15215: 	    }else{ /* mobilav */ 
15216: 	      for(i=1; i<=nlstate;i++)
15217: 		prlim[i][i]=mobaverage[(int)age][i][k];
15218: 	    }
15219: 	  }
15220: 	  
15221: 	  fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
15222: 	  /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
15223: 	  /* printf(" age %4.0f ",age); */
15224: 	  for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
15225: 	    for(i=1, epj[j]=0.;i <=nlstate;i++) {
15226: 	      epj[j] += prlim[i][i]*eij[i][j][(int)age];
15227: 	      /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
15228: 	      /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
15229: 	    }
15230: 	    epj[nlstate+1] +=epj[j];
15231: 	  }
15232: 	  /* printf(" age %4.0f \n",age); */
15233: 	  
15234: 	  for(i=1, vepp=0.;i <=nlstate;i++)
15235: 	    for(j=1;j <=nlstate;j++)
15236: 	      vepp += vareij[i][j][(int)age];
15237: 	  fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
15238: 	  for(j=1;j <=nlstate;j++){
15239: 	    fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
15240: 	  }
15241: 	  fprintf(ficrest,"\n");
15242: 	}
15243:       } /* End vpopbased */
15244:       free_vector(epj,1,nlstate+1);
15245:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
15246:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
15247:       printf("done selection\n");fflush(stdout);
15248:       fprintf(ficlog,"done selection\n");fflush(ficlog);
15249:       
15250:     } /* End k selection or end covariate selection for nres */
15251: 
15252:     printf("done State-specific expectancies\n");fflush(stdout);
15253:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
15254: 
15255:     /* variance-covariance of forward period prevalence */
15256:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
15257: 
15258:     
15259:     free_vector(weight,firstobs,lastobs);
15260:     free_imatrix(Tvardk,0,NCOVMAX,1,2);
15261:     free_imatrix(Tvard,1,NCOVMAX,1,2);
15262:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
15263:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
15264:     free_matrix(mint,1,maxwav,firstobs,lastobs);
15265:     free_ivector(cod,firstobs,lastobs);
15266:     free_ivector(tab,1,NCOVMAX);
15267:     fclose(ficresstdeij);
15268:     fclose(ficrescveij);
15269:     fclose(ficresvij);
15270:     fclose(ficrest);
15271:     fclose(ficpar);
15272:     
15273:     
15274:     /*---------- End : free ----------------*/
15275:     if (mobilav!=0 ||mobilavproj !=0)
15276:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
15277:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
15278:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
15279:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
15280:   }  /* mle==-3 arrives here for freeing */
15281:   /* endfree:*/
15282:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
15283:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
15284:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
15285:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
15286:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
15287:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
15288:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
15289:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
15290:   free_matrix(matcov,1,npar,1,npar);
15291:   free_matrix(hess,1,npar,1,npar);
15292:   /*free_vector(delti,1,npar);*/
15293:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
15294:   free_matrix(agev,1,maxwav,1,imx);
15295:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
15296:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
15297:   
15298:   free_ivector(ncodemax,1,NCOVMAX);
15299:   free_ivector(ncodemaxwundef,1,NCOVMAX);
15300:   free_ivector(Dummy,-1,NCOVMAX);
15301:   free_ivector(Fixed,-1,NCOVMAX);
15302:   free_ivector(DummyV,-1,NCOVMAX);
15303:   free_ivector(FixedV,-1,NCOVMAX);
15304:   free_ivector(Typevar,-1,NCOVMAX);
15305:   free_ivector(Tvar,1,NCOVMAX);
15306:   free_ivector(TvarsQ,1,NCOVMAX);
15307:   free_ivector(TvarsQind,1,NCOVMAX);
15308:   free_ivector(TvarsD,1,NCOVMAX);
15309:   free_ivector(TnsdVar,1,NCOVMAX);
15310:   free_ivector(TvarsDind,1,NCOVMAX);
15311:   free_ivector(TvarFD,1,NCOVMAX);
15312:   free_ivector(TvarFDind,1,NCOVMAX);
15313:   free_ivector(TvarF,1,NCOVMAX);
15314:   free_ivector(TvarFind,1,NCOVMAX);
15315:   free_ivector(TvarV,1,NCOVMAX);
15316:   free_ivector(TvarVind,1,NCOVMAX);
15317:   free_ivector(TvarA,1,NCOVMAX);
15318:   free_ivector(TvarAind,1,NCOVMAX);
15319:   free_ivector(TvarFQ,1,NCOVMAX);
15320:   free_ivector(TvarFQind,1,NCOVMAX);
15321:   free_ivector(TvarVD,1,NCOVMAX);
15322:   free_ivector(TvarVDind,1,NCOVMAX);
15323:   free_ivector(TvarVQ,1,NCOVMAX);
15324:   free_ivector(TvarVQind,1,NCOVMAX);
15325:   free_ivector(TvarAVVA,1,NCOVMAX);
15326:   free_ivector(TvarAVVAind,1,NCOVMAX);
15327:   free_ivector(TvarVVA,1,NCOVMAX);
15328:   free_ivector(TvarVVAind,1,NCOVMAX);
15329:   free_ivector(TvarVV,1,NCOVMAX);
15330:   free_ivector(TvarVVind,1,NCOVMAX);
15331:   
15332:   free_ivector(Tvarsel,1,NCOVMAX);
15333:   free_vector(Tvalsel,1,NCOVMAX);
15334:   free_ivector(Tposprod,1,NCOVMAX);
15335:   free_ivector(Tprod,1,NCOVMAX);
15336:   free_ivector(Tvaraff,1,NCOVMAX);
15337:   free_ivector(invalidvarcomb,0,ncovcombmax);
15338:   free_ivector(Tage,1,NCOVMAX);
15339:   free_ivector(Tmodelind,1,NCOVMAX);
15340:   free_ivector(TmodelInvind,1,NCOVMAX);
15341:   free_ivector(TmodelInvQind,1,NCOVMAX);
15342: 
15343:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
15344: 
15345:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
15346:   /* free_imatrix(codtab,1,100,1,10); */
15347:   fflush(fichtm);
15348:   fflush(ficgp);
15349:   
15350:   
15351:   if((nberr >0) || (nbwarn>0)){
15352:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
15353:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d. Please look at the log file for details.\n",nberr,nbwarn);
15354:   }else{
15355:     printf("End of Imach\n");
15356:     fprintf(ficlog,"End of Imach\n");
15357:   }
15358:   printf("See log file on %s\n",filelog);
15359:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
15360:   /*(void) gettimeofday(&end_time,&tzp);*/
15361:   rend_time = time(NULL);  
15362:   end_time = *localtime(&rend_time);
15363:   /* tml = *localtime(&end_time.tm_sec); */
15364:   strcpy(strtend,asctime(&end_time));
15365:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
15366:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
15367:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
15368:   
15369:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
15370:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
15371:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
15372:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
15373: /*   if(fileappend(fichtm,optionfilehtm)){ */
15374:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
15375:   fclose(fichtm);
15376:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
15377:   fclose(fichtmcov);
15378:   fclose(ficgp);
15379:   fclose(ficlog);
15380:   /*------ End -----------*/
15381:   
15382: 
15383: /* Executes gnuplot */
15384:   
15385:   printf("Before Current directory %s!\n",pathcd);
15386: #ifdef WIN32
15387:   if (_chdir(pathcd) != 0)
15388:     printf("Can't move to directory %s!\n",path);
15389:   if(_getcwd(pathcd,MAXLINE) > 0)
15390: #else
15391:     if(chdir(pathcd) != 0)
15392:       printf("Can't move to directory %s!\n", path);
15393:   if (getcwd(pathcd, MAXLINE) > 0)
15394: #endif 
15395:     printf("Current directory %s!\n",pathcd);
15396:   /*strcat(plotcmd,CHARSEPARATOR);*/
15397:   sprintf(plotcmd,"gnuplot");
15398: #ifdef _WIN32
15399:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
15400: #endif
15401:   if(!stat(plotcmd,&info)){
15402:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
15403:     if(!stat(getenv("GNUPLOTBIN"),&info)){
15404:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
15405:     }else
15406:       strcpy(pplotcmd,plotcmd);
15407: #ifdef __unix
15408:     strcpy(plotcmd,GNUPLOTPROGRAM);
15409:     if(!stat(plotcmd,&info)){
15410:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
15411:     }else
15412:       strcpy(pplotcmd,plotcmd);
15413: #endif
15414:   }else
15415:     strcpy(pplotcmd,plotcmd);
15416:   
15417:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
15418:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
15419:   strcpy(pplotcmd,plotcmd);
15420:   
15421:   if((outcmd=system(plotcmd)) != 0){
15422:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
15423:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
15424:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
15425:     if((outcmd=system(plotcmd)) != 0){
15426:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
15427:       strcpy(plotcmd,pplotcmd);
15428:     }
15429:   }
15430:   printf(" Successful, please wait...");
15431:   while (z[0] != 'q') {
15432:     /* chdir(path); */
15433:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
15434:     scanf("%s",z);
15435: /*     if (z[0] == 'c') system("./imach"); */
15436:     if (z[0] == 'e') {
15437: #ifdef __APPLE__
15438:       sprintf(pplotcmd, "open %s", optionfilehtm);
15439: #elif __linux
15440:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
15441: #else
15442:       sprintf(pplotcmd, "%s", optionfilehtm);
15443: #endif
15444:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
15445:       system(pplotcmd);
15446:     }
15447:     else if (z[0] == 'g') system(plotcmd);
15448:     else if (z[0] == 'q') exit(0);
15449:   }
15450: end:
15451:   while (z[0] != 'q') {
15452:     printf("\nType  q for exiting: "); fflush(stdout);
15453:     scanf("%s",z);
15454:   }
15455:   printf("End\n");
15456:   exit(0);
15457: }

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