File:  [Local Repository] / imach / src / imach.c
Revision 1.358: download - view: text, annotated - select for diffs
Wed Jun 14 14:57:02 2023 UTC (12 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
* imach.c (Module): Testing if conjugate gradient could be quicker when lot of variables POWELLORIGINCONJUGATE

    1: /* $Id: imach.c,v 1.358 2023/06/14 14:57:02 brouard Exp $
    2:   $State: Exp $
    3:   $Log: imach.c,v $
    4:   Revision 1.358  2023/06/14 14:57:02  brouard
    5:   * imach.c (Module): Testing if conjugate gradient could be quicker when lot of variables POWELLORIGINCONJUGATE
    6: 
    7:   Revision 1.357  2023/06/14 14:55:52  brouard
    8:   * imach.c (Module): Testing if conjugate gradient could be quicker when lot of variables POWELLORIGINCONJUGATE
    9: 
   10:   Revision 1.356  2023/05/23 12:08:43  brouard
   11:   Summary: 0.99r46
   12: 
   13:   * imach.c (Module): Fixed PROB_r
   14: 
   15:   Revision 1.355  2023/05/22 17:03:18  brouard
   16:   Summary: 0.99r46
   17: 
   18:   * imach.c (Module): In the ILK....txt file, the number of columns
   19:   before the covariates values is dependent of the number of states (16+nlstate): 0.99r46
   20: 
   21:   Revision 1.354  2023/05/21 05:05:17  brouard
   22:   Summary: Temporary change for imachprax
   23: 
   24:   Revision 1.353  2023/05/08 18:48:22  brouard
   25:   *** empty log message ***
   26: 
   27:   Revision 1.352  2023/04/29 10:46:21  brouard
   28:   *** empty log message ***
   29: 
   30:   Revision 1.351  2023/04/29 10:43:47  brouard
   31:   Summary: 099r45
   32: 
   33:   Revision 1.350  2023/04/24 11:38:06  brouard
   34:   *** empty log message ***
   35: 
   36:   Revision 1.349  2023/01/31 09:19:37  brouard
   37:   Summary: Improvements in models with age*Vn*Vm
   38: 
   39:   Revision 1.347  2022/09/18 14:36:44  brouard
   40:   Summary: version 0.99r42
   41: 
   42:   Revision 1.346  2022/09/16 13:52:36  brouard
   43:   * src/imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
   44: 
   45:   Revision 1.345  2022/09/16 13:40:11  brouard
   46:   Summary: Version 0.99r41
   47: 
   48:   * imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
   49: 
   50:   Revision 1.344  2022/09/14 19:33:30  brouard
   51:   Summary: version 0.99r40
   52: 
   53:   * imach.c (Module): Fixing names of variables in T_ (thanks to Feinuo)
   54: 
   55:   Revision 1.343  2022/09/14 14:22:16  brouard
   56:   Summary: version 0.99r39
   57: 
   58:   * imach.c (Module): Version 0.99r39 with colored dummy covariates
   59:   (fixed or time varying), using new last columns of
   60:   ILK_parameter.txt file.
   61: 
   62:   Revision 1.342  2022/09/11 19:54:09  brouard
   63:   Summary: 0.99r38
   64: 
   65:   * imach.c (Module): Adding timevarying products of any kinds,
   66:   should work before shifting cotvar from ncovcol+nqv columns in
   67:   order to have a correspondance between the column of cotvar and
   68:   the id of column.
   69:   (Module): Some cleaning and adding covariates in ILK.txt
   70: 
   71:   Revision 1.341  2022/09/11 07:58:42  brouard
   72:   Summary: Version 0.99r38
   73: 
   74:   After adding change in cotvar.
   75: 
   76:   Revision 1.340  2022/09/11 07:53:11  brouard
   77:   Summary: Version imach 0.99r37
   78: 
   79:   * imach.c (Module): Adding timevarying products of any kinds,
   80:   should work before shifting cotvar from ncovcol+nqv columns in
   81:   order to have a correspondance between the column of cotvar and
   82:   the id of column.
   83: 
   84:   Revision 1.339  2022/09/09 17:55:22  brouard
   85:   Summary: version 0.99r37
   86: 
   87:   * imach.c (Module): Many improvements for fixing products of fixed
   88:   timevarying as well as fixed * fixed, and test with quantitative
   89:   covariate.
   90: 
   91:   Revision 1.338  2022/09/04 17:40:33  brouard
   92:   Summary: 0.99r36
   93: 
   94:   * imach.c (Module): Now the easy runs i.e. without result or
   95:   model=1+age only did not work. The defautl combination should be 1
   96:   and not 0 because everything hasn't been tranformed yet.
   97: 
   98:   Revision 1.337  2022/09/02 14:26:02  brouard
   99:   Summary: version 0.99r35
  100: 
  101:   * src/imach.c: Version 0.99r35 because it outputs same results with
  102:   1+age+V1+V1*age for females and 1+age for females only
  103:   (education=1 noweight)
  104: 
  105:   Revision 1.336  2022/08/31 09:52:36  brouard
  106:   *** empty log message ***
  107: 
  108:   Revision 1.335  2022/08/31 08:23:16  brouard
  109:   Summary: improvements...
  110: 
  111:   Revision 1.334  2022/08/25 09:08:41  brouard
  112:   Summary: In progress for quantitative
  113: 
  114:   Revision 1.333  2022/08/21 09:10:30  brouard
  115:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
  116:   reassigning covariates: my first idea was that people will always
  117:   use the first covariate V1 into the model but in fact they are
  118:   producing data with many covariates and can use an equation model
  119:   with some of the covariate; it means that in a model V2+V3 instead
  120:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
  121:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
  122:   the equation model is restricted to two variables only (V2, V3)
  123:   and the combination for V2 should be codtabm(k,1) instead of
  124:   (codtabm(k,2), and the code should be
  125:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
  126:   made. All of these should be simplified once a day like we did in
  127:   hpxij() for example by using precov[nres] which is computed in
  128:   decoderesult for each nres of each resultline. Loop should be done
  129:   on the equation model globally by distinguishing only product with
  130:   age (which are changing with age) and no more on type of
  131:   covariates, single dummies, single covariates.
  132: 
  133:   Revision 1.332  2022/08/21 09:06:25  brouard
  134:   Summary: Version 0.99r33
  135: 
  136:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
  137:   reassigning covariates: my first idea was that people will always
  138:   use the first covariate V1 into the model but in fact they are
  139:   producing data with many covariates and can use an equation model
  140:   with some of the covariate; it means that in a model V2+V3 instead
  141:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
  142:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
  143:   the equation model is restricted to two variables only (V2, V3)
  144:   and the combination for V2 should be codtabm(k,1) instead of
  145:   (codtabm(k,2), and the code should be
  146:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
  147:   made. All of these should be simplified once a day like we did in
  148:   hpxij() for example by using precov[nres] which is computed in
  149:   decoderesult for each nres of each resultline. Loop should be done
  150:   on the equation model globally by distinguishing only product with
  151:   age (which are changing with age) and no more on type of
  152:   covariates, single dummies, single covariates.
  153: 
  154:   Revision 1.331  2022/08/07 05:40:09  brouard
  155:   *** empty log message ***
  156: 
  157:   Revision 1.330  2022/08/06 07:18:25  brouard
  158:   Summary: last 0.99r31
  159: 
  160:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
  161: 
  162:   Revision 1.329  2022/08/03 17:29:54  brouard
  163:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
  164: 
  165:   Revision 1.328  2022/07/27 17:40:48  brouard
  166:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
  167: 
  168:   Revision 1.327  2022/07/27 14:47:35  brouard
  169:   Summary: Still a problem for one-step probabilities in case of quantitative variables
  170: 
  171:   Revision 1.326  2022/07/26 17:33:55  brouard
  172:   Summary: some test with nres=1
  173: 
  174:   Revision 1.325  2022/07/25 14:27:23  brouard
  175:   Summary: r30
  176: 
  177:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
  178:   coredumped, revealed by Feiuno, thank you.
  179: 
  180:   Revision 1.324  2022/07/23 17:44:26  brouard
  181:   *** empty log message ***
  182: 
  183:   Revision 1.323  2022/07/22 12:30:08  brouard
  184:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
  185: 
  186:   Revision 1.322  2022/07/22 12:27:48  brouard
  187:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
  188: 
  189:   Revision 1.321  2022/07/22 12:04:24  brouard
  190:   Summary: r28
  191: 
  192:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
  193: 
  194:   Revision 1.320  2022/06/02 05:10:11  brouard
  195:   *** empty log message ***
  196: 
  197:   Revision 1.319  2022/06/02 04:45:11  brouard
  198:   * imach.c (Module): Adding the Wald tests from the log to the main
  199:   htm for better display of the maximum likelihood estimators.
  200: 
  201:   Revision 1.318  2022/05/24 08:10:59  brouard
  202:   * imach.c (Module): Some attempts to find a bug of wrong estimates
  203:   of confidencce intervals with product in the equation modelC
  204: 
  205:   Revision 1.317  2022/05/15 15:06:23  brouard
  206:   * imach.c (Module):  Some minor improvements
  207: 
  208:   Revision 1.316  2022/05/11 15:11:31  brouard
  209:   Summary: r27
  210: 
  211:   Revision 1.315  2022/05/11 15:06:32  brouard
  212:   *** empty log message ***
  213: 
  214:   Revision 1.314  2022/04/13 17:43:09  brouard
  215:   * imach.c (Module): Adding link to text data files
  216: 
  217:   Revision 1.313  2022/04/11 15:57:42  brouard
  218:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
  219: 
  220:   Revision 1.312  2022/04/05 21:24:39  brouard
  221:   *** empty log message ***
  222: 
  223:   Revision 1.311  2022/04/05 21:03:51  brouard
  224:   Summary: Fixed quantitative covariates
  225: 
  226:   	  Fixed covariates (dummy or quantitative)
  227:   	with missing values have never been allowed but are ERRORS and
  228:   	program quits. Standard deviations of fixed covariates were
  229:   	wrongly computed. Mean and standard deviations of time varying
  230:   	covariates are still not computed.
  231: 
  232:   Revision 1.310  2022/03/17 08:45:53  brouard
  233:   Summary: 99r25
  234: 
  235:   Improving detection of errors: result lines should be compatible with
  236:   the model.
  237: 
  238:   Revision 1.309  2021/05/20 12:39:14  brouard
  239:   Summary: Version 0.99r24
  240: 
  241:   Revision 1.308  2021/03/31 13:11:57  brouard
  242:   Summary: Version 0.99r23
  243: 
  244: 
  245:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
  246: 
  247:   Revision 1.307  2021/03/08 18:11:32  brouard
  248:   Summary: 0.99r22 fixed bug on result:
  249: 
  250:   Revision 1.306  2021/02/20 15:44:02  brouard
  251:   Summary: Version 0.99r21
  252: 
  253:   * imach.c (Module): Fix bug on quitting after result lines!
  254:   (Module): Version 0.99r21
  255: 
  256:   Revision 1.305  2021/02/20 15:28:30  brouard
  257:   * imach.c (Module): Fix bug on quitting after result lines!
  258: 
  259:   Revision 1.304  2021/02/12 11:34:20  brouard
  260:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
  261: 
  262:   Revision 1.303  2021/02/11 19:50:15  brouard
  263:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
  264: 
  265:   Revision 1.302  2020/02/22 21:00:05  brouard
  266:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
  267:   and life table from the data without any state)
  268: 
  269:   Revision 1.301  2019/06/04 13:51:20  brouard
  270:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
  271: 
  272:   Revision 1.300  2019/05/22 19:09:45  brouard
  273:   Summary: version 0.99r19 of May 2019
  274: 
  275:   Revision 1.299  2019/05/22 18:37:08  brouard
  276:   Summary: Cleaned 0.99r19
  277: 
  278:   Revision 1.298  2019/05/22 18:19:56  brouard
  279:   *** empty log message ***
  280: 
  281:   Revision 1.297  2019/05/22 17:56:10  brouard
  282:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
  283: 
  284:   Revision 1.296  2019/05/20 13:03:18  brouard
  285:   Summary: Projection syntax simplified
  286: 
  287: 
  288:   We can now start projections, forward or backward, from the mean date
  289:   of inteviews up to or down to a number of years of projection:
  290:   prevforecast=1 yearsfproj=15.3 mobil_average=0
  291:   or
  292:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
  293:   or
  294:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
  295:   or
  296:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
  297: 
  298:   Revision 1.295  2019/05/18 09:52:50  brouard
  299:   Summary: doxygen tex bug
  300: 
  301:   Revision 1.294  2019/05/16 14:54:33  brouard
  302:   Summary: There was some wrong lines added
  303: 
  304:   Revision 1.293  2019/05/09 15:17:34  brouard
  305:   *** empty log message ***
  306: 
  307:   Revision 1.292  2019/05/09 14:17:20  brouard
  308:   Summary: Some updates
  309: 
  310:   Revision 1.291  2019/05/09 13:44:18  brouard
  311:   Summary: Before ncovmax
  312: 
  313:   Revision 1.290  2019/05/09 13:39:37  brouard
  314:   Summary: 0.99r18 unlimited number of individuals
  315: 
  316:   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.
  317: 
  318:   Revision 1.289  2018/12/13 09:16:26  brouard
  319:   Summary: Bug for young ages (<-30) will be in r17
  320: 
  321:   Revision 1.288  2018/05/02 20:58:27  brouard
  322:   Summary: Some bugs fixed
  323: 
  324:   Revision 1.287  2018/05/01 17:57:25  brouard
  325:   Summary: Bug fixed by providing frequencies only for non missing covariates
  326: 
  327:   Revision 1.286  2018/04/27 14:27:04  brouard
  328:   Summary: some minor bugs
  329: 
  330:   Revision 1.285  2018/04/21 21:02:16  brouard
  331:   Summary: Some bugs fixed, valgrind tested
  332: 
  333:   Revision 1.284  2018/04/20 05:22:13  brouard
  334:   Summary: Computing mean and stdeviation of fixed quantitative variables
  335: 
  336:   Revision 1.283  2018/04/19 14:49:16  brouard
  337:   Summary: Some minor bugs fixed
  338: 
  339:   Revision 1.282  2018/02/27 22:50:02  brouard
  340:   *** empty log message ***
  341: 
  342:   Revision 1.281  2018/02/27 19:25:23  brouard
  343:   Summary: Adding second argument for quitting
  344: 
  345:   Revision 1.280  2018/02/21 07:58:13  brouard
  346:   Summary: 0.99r15
  347: 
  348:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
  349: 
  350:   Revision 1.279  2017/07/20 13:35:01  brouard
  351:   Summary: temporary working
  352: 
  353:   Revision 1.278  2017/07/19 14:09:02  brouard
  354:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
  355: 
  356:   Revision 1.277  2017/07/17 08:53:49  brouard
  357:   Summary: BOM files can be read now
  358: 
  359:   Revision 1.276  2017/06/30 15:48:31  brouard
  360:   Summary: Graphs improvements
  361: 
  362:   Revision 1.275  2017/06/30 13:39:33  brouard
  363:   Summary: Saito's color
  364: 
  365:   Revision 1.274  2017/06/29 09:47:08  brouard
  366:   Summary: Version 0.99r14
  367: 
  368:   Revision 1.273  2017/06/27 11:06:02  brouard
  369:   Summary: More documentation on projections
  370: 
  371:   Revision 1.272  2017/06/27 10:22:40  brouard
  372:   Summary: Color of backprojection changed from 6 to 5(yellow)
  373: 
  374:   Revision 1.271  2017/06/27 10:17:50  brouard
  375:   Summary: Some bug with rint
  376: 
  377:   Revision 1.270  2017/05/24 05:45:29  brouard
  378:   *** empty log message ***
  379: 
  380:   Revision 1.269  2017/05/23 08:39:25  brouard
  381:   Summary: Code into subroutine, cleanings
  382: 
  383:   Revision 1.268  2017/05/18 20:09:32  brouard
  384:   Summary: backprojection and confidence intervals of backprevalence
  385: 
  386:   Revision 1.267  2017/05/13 10:25:05  brouard
  387:   Summary: temporary save for backprojection
  388: 
  389:   Revision 1.266  2017/05/13 07:26:12  brouard
  390:   Summary: Version 0.99r13 (improvements and bugs fixed)
  391: 
  392:   Revision 1.265  2017/04/26 16:22:11  brouard
  393:   Summary: imach 0.99r13 Some bugs fixed
  394: 
  395:   Revision 1.264  2017/04/26 06:01:29  brouard
  396:   Summary: Labels in graphs
  397: 
  398:   Revision 1.263  2017/04/24 15:23:15  brouard
  399:   Summary: to save
  400: 
  401:   Revision 1.262  2017/04/18 16:48:12  brouard
  402:   *** empty log message ***
  403: 
  404:   Revision 1.261  2017/04/05 10:14:09  brouard
  405:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
  406: 
  407:   Revision 1.260  2017/04/04 17:46:59  brouard
  408:   Summary: Gnuplot indexations fixed (humm)
  409: 
  410:   Revision 1.259  2017/04/04 13:01:16  brouard
  411:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
  412: 
  413:   Revision 1.258  2017/04/03 10:17:47  brouard
  414:   Summary: Version 0.99r12
  415: 
  416:   Some cleanings, conformed with updated documentation.
  417: 
  418:   Revision 1.257  2017/03/29 16:53:30  brouard
  419:   Summary: Temp
  420: 
  421:   Revision 1.256  2017/03/27 05:50:23  brouard
  422:   Summary: Temporary
  423: 
  424:   Revision 1.255  2017/03/08 16:02:28  brouard
  425:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
  426: 
  427:   Revision 1.254  2017/03/08 07:13:00  brouard
  428:   Summary: Fixing data parameter line
  429: 
  430:   Revision 1.253  2016/12/15 11:59:41  brouard
  431:   Summary: 0.99 in progress
  432: 
  433:   Revision 1.252  2016/09/15 21:15:37  brouard
  434:   *** empty log message ***
  435: 
  436:   Revision 1.251  2016/09/15 15:01:13  brouard
  437:   Summary: not working
  438: 
  439:   Revision 1.250  2016/09/08 16:07:27  brouard
  440:   Summary: continue
  441: 
  442:   Revision 1.249  2016/09/07 17:14:18  brouard
  443:   Summary: Starting values from frequencies
  444: 
  445:   Revision 1.248  2016/09/07 14:10:18  brouard
  446:   *** empty log message ***
  447: 
  448:   Revision 1.247  2016/09/02 11:11:21  brouard
  449:   *** empty log message ***
  450: 
  451:   Revision 1.246  2016/09/02 08:49:22  brouard
  452:   *** empty log message ***
  453: 
  454:   Revision 1.245  2016/09/02 07:25:01  brouard
  455:   *** empty log message ***
  456: 
  457:   Revision 1.244  2016/09/02 07:17:34  brouard
  458:   *** empty log message ***
  459: 
  460:   Revision 1.243  2016/09/02 06:45:35  brouard
  461:   *** empty log message ***
  462: 
  463:   Revision 1.242  2016/08/30 15:01:20  brouard
  464:   Summary: Fixing a lots
  465: 
  466:   Revision 1.241  2016/08/29 17:17:25  brouard
  467:   Summary: gnuplot problem in Back projection to fix
  468: 
  469:   Revision 1.240  2016/08/29 07:53:18  brouard
  470:   Summary: Better
  471: 
  472:   Revision 1.239  2016/08/26 15:51:03  brouard
  473:   Summary: Improvement in Powell output in order to copy and paste
  474: 
  475:   Author:
  476: 
  477:   Revision 1.238  2016/08/26 14:23:35  brouard
  478:   Summary: Starting tests of 0.99
  479: 
  480:   Revision 1.237  2016/08/26 09:20:19  brouard
  481:   Summary: to valgrind
  482: 
  483:   Revision 1.236  2016/08/25 10:50:18  brouard
  484:   *** empty log message ***
  485: 
  486:   Revision 1.235  2016/08/25 06:59:23  brouard
  487:   *** empty log message ***
  488: 
  489:   Revision 1.234  2016/08/23 16:51:20  brouard
  490:   *** empty log message ***
  491: 
  492:   Revision 1.233  2016/08/23 07:40:50  brouard
  493:   Summary: not working
  494: 
  495:   Revision 1.232  2016/08/22 14:20:21  brouard
  496:   Summary: not working
  497: 
  498:   Revision 1.231  2016/08/22 07:17:15  brouard
  499:   Summary: not working
  500: 
  501:   Revision 1.230  2016/08/22 06:55:53  brouard
  502:   Summary: Not working
  503: 
  504:   Revision 1.229  2016/07/23 09:45:53  brouard
  505:   Summary: Completing for func too
  506: 
  507:   Revision 1.228  2016/07/22 17:45:30  brouard
  508:   Summary: Fixing some arrays, still debugging
  509: 
  510:   Revision 1.226  2016/07/12 18:42:34  brouard
  511:   Summary: temp
  512: 
  513:   Revision 1.225  2016/07/12 08:40:03  brouard
  514:   Summary: saving but not running
  515: 
  516:   Revision 1.224  2016/07/01 13:16:01  brouard
  517:   Summary: Fixes
  518: 
  519:   Revision 1.223  2016/02/19 09:23:35  brouard
  520:   Summary: temporary
  521: 
  522:   Revision 1.222  2016/02/17 08:14:50  brouard
  523:   Summary: Probably last 0.98 stable version 0.98r6
  524: 
  525:   Revision 1.221  2016/02/15 23:35:36  brouard
  526:   Summary: minor bug
  527: 
  528:   Revision 1.219  2016/02/15 00:48:12  brouard
  529:   *** empty log message ***
  530: 
  531:   Revision 1.218  2016/02/12 11:29:23  brouard
  532:   Summary: 0.99 Back projections
  533: 
  534:   Revision 1.217  2015/12/23 17:18:31  brouard
  535:   Summary: Experimental backcast
  536: 
  537:   Revision 1.216  2015/12/18 17:32:11  brouard
  538:   Summary: 0.98r4 Warning and status=-2
  539: 
  540:   Version 0.98r4 is now:
  541:    - displaying an error when status is -1, date of interview unknown and date of death known;
  542:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
  543:   Older changes concerning s=-2, dating from 2005 have been supersed.
  544: 
  545:   Revision 1.215  2015/12/16 08:52:24  brouard
  546:   Summary: 0.98r4 working
  547: 
  548:   Revision 1.214  2015/12/16 06:57:54  brouard
  549:   Summary: temporary not working
  550: 
  551:   Revision 1.213  2015/12/11 18:22:17  brouard
  552:   Summary: 0.98r4
  553: 
  554:   Revision 1.212  2015/11/21 12:47:24  brouard
  555:   Summary: minor typo
  556: 
  557:   Revision 1.211  2015/11/21 12:41:11  brouard
  558:   Summary: 0.98r3 with some graph of projected cross-sectional
  559: 
  560:   Author: Nicolas Brouard
  561: 
  562:   Revision 1.210  2015/11/18 17:41:20  brouard
  563:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
  564:   Summary: Adding ftolpl parameter
  565:   Author: N Brouard
  566: 
  567:   We had difficulties to get smoothed confidence intervals. It was due
  568:   to the period prevalence which wasn't computed accurately. The inner
  569:   parameter ftolpl is now an outer parameter of the .imach parameter
  570:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
  571:   computation are long.
  572: 
  573:   Revision 1.208  2015/11/17 14:31:57  brouard
  574:   Summary: temporary
  575: 
  576:   Revision 1.207  2015/10/27 17:36:57  brouard
  577:   *** empty log message ***
  578: 
  579:   Revision 1.206  2015/10/24 07:14:11  brouard
  580:   *** empty log message ***
  581: 
  582:   Revision 1.205  2015/10/23 15:50:53  brouard
  583:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
  584: 
  585:   Revision 1.204  2015/10/01 16:20:26  brouard
  586:   Summary: Some new graphs of contribution to likelihood
  587: 
  588:   Revision 1.203  2015/09/30 17:45:14  brouard
  589:   Summary: looking at better estimation of the hessian
  590: 
  591:   Also a better criteria for convergence to the period prevalence And
  592:   therefore adding the number of years needed to converge. (The
  593:   prevalence in any alive state shold sum to one
  594: 
  595:   Revision 1.202  2015/09/22 19:45:16  brouard
  596:   Summary: Adding some overall graph on contribution to likelihood. Might change
  597: 
  598:   Revision 1.201  2015/09/15 17:34:58  brouard
  599:   Summary: 0.98r0
  600: 
  601:   - Some new graphs like suvival functions
  602:   - Some bugs fixed like model=1+age+V2.
  603: 
  604:   Revision 1.200  2015/09/09 16:53:55  brouard
  605:   Summary: Big bug thanks to Flavia
  606: 
  607:   Even model=1+age+V2. did not work anymore
  608: 
  609:   Revision 1.199  2015/09/07 14:09:23  brouard
  610:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
  611: 
  612:   Revision 1.198  2015/09/03 07:14:39  brouard
  613:   Summary: 0.98q5 Flavia
  614: 
  615:   Revision 1.197  2015/09/01 18:24:39  brouard
  616:   *** empty log message ***
  617: 
  618:   Revision 1.196  2015/08/18 23:17:52  brouard
  619:   Summary: 0.98q5
  620: 
  621:   Revision 1.195  2015/08/18 16:28:39  brouard
  622:   Summary: Adding a hack for testing purpose
  623: 
  624:   After reading the title, ftol and model lines, if the comment line has
  625:   a q, starting with #q, the answer at the end of the run is quit. It
  626:   permits to run test files in batch with ctest. The former workaround was
  627:   $ echo q | imach foo.imach
  628: 
  629:   Revision 1.194  2015/08/18 13:32:00  brouard
  630:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
  631: 
  632:   Revision 1.193  2015/08/04 07:17:42  brouard
  633:   Summary: 0.98q4
  634: 
  635:   Revision 1.192  2015/07/16 16:49:02  brouard
  636:   Summary: Fixing some outputs
  637: 
  638:   Revision 1.191  2015/07/14 10:00:33  brouard
  639:   Summary: Some fixes
  640: 
  641:   Revision 1.190  2015/05/05 08:51:13  brouard
  642:   Summary: Adding digits in output parameters (7 digits instead of 6)
  643: 
  644:   Fix 1+age+.
  645: 
  646:   Revision 1.189  2015/04/30 14:45:16  brouard
  647:   Summary: 0.98q2
  648: 
  649:   Revision 1.188  2015/04/30 08:27:53  brouard
  650:   *** empty log message ***
  651: 
  652:   Revision 1.187  2015/04/29 09:11:15  brouard
  653:   *** empty log message ***
  654: 
  655:   Revision 1.186  2015/04/23 12:01:52  brouard
  656:   Summary: V1*age is working now, version 0.98q1
  657: 
  658:   Some codes had been disabled in order to simplify and Vn*age was
  659:   working in the optimization phase, ie, giving correct MLE parameters,
  660:   but, as usual, outputs were not correct and program core dumped.
  661: 
  662:   Revision 1.185  2015/03/11 13:26:42  brouard
  663:   Summary: Inclusion of compile and links command line for Intel Compiler
  664: 
  665:   Revision 1.184  2015/03/11 11:52:39  brouard
  666:   Summary: Back from Windows 8. Intel Compiler
  667: 
  668:   Revision 1.183  2015/03/10 20:34:32  brouard
  669:   Summary: 0.98q0, trying with directest, mnbrak fixed
  670: 
  671:   We use directest instead of original Powell test; probably no
  672:   incidence on the results, but better justifications;
  673:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
  674:   wrong results.
  675: 
  676:   Revision 1.182  2015/02/12 08:19:57  brouard
  677:   Summary: Trying to keep directest which seems simpler and more general
  678:   Author: Nicolas Brouard
  679: 
  680:   Revision 1.181  2015/02/11 23:22:24  brouard
  681:   Summary: Comments on Powell added
  682: 
  683:   Author:
  684: 
  685:   Revision 1.180  2015/02/11 17:33:45  brouard
  686:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
  687: 
  688:   Revision 1.179  2015/01/04 09:57:06  brouard
  689:   Summary: back to OS/X
  690: 
  691:   Revision 1.178  2015/01/04 09:35:48  brouard
  692:   *** empty log message ***
  693: 
  694:   Revision 1.177  2015/01/03 18:40:56  brouard
  695:   Summary: Still testing ilc32 on OSX
  696: 
  697:   Revision 1.176  2015/01/03 16:45:04  brouard
  698:   *** empty log message ***
  699: 
  700:   Revision 1.175  2015/01/03 16:33:42  brouard
  701:   *** empty log message ***
  702: 
  703:   Revision 1.174  2015/01/03 16:15:49  brouard
  704:   Summary: Still in cross-compilation
  705: 
  706:   Revision 1.173  2015/01/03 12:06:26  brouard
  707:   Summary: trying to detect cross-compilation
  708: 
  709:   Revision 1.172  2014/12/27 12:07:47  brouard
  710:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
  711: 
  712:   Revision 1.171  2014/12/23 13:26:59  brouard
  713:   Summary: Back from Visual C
  714: 
  715:   Still problem with utsname.h on Windows
  716: 
  717:   Revision 1.170  2014/12/23 11:17:12  brouard
  718:   Summary: Cleaning some \%% back to %%
  719: 
  720:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
  721: 
  722:   Revision 1.169  2014/12/22 23:08:31  brouard
  723:   Summary: 0.98p
  724: 
  725:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
  726: 
  727:   Revision 1.168  2014/12/22 15:17:42  brouard
  728:   Summary: update
  729: 
  730:   Revision 1.167  2014/12/22 13:50:56  brouard
  731:   Summary: Testing uname and compiler version and if compiled 32 or 64
  732: 
  733:   Testing on Linux 64
  734: 
  735:   Revision 1.166  2014/12/22 11:40:47  brouard
  736:   *** empty log message ***
  737: 
  738:   Revision 1.165  2014/12/16 11:20:36  brouard
  739:   Summary: After compiling on Visual C
  740: 
  741:   * imach.c (Module): Merging 1.61 to 1.162
  742: 
  743:   Revision 1.164  2014/12/16 10:52:11  brouard
  744:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
  745: 
  746:   * imach.c (Module): Merging 1.61 to 1.162
  747: 
  748:   Revision 1.163  2014/12/16 10:30:11  brouard
  749:   * imach.c (Module): Merging 1.61 to 1.162
  750: 
  751:   Revision 1.162  2014/09/25 11:43:39  brouard
  752:   Summary: temporary backup 0.99!
  753: 
  754:   Revision 1.1  2014/09/16 11:06:58  brouard
  755:   Summary: With some code (wrong) for nlopt
  756: 
  757:   Author:
  758: 
  759:   Revision 1.161  2014/09/15 20:41:41  brouard
  760:   Summary: Problem with macro SQR on Intel compiler
  761: 
  762:   Revision 1.160  2014/09/02 09:24:05  brouard
  763:   *** empty log message ***
  764: 
  765:   Revision 1.159  2014/09/01 10:34:10  brouard
  766:   Summary: WIN32
  767:   Author: Brouard
  768: 
  769:   Revision 1.158  2014/08/27 17:11:51  brouard
  770:   *** empty log message ***
  771: 
  772:   Revision 1.157  2014/08/27 16:26:55  brouard
  773:   Summary: Preparing windows Visual studio version
  774:   Author: Brouard
  775: 
  776:   In order to compile on Visual studio, time.h is now correct and time_t
  777:   and tm struct should be used. difftime should be used but sometimes I
  778:   just make the differences in raw time format (time(&now).
  779:   Trying to suppress #ifdef LINUX
  780:   Add xdg-open for __linux in order to open default browser.
  781: 
  782:   Revision 1.156  2014/08/25 20:10:10  brouard
  783:   *** empty log message ***
  784: 
  785:   Revision 1.155  2014/08/25 18:32:34  brouard
  786:   Summary: New compile, minor changes
  787:   Author: Brouard
  788: 
  789:   Revision 1.154  2014/06/20 17:32:08  brouard
  790:   Summary: Outputs now all graphs of convergence to period prevalence
  791: 
  792:   Revision 1.153  2014/06/20 16:45:46  brouard
  793:   Summary: If 3 live state, convergence to period prevalence on same graph
  794:   Author: Brouard
  795: 
  796:   Revision 1.152  2014/06/18 17:54:09  brouard
  797:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
  798: 
  799:   Revision 1.151  2014/06/18 16:43:30  brouard
  800:   *** empty log message ***
  801: 
  802:   Revision 1.150  2014/06/18 16:42:35  brouard
  803:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
  804:   Author: brouard
  805: 
  806:   Revision 1.149  2014/06/18 15:51:14  brouard
  807:   Summary: Some fixes in parameter files errors
  808:   Author: Nicolas Brouard
  809: 
  810:   Revision 1.148  2014/06/17 17:38:48  brouard
  811:   Summary: Nothing new
  812:   Author: Brouard
  813: 
  814:   Just a new packaging for OS/X version 0.98nS
  815: 
  816:   Revision 1.147  2014/06/16 10:33:11  brouard
  817:   *** empty log message ***
  818: 
  819:   Revision 1.146  2014/06/16 10:20:28  brouard
  820:   Summary: Merge
  821:   Author: Brouard
  822: 
  823:   Merge, before building revised version.
  824: 
  825:   Revision 1.145  2014/06/10 21:23:15  brouard
  826:   Summary: Debugging with valgrind
  827:   Author: Nicolas Brouard
  828: 
  829:   Lot of changes in order to output the results with some covariates
  830:   After the Edimburgh REVES conference 2014, it seems mandatory to
  831:   improve the code.
  832:   No more memory valgrind error but a lot has to be done in order to
  833:   continue the work of splitting the code into subroutines.
  834:   Also, decodemodel has been improved. Tricode is still not
  835:   optimal. nbcode should be improved. Documentation has been added in
  836:   the source code.
  837: 
  838:   Revision 1.143  2014/01/26 09:45:38  brouard
  839:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
  840: 
  841:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  842:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
  843: 
  844:   Revision 1.142  2014/01/26 03:57:36  brouard
  845:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
  846: 
  847:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  848: 
  849:   Revision 1.141  2014/01/26 02:42:01  brouard
  850:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  851: 
  852:   Revision 1.140  2011/09/02 10:37:54  brouard
  853:   Summary: times.h is ok with mingw32 now.
  854: 
  855:   Revision 1.139  2010/06/14 07:50:17  brouard
  856:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
  857:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
  858: 
  859:   Revision 1.138  2010/04/30 18:19:40  brouard
  860:   *** empty log message ***
  861: 
  862:   Revision 1.137  2010/04/29 18:11:38  brouard
  863:   (Module): Checking covariates for more complex models
  864:   than V1+V2. A lot of change to be done. Unstable.
  865: 
  866:   Revision 1.136  2010/04/26 20:30:53  brouard
  867:   (Module): merging some libgsl code. Fixing computation
  868:   of likelione (using inter/intrapolation if mle = 0) in order to
  869:   get same likelihood as if mle=1.
  870:   Some cleaning of code and comments added.
  871: 
  872:   Revision 1.135  2009/10/29 15:33:14  brouard
  873:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  874: 
  875:   Revision 1.134  2009/10/29 13:18:53  brouard
  876:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  877: 
  878:   Revision 1.133  2009/07/06 10:21:25  brouard
  879:   just nforces
  880: 
  881:   Revision 1.132  2009/07/06 08:22:05  brouard
  882:   Many tings
  883: 
  884:   Revision 1.131  2009/06/20 16:22:47  brouard
  885:   Some dimensions resccaled
  886: 
  887:   Revision 1.130  2009/05/26 06:44:34  brouard
  888:   (Module): Max Covariate is now set to 20 instead of 8. A
  889:   lot of cleaning with variables initialized to 0. Trying to make
  890:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
  891: 
  892:   Revision 1.129  2007/08/31 13:49:27  lievre
  893:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
  894: 
  895:   Revision 1.128  2006/06/30 13:02:05  brouard
  896:   (Module): Clarifications on computing e.j
  897: 
  898:   Revision 1.127  2006/04/28 18:11:50  brouard
  899:   (Module): Yes the sum of survivors was wrong since
  900:   imach-114 because nhstepm was no more computed in the age
  901:   loop. Now we define nhstepma in the age loop.
  902:   (Module): In order to speed up (in case of numerous covariates) we
  903:   compute health expectancies (without variances) in a first step
  904:   and then all the health expectancies with variances or standard
  905:   deviation (needs data from the Hessian matrices) which slows the
  906:   computation.
  907:   In the future we should be able to stop the program is only health
  908:   expectancies and graph are needed without standard deviations.
  909: 
  910:   Revision 1.126  2006/04/28 17:23:28  brouard
  911:   (Module): Yes the sum of survivors was wrong since
  912:   imach-114 because nhstepm was no more computed in the age
  913:   loop. Now we define nhstepma in the age loop.
  914:   Version 0.98h
  915: 
  916:   Revision 1.125  2006/04/04 15:20:31  lievre
  917:   Errors in calculation of health expectancies. Age was not initialized.
  918:   Forecasting file added.
  919: 
  920:   Revision 1.124  2006/03/22 17:13:53  lievre
  921:   Parameters are printed with %lf instead of %f (more numbers after the comma).
  922:   The log-likelihood is printed in the log file
  923: 
  924:   Revision 1.123  2006/03/20 10:52:43  brouard
  925:   * imach.c (Module): <title> changed, corresponds to .htm file
  926:   name. <head> headers where missing.
  927: 
  928:   * imach.c (Module): Weights can have a decimal point as for
  929:   English (a comma might work with a correct LC_NUMERIC environment,
  930:   otherwise the weight is truncated).
  931:   Modification of warning when the covariates values are not 0 or
  932:   1.
  933:   Version 0.98g
  934: 
  935:   Revision 1.122  2006/03/20 09:45:41  brouard
  936:   (Module): Weights can have a decimal point as for
  937:   English (a comma might work with a correct LC_NUMERIC environment,
  938:   otherwise the weight is truncated).
  939:   Modification of warning when the covariates values are not 0 or
  940:   1.
  941:   Version 0.98g
  942: 
  943:   Revision 1.121  2006/03/16 17:45:01  lievre
  944:   * imach.c (Module): Comments concerning covariates added
  945: 
  946:   * imach.c (Module): refinements in the computation of lli if
  947:   status=-2 in order to have more reliable computation if stepm is
  948:   not 1 month. Version 0.98f
  949: 
  950:   Revision 1.120  2006/03/16 15:10:38  lievre
  951:   (Module): refinements in the computation of lli if
  952:   status=-2 in order to have more reliable computation if stepm is
  953:   not 1 month. Version 0.98f
  954: 
  955:   Revision 1.119  2006/03/15 17:42:26  brouard
  956:   (Module): Bug if status = -2, the loglikelihood was
  957:   computed as likelihood omitting the logarithm. Version O.98e
  958: 
  959:   Revision 1.118  2006/03/14 18:20:07  brouard
  960:   (Module): varevsij Comments added explaining the second
  961:   table of variances if popbased=1 .
  962:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  963:   (Module): Function pstamp added
  964:   (Module): Version 0.98d
  965: 
  966:   Revision 1.117  2006/03/14 17:16:22  brouard
  967:   (Module): varevsij Comments added explaining the second
  968:   table of variances if popbased=1 .
  969:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  970:   (Module): Function pstamp added
  971:   (Module): Version 0.98d
  972: 
  973:   Revision 1.116  2006/03/06 10:29:27  brouard
  974:   (Module): Variance-covariance wrong links and
  975:   varian-covariance of ej. is needed (Saito).
  976: 
  977:   Revision 1.115  2006/02/27 12:17:45  brouard
  978:   (Module): One freematrix added in mlikeli! 0.98c
  979: 
  980:   Revision 1.114  2006/02/26 12:57:58  brouard
  981:   (Module): Some improvements in processing parameter
  982:   filename with strsep.
  983: 
  984:   Revision 1.113  2006/02/24 14:20:24  brouard
  985:   (Module): Memory leaks checks with valgrind and:
  986:   datafile was not closed, some imatrix were not freed and on matrix
  987:   allocation too.
  988: 
  989:   Revision 1.112  2006/01/30 09:55:26  brouard
  990:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
  991: 
  992:   Revision 1.111  2006/01/25 20:38:18  brouard
  993:   (Module): Lots of cleaning and bugs added (Gompertz)
  994:   (Module): Comments can be added in data file. Missing date values
  995:   can be a simple dot '.'.
  996: 
  997:   Revision 1.110  2006/01/25 00:51:50  brouard
  998:   (Module): Lots of cleaning and bugs added (Gompertz)
  999: 
 1000:   Revision 1.109  2006/01/24 19:37:15  brouard
 1001:   (Module): Comments (lines starting with a #) are allowed in data.
 1002: 
 1003:   Revision 1.108  2006/01/19 18:05:42  lievre
 1004:   Gnuplot problem appeared...
 1005:   To be fixed
 1006: 
 1007:   Revision 1.107  2006/01/19 16:20:37  brouard
 1008:   Test existence of gnuplot in imach path
 1009: 
 1010:   Revision 1.106  2006/01/19 13:24:36  brouard
 1011:   Some cleaning and links added in html output
 1012: 
 1013:   Revision 1.105  2006/01/05 20:23:19  lievre
 1014:   *** empty log message ***
 1015: 
 1016:   Revision 1.104  2005/09/30 16:11:43  lievre
 1017:   (Module): sump fixed, loop imx fixed, and simplifications.
 1018:   (Module): If the status is missing at the last wave but we know
 1019:   that the person is alive, then we can code his/her status as -2
 1020:   (instead of missing=-1 in earlier versions) and his/her
 1021:   contributions to the likelihood is 1 - Prob of dying from last
 1022:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
 1023:   the healthy state at last known wave). Version is 0.98
 1024: 
 1025:   Revision 1.103  2005/09/30 15:54:49  lievre
 1026:   (Module): sump fixed, loop imx fixed, and simplifications.
 1027: 
 1028:   Revision 1.102  2004/09/15 17:31:30  brouard
 1029:   Add the possibility to read data file including tab characters.
 1030: 
 1031:   Revision 1.101  2004/09/15 10:38:38  brouard
 1032:   Fix on curr_time
 1033: 
 1034:   Revision 1.100  2004/07/12 18:29:06  brouard
 1035:   Add version for Mac OS X. Just define UNIX in Makefile
 1036: 
 1037:   Revision 1.99  2004/06/05 08:57:40  brouard
 1038:   *** empty log message ***
 1039: 
 1040:   Revision 1.98  2004/05/16 15:05:56  brouard
 1041:   New version 0.97 . First attempt to estimate force of mortality
 1042:   directly from the data i.e. without the need of knowing the health
 1043:   state at each age, but using a Gompertz model: log u =a + b*age .
 1044:   This is the basic analysis of mortality and should be done before any
 1045:   other analysis, in order to test if the mortality estimated from the
 1046:   cross-longitudinal survey is different from the mortality estimated
 1047:   from other sources like vital statistic data.
 1048: 
 1049:   The same imach parameter file can be used but the option for mle should be -3.
 1050: 
 1051:   Agnès, who wrote this part of the code, tried to keep most of the
 1052:   former routines in order to include the new code within the former code.
 1053: 
 1054:   The output is very simple: only an estimate of the intercept and of
 1055:   the slope with 95% confident intervals.
 1056: 
 1057:   Current limitations:
 1058:   A) Even if you enter covariates, i.e. with the
 1059:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
 1060:   B) There is no computation of Life Expectancy nor Life Table.
 1061: 
 1062:   Revision 1.97  2004/02/20 13:25:42  lievre
 1063:   Version 0.96d. Population forecasting command line is (temporarily)
 1064:   suppressed.
 1065: 
 1066:   Revision 1.96  2003/07/15 15:38:55  brouard
 1067:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
 1068:   rewritten within the same printf. Workaround: many printfs.
 1069: 
 1070:   Revision 1.95  2003/07/08 07:54:34  brouard
 1071:   * imach.c (Repository):
 1072:   (Repository): Using imachwizard code to output a more meaningful covariance
 1073:   matrix (cov(a12,c31) instead of numbers.
 1074: 
 1075:   Revision 1.94  2003/06/27 13:00:02  brouard
 1076:   Just cleaning
 1077: 
 1078:   Revision 1.93  2003/06/25 16:33:55  brouard
 1079:   (Module): On windows (cygwin) function asctime_r doesn't
 1080:   exist so I changed back to asctime which exists.
 1081:   (Module): Version 0.96b
 1082: 
 1083:   Revision 1.92  2003/06/25 16:30:45  brouard
 1084:   (Module): On windows (cygwin) function asctime_r doesn't
 1085:   exist so I changed back to asctime which exists.
 1086: 
 1087:   Revision 1.91  2003/06/25 15:30:29  brouard
 1088:   * imach.c (Repository): Duplicated warning errors corrected.
 1089:   (Repository): Elapsed time after each iteration is now output. It
 1090:   helps to forecast when convergence will be reached. Elapsed time
 1091:   is stamped in powell.  We created a new html file for the graphs
 1092:   concerning matrix of covariance. It has extension -cov.htm.
 1093: 
 1094:   Revision 1.90  2003/06/24 12:34:15  brouard
 1095:   (Module): Some bugs corrected for windows. Also, when
 1096:   mle=-1 a template is output in file "or"mypar.txt with the design
 1097:   of the covariance matrix to be input.
 1098: 
 1099:   Revision 1.89  2003/06/24 12:30:52  brouard
 1100:   (Module): Some bugs corrected for windows. Also, when
 1101:   mle=-1 a template is output in file "or"mypar.txt with the design
 1102:   of the covariance matrix to be input.
 1103: 
 1104:   Revision 1.88  2003/06/23 17:54:56  brouard
 1105:   * 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.
 1106: 
 1107:   Revision 1.87  2003/06/18 12:26:01  brouard
 1108:   Version 0.96
 1109: 
 1110:   Revision 1.86  2003/06/17 20:04:08  brouard
 1111:   (Module): Change position of html and gnuplot routines and added
 1112:   routine fileappend.
 1113: 
 1114:   Revision 1.85  2003/06/17 13:12:43  brouard
 1115:   * imach.c (Repository): Check when date of death was earlier that
 1116:   current date of interview. It may happen when the death was just
 1117:   prior to the death. In this case, dh was negative and likelihood
 1118:   was wrong (infinity). We still send an "Error" but patch by
 1119:   assuming that the date of death was just one stepm after the
 1120:   interview.
 1121:   (Repository): Because some people have very long ID (first column)
 1122:   we changed int to long in num[] and we added a new lvector for
 1123:   memory allocation. But we also truncated to 8 characters (left
 1124:   truncation)
 1125:   (Repository): No more line truncation errors.
 1126: 
 1127:   Revision 1.84  2003/06/13 21:44:43  brouard
 1128:   * imach.c (Repository): Replace "freqsummary" at a correct
 1129:   place. It differs from routine "prevalence" which may be called
 1130:   many times. Probs is memory consuming and must be used with
 1131:   parcimony.
 1132:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
 1133: 
 1134:   Revision 1.83  2003/06/10 13:39:11  lievre
 1135:   *** empty log message ***
 1136: 
 1137:   Revision 1.82  2003/06/05 15:57:20  brouard
 1138:   Add log in  imach.c and  fullversion number is now printed.
 1139: 
 1140: */
 1141: /*
 1142:    Interpolated Markov Chain
 1143: 
 1144:   Short summary of the programme:
 1145:   
 1146:   This program computes Healthy Life Expectancies or State-specific
 1147:   (if states aren't health statuses) Expectancies from
 1148:   cross-longitudinal data. Cross-longitudinal data consist in: 
 1149: 
 1150:   -1- a first survey ("cross") where individuals from different ages
 1151:   are interviewed on their health status or degree of disability (in
 1152:   the case of a health survey which is our main interest)
 1153: 
 1154:   -2- at least a second wave of interviews ("longitudinal") which
 1155:   measure each change (if any) in individual health status.  Health
 1156:   expectancies are computed from the time spent in each health state
 1157:   according to a model. More health states you consider, more time is
 1158:   necessary to reach the Maximum Likelihood of the parameters involved
 1159:   in the model.  The simplest model is the multinomial logistic model
 1160:   where pij is the probability to be observed in state j at the second
 1161:   wave conditional to be observed in state i at the first
 1162:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
 1163:   etc , where 'age' is age and 'sex' is a covariate. If you want to
 1164:   have a more complex model than "constant and age", you should modify
 1165:   the program where the markup *Covariates have to be included here
 1166:   again* invites you to do it.  More covariates you add, slower the
 1167:   convergence.
 1168: 
 1169:   The advantage of this computer programme, compared to a simple
 1170:   multinomial logistic model, is clear when the delay between waves is not
 1171:   identical for each individual. Also, if a individual missed an
 1172:   intermediate interview, the information is lost, but taken into
 1173:   account using an interpolation or extrapolation.  
 1174: 
 1175:   hPijx is the probability to be observed in state i at age x+h
 1176:   conditional to the observed state i at age x. The delay 'h' can be
 1177:   split into an exact number (nh*stepm) of unobserved intermediate
 1178:   states. This elementary transition (by month, quarter,
 1179:   semester or year) is modelled as a multinomial logistic.  The hPx
 1180:   matrix is simply the matrix product of nh*stepm elementary matrices
 1181:   and the contribution of each individual to the likelihood is simply
 1182:   hPijx.
 1183: 
 1184:   Also this programme outputs the covariance matrix of the parameters but also
 1185:   of the life expectancies. It also computes the period (stable) prevalence.
 1186: 
 1187: Back prevalence and projections:
 1188: 
 1189:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
 1190:    double agemaxpar, double ftolpl, int *ncvyearp, double
 1191:    dateprev1,double dateprev2, int firstpass, int lastpass, int
 1192:    mobilavproj)
 1193: 
 1194:     Computes the back prevalence limit for any combination of
 1195:     covariate values k at any age between ageminpar and agemaxpar and
 1196:     returns it in **bprlim. In the loops,
 1197: 
 1198:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
 1199:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
 1200: 
 1201:    - hBijx Back Probability to be in state i at age x-h being in j at x
 1202:    Computes for any combination of covariates k and any age between bage and fage 
 1203:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 1204:  			oldm=oldms;savm=savms;
 1205: 
 1206:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
 1207:      Computes the transition matrix starting at age 'age' over
 1208:      'nhstepm*hstepm*stepm' months (i.e. until
 1209:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
 1210:      nhstepm*hstepm matrices. 
 1211: 
 1212:      Returns p3mat[i][j][h] after calling
 1213:      p3mat[i][j][h]=matprod2(newm,
 1214:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
 1215:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
 1216:      oldm);
 1217: 
 1218: Important routines
 1219: 
 1220: - func (or funcone), computes logit (pij) distinguishing
 1221:   o fixed variables (single or product dummies or quantitative);
 1222:   o varying variables by:
 1223:    (1) wave (single, product dummies, quantitative), 
 1224:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
 1225:        % fixed dummy (treated) or quantitative (not done because time-consuming);
 1226:        % varying dummy (not done) or quantitative (not done);
 1227: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
 1228:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
 1229: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
 1230:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
 1231:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
 1232: 
 1233: 
 1234:   
 1235:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
 1236:            Institut national d'études démographiques, Paris.
 1237:   This software have been partly granted by Euro-REVES, a concerted action
 1238:   from the European Union.
 1239:   It is copyrighted identically to a GNU software product, ie programme and
 1240:   software can be distributed freely for non commercial use. Latest version
 1241:   can be accessed at http://euroreves.ined.fr/imach .
 1242: 
 1243:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
 1244:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
 1245:   
 1246:   **********************************************************************/
 1247: /*
 1248:   main
 1249:   read parameterfile
 1250:   read datafile
 1251:   concatwav
 1252:   freqsummary
 1253:   if (mle >= 1)
 1254:     mlikeli
 1255:   print results files
 1256:   if mle==1 
 1257:      computes hessian
 1258:   read end of parameter file: agemin, agemax, bage, fage, estepm
 1259:       begin-prev-date,...
 1260:   open gnuplot file
 1261:   open html file
 1262:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
 1263:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
 1264:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
 1265:     freexexit2 possible for memory heap.
 1266: 
 1267:   h Pij x                         | pij_nom  ficrestpij
 1268:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
 1269:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
 1270:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
 1271: 
 1272:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
 1273:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
 1274:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
 1275:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
 1276:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
 1277: 
 1278:   forecasting if prevfcast==1 prevforecast call prevalence()
 1279:   health expectancies
 1280:   Variance-covariance of DFLE
 1281:   prevalence()
 1282:    movingaverage()
 1283:   varevsij() 
 1284:   if popbased==1 varevsij(,popbased)
 1285:   total life expectancies
 1286:   Variance of period (stable) prevalence
 1287:  end
 1288: */
 1289: 
 1290: /* #define DEBUG */
 1291: /* #define DEBUGBRENT */
 1292: /* #define DEBUGLINMIN */
 1293: /* #define DEBUGHESS */
 1294: #define DEBUGHESSIJ
 1295: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
 1296: #define POWELL /* Instead of NLOPT */
 1297: #define POWELLNOF3INFF1TEST /* Skip test */
 1298: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
 1299: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
 1300: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
 1301: #define POWELLORIGINCONJUGATE  /* Don't use conjugate but biggest decrease if valuable */
 1302: 
 1303: #include <math.h>
 1304: #include <stdio.h>
 1305: #include <stdlib.h>
 1306: #include <string.h>
 1307: #include <ctype.h>
 1308: 
 1309: #ifdef _WIN32
 1310: #include <io.h>
 1311: #include <windows.h>
 1312: #include <tchar.h>
 1313: #else
 1314: #include <unistd.h>
 1315: #endif
 1316: 
 1317: #include <limits.h>
 1318: #include <sys/types.h>
 1319: 
 1320: #if defined(__GNUC__)
 1321: #include <sys/utsname.h> /* Doesn't work on Windows */
 1322: #endif
 1323: 
 1324: #include <sys/stat.h>
 1325: #include <errno.h>
 1326: /* extern int errno; */
 1327: 
 1328: /* #ifdef LINUX */
 1329: /* #include <time.h> */
 1330: /* #include "timeval.h" */
 1331: /* #else */
 1332: /* #include <sys/time.h> */
 1333: /* #endif */
 1334: 
 1335: #include <time.h>
 1336: 
 1337: #ifdef GSL
 1338: #include <gsl/gsl_errno.h>
 1339: #include <gsl/gsl_multimin.h>
 1340: #endif
 1341: 
 1342: 
 1343: #ifdef NLOPT
 1344: #include <nlopt.h>
 1345: typedef struct {
 1346:   double (* function)(double [] );
 1347: } myfunc_data ;
 1348: #endif
 1349: 
 1350: /* #include <libintl.h> */
 1351: /* #define _(String) gettext (String) */
 1352: 
 1353: #define MAXLINE 16384 /* Was 256 and 1024 and 2048. Overflow with 312 with 2 states and 4 covariates. Should be ok */
 1354: 
 1355: #define GNUPLOTPROGRAM "gnuplot"
 1356: #define GNUPLOTVERSION 5.1
 1357: double gnuplotversion=GNUPLOTVERSION;
 1358: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
 1359: #define FILENAMELENGTH 256
 1360: 
 1361: #define	GLOCK_ERROR_NOPATH		-1	/* empty path */
 1362: #define	GLOCK_ERROR_GETCWD		-2	/* cannot get cwd */
 1363: 
 1364: #define MAXPARM 216 /**< Maximum number of parameters for the optimization was 128 */
 1365: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
 1366: 
 1367: #define NINTERVMAX 8
 1368: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
 1369: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
 1370: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
 1371: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
 1372: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
 1373: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
 1374: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
 1375: #define YEARM 12. /**< Number of months per year */
 1376: /* #define AGESUP 130 */
 1377: /* #define AGESUP 150 */
 1378: #define AGESUP 200
 1379: #define AGEINF 0
 1380: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
 1381: #define AGEBASE 40
 1382: #define AGEOVERFLOW 1.e20
 1383: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
 1384: #ifdef _WIN32
 1385: #define DIRSEPARATOR '\\'
 1386: #define CHARSEPARATOR "\\"
 1387: #define ODIRSEPARATOR '/'
 1388: #else
 1389: #define DIRSEPARATOR '/'
 1390: #define CHARSEPARATOR "/"
 1391: #define ODIRSEPARATOR '\\'
 1392: #endif
 1393: 
 1394: /* $Id: imach.c,v 1.358 2023/06/14 14:57:02 brouard Exp $ */
 1395: /* $State: Exp $ */
 1396: #include "version.h"
 1397: char version[]=__IMACH_VERSION__;
 1398: char copyright[]="Testing conjugate 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";
 1399: char fullversion[]="$Revision: 1.358 $ $Date: 2023/06/14 14:57:02 $"; 
 1400: char strstart[80];
 1401: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
 1402: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
 1403: int debugILK=0; /* debugILK is set by a #d in a comment line */
 1404: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
 1405: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
 1406: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
 1407: int cptcovn=0; /**< cptcovn decodemodel: number of covariates k of the models excluding age*products =6 and age*age but including products */
 1408: int cptcovt=0; /**< cptcovt: total number of covariates of the model (2) nbocc(+)+1 = 8 excepting constant and age and age*age */
 1409: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
 1410: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
 1411: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
 1412: int cptcovprodage=0; /**< Number of fixed covariates with age: V3*age or V2*V3*age 1 */
 1413: int cptcovprodvage=0; /**< Number of varying covariates with age: V7*age or V7*V6*age */
 1414: int cptcovdageprod=0; /**< Number of doubleproducts with age, since 0.99r44 only: age*Vn*Vm for gnuplot printing*/
 1415: int cptcovprodnoage=0; /**< Number of covariate products without age */   
 1416: 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) */
 1417: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
 1418: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
 1419: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
 1420: 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 */
 1421: 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 */
 1422: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (single or product, dummy or quantitative) in the model */
 1423: 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 */
 1424: int nsd=0; /**< Total number of single dummy variables (output) */
 1425: int nsq=0; /**< Total number of single quantitative variables (output) */
 1426: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
 1427: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
 1428: int ntveff=0; /**< ntveff number of effective time varying variables */
 1429: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
 1430: int cptcov=0; /* Working variable */
 1431: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
 1432: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
 1433: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
 1434: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
 1435: int nlstate=2; /* Number of live states */
 1436: int ndeath=1; /* Number of dead states */
 1437: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
 1438: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
 1439: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
 1440: int popbased=0;
 1441: 
 1442: int *wav; /* Number of waves for this individuual 0 is possible */
 1443: int maxwav=0; /* Maxim number of waves */
 1444: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
 1445: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
 1446: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
 1447: 		   to the likelihood and the sum of weights (done by funcone)*/
 1448: int mle=1, weightopt=0;
 1449: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
 1450: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
 1451: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
 1452: 	   * wave mi and wave mi+1 is not an exact multiple of stepm. */
 1453: int countcallfunc=0;  /* Count the number of calls to func */
 1454: int selected(int kvar); /* Is covariate kvar selected for printing results */
 1455: 
 1456: double jmean=1; /* Mean space between 2 waves */
 1457: double **matprod2(); /* test */
 1458: double **oldm, **newm, **savm; /* Working pointers to matrices */
 1459: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
 1460: double	 **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
 1461: 
 1462: /*FILE *fic ; */ /* Used in readdata only */
 1463: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
 1464: FILE *ficlog, *ficrespow;
 1465: int globpr=0; /* Global variable for printing or not */
 1466: double fretone; /* Only one call to likelihood */
 1467: long ipmx=0; /* Number of contributions */
 1468: double sw; /* Sum of weights */
 1469: char filerespow[FILENAMELENGTH];
 1470: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
 1471: FILE *ficresilk;
 1472: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
 1473: FILE *ficresprobmorprev;
 1474: FILE *fichtm, *fichtmcov; /* Html File */
 1475: FILE *ficreseij;
 1476: char filerese[FILENAMELENGTH];
 1477: FILE *ficresstdeij;
 1478: char fileresstde[FILENAMELENGTH];
 1479: FILE *ficrescveij;
 1480: char filerescve[FILENAMELENGTH];
 1481: FILE  *ficresvij;
 1482: char fileresv[FILENAMELENGTH];
 1483: 
 1484: char title[MAXLINE];
 1485: char model[MAXLINE]; /**< The model line */
 1486: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
 1487: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
 1488: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
 1489: char command[FILENAMELENGTH];
 1490: int  outcmd=0;
 1491: 
 1492: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
 1493: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
 1494: char filelog[FILENAMELENGTH]; /* Log file */
 1495: char filerest[FILENAMELENGTH];
 1496: char fileregp[FILENAMELENGTH];
 1497: char popfile[FILENAMELENGTH];
 1498: 
 1499: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
 1500: 
 1501: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
 1502: /* struct timezone tzp; */
 1503: /* extern int gettimeofday(); */
 1504: struct tm tml, *gmtime(), *localtime();
 1505: 
 1506: extern time_t time();
 1507: 
 1508: struct tm start_time, end_time, curr_time, last_time, forecast_time;
 1509: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
 1510: time_t   rlast_btime; /* raw time */
 1511: struct tm tm;
 1512: 
 1513: char strcurr[80], strfor[80];
 1514: 
 1515: char *endptr;
 1516: long lval;
 1517: double dval;
 1518: 
 1519: #define NR_END 1
 1520: #define FREE_ARG char*
 1521: #define FTOL 1.0e-10
 1522: 
 1523: #define NRANSI 
 1524: #define ITMAX 200
 1525: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
 1526: 
 1527: #define TOL 2.0e-4 
 1528: 
 1529: #define CGOLD 0.3819660 
 1530: #define ZEPS 1.0e-10 
 1531: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
 1532: 
 1533: #define GOLD 1.618034 
 1534: #define GLIMIT 100.0 
 1535: #define TINY 1.0e-20 
 1536: 
 1537: static double maxarg1,maxarg2;
 1538: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
 1539: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
 1540:   
 1541: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
 1542: #define rint(a) floor(a+0.5)
 1543: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
 1544: #define mytinydouble 1.0e-16
 1545: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
 1546: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
 1547: /* static double dsqrarg; */
 1548: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
 1549: static double sqrarg;
 1550: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
 1551: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
 1552: int agegomp= AGEGOMP;
 1553: 
 1554: int imx; 
 1555: int stepm=1;
 1556: /* Stepm, step in month: minimum step interpolation*/
 1557: 
 1558: int estepm;
 1559: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
 1560: 
 1561: int m,nb;
 1562: long *num;
 1563: int firstpass=0, lastpass=4,*cod, *cens;
 1564: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
 1565: 		   covariate for which somebody answered excluding 
 1566: 		   undefined. Usually 2: 0 and 1. */
 1567: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
 1568: 			     covariate for which somebody answered including 
 1569: 			     undefined. Usually 3: -1, 0 and 1. */
 1570: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
 1571: double **pmmij, ***probs; /* Global pointer */
 1572: double ***mobaverage, ***mobaverages; /* New global variable */
 1573: double **precov; /* New global variable to store for each resultline, values of model covariates given by the resultlines (in order to speed up)  */
 1574: double *ageexmed,*agecens;
 1575: double dateintmean=0;
 1576:   double anprojd, mprojd, jprojd; /* For eventual projections */
 1577:   double anprojf, mprojf, jprojf;
 1578: 
 1579:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
 1580:   double anbackf, mbackf, jbackf;
 1581:   double jintmean,mintmean,aintmean;  
 1582: double *weight;
 1583: int **s; /* Status */
 1584: double *agedc;
 1585: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
 1586: 		  * covar=matrix(0,NCOVMAX,1,n); 
 1587: 		  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
 1588: double **coqvar; /* Fixed quantitative covariate nqv */
 1589: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
 1590: double ***cotqvar; /* Time varying quantitative covariate itqv */
 1591: double  idx; 
 1592: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
 1593: /* Some documentation */
 1594:       /*   Design original data
 1595:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
 1596:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
 1597:        *                                                             ntv=3     nqtv=1
 1598:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
 1599:        * For time varying covariate, quanti or dummies
 1600:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
 1601:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
 1602:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
 1603:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
 1604:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
 1605:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
 1606:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
 1607:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
 1608:        */
 1609: /* According to the model, more columns can be added to covar by the product of covariates */
 1610: /* 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
 1611:   # States 1=Coresidence, 2 Living alone, 3 Institution
 1612:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
 1613: */
 1614: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1+V4*V3*age */
 1615: /*    kmodel  1  2   3    4     5     6    7     8     9    10 */
 1616: /*Typevar[k]=  0  0   0   2     1    0    2     1     0    3 *//*0 for simple covariate (dummy, quantitative,*/
 1617:                                                                /* fixed or varying), 1 for age product, 2 for*/
 1618:                                                                /* product without age, 3 for age and double product   */
 1619: /*Dummy[k]=    1  0   0   1     3    1    1     2     0     3  *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
 1620:                                                                 /*(single or product without age), 2 dummy*/
 1621:                                                                /* with age product, 3 quant with age product*/
 1622: /*Tvar[k]=     5  4   3   6     5    2    7     1     1     6 */
 1623: /*    nsd         1   2                               3 */ /* Counting single dummies covar fixed or tv */
 1624: /*TnsdVar[Tvar]   1   2                               3 */ 
 1625: /*Tvaraff[nsd]    4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
 1626: /*TvarsD[nsd]     4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
 1627: /*TvarsDind[nsd]  2   3                               9 */ /* position K of single dummy cova */
 1628: /*    nsq      1                     2                  */ /* Counting single quantit tv */
 1629: /* TvarsQ[k]   5                     2                  */ /* Number of single quantitative cova */
 1630: /* TvarsQind   1                     6                  */ /* position K of single quantitative cova */
 1631: /* Tprod[i]=k             1               2             */ /* Position in model of the ith prod without age */
 1632: /* cptcovage                    1               2         3 */ /* Counting cov*age in the model equation */
 1633: /* Tage[cptcovage]=k            5               8         10 */ /* Position in the model of ith cov*age */
 1634: /* 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"*/
 1635: /*  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}*/
 1636: /*  p Tvard[2][1]@21 = {7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0 <repeats 11 times>} */
 1637: /* 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}*/
 1638: /* 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} */
 1639: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2               */ /* Position in model of the ith prod without age */
 1640: /* 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*/
 1641: /* 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 */
 1642: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
 1643: /* Type                    */
 1644: /* V         1  2  3  4  5 */
 1645: /*           F  F  V  V  V */
 1646: /*           D  Q  D  D  Q */
 1647: /*                         */
 1648: int *TvarsD;
 1649: int *TnsdVar;
 1650: int *TvarsDind;
 1651: int *TvarsQ;
 1652: int *TvarsQind;
 1653: 
 1654: #define MAXRESULTLINESPONE 10+1
 1655: int nresult=0;
 1656: int parameterline=0; /* # of the parameter (type) line */
 1657: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
 1658: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
 1659: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
 1660: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
 1661: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
 1662: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
 1663: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
 1664: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
 1665: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
 1666: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
 1667: 
 1668: /* 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
 1669:   # States 1=Coresidence, 2 Living alone, 3 Institution
 1670:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
 1671: */
 1672: /* 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 *\/ */
 1673: 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 */
 1674: 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 */
 1675: 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 */
 1676: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1677: 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 */
 1678: int *TvarAind; /**< TvarindA[1]=5, TvarAind[2]=8  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1679: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1680: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 1681: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
 1682: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
 1683: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
 1684: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
 1685: 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 */
 1686: 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 */
 1687: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
 1688: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
 1689: int *TvarVVA; /* We count ncovvt time varying covariates (single or products with age) and put their name into TvarVVA */
 1690: int *TvarVVAind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
 1691: int *TvarAVVA; /* We count ALL ncovta time varying covariates (single or products with age) and put their name into TvarVVA */
 1692: int *TvarAVVAind; /* We count ALL ncovta time varying covariates (single or products without age) and put their name into TvarVV */
 1693:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
 1694:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age */
 1695:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
 1696:       /* TvarVV={3,1,3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */	       
 1697:       /* 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 */	       
 1698: int *Tvarsel; /**< Selected covariates for output */
 1699: double *Tvalsel; /**< Selected modality value of covariate for output */
 1700: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product, 3 age*Vn*Vm */
 1701: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
 1702: 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 */ 
 1703: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
 1704: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
 1705: int *Tage;
 1706: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
 1707: 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*/
 1708: 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*/ 
 1709: 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  */
 1710: int *Ndum; /** Freq of modality (tricode */
 1711: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
 1712: int **Tvard;
 1713: int **Tvardk;
 1714: int *Tprod;/**< Gives the k position of the k1 product */
 1715: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
 1716: int *Tposprod; /**< Gives the k1 product from the k position */
 1717:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
 1718:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
 1719: int cptcovprod, *Tvaraff, *invalidvarcomb;
 1720: double *lsurv, *lpop, *tpop;
 1721: 
 1722: #define FD 1; /* Fixed dummy covariate */
 1723: #define FQ 2; /* Fixed quantitative covariate */
 1724: #define FP 3; /* Fixed product covariate */
 1725: #define FPDD 7; /* Fixed product dummy*dummy covariate */
 1726: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
 1727: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
 1728: #define VD 10; /* Varying dummy covariate */
 1729: #define VQ 11; /* Varying quantitative covariate */
 1730: #define VP 12; /* Varying product covariate */
 1731: #define VPDD 13; /* Varying product dummy*dummy covariate */
 1732: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
 1733: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
 1734: #define APFD 16; /* Age product * fixed dummy covariate */
 1735: #define APFQ 17; /* Age product * fixed quantitative covariate */
 1736: #define APVD 18; /* Age product * varying dummy covariate */
 1737: #define APVQ 19; /* Age product * varying quantitative covariate */
 1738: 
 1739: #define FTYPE 1; /* Fixed covariate */
 1740: #define VTYPE 2; /* Varying covariate (loop in wave) */
 1741: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
 1742: 
 1743: struct kmodel{
 1744: 	int maintype; /* main type */
 1745: 	int subtype; /* subtype */
 1746: };
 1747: struct kmodel modell[NCOVMAX];
 1748: 
 1749: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
 1750: double ftolhess; /**< Tolerance for computing hessian */
 1751: 
 1752: /**************** split *************************/
 1753: static	int split( char *path, char *dirc, char *name, char *ext, char *finame )
 1754: {
 1755:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
 1756:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
 1757:   */ 
 1758:   char	*ss;				/* pointer */
 1759:   int	l1=0, l2=0;				/* length counters */
 1760: 
 1761:   l1 = strlen(path );			/* length of path */
 1762:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
 1763:   ss= strrchr( path, DIRSEPARATOR );		/* find last / */
 1764:   if ( ss == NULL ) {			/* no directory, so determine current directory */
 1765:     strcpy( name, path );		/* we got the fullname name because no directory */
 1766:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
 1767:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
 1768:     /* get current working directory */
 1769:     /*    extern  char* getcwd ( char *buf , int len);*/
 1770: #ifdef WIN32
 1771:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
 1772: #else
 1773: 	if (getcwd(dirc, FILENAME_MAX) == NULL) {
 1774: #endif
 1775:       return( GLOCK_ERROR_GETCWD );
 1776:     }
 1777:     /* got dirc from getcwd*/
 1778:     printf(" DIRC = %s \n",dirc);
 1779:   } else {				/* strip directory from path */
 1780:     ss++;				/* after this, the filename */
 1781:     l2 = strlen( ss );			/* length of filename */
 1782:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
 1783:     strcpy( name, ss );		/* save file name */
 1784:     strncpy( dirc, path, l1 - l2 );	/* now the directory */
 1785:     dirc[l1-l2] = '\0';			/* add zero */
 1786:     printf(" DIRC2 = %s \n",dirc);
 1787:   }
 1788:   /* We add a separator at the end of dirc if not exists */
 1789:   l1 = strlen( dirc );			/* length of directory */
 1790:   if( dirc[l1-1] != DIRSEPARATOR ){
 1791:     dirc[l1] =  DIRSEPARATOR;
 1792:     dirc[l1+1] = 0; 
 1793:     printf(" DIRC3 = %s \n",dirc);
 1794:   }
 1795:   ss = strrchr( name, '.' );		/* find last / */
 1796:   if (ss >0){
 1797:     ss++;
 1798:     strcpy(ext,ss);			/* save extension */
 1799:     l1= strlen( name);
 1800:     l2= strlen(ss)+1;
 1801:     strncpy( finame, name, l1-l2);
 1802:     finame[l1-l2]= 0;
 1803:   }
 1804: 
 1805:   return( 0 );				/* we're done */
 1806: }
 1807: 
 1808: 
 1809: /******************************************/
 1810: 
 1811: void replace_back_to_slash(char *s, char*t)
 1812: {
 1813:   int i;
 1814:   int lg=0;
 1815:   i=0;
 1816:   lg=strlen(t);
 1817:   for(i=0; i<= lg; i++) {
 1818:     (s[i] = t[i]);
 1819:     if (t[i]== '\\') s[i]='/';
 1820:   }
 1821: }
 1822: 
 1823: char *trimbb(char *out, char *in)
 1824: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
 1825:   char *s;
 1826:   s=out;
 1827:   while (*in != '\0'){
 1828:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
 1829:       in++;
 1830:     }
 1831:     *out++ = *in++;
 1832:   }
 1833:   *out='\0';
 1834:   return s;
 1835: }
 1836: 
 1837: char *trimbtab(char *out, char *in)
 1838: { /* Trim  blanks or tabs in line but keeps first blanks if line starts with blanks */
 1839:   char *s;
 1840:   s=out;
 1841:   while (*in != '\0'){
 1842:     while( (*in == ' ' || *in == '\t')){ /* && *(in+1) != '\0'){*/
 1843:       in++;
 1844:     }
 1845:     *out++ = *in++;
 1846:   }
 1847:   *out='\0';
 1848:   return s;
 1849: }
 1850: 
 1851: /* char *substrchaine(char *out, char *in, char *chain) */
 1852: /* { */
 1853: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
 1854: /*   char *s, *t; */
 1855: /*   t=in;s=out; */
 1856: /*   while ((*in != *chain) && (*in != '\0')){ */
 1857: /*     *out++ = *in++; */
 1858: /*   } */
 1859: 
 1860: /*   /\* *in matches *chain *\/ */
 1861: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
 1862: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1863: /*   } */
 1864: /*   in--; chain--; */
 1865: /*   while ( (*in != '\0')){ */
 1866: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1867: /*     *out++ = *in++; */
 1868: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
 1869: /*   } */
 1870: /*   *out='\0'; */
 1871: /*   out=s; */
 1872: /*   return out; */
 1873: /* } */
 1874: char *substrchaine(char *out, char *in, char *chain)
 1875: {
 1876:   /* Substract chain 'chain' from 'in', return and output 'out' */
 1877:   /* in="V1+V1*age+age*age+V2", chain="+age*age" out="V1+V1*age+V2" */
 1878: 
 1879:   char *strloc;
 1880: 
 1881:   strcpy (out, in);                   /* out="V1+V1*age+age*age+V2" */
 1882:   strloc = strstr(out, chain); /* strloc points to out at "+age*age+V2"  */
 1883:   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" */
 1884:   if(strloc != NULL){ 
 1885:     /* will affect out */ /* strloc+strlen(chain)=|+V2 = "V1+V1*age+age*age|+V2" */ /* Will also work in Unicodek */
 1886:     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)*/
 1887:     /* equivalent to strcpy (strloc, strloc +strlen(chain)) if no overlap; Copies from "+V2" to V1+V1*age+ */
 1888:   }
 1889:   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" */
 1890:   return out;
 1891: }
 1892: 
 1893: 
 1894: char *cutl(char *blocc, char *alocc, char *in, char occ)
 1895: {
 1896:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
 1897:      and alocc starts after first occurence of char 'occ' : ex cutl(blocc,alocc,"abcdef2ghi2j",'2')
 1898:      gives alocc="abcdef" and blocc="ghi2j".
 1899:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
 1900:   */
 1901:   char *s, *t;
 1902:   t=in;s=in;
 1903:   while ((*in != occ) && (*in != '\0')){
 1904:     *alocc++ = *in++;
 1905:   }
 1906:   if( *in == occ){
 1907:     *(alocc)='\0';
 1908:     s=++in;
 1909:   }
 1910:  
 1911:   if (s == t) {/* occ not found */
 1912:     *(alocc-(in-s))='\0';
 1913:     in=s;
 1914:   }
 1915:   while ( *in != '\0'){
 1916:     *blocc++ = *in++;
 1917:   }
 1918: 
 1919:   *blocc='\0';
 1920:   return t;
 1921: }
 1922: char *cutv(char *blocc, char *alocc, char *in, char occ)
 1923: {
 1924:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
 1925:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
 1926:      gives blocc="abcdef2ghi" and alocc="j".
 1927:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
 1928:   */
 1929:   char *s, *t;
 1930:   t=in;s=in;
 1931:   while (*in != '\0'){
 1932:     while( *in == occ){
 1933:       *blocc++ = *in++;
 1934:       s=in;
 1935:     }
 1936:     *blocc++ = *in++;
 1937:   }
 1938:   if (s == t) /* occ not found */
 1939:     *(blocc-(in-s))='\0';
 1940:   else
 1941:     *(blocc-(in-s)-1)='\0';
 1942:   in=s;
 1943:   while ( *in != '\0'){
 1944:     *alocc++ = *in++;
 1945:   }
 1946: 
 1947:   *alocc='\0';
 1948:   return s;
 1949: }
 1950: 
 1951: int nbocc(char *s, char occ)
 1952: {
 1953:   int i,j=0;
 1954:   int lg=20;
 1955:   i=0;
 1956:   lg=strlen(s);
 1957:   for(i=0; i<= lg; i++) {
 1958:     if  (s[i] == occ ) j++;
 1959:   }
 1960:   return j;
 1961: }
 1962: 
 1963: int nboccstr(char *textin, char *chain)
 1964: {
 1965:   /* Counts the number of occurence of "chain"  in string textin */
 1966:   /*  in="+V7*V4+age*V2+age*V3+age*V4"  chain="age" */
 1967:   char *strloc;
 1968:   
 1969:   int i,j=0;
 1970: 
 1971:   i=0;
 1972: 
 1973:   strloc=textin; /* strloc points to "^+V7*V4+age+..." in textin */
 1974:   for(;;) {
 1975:     strloc= strstr(strloc,chain); /* strloc points to first character of chain in textin if found. Example strloc points^ to "+V7*V4+^age" in textin  */
 1976:     if(strloc != NULL){
 1977:       strloc = strloc+strlen(chain); /* strloc points to "+V7*V4+age^" in textin */
 1978:       j++;
 1979:     }else
 1980:       break;
 1981:   }
 1982:   return j;
 1983:   
 1984: }
 1985: /* void cutv(char *u,char *v, char*t, char occ) */
 1986: /* { */
 1987: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
 1988: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
 1989: /*      gives u="abcdef2ghi" and v="j" *\/ */
 1990: /*   int i,lg,j,p=0; */
 1991: /*   i=0; */
 1992: /*   lg=strlen(t); */
 1993: /*   for(j=0; j<=lg-1; j++) { */
 1994: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
 1995: /*   } */
 1996: 
 1997: /*   for(j=0; j<p; j++) { */
 1998: /*     (u[j] = t[j]); */
 1999: /*   } */
 2000: /*      u[p]='\0'; */
 2001: 
 2002: /*    for(j=0; j<= lg; j++) { */
 2003: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
 2004: /*   } */
 2005: /* } */
 2006: 
 2007: #ifdef _WIN32
 2008: char * strsep(char **pp, const char *delim)
 2009: {
 2010:   char *p, *q;
 2011:          
 2012:   if ((p = *pp) == NULL)
 2013:     return 0;
 2014:   if ((q = strpbrk (p, delim)) != NULL)
 2015:   {
 2016:     *pp = q + 1;
 2017:     *q = '\0';
 2018:   }
 2019:   else
 2020:     *pp = 0;
 2021:   return p;
 2022: }
 2023: #endif
 2024: 
 2025: /********************** nrerror ********************/
 2026: 
 2027: void nrerror(char error_text[])
 2028: {
 2029:   fprintf(stderr,"ERREUR ...\n");
 2030:   fprintf(stderr,"%s\n",error_text);
 2031:   exit(EXIT_FAILURE);
 2032: }
 2033: /*********************** vector *******************/
 2034: double *vector(int nl, int nh)
 2035: {
 2036:   double *v;
 2037:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
 2038:   if (!v) nrerror("allocation failure in vector");
 2039:   return v-nl+NR_END;
 2040: }
 2041: 
 2042: /************************ free vector ******************/
 2043: void free_vector(double*v, int nl, int nh)
 2044: {
 2045:   free((FREE_ARG)(v+nl-NR_END));
 2046: }
 2047: 
 2048: /************************ivector *******************************/
 2049: int *ivector(long nl,long nh)
 2050: {
 2051:   int *v;
 2052:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
 2053:   if (!v) nrerror("allocation failure in ivector");
 2054:   return v-nl+NR_END;
 2055: }
 2056: 
 2057: /******************free ivector **************************/
 2058: void free_ivector(int *v, long nl, long nh)
 2059: {
 2060:   free((FREE_ARG)(v+nl-NR_END));
 2061: }
 2062: 
 2063: /************************lvector *******************************/
 2064: long *lvector(long nl,long nh)
 2065: {
 2066:   long *v;
 2067:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
 2068:   if (!v) nrerror("allocation failure in ivector");
 2069:   return v-nl+NR_END;
 2070: }
 2071: 
 2072: /******************free lvector **************************/
 2073: void free_lvector(long *v, long nl, long nh)
 2074: {
 2075:   free((FREE_ARG)(v+nl-NR_END));
 2076: }
 2077: 
 2078: /******************* imatrix *******************************/
 2079: int **imatrix(long nrl, long nrh, long ncl, long nch) 
 2080:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
 2081: { 
 2082:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
 2083:   int **m; 
 2084:   
 2085:   /* allocate pointers to rows */ 
 2086:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
 2087:   if (!m) nrerror("allocation failure 1 in matrix()"); 
 2088:   m += NR_END; 
 2089:   m -= nrl; 
 2090:   
 2091:   
 2092:   /* allocate rows and set pointers to them */ 
 2093:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
 2094:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
 2095:   m[nrl] += NR_END; 
 2096:   m[nrl] -= ncl; 
 2097:   
 2098:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
 2099:   
 2100:   /* return pointer to array of pointers to rows */ 
 2101:   return m; 
 2102: } 
 2103: 
 2104: /****************** free_imatrix *************************/
 2105: void free_imatrix(m,nrl,nrh,ncl,nch)
 2106:       int **m;
 2107:       long nch,ncl,nrh,nrl; 
 2108:      /* free an int matrix allocated by imatrix() */ 
 2109: { 
 2110:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
 2111:   free((FREE_ARG) (m+nrl-NR_END)); 
 2112: } 
 2113: 
 2114: /******************* matrix *******************************/
 2115: double **matrix(long nrl, long nrh, long ncl, long nch)
 2116: {
 2117:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
 2118:   double **m;
 2119: 
 2120:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 2121:   if (!m) nrerror("allocation failure 1 in matrix()");
 2122:   m += NR_END;
 2123:   m -= nrl;
 2124: 
 2125:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 2126:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 2127:   m[nrl] += NR_END;
 2128:   m[nrl] -= ncl;
 2129: 
 2130:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 2131:   return m;
 2132:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
 2133: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
 2134: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
 2135:    */
 2136: }
 2137: 
 2138: /*************************free matrix ************************/
 2139: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
 2140: {
 2141:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 2142:   free((FREE_ARG)(m+nrl-NR_END));
 2143: }
 2144: 
 2145: /******************* ma3x *******************************/
 2146: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
 2147: {
 2148:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
 2149:   double ***m;
 2150: 
 2151:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 2152:   if (!m) nrerror("allocation failure 1 in matrix()");
 2153:   m += NR_END;
 2154:   m -= nrl;
 2155: 
 2156:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 2157:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 2158:   m[nrl] += NR_END;
 2159:   m[nrl] -= ncl;
 2160: 
 2161:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 2162: 
 2163:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
 2164:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
 2165:   m[nrl][ncl] += NR_END;
 2166:   m[nrl][ncl] -= nll;
 2167:   for (j=ncl+1; j<=nch; j++) 
 2168:     m[nrl][j]=m[nrl][j-1]+nlay;
 2169:   
 2170:   for (i=nrl+1; i<=nrh; i++) {
 2171:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
 2172:     for (j=ncl+1; j<=nch; j++) 
 2173:       m[i][j]=m[i][j-1]+nlay;
 2174:   }
 2175:   return m; 
 2176:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
 2177:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
 2178:   */
 2179: }
 2180: 
 2181: /*************************free ma3x ************************/
 2182: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
 2183: {
 2184:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
 2185:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 2186:   free((FREE_ARG)(m+nrl-NR_END));
 2187: }
 2188: 
 2189: /*************** function subdirf ***********/
 2190: char *subdirf(char fileres[])
 2191: {
 2192:   /* Caution optionfilefiname is hidden */
 2193:   strcpy(tmpout,optionfilefiname);
 2194:   strcat(tmpout,"/"); /* Add to the right */
 2195:   strcat(tmpout,fileres);
 2196:   return tmpout;
 2197: }
 2198: 
 2199: /*************** function subdirf2 ***********/
 2200: char *subdirf2(char fileres[], char *preop)
 2201: {
 2202:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
 2203:  Errors in subdirf, 2, 3 while printing tmpout is
 2204:  rewritten within the same printf. Workaround: many printfs */
 2205:   /* Caution optionfilefiname is hidden */
 2206:   strcpy(tmpout,optionfilefiname);
 2207:   strcat(tmpout,"/");
 2208:   strcat(tmpout,preop);
 2209:   strcat(tmpout,fileres);
 2210:   return tmpout;
 2211: }
 2212: 
 2213: /*************** function subdirf3 ***********/
 2214: char *subdirf3(char fileres[], char *preop, char *preop2)
 2215: {
 2216:   
 2217:   /* Caution optionfilefiname is hidden */
 2218:   strcpy(tmpout,optionfilefiname);
 2219:   strcat(tmpout,"/");
 2220:   strcat(tmpout,preop);
 2221:   strcat(tmpout,preop2);
 2222:   strcat(tmpout,fileres);
 2223:   return tmpout;
 2224: }
 2225:  
 2226: /*************** function subdirfext ***********/
 2227: char *subdirfext(char fileres[], char *preop, char *postop)
 2228: {
 2229:   
 2230:   strcpy(tmpout,preop);
 2231:   strcat(tmpout,fileres);
 2232:   strcat(tmpout,postop);
 2233:   return tmpout;
 2234: }
 2235: 
 2236: /*************** function subdirfext3 ***********/
 2237: char *subdirfext3(char fileres[], char *preop, char *postop)
 2238: {
 2239:   
 2240:   /* Caution optionfilefiname is hidden */
 2241:   strcpy(tmpout,optionfilefiname);
 2242:   strcat(tmpout,"/");
 2243:   strcat(tmpout,preop);
 2244:   strcat(tmpout,fileres);
 2245:   strcat(tmpout,postop);
 2246:   return tmpout;
 2247: }
 2248:  
 2249: char *asc_diff_time(long time_sec, char ascdiff[])
 2250: {
 2251:   long sec_left, days, hours, minutes;
 2252:   days = (time_sec) / (60*60*24);
 2253:   sec_left = (time_sec) % (60*60*24);
 2254:   hours = (sec_left) / (60*60) ;
 2255:   sec_left = (sec_left) %(60*60);
 2256:   minutes = (sec_left) /60;
 2257:   sec_left = (sec_left) % (60);
 2258:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
 2259:   return ascdiff;
 2260: }
 2261: 
 2262: /***************** f1dim *************************/
 2263: extern int ncom; 
 2264: extern double *pcom,*xicom;
 2265: extern double (*nrfunc)(double []); 
 2266:  
 2267: double f1dim(double x) 
 2268: { 
 2269:   int j; 
 2270:   double f;
 2271:   double *xt; 
 2272:  
 2273:   xt=vector(1,ncom); 
 2274:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
 2275:   f=(*nrfunc)(xt); 
 2276:   free_vector(xt,1,ncom); 
 2277:   return f; 
 2278: } 
 2279: 
 2280: /*****************brent *************************/
 2281: double brent(double ax, double bx, double cx, double (*f)(double), double tol, 	double *xmin) 
 2282: {
 2283:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
 2284:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
 2285:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
 2286:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
 2287:    * returned function value. 
 2288:   */
 2289:   int iter; 
 2290:   double a,b,d,etemp;
 2291:   double fu=0,fv,fw,fx;
 2292:   double ftemp=0.;
 2293:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
 2294:   double e=0.0; 
 2295:  
 2296:   a=(ax < cx ? ax : cx); 
 2297:   b=(ax > cx ? ax : cx); 
 2298:   x=w=v=bx; 
 2299:   fw=fv=fx=(*f)(x); 
 2300:   for (iter=1;iter<=ITMAX;iter++) { 
 2301:     xm=0.5*(a+b); 
 2302:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
 2303:     /*		if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
 2304:     printf(".");fflush(stdout);
 2305:     fprintf(ficlog,".");fflush(ficlog);
 2306: #ifdef DEBUGBRENT
 2307:     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);
 2308:     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);
 2309:     /*		if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
 2310: #endif
 2311:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
 2312:       *xmin=x; 
 2313:       return fx; 
 2314:     } 
 2315:     ftemp=fu;
 2316:     if (fabs(e) > tol1) { 
 2317:       r=(x-w)*(fx-fv); 
 2318:       q=(x-v)*(fx-fw); 
 2319:       p=(x-v)*q-(x-w)*r; 
 2320:       q=2.0*(q-r); 
 2321:       if (q > 0.0) p = -p; 
 2322:       q=fabs(q); 
 2323:       etemp=e; 
 2324:       e=d; 
 2325:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
 2326: 				d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 2327:       else { 
 2328: 				d=p/q; 
 2329: 				u=x+d; 
 2330: 				if (u-a < tol2 || b-u < tol2) 
 2331: 					d=SIGN(tol1,xm-x); 
 2332:       } 
 2333:     } else { 
 2334:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 2335:     } 
 2336:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
 2337:     fu=(*f)(u); 
 2338:     if (fu <= fx) { 
 2339:       if (u >= x) a=x; else b=x; 
 2340:       SHFT(v,w,x,u) 
 2341:       SHFT(fv,fw,fx,fu) 
 2342:     } else { 
 2343:       if (u < x) a=u; else b=u; 
 2344:       if (fu <= fw || w == x) { 
 2345: 				v=w; 
 2346: 				w=u; 
 2347: 				fv=fw; 
 2348: 				fw=fu; 
 2349:       } else if (fu <= fv || v == x || v == w) { 
 2350: 				v=u; 
 2351: 				fv=fu; 
 2352:       } 
 2353:     } 
 2354:   } 
 2355:   nrerror("Too many iterations in brent"); 
 2356:   *xmin=x; 
 2357:   return fx; 
 2358: } 
 2359: 
 2360: /****************** mnbrak ***********************/
 2361: 
 2362: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
 2363: 	    double (*func)(double)) 
 2364: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
 2365: the downhill direction (defined by the function as evaluated at the initial points) and returns
 2366: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
 2367: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
 2368:    */
 2369:   double ulim,u,r,q, dum;
 2370:   double fu; 
 2371: 
 2372:   double scale=10.;
 2373:   int iterscale=0;
 2374: 
 2375:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
 2376:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
 2377: 
 2378: 
 2379:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
 2380:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
 2381:   /*   *bx = *ax - (*ax - *bx)/scale; */
 2382:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
 2383:   /* } */
 2384: 
 2385:   if (*fb > *fa) { 
 2386:     SHFT(dum,*ax,*bx,dum) 
 2387:     SHFT(dum,*fb,*fa,dum) 
 2388:   } 
 2389:   *cx=(*bx)+GOLD*(*bx-*ax); 
 2390:   *fc=(*func)(*cx); 
 2391: #ifdef DEBUG
 2392:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
 2393:   fprintf(ficlog,"mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
 2394: #endif
 2395:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc. If fc=inf it exits and if flat fb=fc it exits too.*/
 2396:     r=(*bx-*ax)*(*fb-*fc); 
 2397:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
 2398:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
 2399:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
 2400:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
 2401:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
 2402:       fu=(*func)(u); 
 2403: #ifdef DEBUG
 2404:       /* f(x)=A(x-u)**2+f(u) */
 2405:       double A, fparabu; 
 2406:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 2407:       fparabu= *fa - A*(*ax-u)*(*ax-u);
 2408:       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);
 2409:       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);
 2410:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
 2411:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
 2412:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
 2413:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
 2414: #endif 
 2415: #ifdef MNBRAKORIGINAL
 2416: #else
 2417: /*       if (fu > *fc) { */
 2418: /* #ifdef DEBUG */
 2419: /*       printf("mnbrak4  fu > fc \n"); */
 2420: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
 2421: /* #endif */
 2422: /* 	/\* 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 *\\/  *\/ */
 2423: /* 	/\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
 2424: /* 	dum=u; /\* Shifting c and u *\/ */
 2425: /* 	u = *cx; */
 2426: /* 	*cx = dum; */
 2427: /* 	dum = fu; */
 2428: /* 	fu = *fc; */
 2429: /* 	*fc =dum; */
 2430: /*       } else { /\* end *\/ */
 2431: /* #ifdef DEBUG */
 2432: /*       printf("mnbrak3  fu < fc \n"); */
 2433: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
 2434: /* #endif */
 2435: /* 	dum=u; /\* Shifting c and u *\/ */
 2436: /* 	u = *cx; */
 2437: /* 	*cx = dum; */
 2438: /* 	dum = fu; */
 2439: /* 	fu = *fc; */
 2440: /* 	*fc =dum; */
 2441: /*       } */
 2442: #ifdef DEBUGMNBRAK
 2443: 		 double A, fparabu; 
 2444:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 2445:      fparabu= *fa - A*(*ax-u)*(*ax-u);
 2446:      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);
 2447:      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);
 2448: #endif
 2449:       dum=u; /* Shifting c and u */
 2450:       u = *cx;
 2451:       *cx = dum;
 2452:       dum = fu;
 2453:       fu = *fc;
 2454:       *fc =dum;
 2455: #endif
 2456:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
 2457: #ifdef DEBUG
 2458:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
 2459:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
 2460: #endif
 2461:       fu=(*func)(u); 
 2462:       if (fu < *fc) { 
 2463: #ifdef DEBUG
 2464: 				printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
 2465: 			  fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
 2466: #endif
 2467: 			  SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
 2468: 				SHFT(*fb,*fc,fu,(*func)(u)) 
 2469: #ifdef DEBUG
 2470: 					printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
 2471: #endif
 2472:       } 
 2473:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
 2474: #ifdef DEBUG
 2475:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
 2476:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
 2477: #endif
 2478:       u=ulim; 
 2479:       fu=(*func)(u); 
 2480:     } else { /* u could be left to b (if r > q parabola has a maximum) */
 2481: #ifdef DEBUG
 2482:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
 2483:       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);
 2484: #endif
 2485:       u=(*cx)+GOLD*(*cx-*bx); 
 2486:       fu=(*func)(u); 
 2487: #ifdef DEBUG
 2488:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
 2489:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
 2490: #endif
 2491:     } /* end tests */
 2492:     SHFT(*ax,*bx,*cx,u) 
 2493:     SHFT(*fa,*fb,*fc,fu) 
 2494: #ifdef DEBUG
 2495:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
 2496:       fprintf(ficlog, "\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
 2497: #endif
 2498:   } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
 2499: } 
 2500: 
 2501: /*************** linmin ************************/
 2502: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
 2503: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
 2504: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
 2505: the value of func at the returned location p . This is actually all accomplished by calling the
 2506: routines mnbrak and brent .*/
 2507: int ncom; 
 2508: double *pcom,*xicom;
 2509: double (*nrfunc)(double []); 
 2510:  
 2511: #ifdef LINMINORIGINAL
 2512: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
 2513: #else
 2514: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
 2515: #endif
 2516: { 
 2517:   double brent(double ax, double bx, double cx, 
 2518: 	       double (*f)(double), double tol, double *xmin); 
 2519:   double f1dim(double x); 
 2520:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
 2521: 	      double *fc, double (*func)(double)); 
 2522:   int j; 
 2523:   double xx,xmin,bx,ax; 
 2524:   double fx,fb,fa;
 2525: 
 2526: #ifdef LINMINORIGINAL
 2527: #else
 2528:   double scale=10., axs, xxs; /* Scale added for infinity */
 2529: #endif
 2530:   
 2531:   ncom=n; 
 2532:   pcom=vector(1,n); 
 2533:   xicom=vector(1,n); 
 2534:   nrfunc=func; 
 2535:   for (j=1;j<=n;j++) { 
 2536:     pcom[j]=p[j]; 
 2537:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
 2538:   } 
 2539: 
 2540: #ifdef LINMINORIGINAL
 2541:   xx=1.;
 2542: #else
 2543:   axs=0.0;
 2544:   xxs=1.;
 2545:   do{
 2546:     xx= xxs;
 2547: #endif
 2548:     ax=0.;
 2549:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
 2550:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
 2551:     /* 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))   */
 2552:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
 2553:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
 2554:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
 2555:     /* 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]]*/
 2556: #ifdef LINMINORIGINAL
 2557: #else
 2558:     if (fx != fx){
 2559: 			xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
 2560: 			printf("|");
 2561: 			fprintf(ficlog,"|");
 2562: #ifdef DEBUGLINMIN
 2563: 			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);
 2564: #endif
 2565:     }
 2566:   }while(fx != fx && xxs > 1.e-5);
 2567: #endif
 2568:   
 2569: #ifdef DEBUGLINMIN
 2570:   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);
 2571:   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);
 2572: #endif
 2573: #ifdef LINMINORIGINAL
 2574: #else
 2575:   if(fb == fx){ /* Flat function in the direction */
 2576:     xmin=xx;
 2577:     *flat=1;
 2578:   }else{
 2579:     *flat=0;
 2580: #endif
 2581: 		/*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
 2582:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
 2583:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
 2584:   /* fmin = f(p[j] + xmin * xi[j]) */
 2585:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
 2586:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
 2587: #ifdef DEBUG
 2588:   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);
 2589:   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);
 2590: #endif
 2591: #ifdef LINMINORIGINAL
 2592: #else
 2593: 			}
 2594: #endif
 2595: #ifdef DEBUGLINMIN
 2596:   printf("linmin end ");
 2597:   fprintf(ficlog,"linmin end ");
 2598: #endif
 2599:   for (j=1;j<=n;j++) { 
 2600: #ifdef LINMINORIGINAL
 2601:     xi[j] *= xmin; 
 2602: #else
 2603: #ifdef DEBUGLINMIN
 2604:     if(xxs <1.0)
 2605:       printf(" before xi[%d]=%12.8f", j,xi[j]);
 2606: #endif
 2607:     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) */
 2608: #ifdef DEBUGLINMIN
 2609:     if(xxs <1.0)
 2610:       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 );
 2611: #endif
 2612: #endif
 2613:     p[j] += xi[j]; /* Parameters values are updated accordingly */
 2614:   } 
 2615: #ifdef DEBUGLINMIN
 2616:   printf("\n");
 2617:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
 2618:   fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
 2619:   for (j=1;j<=n;j++) { 
 2620:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
 2621:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
 2622:     if(j % ncovmodel == 0){
 2623:       printf("\n");
 2624:       fprintf(ficlog,"\n");
 2625:     }
 2626:   }
 2627: #else
 2628: #endif
 2629:   free_vector(xicom,1,n); 
 2630:   free_vector(pcom,1,n); 
 2631: } 
 2632: 
 2633: 
 2634: /*************** powell ************************/
 2635: /*
 2636: Minimization of a function func of n variables. Input consists in an initial starting point
 2637: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
 2638: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
 2639: such that failure to decrease by more than this amount in one iteration signals doneness. On
 2640: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
 2641: function value at p , and iter is the number of iterations taken. The routine linmin is used.
 2642:  */
 2643: #ifdef LINMINORIGINAL
 2644: #else
 2645: 	int *flatdir; /* Function is vanishing in that direction */
 2646: 	int flat=0, flatd=0; /* Function is vanishing in that direction */
 2647: #endif
 2648: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
 2649: 	    double (*func)(double [])) 
 2650: { 
 2651: #ifdef LINMINORIGINAL
 2652:  void linmin(double p[], double xi[], int n, double *fret, 
 2653: 	      double (*func)(double [])); 
 2654: #else 
 2655:  void linmin(double p[], double xi[], int n, double *fret,
 2656: 	     double (*func)(double []),int *flat); 
 2657: #endif
 2658:  int i,ibig,j,jk,k; 
 2659:   double del,t,*pt,*ptt,*xit;
 2660:   double directest;
 2661:   double fp,fptt;
 2662:   double *xits;
 2663:   int niterf, itmp;
 2664:   int Bigter=0, nBigterf=1;
 2665:   
 2666:   pt=vector(1,n); 
 2667:   ptt=vector(1,n); 
 2668:   xit=vector(1,n); 
 2669:   xits=vector(1,n); 
 2670:   *fret=(*func)(p); 
 2671:   for (j=1;j<=n;j++) pt[j]=p[j]; 
 2672:   rcurr_time = time(NULL);
 2673:   fp=(*fret); /* Initialisation */
 2674:   for (*iter=1;;++(*iter)) { 
 2675:     ibig=0; 
 2676:     del=0.0; 
 2677:     rlast_time=rcurr_time;
 2678:     rlast_btime=rcurr_time;
 2679:     /* (void) gettimeofday(&curr_time,&tzp); */
 2680:     rcurr_time = time(NULL);  
 2681:     curr_time = *localtime(&rcurr_time);
 2682:     /* 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); */
 2683:     /* 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); */
 2684:     Bigter=(*iter - *iter % ncovmodel)/ncovmodel +1; /* Big iteration, i.e on ncovmodel cycle */
 2685:     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);
 2686:     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);
 2687:     fprintf(ficrespow,"%d %d %.12f %d",*iter,Bigter, *fret,curr_time.tm_sec-start_time.tm_sec);
 2688:     fp=(*fret); /* From former iteration or initial value */
 2689:     for (i=1;i<=n;i++) {
 2690:       fprintf(ficrespow," %.12lf", p[i]);
 2691:     }
 2692:     fprintf(ficrespow,"\n");fflush(ficrespow);
 2693:     printf("\n#model=  1      +     age ");
 2694:     fprintf(ficlog,"\n#model=  1      +     age ");
 2695:     if(nagesqr==1){
 2696: 	printf("  + age*age  ");
 2697: 	fprintf(ficlog,"  + age*age  ");
 2698:     }
 2699:     for(j=1;j <=ncovmodel-2;j++){
 2700:       if(Typevar[j]==0) {
 2701: 	printf("  +      V%d  ",Tvar[j]);
 2702: 	fprintf(ficlog,"  +      V%d  ",Tvar[j]);
 2703:       }else if(Typevar[j]==1) {
 2704: 	printf("  +    V%d*age ",Tvar[j]);
 2705: 	fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
 2706:       }else if(Typevar[j]==2) {
 2707: 	printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
 2708: 	fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
 2709:       }else if(Typevar[j]==3) {
 2710: 	printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
 2711: 	fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
 2712:       }
 2713:     }
 2714:     printf("\n");
 2715: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
 2716: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
 2717:     fprintf(ficlog,"\n");
 2718:     for(i=1,jk=1; i <=nlstate; i++){
 2719:       for(k=1; k <=(nlstate+ndeath); k++){
 2720: 	if (k != i) {
 2721: 	  printf("%d%d ",i,k);
 2722: 	  fprintf(ficlog,"%d%d ",i,k);
 2723: 	  for(j=1; j <=ncovmodel; j++){
 2724: 	    printf("%12.7f ",p[jk]);
 2725: 	    fprintf(ficlog,"%12.7f ",p[jk]);
 2726: 	    jk++; 
 2727: 	  }
 2728: 	  printf("\n");
 2729: 	  fprintf(ficlog,"\n");
 2730: 	}
 2731:       }
 2732:     }
 2733:     if(*iter <=3 && *iter >1){
 2734:       tml = *localtime(&rcurr_time);
 2735:       strcpy(strcurr,asctime(&tml));
 2736:       rforecast_time=rcurr_time; 
 2737:       itmp = strlen(strcurr);
 2738:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
 2739: 	strcurr[itmp-1]='\0';
 2740:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 2741:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 2742:       for(nBigterf=1;nBigterf<=31;nBigterf+=10){
 2743: 	niterf=nBigterf*ncovmodel;
 2744: 	/* rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time); */
 2745: 	rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
 2746: 	forecast_time = *localtime(&rforecast_time);
 2747: 	strcpy(strfor,asctime(&forecast_time));
 2748: 	itmp = strlen(strfor);
 2749: 	if(strfor[itmp-1]=='\n')
 2750: 	  strfor[itmp-1]='\0';
 2751: 	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);
 2752: 	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);
 2753:       }
 2754:     }
 2755:     for (i=1;i<=n;i++) { /* For each direction i */
 2756:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
 2757:       fptt=(*fret); 
 2758: #ifdef DEBUG
 2759:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 2760:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 2761: #endif
 2762:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
 2763:       fprintf(ficlog,"%d",i);fflush(ficlog);
 2764: #ifdef LINMINORIGINAL
 2765:       linmin(p,xit,n,fret,func); /* New point i minimizing in direction i has coordinates p[j].*/
 2766:       /* xit[j] gives the n coordinates of direction i as input.*/
 2767:       /* *fret gives the maximum value on direction xit */
 2768: #else
 2769:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
 2770: 			flatdir[i]=flat; /* Function is vanishing in that direction i */
 2771: #endif
 2772: 			/* Outputs are fret(new point p) p is updated and xit rescaled */
 2773:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
 2774: 				/* because that direction will be replaced unless the gain del is small */
 2775: 				/* in comparison with the 'probable' gain, mu^2, with the last average direction. */
 2776: 				/* Unless the n directions are conjugate some gain in the determinant may be obtained */
 2777: 				/* with the new direction. */
 2778: 				del=fabs(fptt-(*fret)); 
 2779: 				ibig=i; 
 2780:       } 
 2781: #ifdef DEBUG
 2782:       printf("%d %.12e",i,(*fret));
 2783:       fprintf(ficlog,"%d %.12e",i,(*fret));
 2784:       for (j=1;j<=n;j++) {
 2785: 				xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
 2786: 				printf(" x(%d)=%.12e",j,xit[j]);
 2787: 				fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
 2788:       }
 2789:       for(j=1;j<=n;j++) {
 2790: 				printf(" p(%d)=%.12e",j,p[j]);
 2791: 				fprintf(ficlog," p(%d)=%.12e",j,p[j]);
 2792:       }
 2793:       printf("\n");
 2794:       fprintf(ficlog,"\n");
 2795: #endif
 2796:     } /* end loop on each direction i */
 2797:     /* Convergence test will use last linmin estimation (fret) and compare to former iteration (fp) */ 
 2798:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
 2799:     for(j=1;j<=n;j++) {
 2800:       if(flatdir[j] >0){
 2801:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
 2802:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
 2803:       }
 2804:       /* printf("\n"); */
 2805:       /* fprintf(ficlog,"\n"); */
 2806:     }
 2807:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
 2808:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
 2809:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
 2810:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
 2811:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
 2812:       /* decreased of more than 3.84  */
 2813:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
 2814:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
 2815:       /* By adding 10 parameters more the gain should be 18.31 */
 2816: 			
 2817:       /* Starting the program with initial values given by a former maximization will simply change */
 2818:       /* the scales of the directions and the directions, because the are reset to canonical directions */
 2819:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
 2820:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
 2821: #ifdef DEBUG
 2822:       int k[2],l;
 2823:       k[0]=1;
 2824:       k[1]=-1;
 2825:       printf("Max: %.12e",(*func)(p));
 2826:       fprintf(ficlog,"Max: %.12e",(*func)(p));
 2827:       for (j=1;j<=n;j++) {
 2828: 	printf(" %.12e",p[j]);
 2829: 	fprintf(ficlog," %.12e",p[j]);
 2830:       }
 2831:       printf("\n");
 2832:       fprintf(ficlog,"\n");
 2833:       for(l=0;l<=1;l++) {
 2834: 	for (j=1;j<=n;j++) {
 2835: 	  ptt[j]=p[j]+(p[j]-pt[j])*k[l];
 2836: 	  printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 2837: 	  fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 2838: 	}
 2839: 	printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 2840: 	fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 2841:       }
 2842: #endif
 2843: 
 2844:       free_vector(xit,1,n); 
 2845:       free_vector(xits,1,n); 
 2846:       free_vector(ptt,1,n); 
 2847:       free_vector(pt,1,n); 
 2848:       return; 
 2849:     } /* enough precision */ 
 2850:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
 2851:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
 2852:       ptt[j]=2.0*p[j]-pt[j]; 
 2853:       xit[j]=p[j]-pt[j]; 
 2854:       pt[j]=p[j]; 
 2855:     } 
 2856:     fptt=(*func)(ptt); /* f_3 */
 2857: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
 2858: 		if (*iter <=4) {
 2859: #else
 2860: #endif
 2861: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
 2862: #else
 2863:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
 2864: #endif
 2865:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
 2866:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
 2867:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
 2868:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
 2869:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
 2870:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
 2871:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
 2872:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
 2873:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
 2874:       /*  Even if f3 <f1, directest can be negative and t >0 */
 2875:       /* mu² and del² are equal when f3=f1 */
 2876: 			/* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
 2877: 			/* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
 2878: 			/* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
 2879: 			/* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
 2880: #ifdef NRCORIGINAL
 2881:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
 2882: #else
 2883:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
 2884:       t= t- del*SQR(fp-fptt);
 2885: #endif
 2886:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
 2887: #ifdef DEBUG
 2888:       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);
 2889:       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);
 2890:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 2891: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 2892:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 2893: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 2894:       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);
 2895:       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);
 2896: #endif
 2897: #ifdef POWELLORIGINAL
 2898:       if (t < 0.0) { /* Then we use it for new direction */
 2899: #else
 2900:       if (directest*t < 0.0) { /* Contradiction between both tests */
 2901: 				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);
 2902:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 2903:         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);
 2904:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 2905:       } 
 2906:       if (directest < 0.0) { /* Then we use it for new direction */
 2907: #endif
 2908: #ifdef DEBUGLINMIN
 2909: 	printf("Before linmin in direction P%d-P0\n",n);
 2910: 	for (j=1;j<=n;j++) {
 2911: 	  printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2912: 	  fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2913: 	  if(j % ncovmodel == 0){
 2914: 	    printf("\n");
 2915: 	    fprintf(ficlog,"\n");
 2916: 	  }
 2917: 	}
 2918: #endif
 2919: #ifdef LINMINORIGINAL
 2920: 	linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
 2921: #else
 2922: 	linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
 2923: 	flatdir[i]=flat; /* Function is vanishing in that direction i */
 2924: #endif
 2925: 	
 2926: #ifdef DEBUGLINMIN
 2927: 	for (j=1;j<=n;j++) { 
 2928: 	  printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2929: 	  fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
 2930: 	  if(j % ncovmodel == 0){
 2931: 	    printf("\n");
 2932: 	    fprintf(ficlog,"\n");
 2933: 	  }
 2934: 	}
 2935: #endif
 2936: #ifdef POWELLORIGINCONJUGATE
 2937: 	for (j=1;j<=n;j++) { 
 2938: 	  xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
 2939: 	  xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
 2940: 	}
 2941: #else
 2942: 	for (j=1;j<=n-1;j++) { 
 2943: 	  xi[j][1]=xi[j][j+1]; /* Standard method of conjugate directions */
 2944: 	  xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
 2945: 	}
 2946: #endif
 2947: #ifdef LINMINORIGINAL
 2948: #else
 2949: 	for (j=1, flatd=0;j<=n;j++) {
 2950: 	  if(flatdir[j]>0)
 2951: 	    flatd++;
 2952: 	}
 2953: 	if(flatd >0){
 2954: 	  printf("%d flat directions: ",flatd);
 2955: 	  fprintf(ficlog,"%d flat directions :",flatd);
 2956: 	  for (j=1;j<=n;j++) { 
 2957: 	    if(flatdir[j]>0){
 2958: 	      printf("%d ",j);
 2959: 	      fprintf(ficlog,"%d ",j);
 2960: 	    }
 2961: 	  }
 2962: 	  printf("\n");
 2963: 	  fprintf(ficlog,"\n");
 2964: #ifdef FLATSUP
 2965:           free_vector(xit,1,n); 
 2966:           free_vector(xits,1,n); 
 2967:           free_vector(ptt,1,n); 
 2968:           free_vector(pt,1,n); 
 2969:           return;
 2970: #endif
 2971: 	}
 2972: #endif
 2973: 	printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 2974: 	fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 2975:   /* The minimization in direction $\xi_1$ gives $P_1$. From $P_1$ minimization in direction $\xi_2$ gives */
 2976:   /* $P_2$. Minimization of line $P_2-P_1$ gives new starting point $P^{(1)}_0$ and direction $\xi_1$ is dropped and replaced by second */
 2977:   /* direction $\xi_1^{(1)}=\xi_2$. Also second direction is replaced by new direction $\xi^{(1)}_2=P_2-P_0$. */
 2978: 
 2979:   /* At the second iteration, starting from $P_0^{(1)}$, minimization amongst $\xi^{(1)}_1$ gives point $P^{(1)}_1$. */
 2980:   /* Minimization amongst $\xi^{(1)}_2=(P_2-P_0)$ gives point $P^{(1)}_2$.  As $P^{(2)}_1$ and */
 2981:   /* $P^{(1)}_0$ are minimizing in the same direction $P^{(1)}_2 - P^{(1)}_1= P_2-P_0$, directions $P^{(1)}_2-P^{(1)}_0$ */
 2982:   /* and $P_2-P_0$ (parallel to $\xi$ and $\xi^c$) are conjugate.  } */
 2983: 
 2984: 	
 2985: #ifdef DEBUG
 2986: 	printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 2987: 	fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 2988: 	for(j=1;j<=n;j++){
 2989: 	  printf(" %lf",xit[j]);
 2990: 	  fprintf(ficlog," %lf",xit[j]);
 2991: 	}
 2992: 	printf("\n");
 2993: 	fprintf(ficlog,"\n");
 2994: #endif
 2995:       } /* end of t or directest negative */
 2996: #ifdef POWELLNOF3INFF1TEST
 2997: #else
 2998:       } /* end if (fptt < fp)  */
 2999: #endif
 3000: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
 3001:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
 3002: #else
 3003: #endif
 3004: 		} /* loop iteration */ 
 3005: } 
 3006:   
 3007: /**** Prevalence limit (stable or period prevalence)  ****************/
 3008:   
 3009:   double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij, int nres)
 3010:   {
 3011:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
 3012:      *   (and selected quantitative values in nres)
 3013:      *  by left multiplying the unit
 3014:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
 3015:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
 3016:      * Wx is row vector: population in state 1, population in state 2, population dead
 3017:      * or prevalence in state 1, prevalence in state 2, 0
 3018:      * newm is the matrix after multiplications, its rows are identical at a factor.
 3019:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
 3020:      * Output is prlim.
 3021:      * Initial matrix pimij 
 3022:      */
 3023:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
 3024:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
 3025:   /*  0,                   0                  , 1} */
 3026:   /*
 3027:    * and after some iteration: */
 3028:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
 3029:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
 3030:   /*  0,                   0                  , 1} */
 3031:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
 3032:   /* {0.51571254859325999, 0.4842874514067399, */
 3033:   /*  0.51326036147820708, 0.48673963852179264} */
 3034:   /* If we start from prlim again, prlim tends to a constant matrix */
 3035:     
 3036:     int i, ii,j,k, k1;
 3037:   double *min, *max, *meandiff, maxmax,sumnew=0.;
 3038:   /* double **matprod2(); */ /* test */
 3039:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
 3040:   double **newm;
 3041:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
 3042:   int ncvloop=0;
 3043:   int first=0;
 3044:   
 3045:   min=vector(1,nlstate);
 3046:   max=vector(1,nlstate);
 3047:   meandiff=vector(1,nlstate);
 3048: 
 3049: 	/* Starting with matrix unity */
 3050:   for (ii=1;ii<=nlstate+ndeath;ii++)
 3051:     for (j=1;j<=nlstate+ndeath;j++){
 3052:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3053:     }
 3054:   
 3055:   cov[1]=1.;
 3056:   
 3057:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 3058:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
 3059:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
 3060:     ncvloop++;
 3061:     newm=savm;
 3062:     /* Covariates have to be included here again */
 3063:     cov[2]=agefin;
 3064:      if(nagesqr==1){
 3065:       cov[3]= agefin*agefin;
 3066:      }
 3067:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
 3068:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
 3069:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
 3070:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
 3071: 	 cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
 3072:        }else{
 3073: 	 cov[2+nagesqr+k1]=precov[nres][k1];
 3074:        }
 3075:      }/* End of loop on model equation */
 3076:      
 3077: /* Start of old code (replaced by a loop on position in the model equation */
 3078:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
 3079:     /* 			/\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
 3080:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
 3081:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
 3082:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
 3083:     /*    * k                  1        2      3    4      5      6     7        8 */
 3084:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
 3085:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
 3086:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
 3087:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
 3088:     /*    *nsd=3                              (1)  (2)           (3) */
 3089:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
 3090:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
 3091:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
 3092:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
 3093:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
 3094:     /*    *                   [1][2]=3                                           [2][2]=2 */
 3095:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
 3096:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
 3097:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
 3098:     /*    *TvarsDpType */
 3099:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
 3100:     /*    * nsd=1              (1)           (2) */
 3101:     /*    *TvarsD[nsd]          3             2 */
 3102:     /*    *TnsdVar           (3)=1          (2)=2 */
 3103:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
 3104:     /*    *Tage[]                  [1]=2           [2]= 3    */
 3105:     /*    *\/ */
 3106:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
 3107:     /*   /\* 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)); *\/ */
 3108:     /* } */
 3109:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
 3110:     /* 			/\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
 3111:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
 3112:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
 3113:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
 3114:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
 3115:     /*   /\* 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]); *\/ */
 3116:     /* } */
 3117:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
 3118:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
 3119:     /* 	cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
 3120:     /* 	/\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
 3121:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
 3122:     /* 	cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
 3123:     /* 	/\* cov[++k1]=Tqresult[nres][k];  *\/ */
 3124:     /*   } */
 3125:     /*   /\* 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]); *\/ */
 3126:     /* } */
 3127:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
 3128:     /*   /\* 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]); *\/ */
 3129:     /*   if(Dummy[Tvard[k][1]]==0){ */
 3130:     /* 	if(Dummy[Tvard[k][2]]==0){ */
 3131:     /* 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 3132:     /* 	  /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
 3133:     /* 	}else{ */
 3134:     /* 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
 3135:     /* 	  /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
 3136:     /* 	} */
 3137:     /*   }else{ */
 3138:     /* 	if(Dummy[Tvard[k][2]]==0){ */
 3139:     /* 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
 3140:     /* 	  /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
 3141:     /* 	}else{ */
 3142:     /* 	  cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
 3143:     /* 	  /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
 3144:     /* 	} */
 3145:     /*   } */
 3146:     /* } /\* End product without age *\/ */
 3147: /* ENd of old code */
 3148:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 3149:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 3150:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 3151:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 3152:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 3153:     /* age and covariate values of ij are in 'cov' */
 3154:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
 3155:     
 3156:     savm=oldm;
 3157:     oldm=newm;
 3158: 
 3159:     for(j=1; j<=nlstate; j++){
 3160:       max[j]=0.;
 3161:       min[j]=1.;
 3162:     }
 3163:     for(i=1;i<=nlstate;i++){
 3164:       sumnew=0;
 3165:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
 3166:       for(j=1; j<=nlstate; j++){ 
 3167: 	prlim[i][j]= newm[i][j]/(1-sumnew);
 3168: 	max[j]=FMAX(max[j],prlim[i][j]);
 3169: 	min[j]=FMIN(min[j],prlim[i][j]);
 3170:       }
 3171:     }
 3172: 
 3173:     maxmax=0.;
 3174:     for(j=1; j<=nlstate; j++){
 3175:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
 3176:       maxmax=FMAX(maxmax,meandiff[j]);
 3177:       /* 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); */
 3178:     } /* j loop */
 3179:     *ncvyear= (int)age- (int)agefin;
 3180:     /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
 3181:     if(maxmax < ftolpl){
 3182:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
 3183:       free_vector(min,1,nlstate);
 3184:       free_vector(max,1,nlstate);
 3185:       free_vector(meandiff,1,nlstate);
 3186:       return prlim;
 3187:     }
 3188:   } /* agefin loop */
 3189:     /* After some age loop it doesn't converge */
 3190:   if(!first){
 3191:     first=1;
 3192:     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);
 3193:     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);
 3194:   }else if (first >=1 && first <10){
 3195:     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);
 3196:     first++;
 3197:   }else if (first ==10){
 3198:     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);
 3199:     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");
 3200:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
 3201:     first++;
 3202:   }
 3203: 
 3204:   /* 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); */
 3205:   free_vector(min,1,nlstate);
 3206:   free_vector(max,1,nlstate);
 3207:   free_vector(meandiff,1,nlstate);
 3208:   
 3209:   return prlim; /* should not reach here */
 3210: }
 3211: 
 3212: 
 3213:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
 3214: 
 3215:  /* 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) */
 3216:  /* 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) */
 3217:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
 3218: {
 3219:   /* Computes the prevalence limit in each live state at age x and for covariate combination ij (<=2**cptcoveff) by left multiplying the unit
 3220:      matrix by transitions matrix until convergence is reached with precision ftolpl */
 3221:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
 3222:   /* Wx is row vector: population in state 1, population in state 2, population dead */
 3223:   /* or prevalence in state 1, prevalence in state 2, 0 */
 3224:   /* newm is the matrix after multiplications, its rows are identical at a factor */
 3225:   /* Initial matrix pimij */
 3226:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
 3227:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
 3228:   /*  0,                   0                  , 1} */
 3229:   /*
 3230:    * and after some iteration: */
 3231:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
 3232:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
 3233:   /*  0,                   0                  , 1} */
 3234:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
 3235:   /* {0.51571254859325999, 0.4842874514067399, */
 3236:   /*  0.51326036147820708, 0.48673963852179264} */
 3237:   /* If we start from prlim again, prlim tends to a constant matrix */
 3238: 
 3239:   int i, ii,j,k, k1;
 3240:   int first=0;
 3241:   double *min, *max, *meandiff, maxmax,sumnew=0.;
 3242:   /* double **matprod2(); */ /* test */
 3243:   double **out, cov[NCOVMAX+1], **bmij();
 3244:   double **newm;
 3245:   double	 **dnewm, **doldm, **dsavm;  /* for use */
 3246:   double	 **oldm, **savm;  /* for use */
 3247: 
 3248:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
 3249:   int ncvloop=0;
 3250:   
 3251:   min=vector(1,nlstate);
 3252:   max=vector(1,nlstate);
 3253:   meandiff=vector(1,nlstate);
 3254: 
 3255:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
 3256:   oldm=oldms; savm=savms;
 3257:   
 3258:   /* Starting with matrix unity */
 3259:   for (ii=1;ii<=nlstate+ndeath;ii++)
 3260:     for (j=1;j<=nlstate+ndeath;j++){
 3261:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 3262:     }
 3263:   
 3264:   cov[1]=1.;
 3265:   
 3266:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 3267:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
 3268:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
 3269:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
 3270:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
 3271:     ncvloop++;
 3272:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
 3273: 		/* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
 3274:     /* Covariates have to be included here again */
 3275:     cov[2]=agefin;
 3276:     if(nagesqr==1){
 3277:       cov[3]= agefin*agefin;;
 3278:     }
 3279:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
 3280:       if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
 3281: 	cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
 3282:       }else{
 3283: 	cov[2+nagesqr+k1]=precov[nres][k1];
 3284:       }
 3285:     }/* End of loop on model equation */
 3286: 
 3287: /* Old code */ 
 3288: 
 3289:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
 3290:     /* 			/\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
 3291:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
 3292:     /*   /\* 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)); *\/ */
 3293:     /* } */
 3294:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
 3295:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
 3296:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
 3297:     /* /\*   /\\* 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])]); *\\/ *\/ */
 3298:     /* /\* } *\/ */
 3299:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
 3300:     /* 			/\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
 3301:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
 3302:     /*   /\* 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]); *\/ */
 3303:     /* } */
 3304:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
 3305:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
 3306:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
 3307:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
 3308:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
 3309:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
 3310:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
 3311:     /* 	cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
 3312:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
 3313:     /* 	cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
 3314:     /*   } */
 3315:     /*   /\* 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]); *\/ */
 3316:     /* } */
 3317:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
 3318:     /*   /\* 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]); *\/ */
 3319:     /*   if(Dummy[Tvard[k][1]]==0){ */
 3320:     /* 	if(Dummy[Tvard[k][2]]==0){ */
 3321:     /* 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 3322:     /* 	}else{ */
 3323:     /* 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
 3324:     /* 	} */
 3325:     /*   }else{ */
 3326:     /* 	if(Dummy[Tvard[k][2]]==0){ */
 3327:     /* 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
 3328:     /* 	}else{ */
 3329:     /* 	  cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
 3330:     /* 	} */
 3331:     /*   } */
 3332:     /* } */
 3333:     
 3334:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 3335:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 3336:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 3337:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 3338:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 3339: 		/* ij should be linked to the correct index of cov */
 3340: 		/* age and covariate values ij are in 'cov', but we need to pass
 3341: 		 * ij for the observed prevalence at age and status and covariate
 3342: 		 * number:  prevacurrent[(int)agefin][ii][ij]
 3343: 		 */
 3344:     /* 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 *\/ */
 3345:     /* 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 *\/ */
 3346:     out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij)); /* Bug Valgrind */
 3347:     /* if((int)age == 86 || (int)age == 87){ */
 3348:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
 3349:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
 3350:     /* 	printf("%d newm= ",i); */
 3351:     /* 	for(j=1;j<=nlstate+ndeath;j++) { */
 3352:     /* 	  printf("%f ",newm[i][j]); */
 3353:     /* 	} */
 3354:     /* 	printf("oldm * "); */
 3355:     /* 	for(j=1;j<=nlstate+ndeath;j++) { */
 3356:     /* 	  printf("%f ",oldm[i][j]); */
 3357:     /* 	} */
 3358:     /* 	printf(" bmmij "); */
 3359:     /* 	for(j=1;j<=nlstate+ndeath;j++) { */
 3360:     /* 	  printf("%f ",pmmij[i][j]); */
 3361:     /* 	} */
 3362:     /* 	printf("\n"); */
 3363:     /*   } */
 3364:     /* } */
 3365:     savm=oldm;
 3366:     oldm=newm;
 3367: 
 3368:     for(j=1; j<=nlstate; j++){
 3369:       max[j]=0.;
 3370:       min[j]=1.;
 3371:     }
 3372:     for(j=1; j<=nlstate; j++){ 
 3373:       for(i=1;i<=nlstate;i++){
 3374: 	/* bprlim[i][j]= newm[i][j]/(1-sumnew); */
 3375: 	bprlim[i][j]= newm[i][j];
 3376: 	max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
 3377: 	min[i]=FMIN(min[i],bprlim[i][j]);
 3378:       }
 3379:     }
 3380: 		
 3381:     maxmax=0.;
 3382:     for(i=1; i<=nlstate; i++){
 3383:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
 3384:       maxmax=FMAX(maxmax,meandiff[i]);
 3385:       /* 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); */
 3386:     } /* i loop */
 3387:     *ncvyear= -( (int)age- (int)agefin);
 3388:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
 3389:     if(maxmax < ftolpl){
 3390:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
 3391:       free_vector(min,1,nlstate);
 3392:       free_vector(max,1,nlstate);
 3393:       free_vector(meandiff,1,nlstate);
 3394:       return bprlim;
 3395:     }
 3396:   } /* agefin loop */
 3397:     /* After some age loop it doesn't converge */
 3398:   if(!first){
 3399:     first=1;
 3400:     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\
 3401: 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);
 3402:   }
 3403:   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\
 3404: 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);
 3405:   /* 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); */
 3406:   free_vector(min,1,nlstate);
 3407:   free_vector(max,1,nlstate);
 3408:   free_vector(meandiff,1,nlstate);
 3409:   
 3410:   return bprlim; /* should not reach here */
 3411: }
 3412: 
 3413: /*************** transition probabilities ***************/ 
 3414: 
 3415: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 3416: {
 3417:   /* According to parameters values stored in x and the covariate's values stored in cov,
 3418:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
 3419:      model to the ncovmodel covariates (including constant and age).
 3420:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 3421:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 3422:      ncth covariate in the global vector x is given by the formula:
 3423:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 3424:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 3425:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 3426:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 3427:      Outputs ps[i][j] or probability to be observed in j being in i according to
 3428:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 3429:      Sum on j ps[i][j] should equal to 1.
 3430:   */
 3431:   double s1, lnpijopii;
 3432:   /*double t34;*/
 3433:   int i,j, nc, ii, jj;
 3434: 
 3435:   for(i=1; i<= nlstate; i++){
 3436:     for(j=1; j<i;j++){
 3437:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 3438: 	/*lnpijopii += param[i][j][nc]*cov[nc];*/
 3439: 	lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 3440: 	/* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 3441:       }
 3442:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 3443:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
 3444:     }
 3445:     for(j=i+1; j<=nlstate+ndeath;j++){
 3446:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 3447: 	/*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 3448: 	lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 3449: 	/* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 3450:       }
 3451:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 3452:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
 3453:     }
 3454:   }
 3455:   
 3456:   for(i=1; i<= nlstate; i++){
 3457:     s1=0;
 3458:     for(j=1; j<i; j++){
 3459:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
 3460:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 3461:     }
 3462:     for(j=i+1; j<=nlstate+ndeath; j++){
 3463:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
 3464:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 3465:     }
 3466:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 3467:     ps[i][i]=1./(s1+1.);
 3468:     /* Computing other pijs */
 3469:     for(j=1; j<i; j++)
 3470:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
 3471:     for(j=i+1; j<=nlstate+ndeath; j++)
 3472:       ps[i][j]= exp(ps[i][j])*ps[i][i];
 3473:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 3474:   } /* end i */
 3475:   
 3476:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 3477:     for(jj=1; jj<= nlstate+ndeath; jj++){
 3478:       ps[ii][jj]=0;
 3479:       ps[ii][ii]=1;
 3480:     }
 3481:   }
 3482: 
 3483: 
 3484:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 3485:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 3486:   /* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 3487:   /*   } */
 3488:   /*   printf("\n "); */
 3489:   /* } */
 3490:   /* printf("\n ");printf("%lf ",cov[2]);*/
 3491:   /*
 3492:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
 3493: 		goto end;*/
 3494:   return ps; /* Pointer is unchanged since its call */
 3495: }
 3496: 
 3497: /*************** backward transition probabilities ***************/ 
 3498: 
 3499:  /* 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 ) */
 3500: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
 3501:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
 3502: {
 3503:   /* Computes the backward probability at age agefin, cov[2], and covariate combination 'ij'. In fact cov is already filled and x too.
 3504:    * Call to pmij(cov and x), call to cross prevalence, sums and inverses, left multiply, and returns in **ps as well as **bmij.
 3505:    */
 3506:   int i, ii, j,k;
 3507:   
 3508:   double **out, **pmij();
 3509:   double sumnew=0.;
 3510:   double agefin;
 3511:   double k3=0.; /* constant of the w_x diagonal matrix (in order for B to sum to 1 even for death state) */
 3512:   double **dnewm, **dsavm, **doldm;
 3513:   double **bbmij;
 3514:   
 3515:   doldm=ddoldms; /* global pointers */
 3516:   dnewm=ddnewms;
 3517:   dsavm=ddsavms;
 3518: 
 3519:   /* Debug */
 3520:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
 3521:   agefin=cov[2];
 3522:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
 3523:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
 3524:      the observed prevalence (with this covariate ij) at beginning of transition */
 3525:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 3526: 
 3527:   /* P_x */
 3528:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
 3529:   /* outputs pmmij which is a stochastic matrix in row */
 3530: 
 3531:   /* Diag(w_x) */
 3532:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
 3533:   sumnew=0.;
 3534:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
 3535:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
 3536:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
 3537:     sumnew+=prevacurrent[(int)agefin][ii][ij];
 3538:   }
 3539:   if(sumnew >0.01){  /* At least some value in the prevalence */
 3540:     for (ii=1;ii<=nlstate+ndeath;ii++){
 3541:       for (j=1;j<=nlstate+ndeath;j++)
 3542: 	doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
 3543:     }
 3544:   }else{
 3545:     for (ii=1;ii<=nlstate+ndeath;ii++){
 3546:       for (j=1;j<=nlstate+ndeath;j++)
 3547:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
 3548:     }
 3549:     /* if(sumnew <0.9){ */
 3550:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
 3551:     /* } */
 3552:   }
 3553:   k3=0.0;  /* We put the last diagonal to 0 */
 3554:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
 3555:       doldm[ii][ii]= k3;
 3556:   }
 3557:   /* End doldm, At the end doldm is diag[(w_i)] */
 3558:   
 3559:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
 3560:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
 3561: 
 3562:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
 3563:   /* w1 p11 + w2 p21 only on live states N1./N..*N11/N1. + N2./N..*N21/N2.=(N11+N21)/N..=N.1/N.. */
 3564:   for (j=1;j<=nlstate+ndeath;j++){
 3565:     sumnew=0.;
 3566:     for (ii=1;ii<=nlstate;ii++){
 3567:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
 3568:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
 3569:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
 3570:     for (ii=1;ii<=nlstate+ndeath;ii++){
 3571: 	/* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
 3572: 	/* 	dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
 3573: 	/* }else if(agefin >= agemaxpar+stepm/YEARM){ */
 3574: 	/* 	dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
 3575: 	/* }else */
 3576:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
 3577:     } /*End ii */
 3578:   } /* 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 */
 3579: 
 3580:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
 3581:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
 3582:   /* end bmij */
 3583:   return ps; /*pointer is unchanged */
 3584: }
 3585: /*************** transition probabilities ***************/ 
 3586: 
 3587: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 3588: {
 3589:   /* According to parameters values stored in x and the covariate's values stored in cov,
 3590:      computes the probability to be observed in state j being in state i by appying the
 3591:      model to the ncovmodel covariates (including constant and age).
 3592:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 3593:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 3594:      ncth covariate in the global vector x is given by the formula:
 3595:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 3596:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 3597:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 3598:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 3599:      Outputs ps[i][j] the probability to be observed in j being in j according to
 3600:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 3601:   */
 3602:   double s1, lnpijopii;
 3603:   /*double t34;*/
 3604:   int i,j, nc, ii, jj;
 3605: 
 3606:   for(i=1; i<= nlstate; i++){
 3607:     for(j=1; j<i;j++){
 3608:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 3609: 	/*lnpijopii += param[i][j][nc]*cov[nc];*/
 3610: 	lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 3611: 	/* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 3612:       }
 3613:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 3614:       /* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 3615:     }
 3616:     for(j=i+1; j<=nlstate+ndeath;j++){
 3617:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 3618: 	/*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 3619: 	lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 3620: 	/* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 3621:       }
 3622:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 3623:     }
 3624:   }
 3625:   
 3626:   for(i=1; i<= nlstate; i++){
 3627:     s1=0;
 3628:     for(j=1; j<i; j++){
 3629:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 3630:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 3631:     }
 3632:     for(j=i+1; j<=nlstate+ndeath; j++){
 3633:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 3634:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 3635:     }
 3636:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 3637:     ps[i][i]=1./(s1+1.);
 3638:     /* Computing other pijs */
 3639:     for(j=1; j<i; j++)
 3640:       ps[i][j]= exp(ps[i][j])*ps[i][i];
 3641:     for(j=i+1; j<=nlstate+ndeath; j++)
 3642:       ps[i][j]= exp(ps[i][j])*ps[i][i];
 3643:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 3644:   } /* end i */
 3645:   
 3646:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 3647:     for(jj=1; jj<= nlstate+ndeath; jj++){
 3648:       ps[ii][jj]=0;
 3649:       ps[ii][ii]=1;
 3650:     }
 3651:   }
 3652:   /* Added for prevbcast */ /* Transposed matrix too */
 3653:   for(jj=1; jj<= nlstate+ndeath; jj++){
 3654:     s1=0.;
 3655:     for(ii=1; ii<= nlstate+ndeath; ii++){
 3656:       s1+=ps[ii][jj];
 3657:     }
 3658:     for(ii=1; ii<= nlstate; ii++){
 3659:       ps[ii][jj]=ps[ii][jj]/s1;
 3660:     }
 3661:   }
 3662:   /* Transposition */
 3663:   for(jj=1; jj<= nlstate+ndeath; jj++){
 3664:     for(ii=jj; ii<= nlstate+ndeath; ii++){
 3665:       s1=ps[ii][jj];
 3666:       ps[ii][jj]=ps[jj][ii];
 3667:       ps[jj][ii]=s1;
 3668:     }
 3669:   }
 3670:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 3671:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 3672:   /* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 3673:   /*   } */
 3674:   /*   printf("\n "); */
 3675:   /* } */
 3676:   /* printf("\n ");printf("%lf ",cov[2]);*/
 3677:   /*
 3678:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
 3679:     goto end;*/
 3680:   return ps;
 3681: }
 3682: 
 3683: 
 3684: /**************** Product of 2 matrices ******************/
 3685: 
 3686: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
 3687: {
 3688:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
 3689:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
 3690:   /* in, b, out are matrice of pointers which should have been initialized 
 3691:      before: only the contents of out is modified. The function returns
 3692:      a pointer to pointers identical to out */
 3693:   int i, j, k;
 3694:   for(i=nrl; i<= nrh; i++)
 3695:     for(k=ncolol; k<=ncoloh; k++){
 3696:       out[i][k]=0.;
 3697:       for(j=ncl; j<=nch; j++)
 3698:   	out[i][k] +=in[i][j]*b[j][k];
 3699:     }
 3700:   return out;
 3701: }
 3702: 
 3703: 
 3704: /************* Higher Matrix Product ***************/
 3705: 
 3706: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij, int nres )
 3707: {
 3708:   /* Already optimized with precov.
 3709:      Computes the transition matrix starting at age 'age' and dummies values in each resultline (loop on ij to find the corresponding combination) to over 
 3710:      'nhstepm*hstepm*stepm' months (i.e. until
 3711:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
 3712:      nhstepm*hstepm matrices. 
 3713:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
 3714:      (typically every 2 years instead of every month which is too big 
 3715:      for the memory).
 3716:      Model is determined by parameters x and covariates have to be 
 3717:      included manually here. 
 3718: 
 3719:      */
 3720: 
 3721:   int i, j, d, h, k, k1;
 3722:   double **out, cov[NCOVMAX+1];
 3723:   double **newm;
 3724:   double agexact;
 3725:   double agebegin, ageend;
 3726: 
 3727:   /* Hstepm could be zero and should return the unit matrix */
 3728:   for (i=1;i<=nlstate+ndeath;i++)
 3729:     for (j=1;j<=nlstate+ndeath;j++){
 3730:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 3731:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 3732:     }
 3733:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 3734:   for(h=1; h <=nhstepm; h++){
 3735:     for(d=1; d <=hstepm; d++){
 3736:       newm=savm;
 3737:       /* Covariates have to be included here again */
 3738:       cov[1]=1.;
 3739:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
 3740:       cov[2]=agexact;
 3741:       if(nagesqr==1){
 3742: 	cov[3]= agexact*agexact;
 3743:       }
 3744:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
 3745:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
 3746:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
 3747: 	if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
 3748: 	  cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
 3749: 	}else{
 3750: 	  cov[2+nagesqr+k1]=precov[nres][k1];
 3751: 	}
 3752:       }/* End of loop on model equation */
 3753: 	/* Old code */ 
 3754: /* 	if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
 3755: /* /\*	   V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
 3756: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
 3757: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
 3758: /* 	/\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
 3759: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
 3760: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
 3761: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
 3762: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
 3763: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
 3764: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
 3765: /* 	  /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
 3766: /* 	  cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
 3767: /* 	  /\* 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]])); *\/ */
 3768: /* 	  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); */
 3769: /* 	  printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
 3770: /* 	}else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
 3771: /* 	  /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
 3772: /* 	  cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
 3773: /* 	  /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
 3774: /* 	  /\* 	/\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
 3775: /* 	  /\* 	cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
 3776: /* 	  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]]); */
 3777: /* 	  printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
 3778: /* 	}else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
 3779: /* 	  /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
 3780: /* 	  /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
 3781: /* 	  cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
 3782: /* 	  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]); */
 3783: /* 	  printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
 3784: 
 3785: /* 	  /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];	 *\/ */
 3786: /* 	  /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
 3787: /* 	  /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
 3788: /* 	  /\* *\/ */
 3789: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
 3790: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
 3791: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
 3792: /* /\*cptcovage=2                   1               2      *\/ */
 3793: /* /\*Tage[k]=                      5               8      *\/	 */
 3794: /* 	}else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
 3795: /* 	  cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];	 */
 3796: /* 	  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]]); */
 3797: /* 	  printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
 3798: /* 	  /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
 3799: /* 	  /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
 3800: /* 	  /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
 3801: /* 	  /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
 3802: /* 	  /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
 3803: /* 	  /\*   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); *\/ */
 3804: /* 	  /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
 3805: /* 	  /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
 3806: /* 	  /\* } *\/ */
 3807: /* 	  /\* 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]); *\/ */
 3808: /* 	}else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
 3809: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
 3810: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
 3811: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
 3812: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
 3813: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
 3814: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
 3815: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
 3816: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
 3817: 	  
 3818: /* 	  /\* 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])]); *\/ */
 3819: /* 	  /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
 3820: /* 	  cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];	 */
 3821: /* 	  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]]); */
 3822: /* 	  printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
 3823: 
 3824: /* 	  /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
 3825: /* 	  /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
 3826: /* 	      /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
 3827: /* 	      /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];	 *\/ */
 3828: /* 	      /\* 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]])]; *\/ */
 3829: /* 	    /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
 3830: /* 	      /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
 3831: /* 	      /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
 3832: /* 	  /\*   } *\/ */
 3833: /* 	  /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
 3834: /* 	  /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
 3835: /* 	  /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
 3836: /* 	  /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
 3837: /* 	  /\*   }else{ /\\* Product of two quant *\\/ *\/ */
 3838: /* 	  /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
 3839: /* 	  /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
 3840: /* 	  /\*   } *\/ */
 3841: /* 	  /\* }/\\*end of products quantitative *\\/ *\/ */
 3842: /* 	}/\*end of products *\/ */
 3843:       /* } /\* End of loop on model equation *\/ */
 3844:       /* for (k=1; k<=cptcovn;k++)  */
 3845:       /* 	cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
 3846:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
 3847:       /* 	cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
 3848:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
 3849:       /* 	cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
 3850:       
 3851:       
 3852:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 3853:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 3854:       /* right multiplication of oldm by the current matrix */
 3855:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
 3856: 		   pmij(pmmij,cov,ncovmodel,x,nlstate));
 3857:       /* if((int)age == 70){ */
 3858:       /* 	printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
 3859:       /* 	for(i=1; i<=nlstate+ndeath; i++) { */
 3860:       /* 	  printf("%d pmmij ",i); */
 3861:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 3862:       /* 	    printf("%f ",pmmij[i][j]); */
 3863:       /* 	  } */
 3864:       /* 	  printf(" oldm "); */
 3865:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 3866:       /* 	    printf("%f ",oldm[i][j]); */
 3867:       /* 	  } */
 3868:       /* 	  printf("\n"); */
 3869:       /* 	} */
 3870:       /* } */
 3871:       savm=oldm;
 3872:       oldm=newm;
 3873:     }
 3874:     for(i=1; i<=nlstate+ndeath; i++)
 3875:       for(j=1;j<=nlstate+ndeath;j++) {
 3876: 	po[i][j][h]=newm[i][j];
 3877: 	/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 3878:       }
 3879:     /*printf("h=%d ",h);*/
 3880:   } /* end h */
 3881:   /*     printf("\n H=%d \n",h); */
 3882:   return po;
 3883: }
 3884: 
 3885: /************* Higher Back Matrix Product ***************/
 3886: /* 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 ) */
 3887: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij, int nres )
 3888: {
 3889:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
 3890:      computes the transition matrix starting at age 'age' over
 3891:      'nhstepm*hstepm*stepm' months (i.e. until
 3892:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
 3893:      nhstepm*hstepm matrices.
 3894:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
 3895:      (typically every 2 years instead of every month which is too big
 3896:      for the memory).
 3897:      Model is determined by parameters x and covariates have to be
 3898:      included manually here. Then we use a call to bmij(x and cov)
 3899:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
 3900:   */
 3901: 
 3902:   int i, j, d, h, k, k1;
 3903:   double **out, cov[NCOVMAX+1], **bmij();
 3904:   double **newm, ***newmm;
 3905:   double agexact;
 3906:   double agebegin, ageend;
 3907:   double **oldm, **savm;
 3908: 
 3909:   newmm=po; /* To be saved */
 3910:   oldm=oldms;savm=savms; /* Global pointers */
 3911:   /* Hstepm could be zero and should return the unit matrix */
 3912:   for (i=1;i<=nlstate+ndeath;i++)
 3913:     for (j=1;j<=nlstate+ndeath;j++){
 3914:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 3915:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 3916:     }
 3917:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 3918:   for(h=1; h <=nhstepm; h++){
 3919:     for(d=1; d <=hstepm; d++){
 3920:       newm=savm;
 3921:       /* Covariates have to be included here again */
 3922:       cov[1]=1.;
 3923:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
 3924:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
 3925:         /* Debug */
 3926:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
 3927:       cov[2]=agexact;
 3928:       if(nagesqr==1){
 3929: 	cov[3]= agexact*agexact;
 3930:       }
 3931:       /** New code */
 3932:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
 3933: 	if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
 3934: 	  cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
 3935: 	}else{
 3936: 	  cov[2+nagesqr+k1]=precov[nres][k1];
 3937: 	}
 3938:       }/* End of loop on model equation */
 3939:       /** End of new code */
 3940:   /** This was old code */
 3941:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
 3942:       /* /\* 	cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
 3943:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
 3944:       /* 	cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
 3945:       /*   /\* 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)); *\/ */
 3946:       /* } */
 3947:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
 3948:       /* 	/\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
 3949:       /* 	cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
 3950:       /* 	/\* 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]); *\/ */
 3951:       /* } */
 3952:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
 3953:       /* 	/\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
 3954:       /* 	if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
 3955:       /* 	  cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
 3956:       /* 	} else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
 3957:       /* 	  cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
 3958:       /* 	} */
 3959:       /* 	/\* 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]); *\/ */
 3960:       /* } */
 3961:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
 3962:       /* 	cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
 3963:       /* 	if(Dummy[Tvard[k][1]]==0){ */
 3964:       /* 	  if(Dummy[Tvard[k][2]]==0){ */
 3965:       /* 	    cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
 3966:       /* 	  }else{ */
 3967:       /* 	    cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
 3968:       /* 	  } */
 3969:       /* 	}else{ */
 3970:       /* 	  if(Dummy[Tvard[k][2]]==0){ */
 3971:       /* 	    cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
 3972:       /* 	  }else{ */
 3973:       /* 	    cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
 3974:       /* 	  } */
 3975:       /* 	} */
 3976:       /* }			 */
 3977:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
 3978:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
 3979: /** End of old code */
 3980:       
 3981:       /* Careful transposed matrix */
 3982:       /* age is in cov[2], prevacurrent at beginning of transition. */
 3983:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
 3984:       /* 						 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
 3985:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
 3986: 		   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
 3987:       /* if((int)age == 70){ */
 3988:       /* 	printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
 3989:       /* 	for(i=1; i<=nlstate+ndeath; i++) { */
 3990:       /* 	  printf("%d pmmij ",i); */
 3991:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 3992:       /* 	    printf("%f ",pmmij[i][j]); */
 3993:       /* 	  } */
 3994:       /* 	  printf(" oldm "); */
 3995:       /* 	  for(j=1;j<=nlstate+ndeath;j++) { */
 3996:       /* 	    printf("%f ",oldm[i][j]); */
 3997:       /* 	  } */
 3998:       /* 	  printf("\n"); */
 3999:       /* 	} */
 4000:       /* } */
 4001:       savm=oldm;
 4002:       oldm=newm;
 4003:     }
 4004:     for(i=1; i<=nlstate+ndeath; i++)
 4005:       for(j=1;j<=nlstate+ndeath;j++) {
 4006: 	po[i][j][h]=newm[i][j];
 4007: 	/* if(h==nhstepm) */
 4008: 	/*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
 4009:       }
 4010:     /* printf("h=%d %.1f ",h, agexact); */
 4011:   } /* end h */
 4012:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
 4013:   return po;
 4014: }
 4015: 
 4016: 
 4017: #ifdef NLOPT
 4018:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
 4019:   double fret;
 4020:   double *xt;
 4021:   int j;
 4022:   myfunc_data *d2 = (myfunc_data *) pd;
 4023: /* xt = (p1-1); */
 4024:   xt=vector(1,n); 
 4025:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
 4026: 
 4027:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
 4028:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
 4029:   printf("Function = %.12lf ",fret);
 4030:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
 4031:   printf("\n");
 4032:  free_vector(xt,1,n);
 4033:   return fret;
 4034: }
 4035: #endif
 4036: 
 4037: /*************** log-likelihood *************/
 4038: double func( double *x)
 4039: {
 4040:   int i, ii, j, k, mi, d, kk, kf=0;
 4041:   int ioffset=0;
 4042:   int ipos=0,iposold=0,ncovv=0;
 4043: 
 4044:   double cotvarv, cotvarvold;
 4045:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 4046:   double **out;
 4047:   double lli; /* Individual log likelihood */
 4048:   int s1, s2;
 4049:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
 4050: 
 4051:   double bbh, survp;
 4052:   double agexact;
 4053:   double agebegin, ageend;
 4054:   /*extern weight */
 4055:   /* We are differentiating ll according to initial status */
 4056:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 4057:   /*for(i=1;i<imx;i++) 
 4058:     printf(" %d\n",s[4][i]);
 4059:   */
 4060: 
 4061:   ++countcallfunc;
 4062: 
 4063:   cov[1]=1.;
 4064: 
 4065:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 4066:   ioffset=0;
 4067:   if(mle==1){
 4068:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 4069:       /* Computes the values of the ncovmodel covariates of the model
 4070: 	 depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
 4071: 	 Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
 4072: 	 to be observed in j being in i according to the model.
 4073:       */
 4074:       ioffset=2+nagesqr ;
 4075:    /* Fixed */
 4076:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummy or quant or prod */
 4077: 	/* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
 4078:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
 4079: 	/*  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 */
 4080:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
 4081: 	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)*/
 4082: 	/* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
 4083:       }
 4084:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
 4085: 	 is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
 4086: 	 has been calculated etc */
 4087:       /* For an individual i, wav[i] gives the number of effective waves */
 4088:       /* We compute the contribution to Likelihood of each effective transition
 4089: 	 mw[mi][i] is real wave of the mi th effectve wave */
 4090:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
 4091: 	 s2=s[mw[mi+1][i]][i];
 4092: 	 And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i] because now is moved after nvocol+nqv 
 4093: 	 But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
 4094: 	 meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
 4095:       */
 4096:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
 4097:       /* Wave varying (but not age varying) */
 4098: 	/* 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*\/ */
 4099: 	/*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
 4100: 	/*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
 4101: 	/* } */
 4102: 	for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
 4103: 	  itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
 4104: 	  ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
 4105: 	  if(FixedV[itv]!=0){ /* Not a fixed covariate */
 4106: 	    cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
 4107: 	  }else{ /* fixed covariate */
 4108: 	    cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
 4109: 	  }
 4110: 	  if(ipos!=iposold){ /* Not a product or first of a product */
 4111: 	    cotvarvold=cotvarv;
 4112: 	  }else{ /* A second product */
 4113: 	    cotvarv=cotvarv*cotvarvold;
 4114: 	  }
 4115: 	  iposold=ipos;
 4116: 	  cov[ioffset+ipos]=cotvarv;
 4117: 	}
 4118: 	/* for products of time varying to be done */
 4119: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 4120: 	  for (j=1;j<=nlstate+ndeath;j++){
 4121: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 4122: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 4123: 	  }
 4124: 
 4125: 	agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
 4126: 	ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
 4127: 	for(d=0; d<dh[mi][i]; d++){
 4128: 	  newm=savm;
 4129: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 4130: 	  cov[2]=agexact;
 4131: 	  if(nagesqr==1)
 4132: 	    cov[3]= agexact*agexact;  /* Should be changed here */
 4133: 	  /* for (kk=1; kk<=cptcovage;kk++) { */
 4134: 	  /*   if(!FixedV[Tvar[Tage[kk]]]) */
 4135: 	  /*     cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /\* Tage[kk] gives the data-covariate associated with age *\/ */
 4136: 	  /*   else */
 4137: 	  /*     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) *\/  */
 4138: 	  /* } */
 4139: 	  for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
 4140: 	    itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
 4141: 	    ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
 4142: 	    if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
 4143: 	      cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
 4144: 	    }else{ /* fixed covariate */
 4145: 	      cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
 4146: 	    }
 4147: 	    if(ipos!=iposold){ /* Not a product or first of a product */
 4148: 	      cotvarvold=cotvarv;
 4149: 	    }else{ /* A second product */
 4150: 	      cotvarv=cotvarv*cotvarvold;
 4151: 	    }
 4152: 	    iposold=ipos;
 4153: 	    cov[ioffset+ipos]=cotvarv*agexact;
 4154: 	    /* For products */
 4155: 	  }
 4156: 	  
 4157: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 4158: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 4159: 	  savm=oldm;
 4160: 	  oldm=newm;
 4161: 	} /* end mult */
 4162: 	
 4163: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 4164: 	/* But now since version 0.9 we anticipate for bias at large stepm.
 4165: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 4166: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
 4167: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
 4168: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 4169: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
 4170: 	 * probability in order to take into account the bias as a fraction of the way
 4171: 				 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
 4172: 				 * -stepm/2 to stepm/2 .
 4173: 				 * For stepm=1 the results are the same as for previous versions of Imach.
 4174: 				 * For stepm > 1 the results are less biased than in previous versions. 
 4175: 				 */
 4176: 	s1=s[mw[mi][i]][i];
 4177: 	s2=s[mw[mi+1][i]][i];
 4178: 	bbh=(double)bh[mi][i]/(double)stepm; 
 4179: 	/* bias bh is positive if real duration
 4180: 	 * is higher than the multiple of stepm and negative otherwise.
 4181: 	 */
 4182: 	/* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
 4183: 	if( s2 > nlstate){ 
 4184: 	  /* i.e. if s2 is a death state and if the date of death is known 
 4185: 	     then the contribution to the likelihood is the probability to 
 4186: 	     die between last step unit time and current  step unit time, 
 4187: 	     which is also equal to probability to die before dh 
 4188: 	     minus probability to die before dh-stepm . 
 4189: 	     In version up to 0.92 likelihood was computed
 4190: 	     as if date of death was unknown. Death was treated as any other
 4191: 	     health state: the date of the interview describes the actual state
 4192: 	     and not the date of a change in health state. The former idea was
 4193: 	     to consider that at each interview the state was recorded
 4194: 	     (healthy, disable or death) and IMaCh was corrected; but when we
 4195: 	     introduced the exact date of death then we should have modified
 4196: 	     the contribution of an exact death to the likelihood. This new
 4197: 	     contribution is smaller and very dependent of the step unit
 4198: 	     stepm. It is no more the probability to die between last interview
 4199: 	     and month of death but the probability to survive from last
 4200: 	     interview up to one month before death multiplied by the
 4201: 	     probability to die within a month. Thanks to Chris
 4202: 	     Jackson for correcting this bug.  Former versions increased
 4203: 	     mortality artificially. The bad side is that we add another loop
 4204: 	     which slows down the processing. The difference can be up to 10%
 4205: 	     lower mortality.
 4206: 	  */
 4207: 	  /* If, at the beginning of the maximization mostly, the
 4208: 	     cumulative probability or probability to be dead is
 4209: 	     constant (ie = 1) over time d, the difference is equal to
 4210: 	     0.  out[s1][3] = savm[s1][3]: probability, being at state
 4211: 	     s1 at precedent wave, to be dead a month before current
 4212: 	     wave is equal to probability, being at state s1 at
 4213: 	     precedent wave, to be dead at mont of the current
 4214: 	     wave. Then the observed probability (that this person died)
 4215: 	     is null according to current estimated parameter. In fact,
 4216: 	     it should be very low but not zero otherwise the log go to
 4217: 	     infinity.
 4218: 	  */
 4219: /* #ifdef INFINITYORIGINAL */
 4220: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 4221: /* #else */
 4222: /* 	  if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
 4223: /* 	    lli=log(mytinydouble); */
 4224: /* 	  else */
 4225: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 4226: /* #endif */
 4227: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 4228: 	  
 4229: 	} else if  ( s2==-1 ) { /* alive */
 4230: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 4231: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 4232: 	  /*survp += out[s1][j]; */
 4233: 	  lli= log(survp);
 4234: 	}
 4235: 	/* else if  (s2==-4) {  */
 4236: 	/*   for (j=3,survp=0. ; j<=nlstate; j++)   */
 4237: 	/*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
 4238: 	/*   lli= log(survp);  */
 4239: 	/* }  */
 4240: 	/* else if  (s2==-5) {  */
 4241: 	/*   for (j=1,survp=0. ; j<=2; j++)   */
 4242: 	/*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
 4243: 	/*   lli= log(survp);  */
 4244: 	/* }  */
 4245: 	else{
 4246: 	  lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 4247: 	  /*  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 */
 4248: 	} 
 4249: 	/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 4250: 	/*if(lli ==000.0)*/
 4251: 	/* 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); */
 4252: 	ipmx +=1;
 4253: 	sw += weight[i];
 4254: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 4255: 	/* if (lli < log(mytinydouble)){ */
 4256: 	/*   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); */
 4257: 	/*   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]); */
 4258: 	/* } */
 4259:       } /* end of wave */
 4260:     } /* end of individual */
 4261:   }  else if(mle==2){
 4262:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 4263:       ioffset=2+nagesqr ;
 4264:       for (k=1; k<=ncovf;k++)
 4265: 	cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
 4266:       for(mi=1; mi<= wav[i]-1; mi++){
 4267: 	for(k=1; k <= ncovv ; k++){
 4268: 	  cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; /* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
 4269: 	}
 4270: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 4271: 	  for (j=1;j<=nlstate+ndeath;j++){
 4272: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 4273: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 4274: 	  }
 4275: 	for(d=0; d<=dh[mi][i]; d++){
 4276: 	  newm=savm;
 4277: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 4278: 	  cov[2]=agexact;
 4279: 	  if(nagesqr==1)
 4280: 	    cov[3]= agexact*agexact;
 4281: 	  for (kk=1; kk<=cptcovage;kk++) {
 4282: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 4283: 	  }
 4284: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 4285: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 4286: 	  savm=oldm;
 4287: 	  oldm=newm;
 4288: 	} /* end mult */
 4289:       
 4290: 	s1=s[mw[mi][i]][i];
 4291: 	s2=s[mw[mi+1][i]][i];
 4292: 	bbh=(double)bh[mi][i]/(double)stepm; 
 4293: 	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 */
 4294: 	ipmx +=1;
 4295: 	sw += weight[i];
 4296: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 4297:       } /* end of wave */
 4298:     } /* end of individual */
 4299:   }  else if(mle==3){  /* exponential inter-extrapolation */
 4300:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 4301:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 4302:       for(mi=1; mi<= wav[i]-1; mi++){
 4303: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 4304: 	  for (j=1;j<=nlstate+ndeath;j++){
 4305: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 4306: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 4307: 	  }
 4308: 	for(d=0; d<dh[mi][i]; d++){
 4309: 	  newm=savm;
 4310: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 4311: 	  cov[2]=agexact;
 4312: 	  if(nagesqr==1)
 4313: 	    cov[3]= agexact*agexact;
 4314: 	  for (kk=1; kk<=cptcovage;kk++) {
 4315: 	    if(!FixedV[Tvar[Tage[kk]]])
 4316: 	      cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
 4317: 	    else
 4318: 	      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) */ 
 4319: 	  }
 4320: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 4321: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 4322: 	  savm=oldm;
 4323: 	  oldm=newm;
 4324: 	} /* end mult */
 4325:       
 4326: 	s1=s[mw[mi][i]][i];
 4327: 	s2=s[mw[mi+1][i]][i];
 4328: 	bbh=(double)bh[mi][i]/(double)stepm; 
 4329: 	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 */
 4330: 	ipmx +=1;
 4331: 	sw += weight[i];
 4332: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 4333:       } /* end of wave */
 4334:     } /* end of individual */
 4335:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
 4336:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 4337:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 4338:       for(mi=1; mi<= wav[i]-1; mi++){
 4339: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 4340: 	  for (j=1;j<=nlstate+ndeath;j++){
 4341: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 4342: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 4343: 	  }
 4344: 	for(d=0; d<dh[mi][i]; d++){
 4345: 	  newm=savm;
 4346: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 4347: 	  cov[2]=agexact;
 4348: 	  if(nagesqr==1)
 4349: 	    cov[3]= agexact*agexact;
 4350: 	  for (kk=1; kk<=cptcovage;kk++) {
 4351: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 4352: 	  }
 4353: 	
 4354: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 4355: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 4356: 	  savm=oldm;
 4357: 	  oldm=newm;
 4358: 	} /* end mult */
 4359:       
 4360: 	s1=s[mw[mi][i]][i];
 4361: 	s2=s[mw[mi+1][i]][i];
 4362: 	if( s2 > nlstate){ 
 4363: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 4364: 	} else if  ( s2==-1 ) { /* alive */
 4365: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 4366: 	    survp += out[s1][j];
 4367: 	  lli= log(survp);
 4368: 	}else{
 4369: 	  lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 4370: 	}
 4371: 	ipmx +=1;
 4372: 	sw += weight[i];
 4373: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 4374: 	/* 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])); */
 4375:       } /* end of wave */
 4376:     } /* end of individual */
 4377:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
 4378:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 4379:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 4380:       for(mi=1; mi<= wav[i]-1; mi++){
 4381: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 4382: 	  for (j=1;j<=nlstate+ndeath;j++){
 4383: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 4384: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 4385: 	  }
 4386: 	for(d=0; d<dh[mi][i]; d++){
 4387: 	  newm=savm;
 4388: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 4389: 	  cov[2]=agexact;
 4390: 	  if(nagesqr==1)
 4391: 	    cov[3]= agexact*agexact;
 4392: 	  for (kk=1; kk<=cptcovage;kk++) {
 4393: 	    if(!FixedV[Tvar[Tage[kk]]])
 4394: 	      cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
 4395: 	    else
 4396: 	      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) */ 
 4397: 	  }
 4398: 	
 4399: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 4400: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 4401: 	  savm=oldm;
 4402: 	  oldm=newm;
 4403: 	} /* end mult */
 4404:       
 4405: 	s1=s[mw[mi][i]][i];
 4406: 	s2=s[mw[mi+1][i]][i];
 4407: 	lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 4408: 	ipmx +=1;
 4409: 	sw += weight[i];
 4410: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 4411: 	/*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]);*/
 4412:       } /* end of wave */
 4413:     } /* end of individual */
 4414:   } /* End of if */
 4415:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 4416:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 4417:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 4418:   return -l;
 4419: }
 4420: 
 4421: /*************** log-likelihood *************/
 4422: double funcone( double *x)
 4423: {
 4424:   /* Same as func but slower because of a lot of printf and if */
 4425:   int i, ii, j, k, mi, d, kk, kv=0, kf=0;
 4426:   int ioffset=0;
 4427:   int ipos=0,iposold=0,ncovv=0;
 4428: 
 4429:   double cotvarv, cotvarvold;
 4430:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 4431:   double **out;
 4432:   double lli; /* Individual log likelihood */
 4433:   double llt;
 4434:   int s1, s2;
 4435:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
 4436: 
 4437:   double bbh, survp;
 4438:   double agexact;
 4439:   double agebegin, ageend;
 4440:   /*extern weight */
 4441:   /* We are differentiating ll according to initial status */
 4442:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 4443:   /*for(i=1;i<imx;i++) 
 4444:     printf(" %d\n",s[4][i]);
 4445:   */
 4446:   cov[1]=1.;
 4447: 
 4448:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 4449:   ioffset=0;
 4450:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 4451:     /* Computes the values of the ncovmodel covariates of the model
 4452:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
 4453:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
 4454:        to be observed in j being in i according to the model.
 4455:     */
 4456:     /* ioffset=2+nagesqr+cptcovage; */
 4457:     ioffset=2+nagesqr;
 4458:     /* Fixed */
 4459:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
 4460:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
 4461:     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 */
 4462:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
 4463:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
 4464:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
 4465:       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)*/
 4466: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
 4467: /*    cov[2+6]=covar[Tvar[6]][i];  */
 4468: /*    cov[2+6]=covar[2][i]; V2  */
 4469: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
 4470: /*    cov[2+7]=covar[Tvar[7]][i];  */
 4471: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
 4472: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
 4473: /*    cov[2+9]=covar[Tvar[9]][i];  */
 4474: /*    cov[2+9]=covar[1][i]; V1  */
 4475:     }
 4476:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
 4477: 	 is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
 4478: 	 has been calculated etc */
 4479:       /* For an individual i, wav[i] gives the number of effective waves */
 4480:       /* We compute the contribution to Likelihood of each effective transition
 4481: 	 mw[mi][i] is real wave of the mi th effectve wave */
 4482:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
 4483: 	 s2=s[mw[mi+1][i]][i];
 4484: 	 And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
 4485:       */
 4486:     /* This part may be useless now because everythin should be in covar */
 4487:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
 4488:     /*   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?)*\/ */
 4489:     /* } */
 4490:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
 4491:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
 4492:     /* } */
 4493:     
 4494: 
 4495:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
 4496:       /* 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 */
 4497:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
 4498:       /* 	/\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
 4499:       /* 	cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
 4500:       /* } */
 4501:       
 4502:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
 4503:       /* model V1+V3+age*V1+age*V3+V1*V3 */
 4504:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
 4505:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
 4506:       /* We need the position of the time varying or product in the model */
 4507:       /* 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 */	       
 4508:       /* TvarVV gives the variable name */
 4509:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
 4510:       *      k=         1   2     3     4         5        6        7       8        9
 4511:       *  varying            1     2                                 3       4        5
 4512:       *  ncovv              1     2                                3 4     5 6      7 8
 4513:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
 4514:       * TvarVVind           2     3                                7 7     8 8      9 9
 4515:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
 4516:       */
 4517:       /* Other model ncovcol=5 nqv=0 ntv=3 nqtv=0 nlstate=3
 4518:        * 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
 4519: 	* FixedV[ncovcol+qv+ntv+nqtv]       V5
 4520: 	* 3           V1  V2     V3    V4   V5 V6     V7  V8 V3*V2 V7*V2  V6*V3 V7*V3 V6*V4 V7*V4
 4521: 	*             0   0      0      0    0  1      1   1  0, 0, 1,1,   1, 0, 1, 0, 1, 0, 1, 0}
 4522: 	* 3           0   0      0      0    0  1      1   1  0,     1      1    1      1    1}
 4523: 	* model=          V2  +  V3  +  V4  +  V6  +  V7  +  V6*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
 4524:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
 4525:         *                +age*V6*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
 4526: 	* model2=          V2  +  V3  +  V4  +  V6  +  V7  +  V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
 4527:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
 4528:         *                +age*V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
 4529: 	* model3=          V2  +  V3  +  V4  +  V6  +  V7  + age*V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
 4530:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
 4531:         *                +V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
 4532: 	* kmodel           1     2      3      4      5        6         7         8         9        10        11    
 4533: 	*                  12       13      14      15       16
 4534: 	*                    17        18         19        20         21
 4535: 	* Tvar[kmodel]     2     3      4      6      7        9        10        11        12        13        14
 4536: 	*                   2       3        4       6        7
 4537: 	*                     9         11          12        13         14            
 4538: 	* cptcovage=5+5 total of covariates with age 
 4539: 	* Tage[cptcovage] age*V2=12      13      14      15       16
 4540: 	*1                   17            18         19        20         21 gives the position in model of covariates associated with age
 4541: 	*3 Tage[cptcovage] age*V3*V2=6  
 4542: 	*3                age*V2=12         13      14      15       16
 4543: 	*3                age*V6*V3=18      19    20   21
 4544: 	* Tvar[Tage[cptcovage]]    Tvar[12]=2      3      4       6         Tvar[16]=7(age*V7)
 4545: 	*     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
 4546: 	* 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
 4547: 	* 3 Tvar[Tage[cptcovage]]    Tvar[6]=9      Tvar[12]=2      3     4       6         Tvar[16]=7(age*V7)
 4548: 	* 3     Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
 4549: 	* 3 Tage[cptcovage] age*V3*V2=6   age*V2=12 age*V3 13    14      15       16
 4550: 	*                    age*V6*V3=18         19        20         21 gives the position in model of covariates associated with age
 4551: 	* 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
 4552: 	* Tvar=                {2, 3, 4, 6, 7,
 4553: 	*                       9, 10, 11, 12, 13, 14,
 4554: 	*              Tvar[12]=2, 3, 4, 6, 7,
 4555: 	*              Tvar[17]=9, 11, 12, 13, 14}
 4556: 	* Typevar[1]@21 = {0, 0, 0, 0, 0,
 4557: 	*                  2, 2, 2, 2, 2, 2,
 4558: 	* 3                3, 2, 2, 2, 2, 2,
 4559: 	*                  1, 1, 1, 1, 1, 
 4560: 	*                  3, 3, 3, 3, 3}
 4561: 	* 3                 2, 3, 3, 3, 3}
 4562: 	* 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
 4563: 	* p Tprod[1]@21 {6, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
 4564: 	* 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}
 4565: 	* 3 Tprod[1]@21 {17, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
 4566: 	* cptcovprod=11 (6+5)
 4567: 	* FixedV[Tvar[Tage[cptcovage]]]]  FixedV[2]=0      FixedV[3]=0      0      1          (age*V7)Tvar[16]=1 FixedV[absolute] not [kmodel]
 4568: 	*   FixedV[Tvar[17]=FixedV[age*V6*V2]=FixedV[9]=1        1         1          1         1  
 4569: 	* 3 FixedV[Tvar[17]=FixedV[age*V3*V2]=FixedV[9]=0        [11]=1         1          1         1  
 4570: 	* FixedV[]          V1=0     V2=0   V3=0  v4=0    V5=0  V6=1    V7=1 v8=1  OK then model dependent
 4571: 	*                   9=1  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
 4572: 	* 3                 9=0  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
 4573: 	* cptcovdageprod=5  for gnuplot printing
 4574: 	* cptcovprodvage=6 
 4575: 	* ncova=15           1        2       3       4       5
 4576: 	*                      6 7        8 9      10 11        12 13     14 15
 4577: 	* TvarA              2        3       4       6       7
 4578: 	*                      6 2        6 7       7 3          6 4       7 4
 4579: 	* TvaAind             12 12      13 13     14 14      15 15       16 16        
 4580: 	* ncovf            1     2      3
 4581: 	*                                    V6       V7      V6*V2     V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
 4582: 	* ncovvt=14                            1      2        3 4       5 6       7 8       9 10     11 12     13 14     
 4583: 	* TvarVV[1]@14 = itv               {V6=6,     7, V6*V2=6, 2,     7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
 4584: 	* TvarVVind[1]@14=                    {4,     5,       6, 6,     7, 7,     8, 8,      9, 9,   10, 10,   11, 11}
 4585: 	* 3 ncovvt=12                        V6       V7      V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
 4586: 	* 3 TvarVV[1]@12 = itv                {6,     7, V7*V2=7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
 4587: 	* 3                                    1      2        3  4      5  6      7  8      9 10     11 12
 4588: 	* TvarVVind[1]@12=         {V6 is in k=4,     5,  7,(4isV2)=7,   8, 8,      9, 9,   10,10,    11,11}TvarVVind[12]=k=11
 4589: 	* TvarV              6, 7, 9, 10, 11, 12, 13, 14
 4590: 	* 3 cptcovprodvage=6
 4591: 	* 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
 4592: 	* 3 TvarAVVA[1]@15= itva 3 2    2      3    4        6       7        6 3         7 3         6 4         7 4 
 4593: 	* 3 ncovta             1 2      3      4    5        6       7        8 9       10 11       12 13        14 15
 4594: 	*?TvarAVVAind[1]@15= V3 is in k=2 1 1  2    3        4       5        4,2         5,2,      4,3           5 3}TvarVVAind[]
 4595: 	* TvarAVVAind[1]@15= V3 is in k=6 6 12  13   14      15      16       18 18       19,19,     20,20        21,21}TvarVVAind[]
 4596: 	* 3 ncovvta=10     +age*V6 + age*V7 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
 4597: 	* 3 we want to compute =cotvar[mw[mi][i]][TvarVVA[ncovva]][i] at position TvarVVAind[ncovva]
 4598: 	* 3 TvarVVA[1]@10= itva   6       7        6 3         7 3         6 4         7 4 
 4599: 	* 3 ncovva                1       2        3 4         5 6         7 8         9 10
 4600: 	* TvarVVAind[1]@10= V6 is in k=4  5        8,8         9, 9,      10,10        11 11}TvarVVAind[]
 4601: 	* TvarVVAind[1]@10=       15       16     18,18        19,19,      20,20        21 21}TvarVVAind[]
 4602: 	* TvarVA              V3*V2=6 6 , 1, 2, 11, 12, 13, 14
 4603: 	* TvarFind[1]@14= {1,    2,     3,     0 <repeats 12 times>}
 4604: 	* Tvar[1]@21=     {2,    3,     4,    6,      7,      9,      10,        11,       12,      13,       14,
 4605: 	*                   2, 3, 4, 6, 7,
 4606: 	*                     6, 8, 9, 10, 11}
 4607: 	* TvarFind[itv]                        0      0       0
 4608: 	* FixedV[itv]                          1      1       1  0      1 0       1 0       1 0       0
 4609: 	*? FixedV[itv]                          1      1       1  0      1 0       1 0       1 0      1 0     1 0
 4610: 	* Tvar[TvarFind[ncovf]]=[1]=2 [2]=3 [4]=4
 4611: 	* Tvar[TvarFind[itv]]                [0]=?      ?ncovv 1 à ncovvt]
 4612: 	*   Not a fixed cotvar[mw][itv][i]     6       7      6  2      7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
 4613: 	*   fixed covar[itv]                  [6]     [7]    [6][2] 
 4614: 	*/
 4615: 
 4616:       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 */
 4617: 	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  */
 4618: 	ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
 4619: 	/* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
 4620: 	if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
 4621: 	  /* printf("DEBUG ncovv=%d, Varying TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
 4622: 	  cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
 4623: 	  /* printf("DEBUG Varying cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
 4624: 	}else{ /* fixed covariate */
 4625: 	  /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
 4626: 	  /* printf("DEBUG ncovv=%d, Fixed TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
 4627: 	  cotvarv=covar[itv][i];  /* Good: In V6*V3, 3 is fixed at position of the data */
 4628: 	  /* printf("DEBUG Fixed cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
 4629: 	}
 4630: 	if(ipos!=iposold){ /* Not a product or first of a product */
 4631: 	  cotvarvold=cotvarv;
 4632: 	}else{ /* A second product */
 4633: 	  cotvarv=cotvarv*cotvarvold;
 4634: 	}
 4635: 	iposold=ipos;
 4636: 	cov[ioffset+ipos]=cotvarv;
 4637: 	/* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
 4638: 	/* For products */
 4639:       }
 4640:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
 4641:       /* 	iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
 4642:       /* 	/\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
 4643:       /* 	/\*           1  2   3      4      5                         *\/ */
 4644:       /* 	/\*itv           1                                           *\/ */
 4645:       /* 	/\* TvarVInd[1]= 2                                           *\/ */
 4646:       /* 	/\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
 4647:       /* 	/\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
 4648:       /* 	/\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
 4649:       /* 	/\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
 4650:       /* 	/\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
 4651:       /* 	cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
 4652:       /* 	/\* 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]); *\/ */
 4653:       /* } */
 4654:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
 4655:       /* 	iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
 4656:       /* 	/\* 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]); *\/ */
 4657:       /* 	cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
 4658:       /* } */
 4659:       for (ii=1;ii<=nlstate+ndeath;ii++)
 4660: 	for (j=1;j<=nlstate+ndeath;j++){
 4661: 	  oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 4662: 	  savm[ii][j]=(ii==j ? 1.0 : 0.0);
 4663: 	}
 4664:       
 4665:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
 4666:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
 4667:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
 4668:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
 4669: 	/*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 4670: 	  and mw[mi+1][i]. dh depends on stepm.*/
 4671: 	newm=savm;
 4672: 	agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
 4673: 	cov[2]=agexact;
 4674: 	if(nagesqr==1)
 4675: 	  cov[3]= agexact*agexact;
 4676: 	for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
 4677: 	  itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
 4678: 	  ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
 4679: 	  /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
 4680: 	  if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
 4681: 	    /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
 4682: 	    cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
 4683: 	  }else{ /* fixed covariate */
 4684: 	    /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
 4685: 	    /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
 4686: 	    cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
 4687: 	  }
 4688: 	  if(ipos!=iposold){ /* Not a product or first of a product */
 4689: 	    cotvarvold=cotvarv;
 4690: 	  }else{ /* A second product */
 4691: 	    /* printf("DEBUG * \n"); */
 4692: 	    cotvarv=cotvarv*cotvarvold;
 4693: 	  }
 4694: 	  iposold=ipos;
 4695: 	  /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
 4696: 	  cov[ioffset+ipos]=cotvarv*agexact;
 4697: 	  /* For products */
 4698: 	}
 4699: 
 4700: 	/* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
 4701: 	/* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 4702: 	out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 4703: 		     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 4704: 	/* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
 4705: 	/* 	     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
 4706: 	savm=oldm;
 4707: 	oldm=newm;
 4708:       } /* end mult */
 4709: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 4710: 	/* But now since version 0.9 we anticipate for bias at large stepm.
 4711: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 4712: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
 4713: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
 4714: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 4715: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
 4716: 	 * probability in order to take into account the bias as a fraction of the way
 4717: 				 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
 4718: 				 * -stepm/2 to stepm/2 .
 4719: 				 * For stepm=1 the results are the same as for previous versions of Imach.
 4720: 				 * For stepm > 1 the results are less biased than in previous versions. 
 4721: 				 */
 4722:       s1=s[mw[mi][i]][i];
 4723:       s2=s[mw[mi+1][i]][i];
 4724:       /* if(s2==-1){ */
 4725:       /* 	printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
 4726:       /* 	/\* exit(1); *\/ */
 4727:       /* } */
 4728:       bbh=(double)bh[mi][i]/(double)stepm; 
 4729:       /* bias is positive if real duration
 4730:        * is higher than the multiple of stepm and negative otherwise.
 4731:        */
 4732:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
 4733: 	lli=log(out[s1][s2] - savm[s1][s2]);
 4734:       } else if  ( s2==-1 ) { /* alive */
 4735: 	for (j=1,survp=0. ; j<=nlstate; j++) 
 4736: 	  survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 4737: 	lli= log(survp);
 4738:       }else if (mle==1){
 4739: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 4740:       } else if(mle==2){
 4741: 	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 */
 4742:       } else if(mle==3){  /* exponential inter-extrapolation */
 4743: 	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 */
 4744:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
 4745: 	lli=log(out[s1][s2]); /* Original formula */
 4746:       } else{  /* mle=0 back to 1 */
 4747: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 4748: 	/*lli=log(out[s1][s2]); */ /* Original formula */
 4749:       } /* End of if */
 4750:       ipmx +=1;
 4751:       sw += weight[i];
 4752:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 4753:       /* Printing covariates values for each contribution for checking */
 4754:       /* 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])); */
 4755:       if(globpr){
 4756: 	fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
 4757:  %11.6f %11.6f %11.6f ", \
 4758: 		num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
 4759: 		2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
 4760: 	/* 	printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
 4761: 	/* %11.6f %11.6f %11.6f ", \ */
 4762: 	/* 		num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
 4763: 	/* 		2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
 4764: 	for(k=1,llt=0.,l=0.; k<=nlstate; k++){
 4765: 	  llt +=ll[k]*gipmx/gsw;
 4766: 	  fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
 4767: 	  /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
 4768: 	}
 4769: 	fprintf(ficresilk," %10.6f ", -llt);
 4770: 	/* printf(" %10.6f\n", -llt); */
 4771: 	/* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
 4772: 	/* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
 4773: 	for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
 4774: 	  fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
 4775: 	}
 4776: 	for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
 4777: 	  ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
 4778: 	  if(ipos!=iposold){ /* Not a product or first of a product */
 4779: 	    fprintf(ficresilk," %g",cov[ioffset+ipos]);
 4780: 	    /* printf(" %g",cov[ioffset+ipos]); */
 4781: 	  }else{
 4782: 	    fprintf(ficresilk,"*");
 4783: 	    /* printf("*"); */
 4784: 	  }
 4785: 	  iposold=ipos;
 4786: 	}
 4787: 	/* for (kk=1; kk<=cptcovage;kk++) { */
 4788: 	/*   if(!FixedV[Tvar[Tage[kk]]]){ */
 4789: 	/*     fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]); */
 4790: 	/*     /\* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); *\/ */
 4791: 	/*   }else{ */
 4792: 	/*     fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
 4793: 	/*     /\* printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\\/  *\/ */
 4794: 	/*   } */
 4795: 	/* } */
 4796: 	for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
 4797: 	  itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
 4798: 	  ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
 4799: 	  /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
 4800: 	  if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
 4801: 	    /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
 4802: 	    cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
 4803: 	  }else{ /* fixed covariate */
 4804: 	    /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
 4805: 	    /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
 4806: 	    cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
 4807: 	  }
 4808: 	  if(ipos!=iposold){ /* Not a product or first of a product */
 4809: 	    cotvarvold=cotvarv;
 4810: 	  }else{ /* A second product */
 4811: 	    /* printf("DEBUG * \n"); */
 4812: 	    cotvarv=cotvarv*cotvarvold;
 4813: 	  }
 4814: 	  cotvarv=cotvarv*agexact;
 4815: 	  fprintf(ficresilk," %g*age",cotvarv);
 4816: 	  iposold=ipos;
 4817: 	  /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
 4818: 	  cov[ioffset+ipos]=cotvarv;
 4819: 	  /* For products */
 4820: 	}
 4821: 	/* printf("\n"); */
 4822: 	/* } /\*  End debugILK *\/ */
 4823: 	fprintf(ficresilk,"\n");
 4824:       } /* End if globpr */
 4825:     } /* end of wave */
 4826:   } /* end of individual */
 4827:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 4828: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 4829:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 4830:   if(globpr==0){ /* First time we count the contributions and weights */
 4831:     gipmx=ipmx;
 4832:     gsw=sw;
 4833:   }
 4834:   return -l;
 4835: }
 4836: 
 4837: 
 4838: /*************** function likelione ***********/
 4839: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
 4840: {
 4841:   /* This routine should help understanding what is done with 
 4842:      the selection of individuals/waves and
 4843:      to check the exact contribution to the likelihood.
 4844:      Plotting could be done.
 4845:   */
 4846:   void pstamp(FILE *ficres);
 4847:   int k, kf, kk, kvar, ncovv, iposold, ipos;
 4848: 
 4849:   if(*globpri !=0){ /* Just counts and sums, no printings */
 4850:     strcpy(fileresilk,"ILK_"); 
 4851:     strcat(fileresilk,fileresu);
 4852:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
 4853:       printf("Problem with resultfile: %s\n", fileresilk);
 4854:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
 4855:     }
 4856:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
 4857:     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");
 4858:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
 4859:     /* 	i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
 4860:     for(k=1; k<=nlstate; k++) 
 4861:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
 4862:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
 4863: 
 4864:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
 4865:       for(kf=1;kf <= ncovf; kf++){
 4866: 	fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
 4867: 	/* printf("V%d",Tvar[TvarFind[kf]]); */
 4868:       }
 4869:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
 4870: 	ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
 4871: 	if(ipos!=iposold){ /* Not a product or first of a product */
 4872: 	  /* printf(" %d",ipos); */
 4873: 	  fprintf(ficresilk," V%d",TvarVV[ncovv]);
 4874: 	}else{
 4875: 	  /* printf("*"); */
 4876: 	  fprintf(ficresilk,"*");
 4877: 	}
 4878: 	iposold=ipos;
 4879:       }
 4880:       for (kk=1; kk<=cptcovage;kk++) {
 4881: 	if(!FixedV[Tvar[Tage[kk]]]){
 4882: 	  /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
 4883: 	  fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
 4884: 	}else{
 4885: 	  fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
 4886: 	  /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
 4887: 	}
 4888:       }
 4889:     /* } /\* End if debugILK *\/ */
 4890:     /* printf("\n"); */
 4891:     fprintf(ficresilk,"\n");
 4892:   } /* End glogpri */
 4893: 
 4894:   *fretone=(*func)(p);
 4895:   if(*globpri !=0){
 4896:     fclose(ficresilk);
 4897:     if (mle ==0)
 4898:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
 4899:     else if(mle >=1)
 4900:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
 4901:     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));
 4902:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
 4903:       
 4904:     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> \
 4905: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
 4906:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
 4907: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
 4908:     
 4909:     for (k=1; k<= nlstate ; k++) {
 4910:       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 \
 4911: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
 4912:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
 4913: 	 kvar=Tvar[TvarFind[kf]];  /* variable */
 4914: 	 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]]);
 4915: 	 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);
 4916: 	 fprintf(fichtm,"<img src=\"%s-p%dj-%d.png\">",subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]);
 4917:       }
 4918:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
 4919: 	ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
 4920: 	kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
 4921: 	/* 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]); */
 4922: 	if(ipos!=iposold){ /* Not a product or first of a product */
 4923: 	  /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
 4924: 	  /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
 4925: 	  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)  */
 4926: 	    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> \
 4927: <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);
 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 loop on states */
 4936: 
 4937: /*     if(debugILK){ */
 4938: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
 4939: /* 	/\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
 4940: /* 	for (k=1; k<= nlstate ; k++) { */
 4941: /* 	  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> \ */
 4942: /* <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]]); */
 4943: /* 	} */
 4944: /*       } */
 4945: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
 4946: /* 	ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
 4947: /* 	kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
 4948: /* 	/\* 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]); *\/ */
 4949: /* 	if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
 4950: /* 	  /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
 4951: /* 	  /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
 4952: /* 	  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)  *\/ */
 4953: /* 	    for (k=1; k<= nlstate ; k++) { */
 4954: /* 	      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> \ */
 4955: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
 4956: /* 	    } /\* End state *\/ */
 4957: /* 	  } /\* End only for dummies time varying (single?) *\/ */
 4958: /* 	}else{ /\* Useless product *\/ */
 4959: /* 	  /\* printf("*"); *\/ */
 4960: /* 	  /\* fprintf(ficresilk,"*"); *\/  */
 4961: /* 	} */
 4962: /* 	iposold=ipos; */
 4963: /*       } /\* For each time varying covariate *\/ */
 4964: /*     }/\* End debugILK *\/ */
 4965:     fflush(fichtm);
 4966:   }/* End globpri */
 4967:   return;
 4968: }
 4969: 
 4970: 
 4971: /*********** Maximum Likelihood Estimation ***************/
 4972: 
 4973: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
 4974: {
 4975:   int i,j,k, jk, jkk=0, iter=0;
 4976:   double **xi;
 4977:   double fret;
 4978:   double fretone; /* Only one call to likelihood */
 4979:   /*  char filerespow[FILENAMELENGTH];*/
 4980:   
 4981:   double * p1; /* Shifted parameters from 0 instead of 1 */
 4982: #ifdef NLOPT
 4983:   int creturn;
 4984:   nlopt_opt opt;
 4985:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
 4986:   double *lb;
 4987:   double minf; /* the minimum objective value, upon return */
 4988: 
 4989:   myfunc_data dinst, *d = &dinst;
 4990: #endif
 4991: 
 4992: 
 4993:   xi=matrix(1,npar,1,npar);
 4994:   for (i=1;i<=npar;i++)  /* Starting with canonical directions j=1,n xi[i=1,n][j] */
 4995:     for (j=1;j<=npar;j++)
 4996:       xi[i][j]=(i==j ? 1.0 : 0.0);
 4997:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
 4998:   strcpy(filerespow,"POW_"); 
 4999:   strcat(filerespow,fileres);
 5000:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
 5001:     printf("Problem with resultfile: %s\n", filerespow);
 5002:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 5003:   }
 5004:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
 5005:   for (i=1;i<=nlstate;i++)
 5006:     for(j=1;j<=nlstate+ndeath;j++)
 5007:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 5008:   fprintf(ficrespow,"\n");
 5009: #ifdef POWELL
 5010: #ifdef LINMINORIGINAL
 5011: #else /* LINMINORIGINAL */
 5012:   
 5013:   flatdir=ivector(1,npar); 
 5014:   for (j=1;j<=npar;j++) flatdir[j]=0; 
 5015: #endif /*LINMINORIGINAL */
 5016: 
 5017: #ifdef FLATSUP
 5018:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
 5019:   /* reorganizing p by suppressing flat directions */
 5020:   for(i=1, jk=1; i <=nlstate; i++){
 5021:     for(k=1; k <=(nlstate+ndeath); k++){
 5022:       if (k != i) {
 5023:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
 5024:         if(flatdir[jk]==1){
 5025:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
 5026:         }
 5027:         for(j=1; j <=ncovmodel; j++){
 5028:           printf("%12.7f ",p[jk]);
 5029:           jk++; 
 5030:         }
 5031:         printf("\n");
 5032:       }
 5033:     }
 5034:   }
 5035: /* skipping */
 5036:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
 5037:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
 5038:     for(k=1; k <=(nlstate+ndeath); k++){
 5039:       if (k != i) {
 5040:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
 5041:         if(flatdir[jk]==1){
 5042:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
 5043:           for(j=1; j <=ncovmodel;  jk++,j++){
 5044:             printf(" p[%d]=%12.7f",jk, p[jk]);
 5045:             /*q[jjk]=p[jk];*/
 5046:           }
 5047:         }else{
 5048:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
 5049:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
 5050:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
 5051:             /*q[jjk]=p[jk];*/
 5052:           }
 5053:         }
 5054:         printf("\n");
 5055:       }
 5056:       fflush(stdout);
 5057:     }
 5058:   }
 5059:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
 5060: #else  /* FLATSUP */
 5061:   powell(p,xi,npar,ftol,&iter,&fret,func);
 5062: #endif  /* FLATSUP */
 5063: 
 5064: #ifdef LINMINORIGINAL
 5065: #else
 5066:       free_ivector(flatdir,1,npar); 
 5067: #endif  /* LINMINORIGINAL*/
 5068: #endif /* POWELL */
 5069: 
 5070: #ifdef NLOPT
 5071: #ifdef NEWUOA
 5072:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
 5073: #else
 5074:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
 5075: #endif
 5076:   lb=vector(0,npar-1);
 5077:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
 5078:   nlopt_set_lower_bounds(opt, lb);
 5079:   nlopt_set_initial_step1(opt, 0.1);
 5080:   
 5081:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
 5082:   d->function = func;
 5083:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
 5084:   nlopt_set_min_objective(opt, myfunc, d);
 5085:   nlopt_set_xtol_rel(opt, ftol);
 5086:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
 5087:     printf("nlopt failed! %d\n",creturn); 
 5088:   }
 5089:   else {
 5090:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
 5091:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
 5092:     iter=1; /* not equal */
 5093:   }
 5094:   nlopt_destroy(opt);
 5095: #endif
 5096: #ifdef FLATSUP
 5097:   /* npared = npar -flatd/ncovmodel; */
 5098:   /* xired= matrix(1,npared,1,npared); */
 5099:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
 5100:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
 5101:   /* free_matrix(xire,1,npared,1,npared); */
 5102: #else  /* FLATSUP */
 5103: #endif /* FLATSUP */
 5104:   free_matrix(xi,1,npar,1,npar);
 5105:   fclose(ficrespow);
 5106:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 5107:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 5108:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 5109: 
 5110: }
 5111: 
 5112: /**** Computes Hessian and covariance matrix ***/
 5113: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
 5114: {
 5115:   double  **a,**y,*x,pd;
 5116:   /* double **hess; */
 5117:   int i, j;
 5118:   int *indx;
 5119: 
 5120:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
 5121:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
 5122:   void lubksb(double **a, int npar, int *indx, double b[]) ;
 5123:   void ludcmp(double **a, int npar, int *indx, double *d) ;
 5124:   double gompertz(double p[]);
 5125:   /* hess=matrix(1,npar,1,npar); */
 5126: 
 5127:   printf("\nCalculation of the hessian matrix. Wait...\n");
 5128:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
 5129:   for (i=1;i<=npar;i++){
 5130:     printf("%d-",i);fflush(stdout);
 5131:     fprintf(ficlog,"%d-",i);fflush(ficlog);
 5132:    
 5133:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
 5134:     
 5135:     /*  printf(" %f ",p[i]);
 5136: 	printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
 5137:   }
 5138:   
 5139:   for (i=1;i<=npar;i++) {
 5140:     for (j=1;j<=npar;j++)  {
 5141:       if (j>i) { 
 5142: 	printf(".%d-%d",i,j);fflush(stdout);
 5143: 	fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
 5144: 	hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
 5145: 	
 5146: 	hess[j][i]=hess[i][j];    
 5147: 	/*printf(" %lf ",hess[i][j]);*/
 5148:       }
 5149:     }
 5150:   }
 5151:   printf("\n");
 5152:   fprintf(ficlog,"\n");
 5153: 
 5154:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
 5155:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
 5156:   
 5157:   a=matrix(1,npar,1,npar);
 5158:   y=matrix(1,npar,1,npar);
 5159:   x=vector(1,npar);
 5160:   indx=ivector(1,npar);
 5161:   for (i=1;i<=npar;i++)
 5162:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
 5163:   ludcmp(a,npar,indx,&pd);
 5164: 
 5165:   for (j=1;j<=npar;j++) {
 5166:     for (i=1;i<=npar;i++) x[i]=0;
 5167:     x[j]=1;
 5168:     lubksb(a,npar,indx,x);
 5169:     for (i=1;i<=npar;i++){ 
 5170:       matcov[i][j]=x[i];
 5171:     }
 5172:   }
 5173: 
 5174:   printf("\n#Hessian matrix#\n");
 5175:   fprintf(ficlog,"\n#Hessian matrix#\n");
 5176:   for (i=1;i<=npar;i++) { 
 5177:     for (j=1;j<=npar;j++) { 
 5178:       printf("%.6e ",hess[i][j]);
 5179:       fprintf(ficlog,"%.6e ",hess[i][j]);
 5180:     }
 5181:     printf("\n");
 5182:     fprintf(ficlog,"\n");
 5183:   }
 5184: 
 5185:   /* printf("\n#Covariance matrix#\n"); */
 5186:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
 5187:   /* for (i=1;i<=npar;i++) {  */
 5188:   /*   for (j=1;j<=npar;j++) {  */
 5189:   /*     printf("%.6e ",matcov[i][j]); */
 5190:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
 5191:   /*   } */
 5192:   /*   printf("\n"); */
 5193:   /*   fprintf(ficlog,"\n"); */
 5194:   /* } */
 5195: 
 5196:   /* Recompute Inverse */
 5197:   /* for (i=1;i<=npar;i++) */
 5198:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
 5199:   /* ludcmp(a,npar,indx,&pd); */
 5200: 
 5201:   /*  printf("\n#Hessian matrix recomputed#\n"); */
 5202: 
 5203:   /* for (j=1;j<=npar;j++) { */
 5204:   /*   for (i=1;i<=npar;i++) x[i]=0; */
 5205:   /*   x[j]=1; */
 5206:   /*   lubksb(a,npar,indx,x); */
 5207:   /*   for (i=1;i<=npar;i++){  */
 5208:   /*     y[i][j]=x[i]; */
 5209:   /*     printf("%.3e ",y[i][j]); */
 5210:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
 5211:   /*   } */
 5212:   /*   printf("\n"); */
 5213:   /*   fprintf(ficlog,"\n"); */
 5214:   /* } */
 5215: 
 5216:   /* Verifying the inverse matrix */
 5217: #ifdef DEBUGHESS
 5218:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
 5219: 
 5220:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
 5221:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
 5222: 
 5223:   for (j=1;j<=npar;j++) {
 5224:     for (i=1;i<=npar;i++){ 
 5225:       printf("%.2f ",y[i][j]);
 5226:       fprintf(ficlog,"%.2f ",y[i][j]);
 5227:     }
 5228:     printf("\n");
 5229:     fprintf(ficlog,"\n");
 5230:   }
 5231: #endif
 5232: 
 5233:   free_matrix(a,1,npar,1,npar);
 5234:   free_matrix(y,1,npar,1,npar);
 5235:   free_vector(x,1,npar);
 5236:   free_ivector(indx,1,npar);
 5237:   /* free_matrix(hess,1,npar,1,npar); */
 5238: 
 5239: 
 5240: }
 5241: 
 5242: /*************** hessian matrix ****************/
 5243: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
 5244: { /* Around values of x, computes the function func and returns the scales delti and hessian */
 5245:   int i;
 5246:   int l=1, lmax=20;
 5247:   double k1,k2, res, fx;
 5248:   double p2[MAXPARM+1]; /* identical to x */
 5249:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 5250:   int k=0,kmax=10;
 5251:   double l1;
 5252: 
 5253:   fx=func(x);
 5254:   for (i=1;i<=npar;i++) p2[i]=x[i];
 5255:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
 5256:     l1=pow(10,l);
 5257:     delts=delt;
 5258:     for(k=1 ; k <kmax; k=k+1){
 5259:       delt = delta*(l1*k);
 5260:       p2[theta]=x[theta] +delt;
 5261:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
 5262:       p2[theta]=x[theta]-delt;
 5263:       k2=func(p2)-fx;
 5264:       /*res= (k1-2.0*fx+k2)/delt/delt; */
 5265:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
 5266:       
 5267: #ifdef DEBUGHESSII
 5268:       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);
 5269:       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);
 5270: #endif
 5271:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
 5272:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 5273: 	k=kmax;
 5274:       }
 5275:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
 5276: 	k=kmax; l=lmax*10;
 5277:       }
 5278:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
 5279: 	delts=delt;
 5280:       }
 5281:     } /* End loop k */
 5282:   }
 5283:   delti[theta]=delts;
 5284:   return res; 
 5285:   
 5286: }
 5287: 
 5288: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
 5289: {
 5290:   int i;
 5291:   int l=1, lmax=20;
 5292:   double k1,k2,k3,k4,res,fx;
 5293:   double p2[MAXPARM+1];
 5294:   int k, kmax=1;
 5295:   double v1, v2, cv12, lc1, lc2;
 5296: 
 5297:   int firstime=0;
 5298:   
 5299:   fx=func(x);
 5300:   for (k=1; k<=kmax; k=k+10) {
 5301:     for (i=1;i<=npar;i++) p2[i]=x[i];
 5302:     p2[thetai]=x[thetai]+delti[thetai]*k;
 5303:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
 5304:     k1=func(p2)-fx;
 5305:   
 5306:     p2[thetai]=x[thetai]+delti[thetai]*k;
 5307:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
 5308:     k2=func(p2)-fx;
 5309:   
 5310:     p2[thetai]=x[thetai]-delti[thetai]*k;
 5311:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
 5312:     k3=func(p2)-fx;
 5313:   
 5314:     p2[thetai]=x[thetai]-delti[thetai]*k;
 5315:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
 5316:     k4=func(p2)-fx;
 5317:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
 5318:     if(k1*k2*k3*k4 <0.){
 5319:       firstime=1;
 5320:       kmax=kmax+10;
 5321:     }
 5322:     if(kmax >=10 || firstime ==1){
 5323:       /* What are the thetai and thetaj? thetai/ncovmodel thetai=(thetai-thetai%ncovmodel)/ncovmodel +thetai%ncovmodel=(line,pos)  */
 5324:       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);
 5325:       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);
 5326:       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);
 5327:       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);
 5328:     }
 5329: #ifdef DEBUGHESSIJ
 5330:     v1=hess[thetai][thetai];
 5331:     v2=hess[thetaj][thetaj];
 5332:     cv12=res;
 5333:     /* Computing eigen value of Hessian matrix */
 5334:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 5335:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 5336:     if ((lc2 <0) || (lc1 <0) ){
 5337:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
 5338:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
 5339:       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);
 5340:       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);
 5341:     }
 5342: #endif
 5343:   }
 5344:   return res;
 5345: }
 5346: 
 5347:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
 5348: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
 5349: /* { */
 5350: /*   int i; */
 5351: /*   int l=1, lmax=20; */
 5352: /*   double k1,k2,k3,k4,res,fx; */
 5353: /*   double p2[MAXPARM+1]; */
 5354: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
 5355: /*   int k=0,kmax=10; */
 5356: /*   double l1; */
 5357:   
 5358: /*   fx=func(x); */
 5359: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
 5360: /*     l1=pow(10,l); */
 5361: /*     delts=delt; */
 5362: /*     for(k=1 ; k <kmax; k=k+1){ */
 5363: /*       delt = delti*(l1*k); */
 5364: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
 5365: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
 5366: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
 5367: /*       k1=func(p2)-fx; */
 5368:       
 5369: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
 5370: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
 5371: /*       k2=func(p2)-fx; */
 5372:       
 5373: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
 5374: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
 5375: /*       k3=func(p2)-fx; */
 5376:       
 5377: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
 5378: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
 5379: /*       k4=func(p2)-fx; */
 5380: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
 5381: /* #ifdef DEBUGHESSIJ */
 5382: /*       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); */
 5383: /*       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); */
 5384: /* #endif */
 5385: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
 5386: /* 	k=kmax; */
 5387: /*       } */
 5388: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
 5389: /* 	k=kmax; l=lmax*10; */
 5390: /*       } */
 5391: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
 5392: /* 	delts=delt; */
 5393: /*       } */
 5394: /*     } /\* End loop k *\/ */
 5395: /*   } */
 5396: /*   delti[theta]=delts; */
 5397: /*   return res;  */
 5398: /* } */
 5399: 
 5400: 
 5401: /************** Inverse of matrix **************/
 5402: void ludcmp(double **a, int n, int *indx, double *d) 
 5403: { 
 5404:   int i,imax,j,k; 
 5405:   double big,dum,sum,temp; 
 5406:   double *vv; 
 5407:  
 5408:   vv=vector(1,n); 
 5409:   *d=1.0; 
 5410:   for (i=1;i<=n;i++) { 
 5411:     big=0.0; 
 5412:     for (j=1;j<=n;j++) 
 5413:       if ((temp=fabs(a[i][j])) > big) big=temp; 
 5414:     if (big == 0.0){
 5415:       printf(" Singular Hessian matrix at row %d:\n",i);
 5416:       for (j=1;j<=n;j++) {
 5417: 	printf(" a[%d][%d]=%f,",i,j,a[i][j]);
 5418: 	fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
 5419:       }
 5420:       fflush(ficlog);
 5421:       fclose(ficlog);
 5422:       nrerror("Singular matrix in routine ludcmp"); 
 5423:     }
 5424:     vv[i]=1.0/big; 
 5425:   } 
 5426:   for (j=1;j<=n;j++) { 
 5427:     for (i=1;i<j;i++) { 
 5428:       sum=a[i][j]; 
 5429:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
 5430:       a[i][j]=sum; 
 5431:     } 
 5432:     big=0.0; 
 5433:     for (i=j;i<=n;i++) { 
 5434:       sum=a[i][j]; 
 5435:       for (k=1;k<j;k++) 
 5436: 	sum -= a[i][k]*a[k][j]; 
 5437:       a[i][j]=sum; 
 5438:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
 5439: 	big=dum; 
 5440: 	imax=i; 
 5441:       } 
 5442:     } 
 5443:     if (j != imax) { 
 5444:       for (k=1;k<=n;k++) { 
 5445: 	dum=a[imax][k]; 
 5446: 	a[imax][k]=a[j][k]; 
 5447: 	a[j][k]=dum; 
 5448:       } 
 5449:       *d = -(*d); 
 5450:       vv[imax]=vv[j]; 
 5451:     } 
 5452:     indx[j]=imax; 
 5453:     if (a[j][j] == 0.0) a[j][j]=TINY; 
 5454:     if (j != n) { 
 5455:       dum=1.0/(a[j][j]); 
 5456:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
 5457:     } 
 5458:   } 
 5459:   free_vector(vv,1,n);  /* Doesn't work */
 5460: ;
 5461: } 
 5462: 
 5463: void lubksb(double **a, int n, int *indx, double b[]) 
 5464: { 
 5465:   int i,ii=0,ip,j; 
 5466:   double sum; 
 5467:  
 5468:   for (i=1;i<=n;i++) { 
 5469:     ip=indx[i]; 
 5470:     sum=b[ip]; 
 5471:     b[ip]=b[i]; 
 5472:     if (ii) 
 5473:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
 5474:     else if (sum) ii=i; 
 5475:     b[i]=sum; 
 5476:   } 
 5477:   for (i=n;i>=1;i--) { 
 5478:     sum=b[i]; 
 5479:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
 5480:     b[i]=sum/a[i][i]; 
 5481:   } 
 5482: } 
 5483: 
 5484: void pstamp(FILE *fichier)
 5485: {
 5486:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
 5487: }
 5488: 
 5489: void date2dmy(double date,double *day, double *month, double *year){
 5490:   double yp=0., yp1=0., yp2=0.;
 5491:   
 5492:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
 5493: 			fractional in yp1 */
 5494:   *year=yp;
 5495:   yp2=modf((yp1*12),&yp);
 5496:   *month=yp;
 5497:   yp1=modf((yp2*30.5),&yp);
 5498:   *day=yp;
 5499:   if(*day==0) *day=1;
 5500:   if(*month==0) *month=1;
 5501: }
 5502: 
 5503: 
 5504: 
 5505: /************ Frequencies ********************/
 5506: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
 5507: 		  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[],	\
 5508: 		  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
 5509: {  /* Some frequencies as well as proposing some starting values */
 5510:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
 5511:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
 5512:   int iind=0, iage=0;
 5513:   int mi; /* Effective wave */
 5514:   int first;
 5515:   double ***freq; /* Frequencies */
 5516:   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 */
 5517:   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);
 5518:   double *meanq, *stdq, *idq;
 5519:   double **meanqt;
 5520:   double *pp, **prop, *posprop, *pospropt;
 5521:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
 5522:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
 5523:   double agebegin, ageend;
 5524:     
 5525:   pp=vector(1,nlstate);
 5526:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
 5527:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
 5528:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
 5529:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
 5530:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
 5531:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
 5532:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
 5533:   meanqt=matrix(1,lastpass,1,nqtveff);
 5534:   strcpy(fileresp,"P_");
 5535:   strcat(fileresp,fileresu);
 5536:   /*strcat(fileresphtm,fileresu);*/
 5537:   if((ficresp=fopen(fileresp,"w"))==NULL) {
 5538:     printf("Problem with prevalence resultfile: %s\n", fileresp);
 5539:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
 5540:     exit(0);
 5541:   }
 5542:   
 5543:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
 5544:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
 5545:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
 5546:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
 5547:     fflush(ficlog);
 5548:     exit(70); 
 5549:   }
 5550:   else{
 5551:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 5552: <hr size=\"2\" color=\"#EC5E5E\"> \n					\
 5553: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
 5554: 	    fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 5555:   }
 5556:   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);
 5557:   
 5558:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
 5559:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
 5560:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
 5561:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
 5562:     fflush(ficlog);
 5563:     exit(70); 
 5564:   } else{
 5565:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 5566: ,<hr size=\"2\" color=\"#EC5E5E\"> \n					\
 5567: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
 5568: 	    fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 5569:   }
 5570:   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);
 5571:   
 5572:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
 5573:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
 5574:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
 5575:   j1=0;
 5576:   
 5577:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
 5578:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
 5579:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
 5580:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 5581:   
 5582:   
 5583:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
 5584:      reference=low_education V1=0,V2=0
 5585:      med_educ                V1=1 V2=0, 
 5586:      high_educ               V1=0 V2=1
 5587:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
 5588:   */
 5589:   dateintsum=0;
 5590:   k2cpt=0;
 5591: 
 5592:   if(cptcoveff == 0 )
 5593:     nl=1;  /* Constant and age model only */
 5594:   else
 5595:     nl=2;
 5596: 
 5597:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
 5598:   /* Loop on nj=1 or 2 if dummy covariates j!=0
 5599:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
 5600:    *     freq[s1][s2][iage] =0.
 5601:    *     Loop on iind
 5602:    *       ++freq[s1][s2][iage] weighted
 5603:    *     end iind
 5604:    *     if covariate and j!0
 5605:    *       headers Variable on one line
 5606:    *     endif cov j!=0
 5607:    *     header of frequency table by age
 5608:    *     Loop on age
 5609:    *       pp[s1]+=freq[s1][s2][iage] weighted
 5610:    *       pos+=freq[s1][s2][iage] weighted
 5611:    *       Loop on s1 initial state
 5612:    *         fprintf(ficresp
 5613:    *       end s1
 5614:    *     end age
 5615:    *     if j!=0 computes starting values
 5616:    *     end compute starting values
 5617:    *   end j1
 5618:    * end nl 
 5619:    */
 5620:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
 5621:     if(nj==1)
 5622:       j=0;  /* First pass for the constant */
 5623:     else{
 5624:       j=cptcoveff; /* Other passes for the covariate values number of simple covariates in the model V2+V1 =2 (simple dummy fixed or time varying) */
 5625:     }
 5626:     first=1;
 5627:     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 */
 5628:       posproptt=0.;
 5629:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
 5630: 	scanf("%d", i);*/
 5631:       for (i=-5; i<=nlstate+ndeath; i++)  
 5632: 	for (s2=-5; s2<=nlstate+ndeath; s2++)  
 5633: 	  for(m=iagemin; m <= iagemax+3; m++)
 5634: 	    freq[i][s2][m]=0;
 5635:       
 5636:       for (i=1; i<=nlstate; i++)  {
 5637: 	for(m=iagemin; m <= iagemax+3; m++)
 5638: 	  prop[i][m]=0;
 5639: 	posprop[i]=0;
 5640: 	pospropt[i]=0;
 5641:       }
 5642:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
 5643:         idq[z1]=0.;
 5644:         meanq[z1]=0.;
 5645:         stdq[z1]=0.;
 5646:       }
 5647:       /* for (z1=1; z1<= nqtveff; z1++) { */
 5648:       /*   for(m=1;m<=lastpass;m++){ */
 5649:       /* 	  meanqt[m][z1]=0.; */
 5650:       /* 	} */
 5651:       /* }       */
 5652:       /* dateintsum=0; */
 5653:       /* k2cpt=0; */
 5654:       
 5655:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
 5656:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
 5657: 	bool=1;
 5658: 	if(j !=0){
 5659: 	  if(anyvaryingduminmodel==0){ /* If All fixed covariates */
 5660: 	    if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
 5661: 	      for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
 5662: 		/* if(Tvaraff[z1] ==-20){ */
 5663: 		/* 	 /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
 5664: 		/* }else  if(Tvaraff[z1] ==-10){ */
 5665: 		/* 	 /\* sumnew+=coqvar[z1][iind]; *\/ */
 5666: 		/* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
 5667: 		/* 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); */
 5668: 		if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
 5669: 		  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
 5670: 		if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
 5671: 		  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
 5672: 		  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
 5673: 		  /* 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", */
 5674: 		  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
 5675:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
 5676: 		  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
 5677: 		} /* Onlyf fixed */
 5678: 	      } /* end z1 */
 5679: 	    } /* cptcoveff > 0 */
 5680: 	  } /* end any */
 5681: 	}/* end j==0 */
 5682: 	if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
 5683: 	  /* for(m=firstpass; m<=lastpass; m++){ */
 5684: 	  for(mi=1; mi<wav[iind];mi++){ /* For each wave */
 5685: 	    m=mw[mi][iind];
 5686: 	    if(j!=0){
 5687: 	      if(anyvaryingduminmodel==1){ /* Some are varying covariates */
 5688: 		for (z1=1; z1<=cptcoveff; z1++) {
 5689: 		  if( Fixed[Tmodelind[z1]]==1){
 5690: 		    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
 5691: 		    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
 5692: 		    if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality. If covariate's 
 5693: 										      value is -1, we don't select. It differs from the 
 5694: 										      constant and age model which counts them. */
 5695: 		      bool=0; /* not selected */
 5696: 		  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
 5697: 		    /* i1=Tvaraff[z1]; */
 5698: 		    /* i2=TnsdVar[i1]; */
 5699: 		    /* i3=nbcode[i1][i2]; */
 5700: 		    /* i4=covar[i1][iind]; */
 5701: 		    /* if(i4 != i3){ */
 5702: 		    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
 5703: 		      bool=0;
 5704: 		    }
 5705: 		  }
 5706: 		}
 5707: 	      }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
 5708: 	    } /* end j==0 */
 5709: 	    /* bool =0 we keep that guy which corresponds to the combination of dummy values */
 5710: 	    if(bool==1){ /*Selected */
 5711: 	      /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
 5712: 		 and mw[mi+1][iind]. dh depends on stepm. */
 5713: 	      agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
 5714: 	      ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
 5715: 	      if(m >=firstpass && m <=lastpass){
 5716: 		k2=anint[m][iind]+(mint[m][iind]/12.);
 5717: 		/*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
 5718: 		if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
 5719: 		if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
 5720: 		if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
 5721: 		  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
 5722: 		if (m<lastpass) {
 5723: 		  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
 5724: 		  /*   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]); */
 5725: 		  if(s[m][iind]==-1)
 5726: 		    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.));
 5727: 		  freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
 5728: 		  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
 5729: 		    if(!isnan(covar[ncovcol+z1][iind])){
 5730: 		      idq[z1]=idq[z1]+weight[iind];
 5731: 		      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
 5732: 		      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
 5733: 		      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
 5734: 		    }
 5735: 		  }
 5736: 		  /* if((int)agev[m][iind] == 55) */
 5737: 		  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
 5738: 		  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
 5739: 		  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 */
 5740: 		}
 5741: 	      } /* end if between passes */  
 5742: 	      if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
 5743: 		dateintsum=dateintsum+k2; /* on all covariates ?*/
 5744: 		k2cpt++;
 5745: 		/* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
 5746: 	      }
 5747: 	    }else{
 5748: 	      bool=1;
 5749: 	    }/* end bool 2 */
 5750: 	  } /* end m */
 5751: 	  /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
 5752: 	  /*   idq[z1]=idq[z1]+weight[iind]; */
 5753: 	  /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
 5754: 	  /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
 5755: 	  /* } */
 5756: 	} /* end bool */
 5757:       } /* end iind = 1 to imx */
 5758:       /* prop[s][age] is fed for any initial and valid live state as well as
 5759: 	 freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
 5760:       
 5761:       
 5762:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 5763:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
 5764:         pstamp(ficresp);
 5765:       if  (cptcoveff>0 && j!=0){
 5766:         pstamp(ficresp);
 5767: 	printf( "\n#********** Variable "); 
 5768: 	fprintf(ficresp, "\n#********** Variable "); 
 5769: 	fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
 5770: 	fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
 5771: 	fprintf(ficlog, "\n#********** Variable "); 
 5772: 	for (z1=1; z1<=cptcoveff; z1++){
 5773: 	  if(!FixedV[Tvaraff[z1]]){
 5774: 	    printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
 5775: 	    fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
 5776: 	    fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
 5777: 	    fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
 5778: 	    fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
 5779: 	  }else{
 5780: 	    printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
 5781: 	    fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
 5782: 	    fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
 5783: 	    fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
 5784: 	    fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
 5785: 	  }
 5786: 	}
 5787: 	printf( "**********\n#");
 5788: 	fprintf(ficresp, "**********\n#");
 5789: 	fprintf(ficresphtm, "**********</h3>\n");
 5790: 	fprintf(ficresphtmfr, "**********</h3>\n");
 5791: 	fprintf(ficlog, "**********\n");
 5792:       }
 5793:       /*
 5794: 	Printing means of quantitative variables if any
 5795:       */
 5796:       for (z1=1; z1<= nqfveff; z1++) {
 5797: 	fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
 5798: 	fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
 5799: 	if(weightopt==1){
 5800: 	  printf(" Weighted mean and standard deviation of");
 5801: 	  fprintf(ficlog," Weighted mean and standard deviation of");
 5802: 	  fprintf(ficresphtmfr," Weighted mean and standard deviation of");
 5803: 	}
 5804: 	/* mu = \frac{w x}{\sum w}
 5805:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
 5806: 	*/
 5807: 	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]));
 5808: 	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]));
 5809: 	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]));
 5810:       }
 5811:       /* for (z1=1; z1<= nqtveff; z1++) { */
 5812:       /* 	for(m=1;m<=lastpass;m++){ */
 5813:       /* 	  fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
 5814:       /*   } */
 5815:       /* } */
 5816: 
 5817:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
 5818:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
 5819:         fprintf(ficresp, " Age");
 5820:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
 5821: 	  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]]);
 5822: 	  fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
 5823: 	}
 5824:       for(i=1; i<=nlstate;i++) {
 5825: 	if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
 5826: 	fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
 5827:       }
 5828:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
 5829:       fprintf(ficresphtm, "\n");
 5830:       
 5831:       /* Header of frequency table by age */
 5832:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
 5833:       fprintf(ficresphtmfr,"<th>Age</th> ");
 5834:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
 5835: 	for(m=-1; m <=nlstate+ndeath; m++){
 5836: 	  if(s2!=0 && m!=0)
 5837: 	    fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
 5838: 	}
 5839:       }
 5840:       fprintf(ficresphtmfr, "\n");
 5841:     
 5842:       /* For each age */
 5843:       for(iage=iagemin; iage <= iagemax+3; iage++){
 5844: 	fprintf(ficresphtm,"<tr>");
 5845: 	if(iage==iagemax+1){
 5846: 	  fprintf(ficlog,"1");
 5847: 	  fprintf(ficresphtmfr,"<tr><th>0</th> ");
 5848: 	}else if(iage==iagemax+2){
 5849: 	  fprintf(ficlog,"0");
 5850: 	  fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
 5851: 	}else if(iage==iagemax+3){
 5852: 	  fprintf(ficlog,"Total");
 5853: 	  fprintf(ficresphtmfr,"<tr><th>Total</th> ");
 5854: 	}else{
 5855: 	  if(first==1){
 5856: 	    first=0;
 5857: 	    printf("See log file for details...\n");
 5858: 	  }
 5859: 	  fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
 5860: 	  fprintf(ficlog,"Age %d", iage);
 5861: 	}
 5862: 	for(s1=1; s1 <=nlstate ; s1++){
 5863: 	  for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
 5864: 	    pp[s1] += freq[s1][m][iage]; 
 5865: 	}
 5866: 	for(s1=1; s1 <=nlstate ; s1++){
 5867: 	  for(m=-1, pos=0; m <=0 ; m++)
 5868: 	    pos += freq[s1][m][iage];
 5869: 	  if(pp[s1]>=1.e-10){
 5870: 	    if(first==1){
 5871: 	      printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
 5872: 	    }
 5873: 	    fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
 5874: 	  }else{
 5875: 	    if(first==1)
 5876: 	      printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
 5877: 	    fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
 5878: 	  }
 5879: 	}
 5880:       
 5881: 	for(s1=1; s1 <=nlstate ; s1++){ 
 5882: 	  /* posprop[s1]=0; */
 5883: 	  for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
 5884: 	    pp[s1] += freq[s1][m][iage];
 5885: 	}	/* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
 5886:       
 5887: 	for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
 5888: 	  pos += pp[s1]; /* pos is the total number of transitions until this age */
 5889: 	  posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
 5890: 					    from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
 5891: 	  pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
 5892: 					  from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
 5893: 	}
 5894: 	
 5895: 	/* Writing ficresp */
 5896: 	if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
 5897:           if( iage <= iagemax){
 5898: 	    fprintf(ficresp," %d",iage);
 5899:           }
 5900:         }else if( nj==2){
 5901:           if( iage <= iagemax){
 5902: 	    fprintf(ficresp," %d",iage);
 5903:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
 5904:           }
 5905: 	}
 5906: 	for(s1=1; s1 <=nlstate ; s1++){
 5907: 	  if(pos>=1.e-5){
 5908: 	    if(first==1)
 5909: 	      printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
 5910: 	    fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
 5911: 	  }else{
 5912: 	    if(first==1)
 5913: 	      printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
 5914: 	    fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
 5915: 	  }
 5916: 	  if( iage <= iagemax){
 5917: 	    if(pos>=1.e-5){
 5918: 	      if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
 5919: 	        fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
 5920:               }else if( nj==2){
 5921: 	        fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
 5922:               }
 5923: 	      fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
 5924: 	      /*probs[iage][s1][j1]= pp[s1]/pos;*/
 5925: 	      /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
 5926: 	    } else{
 5927: 	      if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
 5928: 	      fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
 5929: 	    }
 5930: 	  }
 5931: 	  pospropt[s1] +=posprop[s1];
 5932: 	} /* end loop s1 */
 5933: 	/* pospropt=0.; */
 5934: 	for(s1=-1; s1 <=nlstate+ndeath; s1++){
 5935: 	  for(m=-1; m <=nlstate+ndeath; m++){
 5936: 	    if(freq[s1][m][iage] !=0 ) { /* minimizing output */
 5937: 	      if(first==1){
 5938: 		printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
 5939: 	      }
 5940: 	      /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
 5941: 	      fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
 5942: 	    }
 5943: 	    if(s1!=0 && m!=0)
 5944: 	      fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
 5945: 	  }
 5946: 	} /* end loop s1 */
 5947: 	posproptt=0.; 
 5948: 	for(s1=1; s1 <=nlstate; s1++){
 5949: 	  posproptt += pospropt[s1];
 5950: 	}
 5951: 	fprintf(ficresphtmfr,"</tr>\n ");
 5952: 	fprintf(ficresphtm,"</tr>\n");
 5953: 	if((cptcoveff==0 && nj==1)|| nj==2 ) {
 5954: 	  if(iage <= iagemax)
 5955:  	    fprintf(ficresp,"\n");
 5956: 	}
 5957: 	if(first==1)
 5958: 	  printf("Others in log...\n");
 5959: 	fprintf(ficlog,"\n");
 5960:       } /* end loop age iage */
 5961:       
 5962:       fprintf(ficresphtm,"<tr><th>Tot</th>");
 5963:       for(s1=1; s1 <=nlstate ; s1++){
 5964: 	if(posproptt < 1.e-5){
 5965: 	  fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt);	
 5966: 	}else{
 5967: 	  fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);	
 5968: 	}
 5969:       }
 5970:       fprintf(ficresphtm,"</tr>\n");
 5971:       fprintf(ficresphtm,"</table>\n");
 5972:       fprintf(ficresphtmfr,"</table>\n");
 5973:       if(posproptt < 1.e-5){
 5974: 	fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
 5975: 	fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
 5976: 	fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
 5977: 	printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
 5978: 	invalidvarcomb[j1]=1;
 5979:       }else{
 5980: 	fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
 5981: 	invalidvarcomb[j1]=0;
 5982:       }
 5983:       fprintf(ficresphtmfr,"</table>\n");
 5984:       fprintf(ficlog,"\n");
 5985:       if(j!=0){
 5986: 	printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
 5987: 	for(i=1,s1=1; i <=nlstate; i++){
 5988: 	  for(k=1; k <=(nlstate+ndeath); k++){
 5989: 	    if (k != i) {
 5990: 	      for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
 5991: 		if(jj==1){  /* Constant case (in fact cste + age) */
 5992: 		  if(j1==1){ /* All dummy covariates to zero */
 5993: 		    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
 5994: 		    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
 5995: 		    printf("%d%d ",i,k);
 5996: 		    fprintf(ficlog,"%d%d ",i,k);
 5997: 		    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]));
 5998: 		    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]));
 5999: 		    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
 6000: 		  }
 6001: 		}else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
 6002: 		  for(iage=iagemin; iage <= iagemax+3; iage++){
 6003: 		    x[iage]= (double)iage;
 6004: 		    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
 6005: 		    /* printf("i=%d, k=%d, s1=%d, j1=%d, jj=%d, y[%d]=%f\n",i,k,s1,j1,jj, iage, y[iage]); */
 6006: 		  }
 6007: 		  /* Some are not finite, but linreg will ignore these ages */
 6008: 		  no=0;
 6009: 		  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
 6010: 		  pstart[s1]=b;
 6011: 		  pstart[s1-1]=a;
 6012: 		}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 */ 
 6013: 		  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]);
 6014: 		  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]);
 6015: 		  pstart[s1]= log((freq[i][k][iagemax+3]/freq[i][i][iagemax+3])/(freq[i][k][iagemax+4]/freq[i][i][iagemax+4]));
 6016: 		  printf("%d%d ",i,k);
 6017: 		  fprintf(ficlog,"%d%d ",i,k);
 6018: 		  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]));
 6019: 		}else{ /* Other cases, like quantitative fixed or varying covariates */
 6020: 		  ;
 6021: 		}
 6022: 		/* printf("%12.7f )", param[i][jj][k]); */
 6023: 		/* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
 6024: 		s1++; 
 6025: 	      } /* end jj */
 6026: 	    } /* end k!= i */
 6027: 	  } /* end k */
 6028: 	} /* end i, s1 */
 6029:       } /* end j !=0 */
 6030:     } /* end selected combination of covariate j1 */
 6031:     if(j==0){ /* We can estimate starting values from the occurences in each case */
 6032:       printf("#Freqsummary: Starting values for the constants:\n");
 6033:       fprintf(ficlog,"\n");
 6034:       for(i=1,s1=1; i <=nlstate; i++){
 6035: 	for(k=1; k <=(nlstate+ndeath); k++){
 6036: 	  if (k != i) {
 6037: 	    printf("%d%d ",i,k);
 6038: 	    fprintf(ficlog,"%d%d ",i,k);
 6039: 	    for(jj=1; jj <=ncovmodel; jj++){
 6040: 	      pstart[s1]=p[s1]; /* Setting pstart to p values by default */
 6041: 	      if(jj==1){ /* Age has to be done */
 6042: 		pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
 6043: 		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]));
 6044: 		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]));
 6045: 	      }
 6046: 	      /* printf("%12.7f )", param[i][jj][k]); */
 6047: 	      /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
 6048: 	      s1++; 
 6049: 	    }
 6050: 	    printf("\n");
 6051: 	    fprintf(ficlog,"\n");
 6052: 	  }
 6053: 	}
 6054:       } /* end of state i */
 6055:       printf("#Freqsummary\n");
 6056:       fprintf(ficlog,"\n");
 6057:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
 6058: 	for(s2=-1; s2 <=nlstate+ndeath; s2++){
 6059: 	  /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
 6060: 	  printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
 6061: 	  fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
 6062: 	  /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
 6063: 	  /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
 6064: 	  /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
 6065: 	  /* } */
 6066: 	}
 6067:       } /* end loop s1 */
 6068:       
 6069:       printf("\n");
 6070:       fprintf(ficlog,"\n");
 6071:     } /* end j=0 */
 6072:   } /* end j */
 6073: 
 6074:   if(mle == -2){  /* We want to use these values as starting values */
 6075:     for(i=1, jk=1; i <=nlstate; i++){
 6076:       for(j=1; j <=nlstate+ndeath; j++){
 6077: 	if(j!=i){
 6078: 	  /*ca[0]= k+'a'-1;ca[1]='\0';*/
 6079: 	  printf("%1d%1d",i,j);
 6080: 	  fprintf(ficparo,"%1d%1d",i,j);
 6081: 	  for(k=1; k<=ncovmodel;k++){
 6082: 	    /* 	  printf(" %lf",param[i][j][k]); */
 6083: 	    /* 	  fprintf(ficparo," %lf",param[i][j][k]); */
 6084: 	    p[jk]=pstart[jk];
 6085: 	    printf(" %f ",pstart[jk]);
 6086: 	    fprintf(ficparo," %f ",pstart[jk]);
 6087: 	    jk++;
 6088: 	  }
 6089: 	  printf("\n");
 6090: 	  fprintf(ficparo,"\n");
 6091: 	}
 6092:       }
 6093:     }
 6094:   } /* end mle=-2 */
 6095:   dateintmean=dateintsum/k2cpt; 
 6096:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
 6097:   
 6098:   fclose(ficresp);
 6099:   fclose(ficresphtm);
 6100:   fclose(ficresphtmfr);
 6101:   free_vector(idq,1,nqfveff);
 6102:   free_vector(meanq,1,nqfveff);
 6103:   free_vector(stdq,1,nqfveff);
 6104:   free_matrix(meanqt,1,lastpass,1,nqtveff);
 6105:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
 6106:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
 6107:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
 6108:   free_vector(pospropt,1,nlstate);
 6109:   free_vector(posprop,1,nlstate);
 6110:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
 6111:   free_vector(pp,1,nlstate);
 6112:   /* End of freqsummary */
 6113: }
 6114: 
 6115: /* Simple linear regression */
 6116: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
 6117: 
 6118:   /* y=a+bx regression */
 6119:   double   sumx = 0.0;                        /* sum of x                      */
 6120:   double   sumx2 = 0.0;                       /* sum of x**2                   */
 6121:   double   sumxy = 0.0;                       /* sum of x * y                  */
 6122:   double   sumy = 0.0;                        /* sum of y                      */
 6123:   double   sumy2 = 0.0;                       /* sum of y**2                   */
 6124:   double   sume2 = 0.0;                       /* sum of square or residuals */
 6125:   double yhat;
 6126:   
 6127:   double denom=0;
 6128:   int i;
 6129:   int ne=*no;
 6130:   
 6131:   for ( i=ifi, ne=0;i<=ila;i++) {
 6132:     if(!isfinite(x[i]) || !isfinite(y[i])){
 6133:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
 6134:       continue;
 6135:     }
 6136:     ne=ne+1;
 6137:     sumx  += x[i];       
 6138:     sumx2 += x[i]*x[i];  
 6139:     sumxy += x[i] * y[i];
 6140:     sumy  += y[i];      
 6141:     sumy2 += y[i]*y[i]; 
 6142:     denom = (ne * sumx2 - sumx*sumx);
 6143:     /* 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); */
 6144:   } 
 6145:   
 6146:   denom = (ne * sumx2 - sumx*sumx);
 6147:   if (denom == 0) {
 6148:     // vertical, slope m is infinity
 6149:     *b = INFINITY;
 6150:     *a = 0;
 6151:     if (r) *r = 0;
 6152:     return 1;
 6153:   }
 6154:   
 6155:   *b = (ne * sumxy  -  sumx * sumy) / denom;
 6156:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
 6157:   if (r!=NULL) {
 6158:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
 6159:       sqrt((sumx2 - sumx*sumx/ne) *
 6160: 	   (sumy2 - sumy*sumy/ne));
 6161:   }
 6162:   *no=ne;
 6163:   for ( i=ifi, ne=0;i<=ila;i++) {
 6164:     if(!isfinite(x[i]) || !isfinite(y[i])){
 6165:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
 6166:       continue;
 6167:     }
 6168:     ne=ne+1;
 6169:     yhat = y[i] - *a -*b* x[i];
 6170:     sume2  += yhat * yhat ;       
 6171:     
 6172:     denom = (ne * sumx2 - sumx*sumx);
 6173:     /* 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); */
 6174:   } 
 6175:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
 6176:   *sa= *sb * sqrt(sumx2/ne);
 6177:   
 6178:   return 0; 
 6179: }
 6180: 
 6181: /************ Prevalence ********************/
 6182: 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)
 6183: {  
 6184:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 6185:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 6186:      We still use firstpass and lastpass as another selection.
 6187:   */
 6188:  
 6189:   int i, m, jk, j1, bool, z1,j, iv;
 6190:   int mi; /* Effective wave */
 6191:   int iage;
 6192:   double agebegin, ageend;
 6193: 
 6194:   double **prop;
 6195:   double posprop; 
 6196:   double  y2; /* in fractional years */
 6197:   int iagemin, iagemax;
 6198:   int first; /** to stop verbosity which is redirected to log file */
 6199: 
 6200:   iagemin= (int) agemin;
 6201:   iagemax= (int) agemax;
 6202:   /*pp=vector(1,nlstate);*/
 6203:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
 6204:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
 6205:   j1=0;
 6206:   
 6207:   /*j=cptcoveff;*/
 6208:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 6209:   
 6210:   first=0;
 6211:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
 6212:     for (i=1; i<=nlstate; i++)  
 6213:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
 6214: 	prop[i][iage]=0.0;
 6215:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
 6216:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
 6217:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
 6218:     
 6219:     for (i=1; i<=imx; i++) { /* Each individual */
 6220:       bool=1;
 6221:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
 6222:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
 6223: 	m=mw[mi][i];
 6224: 	/* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
 6225: 	/* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
 6226: 	for (z1=1; z1<=cptcoveff; z1++){
 6227: 	  if( Fixed[Tmodelind[z1]]==1){
 6228: 	    iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
 6229: 	    if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
 6230: 	      bool=0;
 6231: 	  }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
 6232: 	    if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
 6233: 	      bool=0;
 6234: 	    }
 6235: 	}
 6236: 	if(bool==1){ /* Otherwise we skip that wave/person */
 6237: 	  agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
 6238: 	  /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
 6239: 	  if(m >=firstpass && m <=lastpass){
 6240: 	    y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
 6241: 	    if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
 6242: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 6243: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 6244: 	      if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
 6245: 		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); 
 6246: 		exit(1);
 6247: 	      }
 6248: 	      if (s[m][i]>0 && s[m][i]<=nlstate) { 
 6249: 		/*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]]);*/
 6250: 		prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
 6251: 		prop[s[m][i]][iagemax+3] += weight[i]; 
 6252: 	      } /* end valid statuses */ 
 6253: 	    } /* end selection of dates */
 6254: 	  } /* end selection of waves */
 6255: 	} /* end bool */
 6256:       } /* end wave */
 6257:     } /* end individual */
 6258:     for(i=iagemin; i <= iagemax+3; i++){  
 6259:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
 6260: 	posprop += prop[jk][i]; 
 6261:       } 
 6262:       
 6263:       for(jk=1; jk <=nlstate ; jk++){	    
 6264: 	if( i <=  iagemax){ 
 6265: 	  if(posprop>=1.e-5){ 
 6266: 	    probs[i][jk][j1]= prop[jk][i]/posprop;
 6267: 	  } else{
 6268: 	    if(!first){
 6269: 	      first=1;
 6270: 	      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]);
 6271: 	    }else{
 6272: 	      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]);
 6273: 	    }
 6274: 	  }
 6275: 	} 
 6276:       }/* end jk */ 
 6277:     }/* end i */ 
 6278:      /*} *//* end i1 */
 6279:   } /* end j1 */
 6280:   
 6281:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
 6282:   /*free_vector(pp,1,nlstate);*/
 6283:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
 6284: }  /* End of prevalence */
 6285: 
 6286: /************* Waves Concatenation ***************/
 6287: 
 6288: 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)
 6289: {
 6290:   /* Concatenates waves: wav[i] is the number of effective (useful waves in the sense that a non interview is useless) of individual i.
 6291:      Death is a valid wave (if date is known).
 6292:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
 6293:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 6294:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
 6295:   */
 6296: 
 6297:   int i=0, mi=0, m=0, mli=0;
 6298:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
 6299:      double sum=0., jmean=0.;*/
 6300:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
 6301:   int j, k=0,jk, ju, jl;
 6302:   double sum=0.;
 6303:   first=0;
 6304:   firstwo=0;
 6305:   firsthree=0;
 6306:   firstfour=0;
 6307:   jmin=100000;
 6308:   jmax=-1;
 6309:   jmean=0.;
 6310: 
 6311: /* Treating live states */
 6312:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
 6313:     mi=0;  /* First valid wave */
 6314:     mli=0; /* Last valid wave */
 6315:     m=firstpass;  /* Loop on waves */
 6316:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
 6317:       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 */
 6318: 	mli=m-1;/* mw[++mi][i]=m-1; */
 6319:       }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 */
 6320: 	mw[++mi][i]=m; /* Valid wave: incrementing mi and updating mi; mw[mi] is the wave number of mi_th valid transition   */
 6321: 	mli=m;
 6322:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
 6323:       if(m < lastpass){ /* m < lastpass, standard case */
 6324: 	m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
 6325:       }
 6326:       else{ /* m = lastpass, eventual special issue with warning */
 6327: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
 6328: 	break;
 6329: #else
 6330: 	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 */
 6331: 	  if(firsthree == 0){
 6332: 	    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);
 6333: 	    firsthree=1;
 6334: 	  }else if(firsthree >=1 && firsthree < 10){
 6335: 	    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);
 6336: 	    firsthree++;
 6337: 	  }else if(firsthree == 10){
 6338: 	    printf("Information, too many Information flags: no more reported to log either\n");
 6339: 	    fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
 6340: 	    firsthree++;
 6341: 	  }else{
 6342: 	    firsthree++;
 6343: 	  }
 6344: 	  mw[++mi][i]=m; /* Valid transition with unknown status */
 6345: 	  mli=m;
 6346: 	}
 6347: 	if(s[m][i]==-2){ /* Vital status is really unknown */
 6348: 	  nbwarn++;
 6349: 	  if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
 6350: 	    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);
 6351: 	    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);
 6352: 	  }
 6353: 	  break;
 6354: 	}
 6355: 	break;
 6356: #endif
 6357:       }/* End m >= lastpass */
 6358:     }/* end while */
 6359: 
 6360:     /* mi is the last effective wave, m is lastpass, mw[j][i] gives the # of j-th effective wave for individual i */
 6361:     /* After last pass */
 6362: /* Treating death states */
 6363:     if (s[m][i] > nlstate){  /* In a death state */
 6364:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
 6365:       /* } */
 6366:       mi++;	/* Death is another wave */
 6367:       /* if(mi==0)  never been interviewed correctly before death */
 6368:       /* Only death is a correct wave */
 6369:       mw[mi][i]=m;
 6370:     } /* else not in a death state */
 6371: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
 6372:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
 6373:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
 6374: 	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 */
 6375: 	  nbwarn++;
 6376: 	  if(firstfiv==0){
 6377: 	    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 );
 6378: 	    firstfiv=1;
 6379: 	  }else{
 6380: 	    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 );
 6381: 	  }
 6382: 	    s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
 6383: 	}else{ /* Month of Death occured afer last wave month, potential bias */
 6384: 	  nberr++;
 6385: 	  if(firstwo==0){
 6386: 	    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 );
 6387: 	    firstwo=1;
 6388: 	  }
 6389: 	  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 );
 6390: 	}
 6391:       }else{ /* if date of interview is unknown */
 6392: 	/* death is known but not confirmed by death status at any wave */
 6393: 	if(firstfour==0){
 6394: 	  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 );
 6395: 	  firstfour=1;
 6396: 	}
 6397: 	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 );
 6398:       }
 6399:     } /* end if date of death is known */
 6400: #endif
 6401:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
 6402:     /* wav[i]=mw[mi][i];   */
 6403:     if(mi==0){
 6404:       nbwarn++;
 6405:       if(first==0){
 6406: 	printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
 6407: 	first=1;
 6408:       }
 6409:       if(first==1){
 6410: 	fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
 6411:       }
 6412:     } /* end mi==0 */
 6413:   } /* End individuals */
 6414:   /* wav and mw are no more changed */
 6415: 	
 6416:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
 6417:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
 6418: 
 6419: 
 6420:   for(i=1; i<=imx; i++){
 6421:     for(mi=1; mi<wav[i];mi++){
 6422:       if (stepm <=0)
 6423: 	dh[mi][i]=1;
 6424:       else{
 6425: 	if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
 6426: 	  if (agedc[i] < 2*AGESUP) {
 6427: 	    j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
 6428: 	    if(j==0) j=1;  /* Survives at least one month after exam */
 6429: 	    else if(j<0){
 6430: 	      nberr++;
 6431: 	      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]);
 6432: 	      j=1; /* Temporary Dangerous patch */
 6433: 	      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);
 6434: 	      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]);
 6435: 	      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);
 6436: 	    }
 6437: 	    k=k+1;
 6438: 	    if (j >= jmax){
 6439: 	      jmax=j;
 6440: 	      ijmax=i;
 6441: 	    }
 6442: 	    if (j <= jmin){
 6443: 	      jmin=j;
 6444: 	      ijmin=i;
 6445: 	    }
 6446: 	    sum=sum+j;
 6447: 	    /*if (j<0) printf("j=%d num=%d \n",j,i);*/
 6448: 	    /*	  printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
 6449: 	  }
 6450: 	}
 6451: 	else{
 6452: 	  j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 6453: /* 	  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]); */
 6454: 					
 6455: 	  k=k+1;
 6456: 	  if (j >= jmax) {
 6457: 	    jmax=j;
 6458: 	    ijmax=i;
 6459: 	  }
 6460: 	  else if (j <= jmin){
 6461: 	    jmin=j;
 6462: 	    ijmin=i;
 6463: 	  }
 6464: 	  /*	    if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
 6465: 	  /*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]);*/
 6466: 	  if(j<0){
 6467: 	    nberr++;
 6468: 	    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]);
 6469: 	    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]);
 6470: 	  }
 6471: 	  sum=sum+j;
 6472: 	}
 6473: 	jk= j/stepm;
 6474: 	jl= j -jk*stepm;
 6475: 	ju= j -(jk+1)*stepm;
 6476: 	if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
 6477: 	  if(jl==0){
 6478: 	    dh[mi][i]=jk;
 6479: 	    bh[mi][i]=0;
 6480: 	  }else{ /* We want a negative bias in order to only have interpolation ie
 6481: 		  * to avoid the price of an extra matrix product in likelihood */
 6482: 	    dh[mi][i]=jk+1;
 6483: 	    bh[mi][i]=ju;
 6484: 	  }
 6485: 	}else{
 6486: 	  if(jl <= -ju){
 6487: 	    dh[mi][i]=jk;
 6488: 	    bh[mi][i]=jl;	/* bias is positive if real duration
 6489: 				 * is higher than the multiple of stepm and negative otherwise.
 6490: 				 */
 6491: 	  }
 6492: 	  else{
 6493: 	    dh[mi][i]=jk+1;
 6494: 	    bh[mi][i]=ju;
 6495: 	  }
 6496: 	  if(dh[mi][i]==0){
 6497: 	    dh[mi][i]=1; /* At least one step */
 6498: 	    bh[mi][i]=ju; /* At least one step */
 6499: 	    /*  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);*/
 6500: 	  }
 6501: 	} /* end if mle */
 6502:       }
 6503:     } /* end wave */
 6504:   }
 6505:   jmean=sum/k;
 6506:   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);
 6507:   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);
 6508: }
 6509: 
 6510: /*********** Tricode ****************************/
 6511:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
 6512:  {
 6513:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
 6514:    /*	  Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
 6515:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
 6516:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
 6517:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
 6518:     */
 6519: 
 6520:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
 6521:    int modmaxcovj=0; /* Modality max of covariates j */
 6522:    int cptcode=0; /* Modality max of covariates j */
 6523:    int modmincovj=0; /* Modality min of covariates j */
 6524: 
 6525: 
 6526:    /* cptcoveff=0;  */
 6527:    /* *cptcov=0; */
 6528:  
 6529:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
 6530:    for (k=1; k <= maxncov; k++)
 6531:      for(j=1; j<=2; j++)
 6532:        nbcode[k][j]=0; /* Valgrind */
 6533: 
 6534:    /* Loop on covariates without age and products and no quantitative variable */
 6535:    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 */
 6536:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
 6537:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
 6538:      if(Dummy[k]==0 && Typevar[k] !=1 && Typevar[k] != 3  && Typevar[k] != 2){ /* Dummy covariate and not age product nor fixed product */ 
 6539:        switch(Fixed[k]) {
 6540:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
 6541: 	 modmaxcovj=0;
 6542: 	 modmincovj=0;
 6543: 	 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*/
 6544: 	   /* 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])); */
 6545: 	   ij=(int)(covar[Tvar[k]][i]);
 6546: 	   /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
 6547: 	    * If product of Vn*Vm, still boolean *:
 6548: 	    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
 6549: 	    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
 6550: 	   /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
 6551: 	      modality of the nth covariate of individual i. */
 6552: 	   if (ij > modmaxcovj)
 6553: 	     modmaxcovj=ij; 
 6554: 	   else if (ij < modmincovj) 
 6555: 	     modmincovj=ij; 
 6556: 	   if (ij <0 || ij >1 ){
 6557: 	     printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
 6558: 	     fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
 6559: 	     fflush(ficlog);
 6560: 	     exit(1);
 6561: 	   }
 6562: 	   if ((ij < -1) || (ij > NCOVMAX)){
 6563: 	     printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
 6564: 	     exit(1);
 6565: 	   }else
 6566: 	     Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
 6567: 	   /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
 6568: 	   /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
 6569: 	   /* getting the maximum value of the modality of the covariate
 6570: 	      (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
 6571: 	      female ies 1, then modmaxcovj=1.
 6572: 	   */
 6573: 	 } /* end for loop on individuals i */
 6574: 	 printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
 6575: 	 fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
 6576: 	 cptcode=modmaxcovj;
 6577: 	 /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
 6578: 	 /*for (i=0; i<=cptcode; i++) {*/
 6579: 	 for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
 6580: 	   printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
 6581: 	   fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
 6582: 	   if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
 6583: 	     if( j != -1){
 6584: 	       ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
 6585: 				  covariate for which somebody answered excluding 
 6586: 				  undefined. Usually 2: 0 and 1. */
 6587: 	     }
 6588: 	     ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
 6589: 				     covariate for which somebody answered including 
 6590: 				     undefined. Usually 3: -1, 0 and 1. */
 6591: 	   }	/* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
 6592: 		 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
 6593: 	 } /* Ndum[-1] number of undefined modalities */
 6594: 			
 6595: 	 /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
 6596: 	 /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
 6597: 	 /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
 6598: 	 /* modmincovj=3; modmaxcovj = 7; */
 6599: 	 /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
 6600: 	 /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
 6601: 	 /*		 defining two dummy variables: variables V1_1 and V1_2.*/
 6602: 	 /* nbcode[Tvar[j]][ij]=k; */
 6603: 	 /* nbcode[Tvar[j]][1]=0; */
 6604: 	 /* nbcode[Tvar[j]][2]=1; */
 6605: 	 /* nbcode[Tvar[j]][3]=2; */
 6606: 	 /* To be continued (not working yet). */
 6607: 	 ij=0; /* ij is similar to i but can jump over null modalities */
 6608: 
 6609: 	 /* 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*/
 6610: 	 /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
 6611: 	 /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
 6612: 	  * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
 6613: 	 /*, could be restored in the future */
 6614: 	 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*/
 6615: 	   if (Ndum[i] == 0) { /* If nobody responded to this modality k */
 6616: 	     break;
 6617: 	   }
 6618: 	   ij++;
 6619: 	   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*/
 6620: 	   cptcode = ij; /* New max modality for covar j */
 6621: 	 } /* end of loop on modality i=-1 to 1 or more */
 6622: 	 break;
 6623:        case 1: /* Testing on varying covariate, could be simple and
 6624: 		* should look at waves or product of fixed *
 6625: 		* varying. No time to test -1, assuming 0 and 1 only */
 6626: 	 ij=0;
 6627: 	 for(i=0; i<=1;i++){
 6628: 	   nbcode[Tvar[k]][++ij]=i;
 6629: 	 }
 6630: 	 break;
 6631:        default:
 6632: 	 break;
 6633:        } /* end switch */
 6634:      } /* end dummy test */
 6635:      if(Dummy[k]==1 && Typevar[k] !=1 && Typevar[k] !=3 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
 6636:        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*/
 6637: 	 if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
 6638: 	   printf("Error k=%d \n",k);
 6639: 	   exit(1);
 6640: 	 }
 6641: 	 if(isnan(covar[Tvar[k]][i])){
 6642: 	   printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
 6643: 	   fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
 6644: 	   fflush(ficlog);
 6645: 	   exit(1);
 6646:          }
 6647:        }
 6648:      } /* end Quanti */
 6649:    } /* 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*/  
 6650:   
 6651:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
 6652:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
 6653:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
 6654:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
 6655:      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 */ 
 6656:      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 */
 6657:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
 6658:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
 6659:   
 6660:    ij=0;
 6661:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
 6662:    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 */
 6663:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
 6664:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
 6665:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
 6666:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
 6667:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
 6668:        /* Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product*/
 6669:        /* If product not in single variable we don't print results */
 6670:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
 6671:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
 6672:        /* k=       1    2   3     4       5       6      7       8        9  */
 6673:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
 6674:        /* ij            1    2                                            3  */  
 6675:        /* Tvaraff[ij]=  4    3                                            1  */
 6676:        /* Tmodelind[ij]=2    3                                            9  */
 6677:        /* TmodelInvind[ij]=2 1                                            1  */
 6678:        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*/
 6679:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
 6680:        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 */
 6681:        if(Fixed[k]!=0)
 6682: 	 anyvaryingduminmodel=1;
 6683:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
 6684:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
 6685:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
 6686:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
 6687:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
 6688:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
 6689:      } 
 6690:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
 6691:    /* ij--; */
 6692:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
 6693:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
 6694: 		* because they can be excluded from the model and real
 6695: 		* if in the model but excluded because missing values, but how to get k from ij?*/
 6696:    for(j=ij+1; j<= cptcovt; j++){
 6697:      Tvaraff[j]=0;
 6698:      Tmodelind[j]=0;
 6699:    }
 6700:    for(j=ntveff+1; j<= cptcovt; j++){
 6701:      TmodelInvind[j]=0;
 6702:    }
 6703:    /* To be sorted */
 6704:    ;
 6705:  }
 6706: 
 6707: 
 6708: /*********** Health Expectancies ****************/
 6709: 
 6710:  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 )
 6711: 
 6712: {
 6713:   /* Health expectancies, no variances */
 6714:   /* cij is the combination in the list of combination of dummy covariates */
 6715:   /* strstart is a string of time at start of computing */
 6716:   int i, j, nhstepm, hstepm, h, nstepm;
 6717:   int nhstepma, nstepma; /* Decreasing with age */
 6718:   double age, agelim, hf;
 6719:   double ***p3mat;
 6720:   double eip;
 6721: 
 6722:   /* pstamp(ficreseij); */
 6723:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
 6724:   fprintf(ficreseij,"# Age");
 6725:   for(i=1; i<=nlstate;i++){
 6726:     for(j=1; j<=nlstate;j++){
 6727:       fprintf(ficreseij," e%1d%1d ",i,j);
 6728:     }
 6729:     fprintf(ficreseij," e%1d. ",i);
 6730:   }
 6731:   fprintf(ficreseij,"\n");
 6732: 
 6733:   
 6734:   if(estepm < stepm){
 6735:     printf ("Problem %d lower than %d\n",estepm, stepm);
 6736:   }
 6737:   else  hstepm=estepm;   
 6738:   /* We compute the life expectancy from trapezoids spaced every estepm months
 6739:    * This is mainly to measure the difference between two models: for example
 6740:    * if stepm=24 months pijx are given only every 2 years and by summing them
 6741:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 6742:    * progression in between and thus overestimating or underestimating according
 6743:    * to the curvature of the survival function. If, for the same date, we 
 6744:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 6745:    * to compare the new estimate of Life expectancy with the same linear 
 6746:    * hypothesis. A more precise result, taking into account a more precise
 6747:    * curvature will be obtained if estepm is as small as stepm. */
 6748: 
 6749:   /* For example we decided to compute the life expectancy with the smallest unit */
 6750:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 6751:      nhstepm is the number of hstepm from age to agelim 
 6752:      nstepm is the number of stepm from age to agelin. 
 6753:      Look at hpijx to understand the reason which relies in memory size consideration
 6754:      and note for a fixed period like estepm months */
 6755:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 6756:      survival function given by stepm (the optimization length). Unfortunately it
 6757:      means that if the survival funtion is printed only each two years of age and if
 6758:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 6759:      results. So we changed our mind and took the option of the best precision.
 6760:   */
 6761:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 6762: 
 6763:   agelim=AGESUP;
 6764:   /* If stepm=6 months */
 6765:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
 6766:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 6767:     
 6768: /* nhstepm age range expressed in number of stepm */
 6769:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 6770:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 6771:   /* if (stepm >= YEARM) hstepm=1;*/
 6772:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 6773:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6774: 
 6775:   for (age=bage; age<=fage; age ++){ 
 6776:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 6777:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 6778:     /* if (stepm >= YEARM) hstepm=1;*/
 6779:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 6780: 
 6781:     /* If stepm=6 months */
 6782:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 6783:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 6784:     /* printf("HELLO evsij Entering hpxij age=%d cij=%d hstepm=%d x[1]=%f nres=%d\n",(int) age, cij, hstepm, x[1], nres); */
 6785:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
 6786:     
 6787:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 6788:     
 6789:     printf("%d|",(int)age);fflush(stdout);
 6790:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 6791:     
 6792:     /* Computing expectancies */
 6793:     for(i=1; i<=nlstate;i++)
 6794:       for(j=1; j<=nlstate;j++)
 6795: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 6796: 	  eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
 6797: 	  
 6798: 	  /* 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]);*/
 6799: 
 6800: 	}
 6801: 
 6802:     fprintf(ficreseij,"%3.0f",age );
 6803:     for(i=1; i<=nlstate;i++){
 6804:       eip=0;
 6805:       for(j=1; j<=nlstate;j++){
 6806: 	eip +=eij[i][j][(int)age];
 6807: 	fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
 6808:       }
 6809:       fprintf(ficreseij,"%9.4f", eip );
 6810:     }
 6811:     fprintf(ficreseij,"\n");
 6812:     
 6813:   }
 6814:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6815:   printf("\n");
 6816:   fprintf(ficlog,"\n");
 6817:   
 6818: }
 6819: 
 6820:  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 )
 6821: 
 6822: {
 6823:   /* Covariances of health expectancies eij and of total life expectancies according
 6824:      to initial status i, ei. .
 6825:   */
 6826:   /* Very time consuming function, but already optimized with precov */
 6827:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
 6828:   int nhstepma, nstepma; /* Decreasing with age */
 6829:   double age, agelim, hf;
 6830:   double ***p3matp, ***p3matm, ***varhe;
 6831:   double **dnewm,**doldm;
 6832:   double *xp, *xm;
 6833:   double **gp, **gm;
 6834:   double ***gradg, ***trgradg;
 6835:   int theta;
 6836: 
 6837:   double eip, vip;
 6838: 
 6839:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
 6840:   xp=vector(1,npar);
 6841:   xm=vector(1,npar);
 6842:   dnewm=matrix(1,nlstate*nlstate,1,npar);
 6843:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
 6844:   
 6845:   pstamp(ficresstdeij);
 6846:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
 6847:   fprintf(ficresstdeij,"# Age");
 6848:   for(i=1; i<=nlstate;i++){
 6849:     for(j=1; j<=nlstate;j++)
 6850:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
 6851:     fprintf(ficresstdeij," e%1d. ",i);
 6852:   }
 6853:   fprintf(ficresstdeij,"\n");
 6854: 
 6855:   pstamp(ficrescveij);
 6856:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
 6857:   fprintf(ficrescveij,"# Age");
 6858:   for(i=1; i<=nlstate;i++)
 6859:     for(j=1; j<=nlstate;j++){
 6860:       cptj= (j-1)*nlstate+i;
 6861:       for(i2=1; i2<=nlstate;i2++)
 6862: 	for(j2=1; j2<=nlstate;j2++){
 6863: 	  cptj2= (j2-1)*nlstate+i2;
 6864: 	  if(cptj2 <= cptj)
 6865: 	    fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
 6866: 	}
 6867:     }
 6868:   fprintf(ficrescveij,"\n");
 6869:   
 6870:   if(estepm < stepm){
 6871:     printf ("Problem %d lower than %d\n",estepm, stepm);
 6872:   }
 6873:   else  hstepm=estepm;   
 6874:   /* We compute the life expectancy from trapezoids spaced every estepm months
 6875:    * This is mainly to measure the difference between two models: for example
 6876:    * if stepm=24 months pijx are given only every 2 years and by summing them
 6877:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 6878:    * progression in between and thus overestimating or underestimating according
 6879:    * to the curvature of the survival function. If, for the same date, we 
 6880:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 6881:    * to compare the new estimate of Life expectancy with the same linear 
 6882:    * hypothesis. A more precise result, taking into account a more precise
 6883:    * curvature will be obtained if estepm is as small as stepm. */
 6884: 
 6885:   /* For example we decided to compute the life expectancy with the smallest unit */
 6886:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 6887:      nhstepm is the number of hstepm from age to agelim 
 6888:      nstepm is the number of stepm from age to agelin. 
 6889:      Look at hpijx to understand the reason of that which relies in memory size
 6890:      and note for a fixed period like estepm months */
 6891:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 6892:      survival function given by stepm (the optimization length). Unfortunately it
 6893:      means that if the survival funtion is printed only each two years of age and if
 6894:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 6895:      results. So we changed our mind and took the option of the best precision.
 6896:   */
 6897:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 6898: 
 6899:   /* If stepm=6 months */
 6900:   /* nhstepm age range expressed in number of stepm */
 6901:   agelim=AGESUP;
 6902:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
 6903:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 6904:   /* if (stepm >= YEARM) hstepm=1;*/
 6905:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 6906:   
 6907:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6908:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6909:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
 6910:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
 6911:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
 6912:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
 6913: 
 6914:   for (age=bage; age<=fage; age ++){ 
 6915:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 6916:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 6917:     /* if (stepm >= YEARM) hstepm=1;*/
 6918:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 6919: 		
 6920:     /* If stepm=6 months */
 6921:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 6922:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 6923:     
 6924:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 6925: 		
 6926:     /* Computing  Variances of health expectancies */
 6927:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
 6928:        decrease memory allocation */
 6929:     for(theta=1; theta <=npar; theta++){
 6930:       for(i=1; i<=npar; i++){ 
 6931: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 6932: 	xm[i] = x[i] - (i==theta ?delti[theta]:0);
 6933:       }
 6934:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
 6935:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
 6936: 			
 6937:       for(j=1; j<= nlstate; j++){
 6938: 	for(i=1; i<=nlstate; i++){
 6939: 	  for(h=0; h<=nhstepm-1; h++){
 6940: 	    gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
 6941: 	    gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
 6942: 	  }
 6943: 	}
 6944:       }
 6945: 			
 6946:       for(ij=1; ij<= nlstate*nlstate; ij++)
 6947: 	for(h=0; h<=nhstepm-1; h++){
 6948: 	  gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
 6949: 	}
 6950:     }/* End theta */
 6951:     
 6952:     
 6953:     for(h=0; h<=nhstepm-1; h++)
 6954:       for(j=1; j<=nlstate*nlstate;j++)
 6955: 	for(theta=1; theta <=npar; theta++)
 6956: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 6957:     
 6958: 		
 6959:     for(ij=1;ij<=nlstate*nlstate;ij++)
 6960:       for(ji=1;ji<=nlstate*nlstate;ji++)
 6961: 	varhe[ij][ji][(int)age] =0.;
 6962: 		
 6963:     printf("%d|",(int)age);fflush(stdout);
 6964:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 6965:     for(h=0;h<=nhstepm-1;h++){
 6966:       for(k=0;k<=nhstepm-1;k++){
 6967: 	matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
 6968: 	matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
 6969: 	for(ij=1;ij<=nlstate*nlstate;ij++)
 6970: 	  for(ji=1;ji<=nlstate*nlstate;ji++)
 6971: 	    varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
 6972:       }
 6973:     }
 6974:     /* if((int)age ==50){ */
 6975:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
 6976:     /* } */
 6977:     /* Computing expectancies */
 6978:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
 6979:     for(i=1; i<=nlstate;i++)
 6980:       for(j=1; j<=nlstate;j++)
 6981: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 6982: 	  eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
 6983: 					
 6984: 	  /* 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]);*/
 6985: 					
 6986: 	}
 6987: 
 6988:     /* Standard deviation of expectancies ij */		
 6989:     fprintf(ficresstdeij,"%3.0f",age );
 6990:     for(i=1; i<=nlstate;i++){
 6991:       eip=0.;
 6992:       vip=0.;
 6993:       for(j=1; j<=nlstate;j++){
 6994: 	eip += eij[i][j][(int)age];
 6995: 	for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
 6996: 	  vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
 6997: 	fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
 6998:       }
 6999:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
 7000:     }
 7001:     fprintf(ficresstdeij,"\n");
 7002: 		
 7003:     /* Variance of expectancies ij */		
 7004:     fprintf(ficrescveij,"%3.0f",age );
 7005:     for(i=1; i<=nlstate;i++)
 7006:       for(j=1; j<=nlstate;j++){
 7007: 	cptj= (j-1)*nlstate+i;
 7008: 	for(i2=1; i2<=nlstate;i2++)
 7009: 	  for(j2=1; j2<=nlstate;j2++){
 7010: 	    cptj2= (j2-1)*nlstate+i2;
 7011: 	    if(cptj2 <= cptj)
 7012: 	      fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
 7013: 	  }
 7014:       }
 7015:     fprintf(ficrescveij,"\n");
 7016: 		
 7017:   }
 7018:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
 7019:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
 7020:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
 7021:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
 7022:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 7023:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 7024:   printf("\n");
 7025:   fprintf(ficlog,"\n");
 7026: 	
 7027:   free_vector(xm,1,npar);
 7028:   free_vector(xp,1,npar);
 7029:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
 7030:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
 7031:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
 7032: }
 7033:  
 7034: /************ Variance ******************/
 7035:  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)
 7036:  {
 7037:    /** Variance of health expectancies 
 7038:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
 7039:     * double **newm;
 7040:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
 7041:     */
 7042:   
 7043:    /* int movingaverage(); */
 7044:    double **dnewm,**doldm;
 7045:    double **dnewmp,**doldmp;
 7046:    int i, j, nhstepm, hstepm, h, nstepm ;
 7047:    int first=0;
 7048:    int k;
 7049:    double *xp;
 7050:    double **gp, **gm;  /**< for var eij */
 7051:    double ***gradg, ***trgradg; /**< for var eij */
 7052:    double **gradgp, **trgradgp; /**< for var p point j */
 7053:    double *gpp, *gmp; /**< for var p point j */
 7054:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
 7055:    double ***p3mat;
 7056:    double age,agelim, hf;
 7057:    /* double ***mobaverage; */
 7058:    int theta;
 7059:    char digit[4];
 7060:    char digitp[25];
 7061: 
 7062:    char fileresprobmorprev[FILENAMELENGTH];
 7063: 
 7064:    if(popbased==1){
 7065:      if(mobilav!=0)
 7066:        strcpy(digitp,"-POPULBASED-MOBILAV_");
 7067:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
 7068:    }
 7069:    else 
 7070:      strcpy(digitp,"-STABLBASED_");
 7071: 
 7072:    /* if (mobilav!=0) { */
 7073:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 7074:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
 7075:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
 7076:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
 7077:    /*   } */
 7078:    /* } */
 7079: 
 7080:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
 7081:    sprintf(digit,"%-d",ij);
 7082:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
 7083:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
 7084:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
 7085:    strcat(fileresprobmorprev,fileresu);
 7086:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
 7087:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
 7088:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
 7089:    }
 7090:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 7091:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 7092:    pstamp(ficresprobmorprev);
 7093:    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);
 7094:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
 7095: 
 7096:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
 7097:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
 7098:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
 7099:    /* } */
 7100:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
 7101:      /* fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); */
 7102:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
 7103:    }
 7104:    /* for(j=1;j<=cptcoveff;j++)  */
 7105:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
 7106:    fprintf(ficresprobmorprev,"\n");
 7107: 
 7108:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
 7109:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 7110:      fprintf(ficresprobmorprev," p.%-d SE",j);
 7111:      for(i=1; i<=nlstate;i++)
 7112:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 7113:    }  
 7114:    fprintf(ficresprobmorprev,"\n");
 7115:   
 7116:    fprintf(ficgp,"\n# Routine varevsij");
 7117:    fprintf(ficgp,"\nunset title \n");
 7118:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
 7119:    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");
 7120:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
 7121: 
 7122:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 7123:    pstamp(ficresvij);
 7124:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
 7125:    if(popbased==1)
 7126:      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);
 7127:    else
 7128:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
 7129:    fprintf(ficresvij,"# Age");
 7130:    for(i=1; i<=nlstate;i++)
 7131:      for(j=1; j<=nlstate;j++)
 7132:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
 7133:    fprintf(ficresvij,"\n");
 7134: 
 7135:    xp=vector(1,npar);
 7136:    dnewm=matrix(1,nlstate,1,npar);
 7137:    doldm=matrix(1,nlstate,1,nlstate);
 7138:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
 7139:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 7140: 
 7141:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
 7142:    gpp=vector(nlstate+1,nlstate+ndeath);
 7143:    gmp=vector(nlstate+1,nlstate+ndeath);
 7144:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 7145:   
 7146:    if(estepm < stepm){
 7147:      printf ("Problem %d lower than %d\n",estepm, stepm);
 7148:    }
 7149:    else  hstepm=estepm;   
 7150:    /* For example we decided to compute the life expectancy with the smallest unit */
 7151:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 7152:       nhstepm is the number of hstepm from age to agelim 
 7153:       nstepm is the number of stepm from age to agelim. 
 7154:       Look at function hpijx to understand why because of memory size limitations, 
 7155:       we decided (b) to get a life expectancy respecting the most precise curvature of the
 7156:       survival function given by stepm (the optimization length). Unfortunately it
 7157:       means that if the survival funtion is printed every two years of age and if
 7158:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 7159:       results. So we changed our mind and took the option of the best precision.
 7160:    */
 7161:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 7162:    agelim = AGESUP;
 7163:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 7164:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 7165:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 7166:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 7167:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
 7168:      gp=matrix(0,nhstepm,1,nlstate);
 7169:      gm=matrix(0,nhstepm,1,nlstate);
 7170: 		
 7171: 		
 7172:      for(theta=1; theta <=npar; theta++){
 7173:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
 7174: 	 xp[i] = x[i] + (i==theta ?delti[theta]:0);
 7175:        }
 7176:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
 7177: 	* returns into prlim .
 7178: 	*/
 7179:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
 7180: 
 7181:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
 7182:        if (popbased==1) {
 7183: 	 if(mobilav ==0){
 7184: 	   for(i=1; i<=nlstate;i++)
 7185: 	     prlim[i][i]=probs[(int)age][i][ij];
 7186: 	 }else{ /* mobilav */ 
 7187: 	   for(i=1; i<=nlstate;i++)
 7188: 	     prlim[i][i]=mobaverage[(int)age][i][ij];
 7189: 	 }
 7190:        }
 7191:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
 7192: 	*/			
 7193:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  /* Returns p3mat[i][j][h] for h=0 to nhstepm */
 7194:        /**< And for each alive state j, sums over i \f$ w^i_x {}{h}_p^{ij}x\f$, which are the probability
 7195: 	* at horizon h in state j including mortality.
 7196: 	*/
 7197:        for(j=1; j<= nlstate; j++){
 7198: 	 for(h=0; h<=nhstepm; h++){
 7199: 	   for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 7200: 	     gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 7201: 	 }
 7202:        }
 7203:        /* Next for computing shifted+ probability of death (h=1 means
 7204: 	  computed over hstepm matrices product = hstepm*stepm months) 
 7205: 	  as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
 7206:        */
 7207:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
 7208: 	 for(i=1,gpp[j]=0.; i<= nlstate; i++)
 7209: 	   gpp[j] += prlim[i][i]*p3mat[i][j][1];
 7210:        }
 7211:        
 7212:        /* Again with minus shift */
 7213: 			
 7214:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
 7215: 	 xp[i] = x[i] - (i==theta ?delti[theta]:0);
 7216: 
 7217:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
 7218: 			
 7219:        if (popbased==1) {
 7220: 	 if(mobilav ==0){
 7221: 	   for(i=1; i<=nlstate;i++)
 7222: 	     prlim[i][i]=probs[(int)age][i][ij];
 7223: 	 }else{ /* mobilav */ 
 7224: 	   for(i=1; i<=nlstate;i++)
 7225: 	     prlim[i][i]=mobaverage[(int)age][i][ij];
 7226: 	 }
 7227:        }
 7228: 			
 7229:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
 7230: 			
 7231:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
 7232: 	 for(h=0; h<=nhstepm; h++){
 7233: 	   for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 7234: 	     gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 7235: 	 }
 7236:        }
 7237:        /* This for computing probability of death (h=1 means
 7238: 	  computed over hstepm matrices product = hstepm*stepm months) 
 7239: 	  as a weighted average of prlim.
 7240:        */
 7241:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
 7242: 	 for(i=1,gmp[j]=0.; i<= nlstate; i++)
 7243: 	   gmp[j] += prlim[i][i]*p3mat[i][j][1];
 7244:        }    
 7245:        /* end shifting computations */
 7246: 
 7247:        /**< Computing gradient matrix at horizon h 
 7248: 	*/
 7249:        for(j=1; j<= nlstate; j++) /* vareij */
 7250: 	 for(h=0; h<=nhstepm; h++){
 7251: 	   gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 7252: 	 }
 7253:        /**< Gradient of overall mortality p.3 (or p.j) 
 7254: 	*/
 7255:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
 7256: 	 gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
 7257:        }
 7258: 			
 7259:      } /* End theta */
 7260:      
 7261:      /* We got the gradient matrix for each theta and state j */		
 7262:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
 7263: 		
 7264:      for(h=0; h<=nhstepm; h++) /* veij */
 7265:        for(j=1; j<=nlstate;j++)
 7266: 	 for(theta=1; theta <=npar; theta++)
 7267: 	   trgradg[h][j][theta]=gradg[h][theta][j];
 7268: 		
 7269:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
 7270:        for(theta=1; theta <=npar; theta++)
 7271: 	 trgradgp[j][theta]=gradgp[theta][j];
 7272:      /**< as well as its transposed matrix 
 7273:       */		
 7274: 		
 7275:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 7276:      for(i=1;i<=nlstate;i++)
 7277:        for(j=1;j<=nlstate;j++)
 7278: 	 vareij[i][j][(int)age] =0.;
 7279: 
 7280:      /* Computing trgradg by matcov by gradg at age and summing over h
 7281:       * and k (nhstepm) formula 15 of article
 7282:       * Lievre-Brouard-Heathcote
 7283:       */
 7284:      
 7285:      for(h=0;h<=nhstepm;h++){
 7286:        for(k=0;k<=nhstepm;k++){
 7287: 	 matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 7288: 	 matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
 7289: 	 for(i=1;i<=nlstate;i++)
 7290: 	   for(j=1;j<=nlstate;j++)
 7291: 	     vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
 7292:        }
 7293:      }
 7294: 		
 7295:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
 7296:       * p.j overall mortality formula 49 but computed directly because
 7297:       * we compute the grad (wix pijx) instead of grad (pijx),even if
 7298:       * wix is independent of theta.
 7299:       */
 7300:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
 7301:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
 7302:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
 7303:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
 7304: 	 varppt[j][i]=doldmp[j][i];
 7305:      /* end ppptj */
 7306:      /*  x centered again */
 7307: 		
 7308:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
 7309: 		
 7310:      if (popbased==1) {
 7311:        if(mobilav ==0){
 7312: 	 for(i=1; i<=nlstate;i++)
 7313: 	   prlim[i][i]=probs[(int)age][i][ij];
 7314:        }else{ /* mobilav */ 
 7315: 	 for(i=1; i<=nlstate;i++)
 7316: 	   prlim[i][i]=mobaverage[(int)age][i][ij];
 7317:        }
 7318:      }
 7319: 		
 7320:      /* This for computing probability of death (h=1 means
 7321: 	computed over hstepm (estepm) matrices product = hstepm*stepm months) 
 7322: 	as a weighted average of prlim.
 7323:      */
 7324:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
 7325:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
 7326:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
 7327: 	 gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
 7328:      }    
 7329:      /* end probability of death */
 7330: 		
 7331:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
 7332:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 7333:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
 7334:        for(i=1; i<=nlstate;i++){
 7335: 	 fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 7336:        }
 7337:      } 
 7338:      fprintf(ficresprobmorprev,"\n");
 7339: 		
 7340:      fprintf(ficresvij,"%.0f ",age );
 7341:      for(i=1; i<=nlstate;i++)
 7342:        for(j=1; j<=nlstate;j++){
 7343: 	 fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
 7344:        }
 7345:      fprintf(ficresvij,"\n");
 7346:      free_matrix(gp,0,nhstepm,1,nlstate);
 7347:      free_matrix(gm,0,nhstepm,1,nlstate);
 7348:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 7349:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 7350:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 7351:    } /* End age */
 7352:    free_vector(gpp,nlstate+1,nlstate+ndeath);
 7353:    free_vector(gmp,nlstate+1,nlstate+ndeath);
 7354:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
 7355:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 7356:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
 7357:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
 7358:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
 7359:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
 7360:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
 7361:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
 7362:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
 7363:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
 7364:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
 7365:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
 7366:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
 7367:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
 7368:    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);
 7369:    /*  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);
 7370:     */
 7371:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
 7372:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
 7373: 
 7374:    free_vector(xp,1,npar);
 7375:    free_matrix(doldm,1,nlstate,1,nlstate);
 7376:    free_matrix(dnewm,1,nlstate,1,npar);
 7377:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 7378:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
 7379:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 7380:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
 7381:    fclose(ficresprobmorprev);
 7382:    fflush(ficgp);
 7383:    fflush(fichtm); 
 7384:  }  /* end varevsij */
 7385: 
 7386: /************ Variance of prevlim ******************/
 7387:  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)
 7388: {
 7389:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
 7390:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 7391: 
 7392:   double **dnewmpar,**doldm;
 7393:   int i, j, nhstepm, hstepm;
 7394:   double *xp;
 7395:   double *gp, *gm;
 7396:   double **gradg, **trgradg;
 7397:   double **mgm, **mgp;
 7398:   double age,agelim;
 7399:   int theta;
 7400:   
 7401:   pstamp(ficresvpl);
 7402:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
 7403:   fprintf(ficresvpl,"# Age ");
 7404:   if(nresult >=1)
 7405:     fprintf(ficresvpl," Result# ");
 7406:   for(i=1; i<=nlstate;i++)
 7407:       fprintf(ficresvpl," %1d-%1d",i,i);
 7408:   fprintf(ficresvpl,"\n");
 7409: 
 7410:   xp=vector(1,npar);
 7411:   dnewmpar=matrix(1,nlstate,1,npar);
 7412:   doldm=matrix(1,nlstate,1,nlstate);
 7413:   
 7414:   hstepm=1*YEARM; /* Every year of age */
 7415:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 7416:   agelim = AGESUP;
 7417:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 7418:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 7419:     if (stepm >= YEARM) hstepm=1;
 7420:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 7421:     gradg=matrix(1,npar,1,nlstate);
 7422:     mgp=matrix(1,npar,1,nlstate);
 7423:     mgm=matrix(1,npar,1,nlstate);
 7424:     gp=vector(1,nlstate);
 7425:     gm=vector(1,nlstate);
 7426: 
 7427:     for(theta=1; theta <=npar; theta++){
 7428:       for(i=1; i<=npar; i++){ /* Computes gradient */
 7429: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 7430:       }
 7431:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
 7432:       /* 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
 7433:       /* else */
 7434:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
 7435:       for(i=1;i<=nlstate;i++){
 7436: 	gp[i] = prlim[i][i];
 7437: 	mgp[theta][i] = prlim[i][i];
 7438:       }
 7439:       for(i=1; i<=npar; i++) /* Computes gradient */
 7440: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 7441:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
 7442:       /* 	prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
 7443:       /* else */
 7444:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
 7445:       for(i=1;i<=nlstate;i++){
 7446: 	gm[i] = prlim[i][i];
 7447: 	mgm[theta][i] = prlim[i][i];
 7448:       }
 7449:       for(i=1;i<=nlstate;i++)
 7450: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 7451:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
 7452:     } /* End theta */
 7453: 
 7454:     trgradg =matrix(1,nlstate,1,npar);
 7455: 
 7456:     for(j=1; j<=nlstate;j++)
 7457:       for(theta=1; theta <=npar; theta++)
 7458: 	trgradg[j][theta]=gradg[theta][j];
 7459:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
 7460:     /*   printf("\nmgm mgp %d ",(int)age); */
 7461:     /*   for(j=1; j<=nlstate;j++){ */
 7462:     /* 	printf(" %d ",j); */
 7463:     /* 	for(theta=1; theta <=npar; theta++) */
 7464:     /* 	  printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
 7465:     /* 	printf("\n "); */
 7466:     /*   } */
 7467:     /* } */
 7468:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
 7469:     /*   printf("\n gradg %d ",(int)age); */
 7470:     /*   for(j=1; j<=nlstate;j++){ */
 7471:     /* 	printf("%d ",j); */
 7472:     /* 	for(theta=1; theta <=npar; theta++) */
 7473:     /* 	  printf("%d %lf ",theta,gradg[theta][j]); */
 7474:     /* 	printf("\n "); */
 7475:     /*   } */
 7476:     /* } */
 7477: 
 7478:     for(i=1;i<=nlstate;i++)
 7479:       varpl[i][(int)age] =0.;
 7480:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
 7481:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
 7482:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
 7483:     }else{
 7484:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
 7485:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
 7486:     }
 7487:     for(i=1;i<=nlstate;i++)
 7488:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 7489: 
 7490:     fprintf(ficresvpl,"%.0f ",age );
 7491:     if(nresult >=1)
 7492:       fprintf(ficresvpl,"%d ",nres );
 7493:     for(i=1; i<=nlstate;i++){
 7494:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
 7495:       /* for(j=1;j<=nlstate;j++) */
 7496:       /* 	fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
 7497:     }
 7498:     fprintf(ficresvpl,"\n");
 7499:     free_vector(gp,1,nlstate);
 7500:     free_vector(gm,1,nlstate);
 7501:     free_matrix(mgm,1,npar,1,nlstate);
 7502:     free_matrix(mgp,1,npar,1,nlstate);
 7503:     free_matrix(gradg,1,npar,1,nlstate);
 7504:     free_matrix(trgradg,1,nlstate,1,npar);
 7505:   } /* End age */
 7506: 
 7507:   free_vector(xp,1,npar);
 7508:   free_matrix(doldm,1,nlstate,1,npar);
 7509:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
 7510: 
 7511: }
 7512: 
 7513: 
 7514: /************ Variance of backprevalence limit ******************/
 7515:  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)
 7516: {
 7517:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
 7518:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 7519: 
 7520:   double **dnewmpar,**doldm;
 7521:   int i, j, nhstepm, hstepm;
 7522:   double *xp;
 7523:   double *gp, *gm;
 7524:   double **gradg, **trgradg;
 7525:   double **mgm, **mgp;
 7526:   double age,agelim;
 7527:   int theta;
 7528:   
 7529:   pstamp(ficresvbl);
 7530:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
 7531:   fprintf(ficresvbl,"# Age ");
 7532:   if(nresult >=1)
 7533:     fprintf(ficresvbl," Result# ");
 7534:   for(i=1; i<=nlstate;i++)
 7535:       fprintf(ficresvbl," %1d-%1d",i,i);
 7536:   fprintf(ficresvbl,"\n");
 7537: 
 7538:   xp=vector(1,npar);
 7539:   dnewmpar=matrix(1,nlstate,1,npar);
 7540:   doldm=matrix(1,nlstate,1,nlstate);
 7541:   
 7542:   hstepm=1*YEARM; /* Every year of age */
 7543:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 7544:   agelim = AGEINF;
 7545:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
 7546:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 7547:     if (stepm >= YEARM) hstepm=1;
 7548:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 7549:     gradg=matrix(1,npar,1,nlstate);
 7550:     mgp=matrix(1,npar,1,nlstate);
 7551:     mgm=matrix(1,npar,1,nlstate);
 7552:     gp=vector(1,nlstate);
 7553:     gm=vector(1,nlstate);
 7554: 
 7555:     for(theta=1; theta <=npar; theta++){
 7556:       for(i=1; i<=npar; i++){ /* Computes gradient */
 7557: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 7558:       }
 7559:       if(mobilavproj > 0 )
 7560: 	bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
 7561:       else
 7562: 	bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
 7563:       for(i=1;i<=nlstate;i++){
 7564: 	gp[i] = bprlim[i][i];
 7565: 	mgp[theta][i] = bprlim[i][i];
 7566:       }
 7567:      for(i=1; i<=npar; i++) /* Computes gradient */
 7568: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 7569:        if(mobilavproj > 0 )
 7570: 	bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
 7571:        else
 7572: 	bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
 7573:       for(i=1;i<=nlstate;i++){
 7574: 	gm[i] = bprlim[i][i];
 7575: 	mgm[theta][i] = bprlim[i][i];
 7576:       }
 7577:       for(i=1;i<=nlstate;i++)
 7578: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 7579:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
 7580:     } /* End theta */
 7581: 
 7582:     trgradg =matrix(1,nlstate,1,npar);
 7583: 
 7584:     for(j=1; j<=nlstate;j++)
 7585:       for(theta=1; theta <=npar; theta++)
 7586: 	trgradg[j][theta]=gradg[theta][j];
 7587:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
 7588:     /*   printf("\nmgm mgp %d ",(int)age); */
 7589:     /*   for(j=1; j<=nlstate;j++){ */
 7590:     /* 	printf(" %d ",j); */
 7591:     /* 	for(theta=1; theta <=npar; theta++) */
 7592:     /* 	  printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
 7593:     /* 	printf("\n "); */
 7594:     /*   } */
 7595:     /* } */
 7596:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
 7597:     /*   printf("\n gradg %d ",(int)age); */
 7598:     /*   for(j=1; j<=nlstate;j++){ */
 7599:     /* 	printf("%d ",j); */
 7600:     /* 	for(theta=1; theta <=npar; theta++) */
 7601:     /* 	  printf("%d %lf ",theta,gradg[theta][j]); */
 7602:     /* 	printf("\n "); */
 7603:     /*   } */
 7604:     /* } */
 7605: 
 7606:     for(i=1;i<=nlstate;i++)
 7607:       varbpl[i][(int)age] =0.;
 7608:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
 7609:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
 7610:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
 7611:     }else{
 7612:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
 7613:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
 7614:     }
 7615:     for(i=1;i<=nlstate;i++)
 7616:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 7617: 
 7618:     fprintf(ficresvbl,"%.0f ",age );
 7619:     if(nresult >=1)
 7620:       fprintf(ficresvbl,"%d ",nres );
 7621:     for(i=1; i<=nlstate;i++)
 7622:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
 7623:     fprintf(ficresvbl,"\n");
 7624:     free_vector(gp,1,nlstate);
 7625:     free_vector(gm,1,nlstate);
 7626:     free_matrix(mgm,1,npar,1,nlstate);
 7627:     free_matrix(mgp,1,npar,1,nlstate);
 7628:     free_matrix(gradg,1,npar,1,nlstate);
 7629:     free_matrix(trgradg,1,nlstate,1,npar);
 7630:   } /* End age */
 7631: 
 7632:   free_vector(xp,1,npar);
 7633:   free_matrix(doldm,1,nlstate,1,npar);
 7634:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
 7635: 
 7636: }
 7637: 
 7638: /************ Variance of one-step probabilities  ******************/
 7639: 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[])
 7640:  {
 7641:    int i, j=0,  k1, l1, tj;
 7642:    int k2, l2, j1,  z1;
 7643:    int k=0, l;
 7644:    int first=1, first1, first2;
 7645:    int nres=0; /* New */
 7646:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
 7647:    double **dnewm,**doldm;
 7648:    double *xp;
 7649:    double *gp, *gm;
 7650:    double **gradg, **trgradg;
 7651:    double **mu;
 7652:    double age, cov[NCOVMAX+1];
 7653:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
 7654:    int theta;
 7655:    char fileresprob[FILENAMELENGTH];
 7656:    char fileresprobcov[FILENAMELENGTH];
 7657:    char fileresprobcor[FILENAMELENGTH];
 7658:    double ***varpij;
 7659: 
 7660:    strcpy(fileresprob,"PROB_"); 
 7661:    strcat(fileresprob,fileresu);
 7662:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
 7663:      printf("Problem with resultfile: %s\n", fileresprob);
 7664:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
 7665:    }
 7666:    strcpy(fileresprobcov,"PROBCOV_"); 
 7667:    strcat(fileresprobcov,fileresu);
 7668:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
 7669:      printf("Problem with resultfile: %s\n", fileresprobcov);
 7670:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 7671:    }
 7672:    strcpy(fileresprobcor,"PROBCOR_"); 
 7673:    strcat(fileresprobcor,fileresu);
 7674:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 7675:      printf("Problem with resultfile: %s\n", fileresprobcor);
 7676:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 7677:    }
 7678:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 7679:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 7680:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 7681:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 7682:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 7683:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 7684:    pstamp(ficresprob);
 7685:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
 7686:    fprintf(ficresprob,"# Age");
 7687:    pstamp(ficresprobcov);
 7688:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
 7689:    fprintf(ficresprobcov,"# Age");
 7690:    pstamp(ficresprobcor);
 7691:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 7692:    fprintf(ficresprobcor,"# Age");
 7693: 
 7694: 
 7695:    for(i=1; i<=nlstate;i++)
 7696:      for(j=1; j<=(nlstate+ndeath);j++){
 7697:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
 7698:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
 7699:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
 7700:      }  
 7701:    /* fprintf(ficresprob,"\n");
 7702:       fprintf(ficresprobcov,"\n");
 7703:       fprintf(ficresprobcor,"\n");
 7704:    */
 7705:    xp=vector(1,npar);
 7706:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 7707:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 7708:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
 7709:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 7710:    first=1;
 7711:    fprintf(ficgp,"\n# Routine varprob");
 7712:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
 7713:    fprintf(fichtm,"\n");
 7714: 
 7715:    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);
 7716:    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);
 7717:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
 7718: and drawn. It helps understanding how is the covariance between two incidences.\
 7719:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
 7720:    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. \
 7721: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
 7722: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
 7723: standard deviations wide on each axis. <br>\
 7724:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
 7725:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 7726: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
 7727: 
 7728:    cov[1]=1;
 7729:    /* tj=cptcoveff; */
 7730:    tj = (int) pow(2,cptcoveff);
 7731:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
 7732:    j1=0;
 7733: 
 7734:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
 7735:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
 7736:      /* 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); */
 7737:      if(tj != 1 && TKresult[nres]!= j1)
 7738:        continue;
 7739: 
 7740:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
 7741:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
 7742:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
 7743:      if  (cptcovn>0) {
 7744:        fprintf(ficresprob, "\n#********** Variable ");
 7745:        fprintf(ficresprobcov, "\n#********** Variable "); 
 7746:        fprintf(ficgp, "\n#********** Variable ");
 7747:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
 7748:        fprintf(ficresprobcor, "\n#********** Variable ");    
 7749: 
 7750:        /* Including quantitative variables of the resultline to be done */
 7751:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
 7752: 	 /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
 7753: 	 fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
 7754: 	 /* fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s resultline[%d]=%s \n",nres, z1, modelresult[nres][z1], model, nres, resultline[nres]); */
 7755: 	 if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
 7756: 	   if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
 7757: 	     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  */
 7758: 	     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  */
 7759: 	     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  */
 7760: 	     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  */
 7761: 	     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  */
 7762: 	     fprintf(ficresprob,"fixed ");
 7763: 	     fprintf(ficresprobcov,"fixed ");
 7764: 	     fprintf(ficgp,"fixed ");
 7765: 	     fprintf(fichtmcov,"fixed ");
 7766: 	     fprintf(ficresprobcor,"fixed ");
 7767: 	   }else{
 7768: 	     fprintf(ficresprob,"varyi ");
 7769: 	     fprintf(ficresprobcov,"varyi ");
 7770: 	     fprintf(ficgp,"varyi ");
 7771: 	     fprintf(fichtmcov,"varyi ");
 7772: 	     fprintf(ficresprobcor,"varyi ");
 7773: 	   }
 7774: 	 }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
 7775: 	   /* For each selected (single) quantitative value */
 7776: 	   fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
 7777: 	   if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
 7778: 	     fprintf(ficresprob,"fixed ");
 7779: 	     fprintf(ficresprobcov,"fixed ");
 7780: 	     fprintf(ficgp,"fixed ");
 7781: 	     fprintf(fichtmcov,"fixed ");
 7782: 	     fprintf(ficresprobcor,"fixed ");
 7783: 	   }else{
 7784: 	     fprintf(ficresprob,"varyi ");
 7785: 	     fprintf(ficresprobcov,"varyi ");
 7786: 	     fprintf(ficgp,"varyi ");
 7787: 	     fprintf(fichtmcov,"varyi ");
 7788: 	     fprintf(ficresprobcor,"varyi ");
 7789: 	   }
 7790: 	 }else{
 7791: 	   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 */
 7792: 	   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 */
 7793: 	   exit(1);
 7794: 	 }
 7795:        } /* End loop on variable of this resultline */
 7796:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
 7797:        fprintf(ficresprob, "**********\n#\n");
 7798:        fprintf(ficresprobcov, "**********\n#\n");
 7799:        fprintf(ficgp, "**********\n#\n");
 7800:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
 7801:        fprintf(ficresprobcor, "**********\n#");    
 7802:        if(invalidvarcomb[j1]){
 7803: 	 fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
 7804: 	 fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
 7805: 	 continue;
 7806:        }
 7807:      }
 7808:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
 7809:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 7810:      gp=vector(1,(nlstate)*(nlstate+ndeath));
 7811:      gm=vector(1,(nlstate)*(nlstate+ndeath));
 7812:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
 7813:        cov[2]=age;
 7814:        if(nagesqr==1)
 7815: 	 cov[3]= age*age;
 7816:        /* New code end of combination but for each resultline */
 7817:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
 7818: 	 if(Typevar[k1]==1 || Typevar[k1] ==3){ /* A product with age */
 7819: 	   cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
 7820: 	 }else{
 7821: 	   cov[2+nagesqr+k1]=precov[nres][k1];
 7822: 	 }
 7823:        }/* End of loop on model equation */
 7824: /* Old code */
 7825:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
 7826:        /* /\* 	 cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
 7827:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
 7828:        /* 	 /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
 7829:        /* 	 cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
 7830:        /* 	 /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
 7831:        /* 								    * 1  1 1 1 1 */
 7832:        /* 								    * 2  2 1 1 1 */
 7833:        /* 								    * 3  1 2 1 1 */
 7834:        /* 								    *\/ */
 7835:        /* 	 /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
 7836:        /* } */
 7837:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
 7838:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
 7839:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
 7840:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
 7841:        /* 	 if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
 7842:        /* 	   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
 7843:        /* 	   /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
 7844:        /* 	 } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
 7845:        /* 	   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]); */
 7846:        /* 	   /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
 7847:        /* 	   /\* exit(1); *\/ */
 7848:        /* 	   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
 7849:        /* 	 } */
 7850:        /* 	 /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
 7851:        /* } */
 7852:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
 7853:        /* 	 if(Dummy[Tvard[k][1]]==0){ */
 7854:        /* 	   if(Dummy[Tvard[k][2]]==0){ */
 7855:        /* 	     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]])]; */
 7856:        /* 	     /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
 7857:        /* 	   }else{ /\* Should we use the mean of the quantitative variables? *\/ */
 7858:        /* 	     cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
 7859:        /* 	     /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
 7860:        /* 	   } */
 7861:        /* 	 }else{ */
 7862:        /* 	   if(Dummy[Tvard[k][2]]==0){ */
 7863:        /* 	     cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
 7864:        /* 	     /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
 7865:        /* 	   }else{ */
 7866:        /* 	     cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
 7867:        /* 	     /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
 7868:        /* 	   } */
 7869:        /* 	 } */
 7870:        /* 	 /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
 7871:        /* } */			
 7872: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/			
 7873:        for(theta=1; theta <=npar; theta++){
 7874: 	 for(i=1; i<=npar; i++)
 7875: 	   xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
 7876: 				
 7877: 	 pmij(pmmij,cov,ncovmodel,xp,nlstate);
 7878: 				
 7879: 	 k=0;
 7880: 	 for(i=1; i<= (nlstate); i++){
 7881: 	   for(j=1; j<=(nlstate+ndeath);j++){
 7882: 	     k=k+1;
 7883: 	     gp[k]=pmmij[i][j];
 7884: 	   }
 7885: 	 }
 7886: 				
 7887: 	 for(i=1; i<=npar; i++)
 7888: 	   xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
 7889: 				
 7890: 	 pmij(pmmij,cov,ncovmodel,xp,nlstate);
 7891: 	 k=0;
 7892: 	 for(i=1; i<=(nlstate); i++){
 7893: 	   for(j=1; j<=(nlstate+ndeath);j++){
 7894: 	     k=k+1;
 7895: 	     gm[k]=pmmij[i][j];
 7896: 	   }
 7897: 	 }
 7898: 				
 7899: 	 for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
 7900: 	   gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
 7901:        }
 7902: 
 7903:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
 7904: 	 for(theta=1; theta <=npar; theta++)
 7905: 	   trgradg[j][theta]=gradg[theta][j];
 7906: 			
 7907:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
 7908:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
 7909: 			
 7910:        pmij(pmmij,cov,ncovmodel,x,nlstate);
 7911: 			
 7912:        k=0;
 7913:        for(i=1; i<=(nlstate); i++){
 7914: 	 for(j=1; j<=(nlstate+ndeath);j++){
 7915: 	   k=k+1;
 7916: 	   mu[k][(int) age]=pmmij[i][j];
 7917: 	 }
 7918:        }
 7919:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 7920: 	 for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 7921: 	   varpij[i][j][(int)age] = doldm[i][j];
 7922: 			
 7923:        /*printf("\n%d ",(int)age);
 7924: 	 for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 7925: 	 printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 7926: 	 fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 7927: 	 }*/
 7928: 			
 7929:        fprintf(ficresprob,"\n%d ",(int)age);
 7930:        fprintf(ficresprobcov,"\n%d ",(int)age);
 7931:        fprintf(ficresprobcor,"\n%d ",(int)age);
 7932: 			
 7933:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
 7934: 	 fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
 7935:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 7936: 	 fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
 7937: 	 fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
 7938:        }
 7939:        i=0;
 7940:        for (k=1; k<=(nlstate);k++){
 7941: 	 for (l=1; l<=(nlstate+ndeath);l++){ 
 7942: 	   i++;
 7943: 	   fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 7944: 	   fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
 7945: 	   for (j=1; j<=i;j++){
 7946: 	     /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
 7947: 	     fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
 7948: 	     fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
 7949: 	   }
 7950: 	 }
 7951:        }/* end of loop for state */
 7952:      } /* end of loop for age */
 7953:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
 7954:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 7955:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 7956:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 7957:     
 7958:      /* Confidence intervalle of pij  */
 7959:      /*
 7960:        fprintf(ficgp,"\nunset parametric;unset label");
 7961:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
 7962:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 7963:        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);
 7964:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
 7965:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
 7966:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
 7967:      */
 7968: 		
 7969:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
 7970:      first1=1;first2=2;
 7971:      for (k2=1; k2<=(nlstate);k2++){
 7972:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
 7973: 	 if(l2==k2) continue;
 7974: 	 j=(k2-1)*(nlstate+ndeath)+l2;
 7975: 	 for (k1=1; k1<=(nlstate);k1++){
 7976: 	   for (l1=1; l1<=(nlstate+ndeath);l1++){ 
 7977: 	     if(l1==k1) continue;
 7978: 	     i=(k1-1)*(nlstate+ndeath)+l1;
 7979: 	     if(i<=j) continue;
 7980: 	     for (age=bage; age<=fage; age ++){ 
 7981: 	       if ((int)age %5==0){
 7982: 		 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
 7983: 		 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
 7984: 		 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
 7985: 		 mu1=mu[i][(int) age]/stepm*YEARM ;
 7986: 		 mu2=mu[j][(int) age]/stepm*YEARM;
 7987: 		 c12=cv12/sqrt(v1*v2);
 7988: 		 /* Computing eigen value of matrix of covariance */
 7989: 		 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 7990: 		 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 7991: 		 if ((lc2 <0) || (lc1 <0) ){
 7992: 		   if(first2==1){
 7993: 		     first1=0;
 7994: 		     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);
 7995: 		   }
 7996: 		   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);
 7997: 		   /* lc1=fabs(lc1); */ /* If we want to have them positive */
 7998: 		   /* lc2=fabs(lc2); */
 7999: 		 }
 8000: 								
 8001: 		 /* Eigen vectors */
 8002: 		 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
 8003: 		   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
 8004: 		   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
 8005: 		   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
 8006: 		 }else
 8007: 		   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
 8008: 		 /*v21=sqrt(1.-v11*v11); *//* error */
 8009: 		 v21=(lc1-v1)/cv12*v11;
 8010: 		 v12=-v21;
 8011: 		 v22=v11;
 8012: 		 tnalp=v21/v11;
 8013: 		 if(first1==1){
 8014: 		   first1=0;
 8015: 		   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);
 8016: 		 }
 8017: 		 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);
 8018: 		 /*printf(fignu*/
 8019: 		 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
 8020: 		 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
 8021: 		 if(first==1){
 8022: 		   first=0;
 8023: 		   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
 8024: 		   fprintf(ficgp,"\nset parametric;unset label");
 8025: 		   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);
 8026: 		   fprintf(ficgp,"\nset ter svg size 640, 480");
 8027: 		   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
 8028:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">																		\
 8029: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
 8030: 			   subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,	\
 8031: 			   subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 8032: 		   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 8033: 		   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
 8034: 		   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 8035: 		   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 8036: 		   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 8037: 		   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",	\
 8038: 			   mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
 8039: 			   mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
 8040: 		 }else{
 8041: 		   first=0;
 8042: 		   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
 8043: 		   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 8044: 		   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 8045: 		   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", \
 8046: 			   mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),	\
 8047: 			   mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
 8048: 		 }/* if first */
 8049: 	       } /* age mod 5 */
 8050: 	     } /* end loop age */
 8051: 	     fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
 8052: 	     first=1;
 8053: 	   } /*l12 */
 8054: 	 } /* k12 */
 8055:        } /*l1 */
 8056:      }/* k1 */
 8057:    }  /* loop on combination of covariates j1 */
 8058:    } /* loop on nres */
 8059:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 8060:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
 8061:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 8062:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
 8063:    free_vector(xp,1,npar);
 8064:    fclose(ficresprob);
 8065:    fclose(ficresprobcov);
 8066:    fclose(ficresprobcor);
 8067:    fflush(ficgp);
 8068:    fflush(fichtmcov);
 8069:  }
 8070: 
 8071: 
 8072: /******************* Printing html file ***********/
 8073: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
 8074: 		  int lastpass, int stepm, int weightopt, char model[],\
 8075: 		  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 8076: 		  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
 8077: 		  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
 8078: 		  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
 8079:   int jj1, k1, i1, cpt, k4, nres;
 8080:   /* In fact some results are already printed in fichtm which is open */
 8081:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
 8082:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
 8083: </ul>");
 8084: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
 8085: /* </ul>", model); */
 8086:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
 8087:    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",
 8088: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
 8089:    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) ",
 8090: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
 8091:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
 8092:    fprintf(fichtm,"\
 8093:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 8094: 	   stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
 8095:    fprintf(fichtm,"\
 8096:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 8097: 	   stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
 8098:    fprintf(fichtm,"\
 8099:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 8100: 	   subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
 8101:    fprintf(fichtm,"\
 8102:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 8103: 	   subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
 8104:    fprintf(fichtm,"\
 8105:  - (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): \
 8106:    <a href=\"%s\">%s</a> <br>\n",
 8107: 	   estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
 8108:    if(prevfcast==1){
 8109:      fprintf(fichtm,"\
 8110:  - Prevalence projections by age and states:				\
 8111:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
 8112:    }
 8113: 
 8114: 
 8115:    m=pow(2,cptcoveff);
 8116:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 8117: 
 8118:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
 8119: 
 8120:    jj1=0;
 8121: 
 8122:    fprintf(fichtm," \n<ul>");
 8123:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 8124:      /* k1=nres; */
 8125:      k1=TKresult[nres];
 8126:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
 8127:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
 8128:    /*   if(m != 1 && TKresult[nres]!= k1) */
 8129:    /*     continue; */
 8130:      jj1++;
 8131:      if (cptcovn > 0) {
 8132:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
 8133:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
 8134: 	 fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
 8135:        }
 8136:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
 8137:        /* 	 fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
 8138:        /* } */
 8139:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 8140:        /* 	 fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
 8141:        /* } */
 8142:        fprintf(fichtm,"\">");
 8143:        
 8144:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
 8145:        fprintf(fichtm,"************ Results for covariates");
 8146:        for (cpt=1; cpt<=cptcovs;cpt++){ 
 8147: 	 fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
 8148:        }
 8149:        /* fprintf(fichtm,"************ Results for covariates"); */
 8150:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
 8151:        /* 	 fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[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:        if(invalidvarcomb[k1]){
 8157: 	 fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
 8158: 	 continue;
 8159:        }
 8160:        fprintf(fichtm,"</a></li>");
 8161:      } /* cptcovn >0 */
 8162:    }
 8163:    fprintf(fichtm," \n</ul>");
 8164: 
 8165:    jj1=0;
 8166: 
 8167:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 8168:      /* k1=nres; */
 8169:      k1=TKresult[nres];
 8170:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
 8171:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
 8172:    /*   if(m != 1 && TKresult[nres]!= k1) */
 8173:    /*     continue; */
 8174: 
 8175:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
 8176:      jj1++;
 8177:      if (cptcovn > 0) {
 8178:        fprintf(fichtm,"\n<p><a name=\"rescov");
 8179:        for (cpt=1; cpt<=cptcovs;cpt++){ 
 8180: 	 fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
 8181:        }
 8182:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 8183:        /* 	 fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
 8184:        /* } */
 8185:        fprintf(fichtm,"\"</a>");
 8186:  
 8187:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 8188:        for (cpt=1; cpt<=cptcovs;cpt++){ 
 8189: 	 fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
 8190: 	 printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
 8191: 	 /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
 8192: 	 /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
 8193:        }
 8194:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
 8195:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
 8196:        if(invalidvarcomb[k1]){
 8197: 	 fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
 8198: 	 printf("\nCombination (%d) ignored because no cases \n",k1); 
 8199: 	 continue;
 8200:        }
 8201:      }
 8202:      /* aij, bij */
 8203:      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> \
 8204: <img src=\"%s_%d-1-%d.svg\">",model,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres);
 8205:      /* Pij */
 8206:      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> \
 8207: <img src=\"%s_%d-2-%d.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres);     
 8208:      /* Quasi-incidences */
 8209:      fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
 8210:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
 8211:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
 8212: 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> \
 8213: <img src=\"%s_%d-3-%d.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres); 
 8214:      /* Survival functions (period) in state j */
 8215:      for(cpt=1; cpt<=nlstate;cpt++){
 8216:        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);
 8217:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
 8218:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
 8219:      }
 8220:      /* State specific survival functions (period) */
 8221:      for(cpt=1; cpt<=nlstate;cpt++){
 8222:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
 8223:  And probability to be observed in various states (up to %d) being in state %d at different ages.	\
 8224:  <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);
 8225:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
 8226:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
 8227:      }
 8228:      /* Period (forward stable) prevalence in each health state */
 8229:      for(cpt=1; cpt<=nlstate;cpt++){
 8230:        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);
 8231:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
 8232:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
 8233:      }
 8234:      if(prevbcast==1){
 8235:        /* Backward prevalence in each health state */
 8236:        for(cpt=1; cpt<=nlstate;cpt++){
 8237: 	 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);
 8238: 	 fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
 8239: 	 fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
 8240:        }
 8241:      }
 8242:      if(prevfcast==1){
 8243:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
 8244:        for(cpt=1; cpt<=nlstate;cpt++){
 8245: 	 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);
 8246: 	 fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
 8247: 	 fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
 8248: 		 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
 8249:        }
 8250:      }
 8251:      if(prevbcast==1){
 8252:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
 8253:        for(cpt=1; cpt<=nlstate;cpt++){
 8254: 	 fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
 8255:  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 \
 8256:  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) \
 8257: 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);
 8258: 	 fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
 8259: 	 fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
 8260:        }
 8261:      }
 8262: 	 
 8263:      for(cpt=1; cpt<=nlstate;cpt++) {
 8264:        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);
 8265:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
 8266:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
 8267:      }
 8268:      /* } /\* end i1 *\/ */
 8269:    }/* End k1=nres */
 8270:    fprintf(fichtm,"</ul>");
 8271: 
 8272:    fprintf(fichtm,"\
 8273: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
 8274:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
 8275:  - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
 8276: But because parameters are usually highly correlated (a higher incidence of disability \
 8277: and a higher incidence of recovery can give very close observed transition) it might \
 8278: be very useful to look not only at linear confidence intervals estimated from the \
 8279: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
 8280: (parameters) of the logistic regression, it might be more meaningful to visualize the \
 8281: covariance matrix of the one-step probabilities. \
 8282: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
 8283: 
 8284:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 8285: 	   subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
 8286:    fprintf(fichtm,"\
 8287:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 8288: 	   subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
 8289: 
 8290:    fprintf(fichtm,"\
 8291:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 8292: 	   subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
 8293:    fprintf(fichtm,"\
 8294:  - 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): \
 8295:    <a href=\"%s\">%s</a> <br>\n</li>",
 8296: 	   estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
 8297:    fprintf(fichtm,"\
 8298:  - (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): \
 8299:    <a href=\"%s\">%s</a> <br>\n</li>",
 8300: 	   estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
 8301:    fprintf(fichtm,"\
 8302:  - 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",
 8303: 	   estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
 8304:    fprintf(fichtm,"\
 8305:  - 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",
 8306: 	   estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
 8307:    fprintf(fichtm,"\
 8308:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
 8309: 	   subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
 8310: 
 8311: /*  if(popforecast==1) fprintf(fichtm,"\n */
 8312: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
 8313: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
 8314: /* 	<br>",fileres,fileres,fileres,fileres); */
 8315: /*  else  */
 8316: /*    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); */
 8317:    fflush(fichtm);
 8318: 
 8319:    m=pow(2,cptcoveff);
 8320:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 8321: 
 8322:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
 8323: 
 8324:   jj1=0;
 8325: 
 8326:    fprintf(fichtm," \n<ul>");
 8327:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 8328:      /* k1=nres; */
 8329:      k1=TKresult[nres];
 8330:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
 8331:      /* if(m != 1 && TKresult[nres]!= k1) */
 8332:      /*   continue; */
 8333:      jj1++;
 8334:      if (cptcovn > 0) {
 8335:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
 8336:        for (cpt=1; cpt<=cptcovs;cpt++){ 
 8337: 	 fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
 8338:        }
 8339:        fprintf(fichtm,"\">");
 8340:        
 8341:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
 8342:        fprintf(fichtm,"************ Results for covariates");
 8343:        for (cpt=1; cpt<=cptcovs;cpt++){ 
 8344: 	 fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
 8345:        }
 8346:        if(invalidvarcomb[k1]){
 8347: 	 fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
 8348: 	 continue;
 8349:        }
 8350:        fprintf(fichtm,"</a></li>");
 8351:      } /* cptcovn >0 */
 8352:    } /* End nres */
 8353:    fprintf(fichtm," \n</ul>");
 8354: 
 8355:    jj1=0;
 8356: 
 8357:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 8358:      /* k1=nres; */
 8359:      k1=TKresult[nres];
 8360:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
 8361:      /* for(k1=1; k1<=m;k1++){ */
 8362:      /* if(m != 1 && TKresult[nres]!= k1) */
 8363:      /*   continue; */
 8364:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
 8365:      jj1++;
 8366:      if (cptcovn > 0) {
 8367:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
 8368:        for (cpt=1; cpt<=cptcovs;cpt++){ 
 8369: 	 fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
 8370:        }
 8371:        fprintf(fichtm,"\"</a>");
 8372:        
 8373:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 8374:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
 8375: 	 fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
 8376: 	 printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
 8377: 	 /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
 8378:        }
 8379: 
 8380:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
 8381: 
 8382:        if(invalidvarcomb[k1]){
 8383: 	 fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
 8384: 	 continue;
 8385:        }
 8386:      } /* If cptcovn >0 */
 8387:      for(cpt=1; cpt<=nlstate;cpt++) {
 8388:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
 8389: 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);
 8390:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
 8391:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
 8392:      }
 8393:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
 8394: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
 8395: true period expectancies (those weighted with period prevalences are also\
 8396:  drawn in addition to the population based expectancies computed using\
 8397:  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);
 8398:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
 8399:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
 8400:      /* } /\* end i1 *\/ */
 8401:   }/* End nres */
 8402:    fprintf(fichtm,"</ul>");
 8403:    fflush(fichtm);
 8404: }
 8405: 
 8406: /******************* Gnuplot file **************/
 8407: 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){
 8408: 
 8409:   char dirfileres[256],optfileres[256];
 8410:   char gplotcondition[256], gplotlabel[256];
 8411:   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;
 8412:   int lv=0, vlv=0, kl=0;
 8413:   int ng=0;
 8414:   int vpopbased;
 8415:   int ioffset; /* variable offset for columns */
 8416:   int iyearc=1; /* variable column for year of projection  */
 8417:   int iagec=1; /* variable column for age of projection  */
 8418:   int nres=0; /* Index of resultline */
 8419:   int istart=1; /* For starting graphs in projections */
 8420: 
 8421: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
 8422: /*     printf("Problem with file %s",optionfilegnuplot); */
 8423: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
 8424: /*   } */
 8425: 
 8426:   /*#ifdef windows */
 8427:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 8428:   /*#endif */
 8429:   m=pow(2,cptcoveff);
 8430: 
 8431:   /* diagram of the model */
 8432:   fprintf(ficgp,"\n#Diagram of the model \n");
 8433:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
 8434:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
 8435:   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);
 8436: 
 8437:   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);
 8438:   fprintf(ficgp,"\n#show arrow\nunset label\n");
 8439:   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);
 8440:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
 8441:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
 8442:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
 8443:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
 8444: 
 8445:   /* Contribution to likelihood */
 8446:   /* Plot the probability implied in the likelihood */
 8447:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
 8448:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
 8449:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
 8450:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
 8451: /* nice for mle=4 plot by number of matrix products.
 8452:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
 8453: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
 8454:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
 8455:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
 8456:   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));
 8457:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
 8458:   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));
 8459:   for (i=1; i<= nlstate ; i ++) {
 8460:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
 8461:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
 8462:     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);
 8463:     for (j=2; j<= nlstate+ndeath ; j ++) {
 8464:       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);
 8465:     }
 8466:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
 8467:   }
 8468:   /* 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 */		 
 8469:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
 8470:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
 8471:   fprintf(ficgp,"\nset out;unset log\n");
 8472:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
 8473: 
 8474:   /* Plot the probability implied in the likelihood by covariate value */
 8475:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
 8476:   /* if(debugILK==1){ */
 8477:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
 8478:     kvar=Tvar[TvarFind[kf]]; /* variable name */
 8479:     /* k=18+Tvar[TvarFind[kf]];/\*offset because there are 18 columns in the ILK_ file but could be placed else where *\/ */
 8480:     /* k=18+kf;/\*offset because there are 18 columns in the ILK_ file *\/ */
 8481:     /* k=19+kf;/\*offset because there are 19 columns in the ILK_ file *\/ */
 8482:     k=16+nlstate+kf;/*offset because there are 19 columns in the ILK_ file, first cov Vn on col 21 with 4 living states */
 8483:     for (i=1; i<= nlstate ; i ++) {
 8484:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
 8485:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
 8486:       if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
 8487: 	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);
 8488: 	for (j=2; j<= nlstate+ndeath ; j ++) {
 8489: 	  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);
 8490: 	}
 8491:       }else{
 8492: 	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);
 8493: 	for (j=2; j<= nlstate+ndeath ; j ++) {
 8494: 	  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);
 8495: 	}
 8496:       }
 8497:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
 8498:     }
 8499:   } /* End of each covariate dummy */
 8500:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
 8501:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
 8502:      *     kmodel       =     1   2     3     4         5        6        7       8        9
 8503:      *  varying                   1     2                                 3       4        5
 8504:      *  ncovv                     1     2                                3 4     5 6      7 8
 8505:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
 8506:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
 8507:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
 8508:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
 8509:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
 8510:      */
 8511:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
 8512:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
 8513:     /* 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]); */
 8514:     if(ipos!=iposold){ /* Not a product or first of a product */
 8515:       /* printf(" %d",ipos); */
 8516:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
 8517:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
 8518:       kk++; /* Position of the ncovv column in ILK_ */
 8519:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
 8520:       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)  */
 8521: 	for (i=1; i<= nlstate ; i ++) {
 8522: 	  fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
 8523: 	  fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
 8524: 
 8525: 	    /* printf("Before DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
 8526: 	  if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
 8527: 	    /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
 8528: 	    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);
 8529: 	    for (j=2; j<= nlstate+ndeath ; j ++) {
 8530: 	      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);
 8531: 	    }
 8532: 	  }else{
 8533: 	    /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
 8534: 	    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);
 8535: 	    for (j=2; j<= nlstate+ndeath ; j ++) {
 8536: 	      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);
 8537: 	    }
 8538: 	  }
 8539: 	  fprintf(ficgp,";\nset out; unset ylabel;\n"); 
 8540: 	}
 8541:       }/* End if dummy varying */
 8542:     }else{ /*Product */
 8543:       /* printf("*"); */
 8544:       /* fprintf(ficresilk,"*"); */
 8545:     }
 8546:     iposold=ipos;
 8547:   } /* For each time varying covariate */
 8548:   /* } /\* debugILK==1 *\/ */
 8549:   /* 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 */		 
 8550:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
 8551:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
 8552:   fprintf(ficgp,"\nset out;unset log\n");
 8553:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
 8554: 
 8555: 
 8556:   
 8557:   strcpy(dirfileres,optionfilefiname);
 8558:   strcpy(optfileres,"vpl");
 8559:   /* 1eme*/
 8560:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
 8561:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
 8562:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 8563: 	k1=TKresult[nres];
 8564: 	if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
 8565: 	/* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
 8566: 	/* if(m != 1 && TKresult[nres]!= k1) */
 8567: 	/*   continue; */
 8568: 	/* We are interested in selected combination by the resultline */
 8569: 	/* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
 8570: 	fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
 8571: 	strcpy(gplotlabel,"(");
 8572: 	for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 8573: 	  fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 8574: 	  sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 8575: 
 8576: 	/* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
 8577: 	/*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
 8578: 	/*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
 8579: 	/*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
 8580: 	/*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
 8581: 	/*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
 8582: 	/*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
 8583: 	/*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
 8584: 	/*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
 8585: 	/*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
 8586: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
 8587: 	/* } */
 8588: 	/* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 8589: 	/*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
 8590: 	/*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
 8591: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
 8592: 	}
 8593: 	strcpy(gplotlabel+strlen(gplotlabel),")");
 8594: 	/* printf("\n#\n"); */
 8595: 	fprintf(ficgp,"\n#\n");
 8596: 	if(invalidvarcomb[k1]){
 8597:           /*k1=k1-1;*/ /* To be checked */
 8598: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 8599: 	  continue;
 8600: 	}
 8601:       
 8602: 	fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
 8603: 	fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
 8604: 	/* fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel); */
 8605: 	fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
 8606: 	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);
 8607: 	/* 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); */
 8608:       /* k1-1 error should be nres-1*/
 8609: 	for (i=1; i<= nlstate ; i ++) {
 8610: 	  if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 8611: 	  else        fprintf(ficgp," %%*lf (%%*lf)");
 8612: 	}
 8613: 	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);
 8614: 	for (i=1; i<= nlstate ; i ++) {
 8615: 	  if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 8616: 	  else fprintf(ficgp," %%*lf (%%*lf)");
 8617: 	} 
 8618: 	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); 
 8619: 	for (i=1; i<= nlstate ; i ++) {
 8620: 	  if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 8621: 	  else fprintf(ficgp," %%*lf (%%*lf)");
 8622: 	}  
 8623: 	/* 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)); */
 8624: 	
 8625: 	fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
 8626:         if(cptcoveff ==0){
 8627: 	  fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",	 2+3*(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: 	    kl++;
 8638: 	    /* 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 *\/ */
 8639: 	    /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
 8640: 	    /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
 8641: 	    /* ''  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*/
 8642: 	    if(k==cptcoveff){
 8643: 	      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], \
 8644: 		      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
 8645: 	    }else{
 8646: 	      fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
 8647: 	      kl++;
 8648: 	    }
 8649: 	  } /* end covariate */
 8650: 	} /* end if no covariate */
 8651: 
 8652: 	if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
 8653: 	  /* 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); */
 8654: 	  fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
 8655: 	  if(cptcoveff ==0){
 8656: 	    fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",	 2+(cpt-1),  cpt );
 8657: 	  }else{
 8658: 	    kl=0;
 8659: 	    for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
 8660: 	      /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
 8661: 	      lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
 8662: 	      /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 8663: 	      /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 8664: 	      /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 8665: 	      /* vlv= nbcode[Tvaraff[k]][lv]; */
 8666: 	      vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
 8667: 	      kl++;
 8668: 	      /* 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 *\/ */
 8669: 	      /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
 8670: 	      /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
 8671: 	      /* ''  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*/
 8672: 	      if(k==cptcoveff){
 8673: 		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], \
 8674: 			2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
 8675: 	      }else{
 8676: 		fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
 8677: 		kl++;
 8678: 	      }
 8679: 	    } /* end covariate */
 8680: 	  } /* end if no covariate */
 8681: 	  if(prevbcast == 1){
 8682: 	    fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
 8683: 	    /* k1-1 error should be nres-1*/
 8684: 	    for (i=1; i<= nlstate ; i ++) {
 8685: 	      if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 8686: 	      else        fprintf(ficgp," %%*lf (%%*lf)");
 8687: 	    }
 8688: 	    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);
 8689: 	    for (i=1; i<= nlstate ; i ++) {
 8690: 	      if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 8691: 	      else fprintf(ficgp," %%*lf (%%*lf)");
 8692: 	    } 
 8693: 	    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); 
 8694: 	    for (i=1; i<= nlstate ; i ++) {
 8695: 	      if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 8696: 	      else fprintf(ficgp," %%*lf (%%*lf)");
 8697: 	    } 
 8698: 	    fprintf(ficgp,"\" t\"\" w l lt 4");
 8699: 	  } /* end if backprojcast */
 8700: 	} /* end if prevbcast */
 8701: 	/* fprintf(ficgp,"\nset out ;unset label;\n"); */
 8702: 	fprintf(ficgp,"\nset out ;unset title;\n");
 8703:       } /* nres */
 8704:     /* } /\* k1 *\/ */
 8705:   } /* cpt */
 8706: 
 8707:   
 8708:   /*2 eme*/
 8709:   /* for (k1=1; k1<= m ; k1 ++){   */
 8710:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 8711:       k1=TKresult[nres];
 8712:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
 8713:       /* if(m != 1 && TKresult[nres]!= k1) */
 8714:       /* 	continue; */
 8715:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
 8716:       strcpy(gplotlabel,"(");
 8717:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 8718: 	fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 8719: 	sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 8720:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
 8721:       /* 	/\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
 8722:       /* 	lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
 8723:       /* 	/\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
 8724:       /* 	/\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
 8725:       /* 	/\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
 8726:       /* 	/\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
 8727:       /* 	vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
 8728:       /* 	fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
 8729:       /* 	sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
 8730:       /* } */
 8731:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
 8732:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 8733:       /* 	printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
 8734:       /* 	fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
 8735:       /* 	sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
 8736:       }
 8737:       strcpy(gplotlabel+strlen(gplotlabel),")");
 8738:       fprintf(ficgp,"\n#\n");
 8739:       if(invalidvarcomb[k1]){
 8740: 	fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 8741: 	continue;
 8742:       }
 8743: 			
 8744:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
 8745:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 8746: 	fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
 8747: 	if(vpopbased==0){
 8748: 	  fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
 8749: 	}else
 8750: 	  fprintf(ficgp,"\nreplot ");
 8751: 	for (i=1; i<= nlstate+1 ; i ++) {
 8752: 	  k=2*i;
 8753: 	  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);
 8754: 	  for (j=1; j<= nlstate+1 ; j ++) {
 8755: 	    if (j==i) fprintf(ficgp," %%lf (%%lf)");
 8756: 	    else fprintf(ficgp," %%*lf (%%*lf)");
 8757: 	  }   
 8758: 	  if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
 8759: 	  else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
 8760: 	  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);
 8761: 	  for (j=1; j<= nlstate+1 ; j ++) {
 8762: 	    if (j==i) fprintf(ficgp," %%lf (%%lf)");
 8763: 	    else fprintf(ficgp," %%*lf (%%*lf)");
 8764: 	  }   
 8765: 	  fprintf(ficgp,"\" t\"\" w l lt 0,");
 8766: 	  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);
 8767: 	  for (j=1; j<= nlstate+1 ; j ++) {
 8768: 	    if (j==i) fprintf(ficgp," %%lf (%%lf)");
 8769: 	    else fprintf(ficgp," %%*lf (%%*lf)");
 8770: 	  }   
 8771: 	  if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
 8772: 	  else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
 8773: 	} /* state */
 8774:       } /* vpopbased */
 8775:       fprintf(ficgp,"\nset out;set out \"%s_%d-%d.svg\"; replot; set out; unset label;\n",subdirf2(optionfilefiname,"E_"),k1,nres); /* Buggy gnuplot */
 8776:     } /* end nres */
 8777:   /* } /\* k1 end 2 eme*\/ */
 8778: 	
 8779: 	
 8780:   /*3eme*/
 8781:   /* for (k1=1; k1<= m ; k1 ++){ */
 8782:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 8783:       k1=TKresult[nres];
 8784:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
 8785:       /* if(m != 1 && TKresult[nres]!= k1) */
 8786:       /* 	continue; */
 8787: 
 8788:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
 8789: 	fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
 8790: 	strcpy(gplotlabel,"(");
 8791: 	for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 8792: 	  fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 8793: 	  sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 8794: 	/* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
 8795: 	/*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
 8796: 	/*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
 8797: 	/*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
 8798: 	/*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
 8799: 	/*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
 8800: 	/*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
 8801: 	/*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
 8802: 	/*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
 8803: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
 8804: 	/* } */
 8805: 	/* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 8806: 	/*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
 8807: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
 8808: 	}
 8809: 	strcpy(gplotlabel+strlen(gplotlabel),")");
 8810: 	fprintf(ficgp,"\n#\n");
 8811: 	if(invalidvarcomb[k1]){
 8812: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 8813: 	  continue;
 8814: 	}
 8815: 			
 8816: 	/*       k=2+nlstate*(2*cpt-2); */
 8817: 	k=2+(nlstate+1)*(cpt-1);
 8818: 	fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
 8819: 	fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
 8820: 	fprintf(ficgp,"set ter svg size 640, 480\n\
 8821: 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);
 8822: 	/*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 8823: 	  for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 8824: 	  fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 8825: 	  fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 8826: 	  for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 8827: 	  fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 8828: 				
 8829: 	*/
 8830: 	for (i=1; i< nlstate ; i ++) {
 8831: 	  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);
 8832: 	  /*	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);*/
 8833: 				
 8834: 	} 
 8835: 	fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),nres-1,nres-1,k+nlstate,cpt);
 8836:       }
 8837:       fprintf(ficgp,"\nunset label;\n");
 8838:     } /* end nres */
 8839:   /* } /\* end kl 3eme *\/ */
 8840:   
 8841:   /* 4eme */
 8842:   /* Survival functions (period) from state i in state j by initial state i */
 8843:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
 8844:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 8845:       k1=TKresult[nres];
 8846:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
 8847:       /* if(m != 1 && TKresult[nres]!= k1) */
 8848:       /* 	continue; */
 8849:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
 8850: 	strcpy(gplotlabel,"(");
 8851: 	fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
 8852: 	for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 8853: 	  fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 8854: 	  sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 8855: 	/* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
 8856: 	/*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
 8857: 	/*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
 8858: 	/*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
 8859: 	/*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
 8860: 	/*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
 8861: 	/*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
 8862: 	/*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
 8863: 	/*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
 8864: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
 8865: 	/* } */
 8866: 	/* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 8867: 	/*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 8868: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 8869: 	}	
 8870: 	strcpy(gplotlabel+strlen(gplotlabel),")");
 8871: 	fprintf(ficgp,"\n#\n");
 8872: 	if(invalidvarcomb[k1]){
 8873: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 8874: 	  continue;
 8875: 	}
 8876:       
 8877: 	fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
 8878: 	fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
 8879: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
 8880: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
 8881: 	k=3;
 8882: 	for (i=1; i<= nlstate ; i ++){
 8883: 	  if(i==1){
 8884: 	    fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 8885: 	  }else{
 8886: 	    fprintf(ficgp,", '' ");
 8887: 	  }
 8888: 	  l=(nlstate+ndeath)*(i-1)+1;
 8889: 	  fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 8890: 	  for (j=2; j<= nlstate+ndeath ; j ++)
 8891: 	    fprintf(ficgp,"+$%d",k+l+j-1);
 8892: 	  fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
 8893: 	} /* nlstate */
 8894: 	fprintf(ficgp,"\nset out; unset label;\n");
 8895:       } /* end cpt state*/ 
 8896:     } /* end nres */
 8897:   /* } /\* end covariate k1 *\/   */
 8898: 
 8899: /* 5eme */
 8900:   /* Survival functions (period) from state i in state j by final state j */
 8901:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
 8902:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 8903:       k1=TKresult[nres];
 8904:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
 8905:       /* if(m != 1 && TKresult[nres]!= k1) */
 8906:       /* 	continue; */
 8907:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
 8908: 	strcpy(gplotlabel,"(");
 8909: 	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);
 8910: 	for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 8911: 	  fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 8912: 	  sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 8913: 	/* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
 8914: 	/*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
 8915: 	/*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
 8916: 	/*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
 8917: 	/*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
 8918: 	/*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
 8919: 	/*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
 8920: 	/*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
 8921: 	/*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
 8922: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
 8923: 	/* } */
 8924: 	/* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 8925: 	/*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 8926: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 8927: 	}	
 8928: 	strcpy(gplotlabel+strlen(gplotlabel),")");
 8929: 	fprintf(ficgp,"\n#\n");
 8930: 	if(invalidvarcomb[k1]){
 8931: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 8932: 	  continue;
 8933: 	}
 8934:       
 8935: 	fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
 8936: 	fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
 8937: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
 8938: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
 8939: 	k=3;
 8940: 	for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
 8941: 	  if(j==1)
 8942: 	    fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 8943: 	  else
 8944: 	    fprintf(ficgp,", '' ");
 8945: 	  l=(nlstate+ndeath)*(cpt-1) +j;
 8946: 	  fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
 8947: 	  /* for (i=2; i<= nlstate+ndeath ; i ++) */
 8948: 	  /*   fprintf(ficgp,"+$%d",k+l+i-1); */
 8949: 	  fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
 8950: 	} /* nlstate */
 8951: 	fprintf(ficgp,", '' ");
 8952: 	fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
 8953: 	for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
 8954: 	  l=(nlstate+ndeath)*(cpt-1) +j;
 8955: 	  if(j < nlstate)
 8956: 	    fprintf(ficgp,"$%d +",k+l);
 8957: 	  else
 8958: 	    fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
 8959: 	}
 8960: 	fprintf(ficgp,"\nset out; unset label;\n");
 8961:       } /* end cpt state*/ 
 8962:     /* } /\* end covariate *\/   */
 8963:   } /* end nres */
 8964:   
 8965: /* 6eme */
 8966:   /* CV preval stable (period) for each covariate */
 8967:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
 8968:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 8969:      k1=TKresult[nres];
 8970:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
 8971:      /* if(m != 1 && TKresult[nres]!= k1) */
 8972:      /*  continue; */
 8973:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
 8974:       strcpy(gplotlabel,"(");      
 8975:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
 8976:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 8977: 	fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 8978: 	sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 8979:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
 8980:       /* 	/\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
 8981:       /* 	lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
 8982:       /* 	/\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
 8983:       /* 	/\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
 8984:       /* 	/\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
 8985:       /* 	/\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
 8986:       /* 	vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
 8987:       /* 	fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
 8988:       /* 	sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
 8989:       /* } */
 8990:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 8991:       /* 	fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 8992:       /* 	sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 8993:       }	
 8994:       strcpy(gplotlabel+strlen(gplotlabel),")");
 8995:       fprintf(ficgp,"\n#\n");
 8996:       if(invalidvarcomb[k1]){
 8997: 	fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 8998: 	continue;
 8999:       }
 9000:       
 9001:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
 9002:       fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
 9003:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 9004: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
 9005:       k=3; /* Offset */
 9006:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
 9007: 	if(i==1)
 9008: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
 9009: 	else
 9010: 	  fprintf(ficgp,", '' ");
 9011: 	l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
 9012: 	fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 9013: 	for (j=2; j<= nlstate ; j ++)
 9014: 	  fprintf(ficgp,"+$%d",k+l+j-1);
 9015: 	fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
 9016:       } /* nlstate */
 9017:       fprintf(ficgp,"\nset out; unset label;\n");
 9018:     } /* end cpt state*/ 
 9019:   } /* end covariate */  
 9020:   
 9021:   
 9022: /* 7eme */
 9023:   if(prevbcast == 1){
 9024:     /* CV backward prevalence  for each covariate */
 9025:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
 9026:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 9027:       k1=TKresult[nres];
 9028:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
 9029:       /* if(m != 1 && TKresult[nres]!= k1) */
 9030:       /* 	continue; */
 9031:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
 9032: 	strcpy(gplotlabel,"(");      
 9033:  	fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
 9034: 	for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 9035: 	  fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 9036: 	  sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 9037: 	/* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
 9038: 	/*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
 9039: 	/*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
 9040: 	/*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
 9041: 	/*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
 9042: 	/*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
 9043: 	/*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
 9044: 	/*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
 9045: 	/*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
 9046: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
 9047: 	/* } */
 9048: 	/* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 9049: 	/*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 9050: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 9051: 	}	
 9052: 	strcpy(gplotlabel+strlen(gplotlabel),")");
 9053: 	fprintf(ficgp,"\n#\n");
 9054: 	if(invalidvarcomb[k1]){
 9055: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 9056: 	  continue;
 9057: 	}
 9058: 	
 9059: 	fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
 9060: 	fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
 9061: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 9062: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
 9063: 	k=3; /* Offset */
 9064: 	for (i=1; i<= nlstate ; i ++){ /* State of arrival */
 9065: 	  if(i==1)
 9066: 	    fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
 9067: 	  else
 9068: 	    fprintf(ficgp,", '' ");
 9069: 	  /* l=(nlstate+ndeath)*(i-1)+1; */
 9070: 	  l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
 9071: 	  /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
 9072: 	  /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
 9073: 	  fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
 9074: 	  /* for (j=2; j<= nlstate ; j ++) */
 9075: 	  /* 	fprintf(ficgp,"+$%d",k+l+j-1); */
 9076: 	  /* 	/\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
 9077: 	  fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
 9078: 	} /* nlstate */
 9079: 	fprintf(ficgp,"\nset out; unset label;\n");
 9080:       } /* end cpt state*/ 
 9081:     } /* end covariate */  
 9082:   } /* End if prevbcast */
 9083:   
 9084:   /* 8eme */
 9085:   if(prevfcast==1){
 9086:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
 9087:     
 9088:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
 9089:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 9090:       k1=TKresult[nres];
 9091:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
 9092:       /* if(m != 1 && TKresult[nres]!= k1) */
 9093:       /* 	continue; */
 9094:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 9095: 	strcpy(gplotlabel,"(");      
 9096: 	fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
 9097: 	for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 9098: 	  fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 9099: 	  sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 9100: 	/* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
 9101: 	/*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
 9102: 	/*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
 9103: 	/*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
 9104: 	/*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
 9105: 	/*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
 9106: 	/*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
 9107: 	/*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
 9108: 	/*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
 9109: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
 9110: 	/* } */
 9111: 	/* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 9112: 	/*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 9113: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 9114: 	}	
 9115: 	strcpy(gplotlabel+strlen(gplotlabel),")");
 9116: 	fprintf(ficgp,"\n#\n");
 9117: 	if(invalidvarcomb[k1]){
 9118: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 9119: 	  continue;
 9120: 	}
 9121: 	
 9122: 	fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
 9123: 	fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
 9124: 	fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
 9125: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
 9126: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
 9127: 
 9128: 	/* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
 9129: 	istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
 9130: 	/*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
 9131: 	for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
 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: 	  /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 9135: 	  /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 9136: 	  if(i==istart){
 9137: 	    fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
 9138: 	  }else{
 9139: 	    fprintf(ficgp,",\\\n '' ");
 9140: 	  }
 9141: 	  if(cptcoveff ==0){ /* No covariate */
 9142: 	    ioffset=2; /* Age is in 2 */
 9143: 	    /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
 9144: 	    /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
 9145: 	    /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
 9146: 	    /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
 9147: 	    fprintf(ficgp," u %d:(", ioffset); 
 9148: 	    if(i==nlstate+1){
 9149: 	      fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",	\
 9150: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
 9151: 	      fprintf(ficgp,",\\\n '' ");
 9152: 	      fprintf(ficgp," u %d:(",ioffset); 
 9153: 	      fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
 9154: 		     offyear,				\
 9155: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
 9156: 	    }else
 9157: 	      fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",	\
 9158: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
 9159: 	  }else{ /* more than 2 covariates */
 9160: 	    ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
 9161: 	    /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 9162: 	    /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
 9163: 	    iyearc=ioffset-1;
 9164: 	    iagec=ioffset;
 9165: 	    fprintf(ficgp," u %d:(",ioffset); 
 9166: 	    kl=0;
 9167: 	    strcpy(gplotcondition,"(");
 9168: 	    /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
 9169: 	      /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
 9170: 	    for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 9171: 	      /* lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
 9172: 	      lv=Tvresult[nres][k];
 9173: 	      vlv=TinvDoQresult[nres][Tvresult[nres][k]];
 9174: 	      /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 9175: 	      /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 9176: 	      /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 9177: 	      /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
 9178: 	      /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
 9179: 	      kl++;
 9180: 	      /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
 9181: 	      sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,lv, kl+1, vlv );
 9182: 	      kl++;
 9183: 	      if(k <cptcovs && cptcovs>1)
 9184: 		sprintf(gplotcondition+strlen(gplotcondition)," && ");
 9185: 	    }
 9186: 	    strcpy(gplotcondition+strlen(gplotcondition),")");
 9187: 	    /* 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 *\/ */
 9188: 	    /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
 9189: 	    /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
 9190: 	    /* ''  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*/
 9191: 	    if(i==nlstate+1){
 9192: 	      fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
 9193: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
 9194: 	      fprintf(ficgp,",\\\n '' ");
 9195: 	      fprintf(ficgp," u %d:(",iagec); 
 9196: 	      fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
 9197: 		      iyearc, iagec, offyear,				\
 9198: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
 9199: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
 9200: 	    }else{
 9201: 	      fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
 9202: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
 9203: 	    }
 9204: 	  } /* end if covariate */
 9205: 	} /* nlstate */
 9206: 	fprintf(ficgp,"\nset out; unset label;\n");
 9207:       } /* end cpt state*/
 9208:     } /* end covariate */
 9209:   } /* End if prevfcast */
 9210:   
 9211:   if(prevbcast==1){
 9212:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
 9213:     
 9214:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
 9215:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 9216:      k1=TKresult[nres];
 9217:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
 9218:        /* if(m != 1 && TKresult[nres]!= k1) */
 9219:        /* 	continue; */
 9220:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 9221: 	strcpy(gplotlabel,"(");      
 9222: 	fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
 9223: 	for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
 9224: 	  fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 9225: 	  sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 9226: 	/* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
 9227: 	/*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
 9228: 	/*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
 9229: 	/*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
 9230: 	/*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
 9231: 	/*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
 9232: 	/*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
 9233: 	/*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
 9234: 	/*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
 9235: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
 9236: 	/* } */
 9237: 	/* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 9238: 	/*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 9239: 	/*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 9240: 	}	
 9241: 	strcpy(gplotlabel+strlen(gplotlabel),")");
 9242: 	fprintf(ficgp,"\n#\n");
 9243: 	if(invalidvarcomb[k1]){
 9244: 	  fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
 9245: 	  continue;
 9246: 	}
 9247: 	
 9248: 	fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
 9249: 	fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
 9250: 	fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
 9251: 	fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
 9252: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
 9253: 
 9254: 	/* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
 9255: 	istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
 9256: 	/*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
 9257: 	for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
 9258: 	  /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 9259: 	  /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 9260: 	  /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 9261: 	  /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
 9262: 	  if(i==istart){
 9263: 	    fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
 9264: 	  }else{
 9265: 	    fprintf(ficgp,",\\\n '' ");
 9266: 	  }
 9267: 	  /* if(cptcoveff ==0){ /\* No covariate *\/ */
 9268: 	  if(cptcovs ==0){ /* No covariate */
 9269: 	    ioffset=2; /* Age is in 2 */
 9270: 	    /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
 9271: 	    /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
 9272: 	    /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
 9273: 	    /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
 9274: 	    fprintf(ficgp," u %d:(", ioffset); 
 9275: 	    if(i==nlstate+1){
 9276: 	      fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ",	\
 9277: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
 9278: 	      fprintf(ficgp,",\\\n '' ");
 9279: 	      fprintf(ficgp," u %d:(",ioffset); 
 9280: 	      fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
 9281: 		     offbyear,				\
 9282: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
 9283: 	    }else
 9284: 	      fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",	\
 9285: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
 9286: 	  }else{ /* more than 2 covariates */
 9287: 	    ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
 9288: 	    /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
 9289: 	    /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
 9290: 	    iyearc=ioffset-1;
 9291: 	    iagec=ioffset;
 9292: 	    fprintf(ficgp," u %d:(",ioffset); 
 9293: 	    kl=0;
 9294: 	    strcpy(gplotcondition,"(");
 9295: 	    for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
 9296: 	      if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
 9297: 		/* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
 9298: 		/* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
 9299: 		/* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
 9300: 		lv=Tvresult[nres][k];
 9301: 		vlv=TinvDoQresult[nres][Tvresult[nres][k]];
 9302: 		/* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
 9303: 		/* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
 9304: 		/* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
 9305: 		/* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
 9306: 		/* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
 9307: 		kl++;
 9308: 		/* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
 9309: 		sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
 9310: 		kl++;
 9311: 		if(k <cptcovs && cptcovs>1)
 9312: 		  sprintf(gplotcondition+strlen(gplotcondition)," && ");
 9313: 	      }
 9314: 	    }
 9315: 	    strcpy(gplotcondition+strlen(gplotcondition),")");
 9316: 	    /* 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 *\/ */
 9317: 	    /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
 9318: 	    /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
 9319: 	    /* ''  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*/
 9320: 	    if(i==nlstate+1){
 9321: 	      fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
 9322: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
 9323: 	      fprintf(ficgp,",\\\n '' ");
 9324: 	      fprintf(ficgp," u %d:(",iagec); 
 9325: 	      /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
 9326: 	      fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
 9327: 		      iyearc,iagec,offbyear,				\
 9328: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
 9329: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
 9330: 	    }else{
 9331: 	      /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
 9332: 	      fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
 9333: 		      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
 9334: 	    }
 9335: 	  } /* end if covariate */
 9336: 	} /* nlstate */
 9337: 	fprintf(ficgp,"\nset out; unset label;\n");
 9338:       } /* end cpt state*/
 9339:     } /* end covariate */
 9340:   } /* End if prevbcast */
 9341:   
 9342:   
 9343:   /* 9eme writing MLE parameters */
 9344:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
 9345:   for(i=1,jk=1; i <=nlstate; i++){
 9346:     fprintf(ficgp,"# initial state %d\n",i);
 9347:     for(k=1; k <=(nlstate+ndeath); k++){
 9348:       if (k != i) {
 9349: 	fprintf(ficgp,"#   current state %d\n",k);
 9350: 	for(j=1; j <=ncovmodel; j++){
 9351: 	  fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
 9352: 	  jk++; 
 9353: 	}
 9354: 	fprintf(ficgp,"\n");
 9355:       }
 9356:     }
 9357:   }
 9358:   fprintf(ficgp,"##############\n#\n");
 9359:   
 9360:   /*goto avoid;*/
 9361:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
 9362:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
 9363:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
 9364:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
 9365:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
 9366:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
 9367:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 9368:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 9369:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 9370:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 9371:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
 9372:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 9373:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
 9374:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
 9375:   fprintf(ficgp,"#\n");
 9376:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
 9377:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
 9378:     fprintf(ficgp,"#model=1+age+%s \n",model);
 9379:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
 9380:     /* fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/\* to be checked *\/ */
 9381:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcovs,m);/* to be checked */
 9382:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
 9383:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
 9384:      /* k1=nres; */
 9385:       k1=TKresult[nres];
 9386:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
 9387:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
 9388:       strcpy(gplotlabel,"(");
 9389:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
 9390:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
 9391: 	/* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
 9392: 	   TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
 9393: 	fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 9394: 	sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
 9395:       }
 9396:       /* if(m != 1 && TKresult[nres]!= k1) */
 9397:       /* 	continue; */
 9398:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
 9399:       /* strcpy(gplotlabel,"("); */
 9400:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
 9401:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
 9402:       /* 	/\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
 9403:       /* 	lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
 9404:       /* 	/\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
 9405:       /* 	/\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
 9406:       /* 	/\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
 9407:       /* 	/\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
 9408:       /* 	vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
 9409:       /* 	fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
 9410:       /* 	sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
 9411:       /* } */
 9412:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
 9413:       /* 	fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 9414:       /* 	sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
 9415:       /* }	 */
 9416:       strcpy(gplotlabel+strlen(gplotlabel),")");
 9417:       fprintf(ficgp,"\n#\n");
 9418:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
 9419:       fprintf(ficgp,"\nset key outside ");
 9420:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
 9421:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
 9422:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
 9423:       if (ng==1){
 9424: 	fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
 9425: 	fprintf(ficgp,"\nunset log y");
 9426:       }else if (ng==2){
 9427: 	fprintf(ficgp,"\nset ylabel \"Probability\"\n");
 9428: 	fprintf(ficgp,"\nset log y");
 9429:       }else if (ng==3){
 9430: 	fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
 9431: 	fprintf(ficgp,"\nset log y");
 9432:       }else
 9433: 	fprintf(ficgp,"\nunset title ");
 9434:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
 9435:       i=1;
 9436:       for(k2=1; k2<=nlstate; k2++) {
 9437: 	k3=i;
 9438: 	for(k=1; k<=(nlstate+ndeath); k++) {
 9439: 	  if (k != k2){
 9440: 	    switch( ng) {
 9441: 	    case 1:
 9442: 	      if(nagesqr==0)
 9443: 		fprintf(ficgp," p%d+p%d*x",i,i+1);
 9444: 	      else /* nagesqr =1 */
 9445: 		fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
 9446: 	      break;
 9447: 	    case 2: /* ng=2 */
 9448: 	      if(nagesqr==0)
 9449: 		fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
 9450: 	      else /* nagesqr =1 */
 9451: 		fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
 9452: 	      break;
 9453: 	    case 3:
 9454: 	      if(nagesqr==0)
 9455: 		fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
 9456: 	      else /* nagesqr =1 */
 9457: 		fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
 9458: 	      break;
 9459: 	    }
 9460: 	    ij=1;/* To be checked else nbcode[0][0] wrong */
 9461: 	    ijp=1; /* product no age */
 9462: 	    /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
 9463: 	    for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
 9464: 	      /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
 9465: 	      switch(Typevar[j]){
 9466: 	      case 1:
 9467: 		if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
 9468: 		  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
 9469: 		    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
 9470: 		      if(DummyV[j]==0){/* Bug valgrind */
 9471: 			fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
 9472: 		      }else{ /* quantitative */
 9473: 			fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
 9474: 			/* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
 9475: 		      }
 9476: 		      ij++;
 9477: 		    }
 9478: 		  }
 9479: 		}
 9480: 		break;
 9481: 	      case 2:
 9482: 		if(cptcovprod >0){
 9483: 		  if(j==Tprod[ijp]) { /* */ 
 9484: 		    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
 9485: 		    if(ijp <=cptcovprod) { /* Product */
 9486: 		      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
 9487: 			if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
 9488: 			  /* 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)]); */
 9489: 			  fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
 9490: 			}else{ /* Vn is dummy and Vm is quanti */
 9491: 			  /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
 9492: 			  fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
 9493: 			}
 9494: 		      }else{ /* Vn*Vm Vn is quanti */
 9495: 			if(DummyV[Tvard[ijp][2]]==0){
 9496: 			  fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
 9497: 			}else{ /* Both quanti */
 9498: 			  fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
 9499: 			}
 9500: 		      }
 9501: 		      ijp++;
 9502: 		    }
 9503: 		  } /* end Tprod */
 9504: 		}
 9505: 		break;
 9506: 	      case 3:
 9507: 		if(cptcovdageprod >0){
 9508: 		  /* if(j==Tprod[ijp]) { */ /* not necessary */ 
 9509: 		    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
 9510: 		    if(ijp <=cptcovprod) { /* Product Vn*Vm and age*VN*Vm*/
 9511: 		      if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
 9512: 			if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
 9513: 			  /* 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)]); */
 9514: 			  fprintf(ficgp,"+p%d*%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
 9515: 			}else{ /* Vn is dummy and Vm is quanti */
 9516: 			  /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
 9517: 			  fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
 9518: 			}
 9519: 		      }else{ /* age* Vn*Vm Vn is quanti HERE */
 9520: 			if(DummyV[Tvard[ijp][2]]==0){
 9521: 			  fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvardk[ijp][2]],Tqinvresult[nres][Tvardk[ijp][1]]);
 9522: 			}else{ /* Both quanti */
 9523: 			  fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
 9524: 			}
 9525: 		      }
 9526: 		      ijp++;
 9527: 		    }
 9528: 		    /* } */ /* end Tprod */
 9529: 		}
 9530: 		break;
 9531: 	      case 0:
 9532: 		/* simple covariate */
 9533: 		/* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
 9534: 		if(Dummy[j]==0){
 9535: 		  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
 9536: 		}else{ /* quantitative */
 9537: 		  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
 9538: 		  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
 9539: 		}
 9540: 	       /* end simple */
 9541: 		break;
 9542: 	      default:
 9543: 		break;
 9544: 	      } /* end switch */
 9545: 	    } /* end j */
 9546: 	  }else{ /* k=k2 */
 9547: 	    if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
 9548: 	      fprintf(ficgp," (1.");i=i-ncovmodel;
 9549: 	    }else
 9550: 	      i=i-ncovmodel;
 9551: 	  }
 9552: 	  
 9553: 	  if(ng != 1){
 9554: 	    fprintf(ficgp,")/(1");
 9555: 	    
 9556: 	    for(cpt=1; cpt <=nlstate; cpt++){ 
 9557: 	      if(nagesqr==0)
 9558: 		fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
 9559: 	      else /* nagesqr =1 */
 9560: 		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);
 9561: 	       
 9562: 	      ij=1;
 9563: 	      ijp=1;
 9564: 	      /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
 9565: 	      for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
 9566: 		switch(Typevar[j]){
 9567: 		case 1:
 9568: 		  if(cptcovage >0){ 
 9569: 		    if(j==Tage[ij]) { /* Bug valgrind */
 9570: 		      if(ij <=cptcovage) { /* Bug valgrind */
 9571: 			if(DummyV[j]==0){/* Bug valgrind */
 9572: 			  /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
 9573: 			  /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
 9574: 			  fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
 9575: 			  /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
 9576: 			  /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
 9577: 			}else{ /* quantitative */
 9578: 			  /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
 9579: 			  fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
 9580: 			  /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
 9581: 			  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
 9582: 			}
 9583: 			ij++;
 9584: 		      }
 9585: 		    }
 9586: 		  }
 9587: 		  break;
 9588: 		case 2:
 9589: 		  if(cptcovprod >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[Tvard[ijp][1]]==0){/* Vn is dummy */
 9594: 			  if(DummyV[Tvard[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",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[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",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
 9601: 			    /* fprintf(ficgp,"+p%d*%d*%f",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[Tvard[ijp][2]]==0){
 9605: 			    fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
 9606: 			    /* fprintf(ficgp,"+p%d*%d*%f",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][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
 9609: 			    /* fprintf(ficgp,"+p%d*%f*%f",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 3:
 9618: 		  if(cptcovdageprod >0){
 9619: 		    /* if(j==Tprod[ijp]) { /\* *\/  */
 9620: 		      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
 9621: 		      if(ijp <=cptcovprod) { /* Product */
 9622: 			if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
 9623: 			  if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
 9624: 			    /* 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)]); */
 9625: 			    fprintf(ficgp,"+p%d*%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvardk[ijp][1]],Tinvresult[nres][Tvardk[ijp][2]]);
 9626: 			    /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
 9627: 			  }else{ /* Vn is dummy and Vm is quanti */
 9628: 			    /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
 9629: 			    fprintf(ficgp,"+p%d*%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
 9630: 			    /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
 9631: 			  }
 9632: 			}else{ /* Vn*Vm Vn is quanti */
 9633: 			  if(DummyV[Tvardk[ijp][2]]==0){
 9634: 			    fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvardk[ijp][2]],Tqinvresult[nres][Tvardk[ijp][1]]);
 9635: 			    /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
 9636: 			  }else{ /* Both quanti */
 9637: 			    fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
 9638: 			    /* fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
 9639: 			  } 
 9640: 			}
 9641: 			ijp++;
 9642: 		      }
 9643: 		    /* } /\* end Tprod *\/ */
 9644: 		  } /* end if */
 9645: 		  break;
 9646: 		case 0: 
 9647: 		  /* simple covariate */
 9648: 		  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
 9649: 		  if(Dummy[j]==0){
 9650: 		    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
 9651: 		    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
 9652: 		    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
 9653: 		  }else{ /* quantitative */
 9654: 		    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
 9655: 		    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
 9656: 		    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
 9657: 		  }
 9658: 		  /* end simple */
 9659: 		  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
 9660: 		  break;
 9661: 		default:
 9662: 		  break;
 9663: 		} /* end switch */
 9664: 	      }
 9665: 	      fprintf(ficgp,")");
 9666: 	    }
 9667: 	    fprintf(ficgp,")");
 9668: 	    if(ng ==2)
 9669: 	      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);
 9670: 	    else /* ng= 3 */
 9671: 	      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);
 9672:           }else{ /* end ng <> 1 */
 9673: 	    if( k !=k2) /* logit p11 is hard to draw */
 9674: 	      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);
 9675: 	  }
 9676: 	  if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
 9677: 	    fprintf(ficgp,",");
 9678: 	  if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
 9679: 	    fprintf(ficgp,",");
 9680: 	  i=i+ncovmodel;
 9681: 	} /* end k */
 9682:       } /* end k2 */
 9683:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
 9684:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
 9685:     } /* end resultline */
 9686:   } /* end ng */
 9687:   /* avoid: */
 9688:   fflush(ficgp); 
 9689: }  /* end gnuplot */
 9690: 
 9691: 
 9692: /*************** Moving average **************/
 9693: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
 9694:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
 9695:    
 9696:    int i, cpt, cptcod;
 9697:    int modcovmax =1;
 9698:    int mobilavrange, mob;
 9699:    int iage=0;
 9700:    int firstA1=0, firstA2=0;
 9701: 
 9702:    double sum=0., sumr=0.;
 9703:    double age;
 9704:    double *sumnewp, *sumnewm, *sumnewmr;
 9705:    double *agemingood, *agemaxgood; 
 9706:    double *agemingoodr, *agemaxgoodr; 
 9707:   
 9708:   
 9709:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
 9710:    /* 		   a covariate has 2 modalities, should be equal to ncovcombmax   */
 9711: 
 9712:    sumnewp = vector(1,ncovcombmax);
 9713:    sumnewm = vector(1,ncovcombmax);
 9714:    sumnewmr = vector(1,ncovcombmax);
 9715:    agemingood = vector(1,ncovcombmax);	
 9716:    agemingoodr = vector(1,ncovcombmax);	
 9717:    agemaxgood = vector(1,ncovcombmax);
 9718:    agemaxgoodr = vector(1,ncovcombmax);
 9719: 
 9720:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
 9721:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
 9722:      sumnewp[cptcod]=0.;
 9723:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
 9724:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
 9725:    }
 9726:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
 9727:   
 9728:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
 9729:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
 9730:      else mobilavrange=mobilav;
 9731:      for (age=bage; age<=fage; age++)
 9732:        for (i=1; i<=nlstate;i++)
 9733: 	 for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
 9734: 	   mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 9735:      /* We keep the original values on the extreme ages bage, fage and for 
 9736: 	fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
 9737: 	we use a 5 terms etc. until the borders are no more concerned. 
 9738:      */ 
 9739:      for (mob=3;mob <=mobilavrange;mob=mob+2){
 9740:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
 9741: 	 for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
 9742: 	   sumnewm[cptcod]=0.;
 9743: 	   for (i=1; i<=nlstate;i++){
 9744: 	     mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
 9745: 	     for (cpt=1;cpt<=(mob-1)/2;cpt++){
 9746: 	       mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
 9747: 	       mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
 9748: 	     }
 9749: 	     mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
 9750: 	     sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 9751: 	   } /* end i */
 9752: 	   if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
 9753: 	 } /* end cptcod */
 9754:        }/* end age */
 9755:      }/* end mob */
 9756:    }else{
 9757:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
 9758:      return -1;
 9759:    }
 9760: 
 9761:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
 9762:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
 9763:      if(invalidvarcomb[cptcod]){
 9764:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
 9765:        continue;
 9766:      }
 9767: 
 9768:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
 9769:        sumnewm[cptcod]=0.;
 9770:        sumnewmr[cptcod]=0.;
 9771:        for (i=1; i<=nlstate;i++){
 9772: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 9773: 	 sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
 9774:        }
 9775:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
 9776: 	 agemingoodr[cptcod]=age;
 9777:        }
 9778:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
 9779: 	   agemingood[cptcod]=age;
 9780:        }
 9781:      } /* age */
 9782:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
 9783:        sumnewm[cptcod]=0.;
 9784:        sumnewmr[cptcod]=0.;
 9785:        for (i=1; i<=nlstate;i++){
 9786: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 9787: 	 sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
 9788:        }
 9789:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
 9790: 	 agemaxgoodr[cptcod]=age;
 9791:        }
 9792:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
 9793: 	 agemaxgood[cptcod]=age;
 9794:        }
 9795:      } /* age */
 9796:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
 9797:      /* but they will change */
 9798:      firstA1=0;firstA2=0;
 9799:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
 9800:        sumnewm[cptcod]=0.;
 9801:        sumnewmr[cptcod]=0.;
 9802:        for (i=1; i<=nlstate;i++){
 9803: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 9804: 	 sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
 9805:        }
 9806:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
 9807: 	 if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
 9808: 	   agemaxgoodr[cptcod]=age;  /* age min */
 9809: 	   for (i=1; i<=nlstate;i++)
 9810: 	     mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 9811: 	 }else{ /* bad we change the value with the values of good ages */
 9812: 	   for (i=1; i<=nlstate;i++){
 9813: 	     mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
 9814: 	   } /* i */
 9815: 	 } /* end bad */
 9816:        }else{
 9817: 	 if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
 9818: 	   agemaxgood[cptcod]=age;
 9819: 	 }else{ /* bad we change the value with the values of good ages */
 9820: 	   for (i=1; i<=nlstate;i++){
 9821: 	     mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
 9822: 	   } /* i */
 9823: 	 } /* end bad */
 9824:        }/* end else */
 9825:        sum=0.;sumr=0.;
 9826:        for (i=1; i<=nlstate;i++){
 9827: 	 sum+=mobaverage[(int)age][i][cptcod];
 9828: 	 sumr+=probs[(int)age][i][cptcod];
 9829:        }
 9830:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
 9831: 	 if(!firstA1){
 9832: 	   firstA1=1;
 9833: 	   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);
 9834: 	 }
 9835: 	 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);
 9836:        } /* end bad */
 9837:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
 9838:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
 9839: 	 if(!firstA2){
 9840: 	   firstA2=1;
 9841: 	   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);
 9842: 	 }
 9843: 	 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);
 9844:        } /* end bad */
 9845:      }/* age */
 9846: 
 9847:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
 9848:        sumnewm[cptcod]=0.;
 9849:        sumnewmr[cptcod]=0.;
 9850:        for (i=1; i<=nlstate;i++){
 9851: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 9852: 	 sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
 9853:        } 
 9854:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
 9855: 	 if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
 9856: 	   agemingoodr[cptcod]=age;
 9857: 	   for (i=1; i<=nlstate;i++)
 9858: 	     mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 9859: 	 }else{ /* bad we change the value with the values of good ages */
 9860: 	   for (i=1; i<=nlstate;i++){
 9861: 	     mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
 9862: 	   } /* i */
 9863: 	 } /* end bad */
 9864:        }else{
 9865: 	 if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
 9866: 	   agemingood[cptcod]=age;
 9867: 	 }else{ /* bad */
 9868: 	   for (i=1; i<=nlstate;i++){
 9869: 	     mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
 9870: 	   } /* i */
 9871: 	 } /* end bad */
 9872:        }/* end else */
 9873:        sum=0.;sumr=0.;
 9874:        for (i=1; i<=nlstate;i++){
 9875: 	 sum+=mobaverage[(int)age][i][cptcod];
 9876: 	 sumr+=mobaverage[(int)age][i][cptcod];
 9877:        }
 9878:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
 9879: 	 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);
 9880:        } /* end bad */
 9881:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
 9882:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
 9883: 	 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);
 9884:        } /* end bad */
 9885:      }/* age */
 9886: 
 9887: 		
 9888:      for (age=bage; age<=fage; age++){
 9889:        /* printf("%d %d ", cptcod, (int)age); */
 9890:        sumnewp[cptcod]=0.;
 9891:        sumnewm[cptcod]=0.;
 9892:        for (i=1; i<=nlstate;i++){
 9893: 	 sumnewp[cptcod]+=probs[(int)age][i][cptcod];
 9894: 	 sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
 9895: 	 /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
 9896:        }
 9897:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
 9898:      }
 9899:      /* printf("\n"); */
 9900:      /* } */
 9901: 
 9902:      /* brutal averaging */
 9903:      /* for (i=1; i<=nlstate;i++){ */
 9904:      /*   for (age=1; age<=bage; age++){ */
 9905:      /* 	 mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
 9906:      /* 	 /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
 9907:      /*   }	 */
 9908:      /*   for (age=fage; age<=AGESUP; age++){ */
 9909:      /* 	 mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
 9910:      /* 	 /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
 9911:      /*   } */
 9912:      /* } /\* end i status *\/ */
 9913:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
 9914:      /*   for (age=1; age<=AGESUP; age++){ */
 9915:      /* 	 /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
 9916:      /* 	 mobaverage[(int)age][i][cptcod]=0.; */
 9917:      /*   } */
 9918:      /* } */
 9919:    }/* end cptcod */
 9920:    free_vector(agemaxgoodr,1, ncovcombmax);
 9921:    free_vector(agemaxgood,1, ncovcombmax);
 9922:    free_vector(agemingood,1, ncovcombmax);
 9923:    free_vector(agemingoodr,1, ncovcombmax);
 9924:    free_vector(sumnewmr,1, ncovcombmax);
 9925:    free_vector(sumnewm,1, ncovcombmax);
 9926:    free_vector(sumnewp,1, ncovcombmax);
 9927:    return 0;
 9928:  }/* End movingaverage */
 9929:  
 9930: 
 9931:  
 9932: /************** Forecasting ******************/
 9933: /* 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)*/
 9934: 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){
 9935:   /* dateintemean, mean date of interviews
 9936:      dateprojd, year, month, day of starting projection 
 9937:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
 9938:      agemin, agemax range of age
 9939:      dateprev1 dateprev2 range of dates during which prevalence is computed
 9940:   */
 9941:   /* double anprojd, mprojd, jprojd; */
 9942:   /* double anprojf, mprojf, jprojf; */
 9943:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
 9944:   double agec; /* generic age */
 9945:   double agelim, ppij, yp,yp1,yp2;
 9946:   double *popeffectif,*popcount;
 9947:   double ***p3mat;
 9948:   /* double ***mobaverage; */
 9949:   char fileresf[FILENAMELENGTH];
 9950: 
 9951:   agelim=AGESUP;
 9952:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 9953:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 9954:      We still use firstpass and lastpass as another selection.
 9955:   */
 9956:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
 9957:   /* 	      firstpass, lastpass,  stepm,  weightopt, model); */
 9958:  
 9959:   strcpy(fileresf,"F_"); 
 9960:   strcat(fileresf,fileresu);
 9961:   if((ficresf=fopen(fileresf,"w"))==NULL) {
 9962:     printf("Problem with forecast resultfile: %s\n", fileresf);
 9963:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
 9964:   }
 9965:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
 9966:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
 9967: 
 9968:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 9969: 
 9970: 
 9971:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 9972:   if (stepm<=12) stepsize=1;
 9973:   if(estepm < stepm){
 9974:     printf ("Problem %d lower than %d\n",estepm, stepm);
 9975:   }
 9976:   else{
 9977:     hstepm=estepm;   
 9978:   }
 9979:   if(estepm > stepm){ /* Yes every two year */
 9980:     stepsize=2;
 9981:   }
 9982:   hstepm=hstepm/stepm;
 9983: 
 9984:   
 9985:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
 9986:   /*                              fractional in yp1 *\/ */
 9987:   /* aintmean=yp; */
 9988:   /* yp2=modf((yp1*12),&yp); */
 9989:   /* mintmean=yp; */
 9990:   /* yp1=modf((yp2*30.5),&yp); */
 9991:   /* jintmean=yp; */
 9992:   /* if(jintmean==0) jintmean=1; */
 9993:   /* if(mintmean==0) mintmean=1; */
 9994: 
 9995: 
 9996:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
 9997:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
 9998:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
 9999:   /* i1=pow(2,cptcoveff); */
10000:   /* if (cptcovn < 1){i1=1;} */
10001:   
10002:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
10003:   
10004:   fprintf(ficresf,"#****** Routine prevforecast **\n");
10005:   
10006: /* 	      if (h==(int)(YEARM*yearp)){ */
10007:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
10008:     k=TKresult[nres];
10009:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
10010:     /*  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) *\/ */
10011:     /* if(i1 != 1 && TKresult[nres]!= k) */
10012:     /*   continue; */
10013:     /* if(invalidvarcomb[k]){ */
10014:     /*   printf("\nCombination (%d) projection ignored because no cases \n",k);  */
10015:     /*   continue; */
10016:     /* } */
10017:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
10018:     for(j=1;j<=cptcovs;j++){
10019:       /* for(j=1;j<=cptcoveff;j++) { */
10020:     /*   /\* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); *\/ */
10021:     /*   fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
10022:     /* } */
10023:     /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
10024:     /*   fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
10025:     /* } */
10026:       fprintf(ficresf," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
10027:     }
10028:  
10029:     fprintf(ficresf," yearproj age");
10030:     for(j=1; j<=nlstate+ndeath;j++){ 
10031:       for(i=1; i<=nlstate;i++) 	      
10032: 	fprintf(ficresf," p%d%d",i,j);
10033:       fprintf(ficresf," wp.%d",j);
10034:     }
10035:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
10036:       fprintf(ficresf,"\n");
10037:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
10038:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
10039:       for (agec=fage; agec>=(bage); agec--){ 
10040: 	nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
10041: 	nhstepm = nhstepm/hstepm; 
10042: 	p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
10043: 	oldm=oldms;savm=savms;
10044: 	/* We compute pii at age agec over nhstepm);*/
10045: 	hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
10046: 	/* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
10047: 	for (h=0; h<=nhstepm; h++){
10048: 	  if (h*hstepm/YEARM*stepm ==yearp) {
10049: 	    break;
10050: 	  }
10051: 	}
10052: 	fprintf(ficresf,"\n");
10053: 	/* for(j=1;j<=cptcoveff;j++)  */
10054: 	for(j=1;j<=cptcovs;j++) 
10055: 	  fprintf(ficresf,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
10056: 	  /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
10057: 	  /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* TnsdVar[Tvaraff]  correct *\/ */
10058: 	fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
10059: 	
10060: 	for(j=1; j<=nlstate+ndeath;j++) {
10061: 	  ppij=0.;
10062: 	  for(i=1; i<=nlstate;i++) {
10063: 	    if (mobilav>=1)
10064: 	     ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
10065: 	    else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
10066: 	    	ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
10067: 	    }
10068: 	    fprintf(ficresf," %.3f", p3mat[i][j][h]);
10069: 	  } /* end i */
10070: 	  fprintf(ficresf," %.3f", ppij);
10071: 	}/* end j */
10072: 	free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
10073:       } /* end agec */
10074:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
10075:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
10076:     } /* end yearp */
10077:   } /* end  k */
10078: 	
10079:   fclose(ficresf);
10080:   printf("End of Computing forecasting \n");
10081:   fprintf(ficlog,"End of Computing forecasting\n");
10082: 
10083: }
10084: 
10085: /************** Back Forecasting ******************/
10086:  /* 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){ */
10087:  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){
10088:   /* back1, year, month, day of starting backprojection
10089:      agemin, agemax range of age
10090:      dateprev1 dateprev2 range of dates during which prevalence is computed
10091:      anback2 year of end of backprojection (same day and month as back1).
10092:      prevacurrent and prev are prevalences.
10093:   */
10094:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
10095:   double agec; /* generic age */
10096:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
10097:   double *popeffectif,*popcount;
10098:   double ***p3mat;
10099:   /* double ***mobaverage; */
10100:   char fileresfb[FILENAMELENGTH];
10101:  
10102:   agelim=AGEINF;
10103:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
10104:      in each health status at the date of interview (if between dateprev1 and dateprev2).
10105:      We still use firstpass and lastpass as another selection.
10106:   */
10107:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
10108:   /* 	      firstpass, lastpass,  stepm,  weightopt, model); */
10109: 
10110:   /*Do we need to compute prevalence again?*/
10111: 
10112:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
10113:   
10114:   strcpy(fileresfb,"FB_");
10115:   strcat(fileresfb,fileresu);
10116:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
10117:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
10118:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
10119:   }
10120:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
10121:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
10122:   
10123:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
10124:   
10125:    
10126:   stepsize=(int) (stepm+YEARM-1)/YEARM;
10127:   if (stepm<=12) stepsize=1;
10128:   if(estepm < stepm){
10129:     printf ("Problem %d lower than %d\n",estepm, stepm);
10130:   }
10131:   else{
10132:     hstepm=estepm;   
10133:   }
10134:   if(estepm >= stepm){ /* Yes every two year */
10135:     stepsize=2;
10136:   }
10137:   
10138:   hstepm=hstepm/stepm;
10139:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
10140:   /*                              fractional in yp1 *\/ */
10141:   /* aintmean=yp; */
10142:   /* yp2=modf((yp1*12),&yp); */
10143:   /* mintmean=yp; */
10144:   /* yp1=modf((yp2*30.5),&yp); */
10145:   /* jintmean=yp; */
10146:   /* if(jintmean==0) jintmean=1; */
10147:   /* if(mintmean==0) jintmean=1; */
10148:   
10149:   /* i1=pow(2,cptcoveff); */
10150:   /* if (cptcovn < 1){i1=1;} */
10151:   
10152:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
10153:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
10154:   
10155:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
10156:   
10157:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
10158:     k=TKresult[nres];
10159:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
10160:   /* for(k=1; k<=i1;k++){ */
10161:   /*   if(i1 != 1 && TKresult[nres]!= k) */
10162:   /*     continue; */
10163:   /*   if(invalidvarcomb[k]){ */
10164:   /*     printf("\nCombination (%d) projection ignored because no cases \n",k);  */
10165:   /*     continue; */
10166:   /*   } */
10167:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
10168:     for(j=1;j<=cptcovs;j++){
10169:     /* for(j=1;j<=cptcoveff;j++) { */
10170:     /*   fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
10171:     /* } */
10172:       fprintf(ficresfb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
10173:     }
10174:    /*  fprintf(ficrespij,"******\n"); */
10175:    /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
10176:    /*    fprintf(ficresfb," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
10177:    /*  } */
10178:     fprintf(ficresfb," yearbproj age");
10179:     for(j=1; j<=nlstate+ndeath;j++){
10180:       for(i=1; i<=nlstate;i++)
10181: 	fprintf(ficresfb," b%d%d",i,j);
10182:       fprintf(ficresfb," b.%d",j);
10183:     }
10184:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
10185:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
10186:       fprintf(ficresfb,"\n");
10187:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
10188:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
10189:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
10190:       for (agec=bage; agec<=fage; agec++){  /* testing */
10191: 	/* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
10192: 	nhstepm=(int) (agec-agelim) *YEARM/stepm;/*	nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
10193: 	nhstepm = nhstepm/hstepm;
10194: 	p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
10195: 	oldm=oldms;savm=savms;
10196: 	/* computes hbxij at age agec over 1 to nhstepm */
10197: 	/* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
10198: 	hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
10199: 	/* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
10200: 	/* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
10201: 	/* printf(" agec=%.2f\n",agec);fflush(stdout); */
10202: 	for (h=0; h<=nhstepm; h++){
10203: 	  if (h*hstepm/YEARM*stepm ==-yearp) {
10204: 	    break;
10205: 	  }
10206: 	}
10207: 	fprintf(ficresfb,"\n");
10208: 	/* for(j=1;j<=cptcoveff;j++) */
10209: 	for(j=1;j<=cptcovs;j++)
10210: 	  fprintf(ficresfb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
10211: 	  /* fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
10212: 	fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
10213: 	for(i=1; i<=nlstate+ndeath;i++) {
10214: 	  ppij=0.;ppi=0.;
10215: 	  for(j=1; j<=nlstate;j++) {
10216: 	    /* if (mobilav==1) */
10217: 	    ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
10218: 	    ppi=ppi+prevacurrent[(int)agec][j][k];
10219: 	    /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
10220: 	    /* ppi=ppi+mobaverage[(int)agec][j][k]; */
10221: 	      /* else { */
10222: 	      /* 	ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
10223: 	      /* } */
10224: 	    fprintf(ficresfb," %.3f", p3mat[i][j][h]);
10225: 	  } /* end j */
10226: 	  if(ppi <0.99){
10227: 	    printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
10228: 	    fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
10229: 	  }
10230: 	  fprintf(ficresfb," %.3f", ppij);
10231: 	}/* end j */
10232: 	free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
10233:       } /* end agec */
10234:     } /* end yearp */
10235:   } /* end k */
10236:   
10237:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
10238:   
10239:   fclose(ficresfb);
10240:   printf("End of Computing Back forecasting \n");
10241:   fprintf(ficlog,"End of Computing Back forecasting\n");
10242: 	
10243: }
10244: 
10245: /* Variance of prevalence limit: varprlim */
10246:  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){
10247:     /*------- Variance of forward period (stable) prevalence------*/   
10248:  
10249:    char fileresvpl[FILENAMELENGTH];  
10250:    FILE *ficresvpl;
10251:    double **oldm, **savm;
10252:    double **varpl; /* Variances of prevalence limits by age */   
10253:    int i1, k, nres, j ;
10254:    
10255:     strcpy(fileresvpl,"VPL_");
10256:     strcat(fileresvpl,fileresu);
10257:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
10258:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
10259:       exit(0);
10260:     }
10261:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
10262:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
10263:     
10264:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
10265:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
10266:     
10267:     i1=pow(2,cptcoveff);
10268:     if (cptcovn < 1){i1=1;}
10269: 
10270:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
10271:        k=TKresult[nres];
10272:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
10273:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
10274:       if(i1 != 1 && TKresult[nres]!= k)
10275: 	continue;
10276:       fprintf(ficresvpl,"\n#****** ");
10277:       printf("\n#****** ");
10278:       fprintf(ficlog,"\n#****** ");
10279:       for(j=1;j<=cptcovs;j++) {
10280: 	fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
10281: 	fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
10282: 	printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
10283: 	/* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
10284: 	/* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
10285:       }
10286:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
10287:       /* 	printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
10288:       /* 	fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
10289:       /* 	fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
10290:       /* }	 */
10291:       fprintf(ficresvpl,"******\n");
10292:       printf("******\n");
10293:       fprintf(ficlog,"******\n");
10294:       
10295:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
10296:       oldm=oldms;savm=savms;
10297:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
10298:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
10299:       /*}*/
10300:     }
10301:     
10302:     fclose(ficresvpl);
10303:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
10304:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
10305: 
10306:  }
10307: /* Variance of back prevalence: varbprlim */
10308:  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){
10309:       /*------- Variance of back (stable) prevalence------*/
10310: 
10311:    char fileresvbl[FILENAMELENGTH];  
10312:    FILE  *ficresvbl;
10313: 
10314:    double **oldm, **savm;
10315:    double **varbpl; /* Variances of back prevalence limits by age */   
10316:    int i1, k, nres, j ;
10317: 
10318:    strcpy(fileresvbl,"VBL_");
10319:    strcat(fileresvbl,fileresu);
10320:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
10321:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
10322:      exit(0);
10323:    }
10324:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
10325:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
10326:    
10327:    
10328:    i1=pow(2,cptcoveff);
10329:    if (cptcovn < 1){i1=1;}
10330:    
10331:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
10332:      k=TKresult[nres];
10333:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
10334:     /* for(k=1; k<=i1;k++){ */
10335:     /*    if(i1 != 1 && TKresult[nres]!= k) */
10336:     /* 	 continue; */
10337:        fprintf(ficresvbl,"\n#****** ");
10338:        printf("\n#****** ");
10339:        fprintf(ficlog,"\n#****** ");
10340:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
10341: 	 printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
10342: 	 fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
10343: 	 fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
10344:        /* for(j=1;j<=cptcoveff;j++) { */
10345:        /* 	 fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
10346:        /* 	 fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
10347:        /* 	 printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
10348:        /* } */
10349:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
10350:        /* 	 printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
10351:        /* 	 fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
10352:        /* 	 fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
10353:        }
10354:        fprintf(ficresvbl,"******\n");
10355:        printf("******\n");
10356:        fprintf(ficlog,"******\n");
10357:        
10358:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
10359:        oldm=oldms;savm=savms;
10360:        
10361:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
10362:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
10363:        /*}*/
10364:      }
10365:    
10366:    fclose(ficresvbl);
10367:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
10368:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
10369: 
10370:  } /* End of varbprlim */
10371: 
10372: /************** Forecasting *****not tested NB*************/
10373: /* 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){ */
10374:   
10375: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
10376: /*   int *popage; */
10377: /*   double calagedatem, agelim, kk1, kk2; */
10378: /*   double *popeffectif,*popcount; */
10379: /*   double ***p3mat,***tabpop,***tabpopprev; */
10380: /*   /\* double ***mobaverage; *\/ */
10381: /*   char filerespop[FILENAMELENGTH]; */
10382: 
10383: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
10384: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
10385: /*   agelim=AGESUP; */
10386: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
10387:   
10388: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
10389:   
10390:   
10391: /*   strcpy(filerespop,"POP_");  */
10392: /*   strcat(filerespop,fileresu); */
10393: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
10394: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
10395: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
10396: /*   } */
10397: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
10398: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
10399: 
10400: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
10401: 
10402: /*   /\* if (mobilav!=0) { *\/ */
10403: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
10404: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
10405: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
10406: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
10407: /*   /\*   } *\/ */
10408: /*   /\* } *\/ */
10409: 
10410: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
10411: /*   if (stepm<=12) stepsize=1; */
10412:   
10413: /*   agelim=AGESUP; */
10414:   
10415: /*   hstepm=1; */
10416: /*   hstepm=hstepm/stepm;  */
10417: 	
10418: /*   if (popforecast==1) { */
10419: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
10420: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
10421: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
10422: /*     }  */
10423: /*     popage=ivector(0,AGESUP); */
10424: /*     popeffectif=vector(0,AGESUP); */
10425: /*     popcount=vector(0,AGESUP); */
10426:     
10427: /*     i=1;    */
10428: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
10429:     
10430: /*     imx=i; */
10431: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
10432: /*   } */
10433:   
10434: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
10435: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
10436: /*       k=k+1; */
10437: /*       fprintf(ficrespop,"\n#******"); */
10438: /*       for(j=1;j<=cptcoveff;j++) { */
10439: /* 	fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
10440: /*       } */
10441: /*       fprintf(ficrespop,"******\n"); */
10442: /*       fprintf(ficrespop,"# Age"); */
10443: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
10444: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
10445:       
10446: /*       for (cpt=0; cpt<=0;cpt++) {  */
10447: /* 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
10448: 	
10449: /* 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
10450: /* 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
10451: /* 	  nhstepm = nhstepm/hstepm;  */
10452: 	  
10453: /* 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
10454: /* 	  oldm=oldms;savm=savms; */
10455: /* 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
10456: 	  
10457: /* 	  for (h=0; h<=nhstepm; h++){ */
10458: /* 	    if (h==(int) (calagedatem+YEARM*cpt)) { */
10459: /* 	      fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
10460: /* 	    }  */
10461: /* 	    for(j=1; j<=nlstate+ndeath;j++) { */
10462: /* 	      kk1=0.;kk2=0; */
10463: /* 	      for(i=1; i<=nlstate;i++) {	       */
10464: /* 		if (mobilav==1)  */
10465: /* 		  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
10466: /* 		else { */
10467: /* 		  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
10468: /* 		} */
10469: /* 	      } */
10470: /* 	      if (h==(int)(calagedatem+12*cpt)){ */
10471: /* 		tabpop[(int)(agedeb)][j][cptcod]=kk1; */
10472: /* 		/\*fprintf(ficrespop," %.3f", kk1); */
10473: /* 		  if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
10474: /* 	      } */
10475: /* 	    } */
10476: /* 	    for(i=1; i<=nlstate;i++){ */
10477: /* 	      kk1=0.; */
10478: /* 	      for(j=1; j<=nlstate;j++){ */
10479: /* 		kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
10480: /* 	      } */
10481: /* 	      tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
10482: /* 	    } */
10483: 	    
10484: /* 	    if (h==(int)(calagedatem+12*cpt)) */
10485: /* 	      for(j=1; j<=nlstate;j++)  */
10486: /* 		fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
10487: /* 	  } */
10488: /* 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
10489: /* 	} */
10490: /*       } */
10491:       
10492: /*       /\******\/ */
10493:       
10494: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
10495: /* 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
10496: /* 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
10497: /* 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
10498: /* 	  nhstepm = nhstepm/hstepm;  */
10499: 	  
10500: /* 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
10501: /* 	  oldm=oldms;savm=savms; */
10502: /* 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
10503: /* 	  for (h=0; h<=nhstepm; h++){ */
10504: /* 	    if (h==(int) (calagedatem+YEARM*cpt)) { */
10505: /* 	      fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
10506: /* 	    }  */
10507: /* 	    for(j=1; j<=nlstate+ndeath;j++) { */
10508: /* 	      kk1=0.;kk2=0; */
10509: /* 	      for(i=1; i<=nlstate;i++) {	       */
10510: /* 		kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];	 */
10511: /* 	      } */
10512: /* 	      if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);	 */
10513: /* 	    } */
10514: /* 	  } */
10515: /* 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
10516: /* 	} */
10517: /*       } */
10518: /*     }  */
10519: /*   } */
10520:   
10521: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
10522:   
10523: /*   if (popforecast==1) { */
10524: /*     free_ivector(popage,0,AGESUP); */
10525: /*     free_vector(popeffectif,0,AGESUP); */
10526: /*     free_vector(popcount,0,AGESUP); */
10527: /*   } */
10528: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
10529: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
10530: /*   fclose(ficrespop); */
10531: /* } /\* End of popforecast *\/ */
10532:  
10533: int fileappend(FILE *fichier, char *optionfich)
10534: {
10535:   if((fichier=fopen(optionfich,"a"))==NULL) {
10536:     printf("Problem with file: %s\n", optionfich);
10537:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
10538:     return (0);
10539:   }
10540:   fflush(fichier);
10541:   return (1);
10542: }
10543: 
10544: 
10545: /**************** function prwizard **********************/
10546: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
10547: {
10548: 
10549:   /* Wizard to print covariance matrix template */
10550: 
10551:   char ca[32], cb[32];
10552:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
10553:   int numlinepar;
10554: 
10555:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
10556:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
10557:   for(i=1; i <=nlstate; i++){
10558:     jj=0;
10559:     for(j=1; j <=nlstate+ndeath; j++){
10560:       if(j==i) continue;
10561:       jj++;
10562:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
10563:       printf("%1d%1d",i,j);
10564:       fprintf(ficparo,"%1d%1d",i,j);
10565:       for(k=1; k<=ncovmodel;k++){
10566: 	/* 	  printf(" %lf",param[i][j][k]); */
10567: 	/* 	  fprintf(ficparo," %lf",param[i][j][k]); */
10568: 	printf(" 0.");
10569: 	fprintf(ficparo," 0.");
10570:       }
10571:       printf("\n");
10572:       fprintf(ficparo,"\n");
10573:     }
10574:   }
10575:   printf("# Scales (for hessian or gradient estimation)\n");
10576:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
10577:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
10578:   for(i=1; i <=nlstate; i++){
10579:     jj=0;
10580:     for(j=1; j <=nlstate+ndeath; j++){
10581:       if(j==i) continue;
10582:       jj++;
10583:       fprintf(ficparo,"%1d%1d",i,j);
10584:       printf("%1d%1d",i,j);
10585:       fflush(stdout);
10586:       for(k=1; k<=ncovmodel;k++){
10587: 	/* 	printf(" %le",delti3[i][j][k]); */
10588: 	/* 	fprintf(ficparo," %le",delti3[i][j][k]); */
10589: 	printf(" 0.");
10590: 	fprintf(ficparo," 0.");
10591:       }
10592:       numlinepar++;
10593:       printf("\n");
10594:       fprintf(ficparo,"\n");
10595:     }
10596:   }
10597:   printf("# Covariance matrix\n");
10598: /* # 121 Var(a12)\n\ */
10599: /* # 122 Cov(b12,a12) Var(b12)\n\ */
10600: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
10601: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
10602: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
10603: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
10604: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
10605: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
10606:   fflush(stdout);
10607:   fprintf(ficparo,"# Covariance matrix\n");
10608:   /* # 121 Var(a12)\n\ */
10609:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
10610:   /* #   ...\n\ */
10611:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
10612:   
10613:   for(itimes=1;itimes<=2;itimes++){
10614:     jj=0;
10615:     for(i=1; i <=nlstate; i++){
10616:       for(j=1; j <=nlstate+ndeath; j++){
10617: 	if(j==i) continue;
10618: 	for(k=1; k<=ncovmodel;k++){
10619: 	  jj++;
10620: 	  ca[0]= k+'a'-1;ca[1]='\0';
10621: 	  if(itimes==1){
10622: 	    printf("#%1d%1d%d",i,j,k);
10623: 	    fprintf(ficparo,"#%1d%1d%d",i,j,k);
10624: 	  }else{
10625: 	    printf("%1d%1d%d",i,j,k);
10626: 	    fprintf(ficparo,"%1d%1d%d",i,j,k);
10627: 	    /* 	printf(" %.5le",matcov[i][j]); */
10628: 	  }
10629: 	  ll=0;
10630: 	  for(li=1;li <=nlstate; li++){
10631: 	    for(lj=1;lj <=nlstate+ndeath; lj++){
10632: 	      if(lj==li) continue;
10633: 	      for(lk=1;lk<=ncovmodel;lk++){
10634: 		ll++;
10635: 		if(ll<=jj){
10636: 		  cb[0]= lk +'a'-1;cb[1]='\0';
10637: 		  if(ll<jj){
10638: 		    if(itimes==1){
10639: 		      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
10640: 		      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
10641: 		    }else{
10642: 		      printf(" 0.");
10643: 		      fprintf(ficparo," 0.");
10644: 		    }
10645: 		  }else{
10646: 		    if(itimes==1){
10647: 		      printf(" Var(%s%1d%1d)",ca,i,j);
10648: 		      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
10649: 		    }else{
10650: 		      printf(" 0.");
10651: 		      fprintf(ficparo," 0.");
10652: 		    }
10653: 		  }
10654: 		}
10655: 	      } /* end lk */
10656: 	    } /* end lj */
10657: 	  } /* end li */
10658: 	  printf("\n");
10659: 	  fprintf(ficparo,"\n");
10660: 	  numlinepar++;
10661: 	} /* end k*/
10662:       } /*end j */
10663:     } /* end i */
10664:   } /* end itimes */
10665: 
10666: } /* end of prwizard */
10667: /******************* Gompertz Likelihood ******************************/
10668: double gompertz(double x[])
10669: { 
10670:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
10671:   int i,n=0; /* n is the size of the sample */
10672: 
10673:   for (i=1;i<=imx ; i++) {
10674:     sump=sump+weight[i];
10675:     /*    sump=sump+1;*/
10676:     num=num+1;
10677:   }
10678:   L=0.0;
10679:   /* agegomp=AGEGOMP; */
10680:   /* for (i=0; i<=imx; i++) 
10681:      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]);*/
10682: 
10683:   for (i=1;i<=imx ; i++) {
10684:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
10685:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
10686:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
10687:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
10688:      * +
10689:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
10690:      */
10691:      if (wav[i] > 1 || agedc[i] < AGESUP) {
10692:        if (cens[i] == 1){
10693: 	 A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
10694:        } else if (cens[i] == 0){
10695: 	A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
10696: 	  +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
10697:       } else
10698: 	 printf("Gompertz cens[%d] neither 1 nor 0\n",i);
10699:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
10700:        L=L+A*weight[i];
10701: 	/* 	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]);*/
10702:      }
10703:   }
10704: 
10705:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
10706:  
10707:   return -2*L*num/sump;
10708: }
10709: 
10710: #ifdef GSL
10711: /******************* Gompertz_f Likelihood ******************************/
10712: double gompertz_f(const gsl_vector *v, void *params)
10713: { 
10714:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
10715:   double *x= (double *) v->data;
10716:   int i,n=0; /* n is the size of the sample */
10717: 
10718:   for (i=0;i<=imx-1 ; i++) {
10719:     sump=sump+weight[i];
10720:     /*    sump=sump+1;*/
10721:     num=num+1;
10722:   }
10723:  
10724:  
10725:   /* for (i=0; i<=imx; i++) 
10726:      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]);*/
10727:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
10728:   for (i=1;i<=imx ; i++)
10729:     {
10730:       if (cens[i] == 1 && wav[i]>1)
10731: 	A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
10732:       
10733:       if (cens[i] == 0 && wav[i]>1)
10734: 	A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
10735: 	     +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
10736:       
10737:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
10738:       if (wav[i] > 1 ) { /* ??? */
10739: 	LL=LL+A*weight[i];
10740: 	/* 	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]);*/
10741:       }
10742:     }
10743: 
10744:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
10745:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
10746:  
10747:   return -2*LL*num/sump;
10748: }
10749: #endif
10750: 
10751: /******************* Printing html file ***********/
10752: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
10753: 		  int lastpass, int stepm, int weightopt, char model[],\
10754: 		  int imx,  double p[],double **matcov,double agemortsup){
10755:   int i,k;
10756: 
10757:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
10758:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
10759:   for (i=1;i<=2;i++) 
10760:     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]));
10761:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
10762:   fprintf(fichtm,"</ul>");
10763: 
10764: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
10765: 
10766:  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>");
10767: 
10768:  for (k=agegomp;k<(agemortsup-2);k++) 
10769:    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]);
10770: 
10771:  
10772:   fflush(fichtm);
10773: }
10774: 
10775: /******************* Gnuplot file **************/
10776: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
10777: 
10778:   char dirfileres[132],optfileres[132];
10779: 
10780:   int ng;
10781: 
10782: 
10783:   /*#ifdef windows */
10784:   fprintf(ficgp,"cd \"%s\" \n",pathc);
10785:     /*#endif */
10786: 
10787: 
10788:   strcpy(dirfileres,optionfilefiname);
10789:   strcpy(optfileres,"vpl");
10790:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
10791:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
10792:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
10793:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
10794:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
10795: 
10796: } 
10797: 
10798: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
10799: {
10800: 
10801:   /*-------- data file ----------*/
10802:   FILE *fic;
10803:   char dummy[]="                         ";
10804:   int i=0, j=0, n=0, iv=0, v;
10805:   int lstra;
10806:   int linei, month, year,iout;
10807:   int noffset=0; /* This is the offset if BOM data file */
10808:   char line[MAXLINE], linetmp[MAXLINE];
10809:   char stra[MAXLINE], strb[MAXLINE];
10810:   char *stratrunc;
10811: 
10812:   /* DummyV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
10813:   /* FixedV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
10814:   
10815:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
10816:   
10817:   if((fic=fopen(datafile,"r"))==NULL)    {
10818:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
10819:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
10820:   }
10821: 
10822:     /* Is it a BOM UTF-8 Windows file? */
10823:   /* First data line */
10824:   linei=0;
10825:   while(fgets(line, MAXLINE, fic)) {
10826:     noffset=0;
10827:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
10828:     {
10829:       noffset=noffset+3;
10830:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
10831:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
10832:       fflush(ficlog); return 1;
10833:     }
10834:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
10835:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
10836:     {
10837:       noffset=noffset+2;
10838:       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);
10839:       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);
10840:       fflush(ficlog); return 1;
10841:     }
10842:     else if( line[0] == 0 && line[1] == 0)
10843:     {
10844:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
10845: 	noffset=noffset+4;
10846: 	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);
10847: 	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);
10848: 	fflush(ficlog); return 1;
10849:       }
10850:     } else{
10851:       ;/*printf(" Not a BOM file\n");*/
10852:     }
10853:         /* If line starts with a # it is a comment */
10854:     if (line[noffset] == '#') {
10855:       linei=linei+1;
10856:       break;
10857:     }else{
10858:       break;
10859:     }
10860:   }
10861:   fclose(fic);
10862:   if((fic=fopen(datafile,"r"))==NULL)    {
10863:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
10864:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
10865:   }
10866:   /* Not a Bom file */
10867:   
10868:   i=1;
10869:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
10870:     linei=linei+1;
10871:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
10872:       if(line[j] == '\t')
10873: 	line[j] = ' ';
10874:     }
10875:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
10876:       ;
10877:     };
10878:     line[j+1]=0;  /* Trims blanks at end of line */
10879:     if(line[0]=='#'){
10880:       fprintf(ficlog,"Comment line\n%s\n",line);
10881:       printf("Comment line\n%s\n",line);
10882:       continue;
10883:     }
10884:     trimbb(linetmp,line); /* Trims multiple blanks in line */
10885:     strcpy(line, linetmp);
10886:     
10887:     /* Loops on waves */
10888:     for (j=maxwav;j>=1;j--){
10889:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
10890: 	cutv(stra, strb, line, ' '); 
10891: 	if(strb[0]=='.') { /* Missing value */
10892: 	  lval=-1;
10893: 	  cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
10894: 	  cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
10895: 	  if(isalpha(strb[1])) { /* .m or .d Really Missing value */
10896: 	    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);
10897: 	    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);
10898: 	    return 1;
10899: 	  }
10900: 	}else{
10901: 	  errno=0;
10902: 	  /* what_kind_of_number(strb); */
10903: 	  dval=strtod(strb,&endptr); 
10904: 	  /* if( strb[0]=='\0' || (*endptr != '\0')){ */
10905: 	  /* if(strb != endptr && *endptr == '\0') */
10906: 	  /*    dval=dlval; */
10907: 	  /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
10908: 	  if( strb[0]=='\0' || (*endptr != '\0')){
10909: 	    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);
10910: 	    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);
10911: 	    return 1;
10912: 	  }
10913: 	  cotqvar[j][iv][i]=dval; 
10914: 	  cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
10915: 	}
10916: 	strcpy(line,stra);
10917:       }/* end loop ntqv */
10918:       
10919:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
10920: 	cutv(stra, strb, line, ' '); 
10921: 	if(strb[0]=='.') { /* Missing value */
10922: 	  lval=-1;
10923: 	}else{
10924: 	  errno=0;
10925: 	  lval=strtol(strb,&endptr,10); 
10926: 	  /*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
10927: 	  if( strb[0]=='\0' || (*endptr != '\0')){
10928: 	    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);
10929: 	    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);
10930: 	    return 1;
10931: 	  }
10932: 	}
10933: 	if(lval <-1 || lval >1){
10934: 	  printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
10935:  Should be a value of %d(nth) covariate of wave %d (0 should be the value for the reference and 1\n \
10936:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
10937:  For example, for multinomial values like 1, 2 and 3,\n			\
10938:  build V1=0 V2=0 for the reference value (1),\n				\
10939:         V1=1 V2=0 for (2) \n						\
10940:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
10941:  output of IMaCh is often meaningless.\n				\
10942:  Exiting.\n",lval,linei, i,line,iv,j);
10943: 	  fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
10944:  Should be a value of %d(nth) covariate of wave %d (0 should be the value for the reference and 1\n \
10945:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
10946:  For example, for multinomial values like 1, 2 and 3,\n			\
10947:  build V1=0 V2=0 for the reference value (1),\n				\
10948:         V1=1 V2=0 for (2) \n						\
10949:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
10950:  output of IMaCh is often meaningless.\n				\
10951:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
10952: 	  return 1;
10953: 	}
10954: 	cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
10955: 	strcpy(line,stra);
10956:       }/* end loop ntv */
10957:       
10958:       /* Statuses  at wave */
10959:       cutv(stra, strb, line, ' '); 
10960:       if(strb[0]=='.') { /* Missing value */
10961: 	lval=-1;
10962:       }else{
10963: 	errno=0;
10964: 	lval=strtol(strb,&endptr,10); 
10965: 	/*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
10966: 	if( strb[0]=='\0' || (*endptr != '\0' )){
10967: 	  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);
10968: 	  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);
10969: 	  return 1;
10970: 	}else if( lval==0 || lval > nlstate+ndeath){
10971: 	  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);
10972: 	  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);
10973: 	  return 1;
10974: 	}
10975:       }
10976:       
10977:       s[j][i]=lval;
10978:       
10979:       /* Date of Interview */
10980:       strcpy(line,stra);
10981:       cutv(stra, strb,line,' ');
10982:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
10983:       }
10984:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
10985: 	month=99;
10986: 	year=9999;
10987:       }else{
10988: 	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);
10989: 	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);
10990: 	return 1;
10991:       }
10992:       anint[j][i]= (double) year; 
10993:       mint[j][i]= (double)month;
10994:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
10995:       /* 	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]); */
10996:       /* 	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]); */
10997:       /* } */
10998:       strcpy(line,stra);
10999:     } /* End loop on waves */
11000:     
11001:     /* Date of death */
11002:     cutv(stra, strb,line,' '); 
11003:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
11004:     }
11005:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
11006:       month=99;
11007:       year=9999;
11008:     }else{
11009:       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);
11010:       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);
11011:       return 1;
11012:     }
11013:     andc[i]=(double) year; 
11014:     moisdc[i]=(double) month; 
11015:     strcpy(line,stra);
11016:     
11017:     /* Date of birth */
11018:     cutv(stra, strb,line,' '); 
11019:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
11020:     }
11021:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
11022:       month=99;
11023:       year=9999;
11024:     }else{
11025:       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);
11026:       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);
11027:       return 1;
11028:     }
11029:     if (year==9999) {
11030:       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);
11031:       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);
11032:       return 1;
11033:       
11034:     }
11035:     annais[i]=(double)(year);
11036:     moisnais[i]=(double)(month);
11037:     for (j=1;j<=maxwav;j++){
11038:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
11039: 	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]);
11040: 	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]);
11041:       }
11042:     }
11043: 
11044:     strcpy(line,stra);
11045:     
11046:     /* Sample weight */
11047:     cutv(stra, strb,line,' '); 
11048:     errno=0;
11049:     dval=strtod(strb,&endptr); 
11050:     if( strb[0]=='\0' || (*endptr != '\0')){
11051:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
11052:       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);
11053:       fflush(ficlog);
11054:       return 1;
11055:     }
11056:     weight[i]=dval; 
11057:     strcpy(line,stra);
11058:     
11059:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
11060:       cutv(stra, strb, line, ' '); 
11061:       if(strb[0]=='.') { /* Missing value */
11062: 	lval=-1;
11063: 	coqvar[iv][i]=NAN; 
11064: 	covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
11065:       }else{
11066: 	errno=0;
11067: 	/* what_kind_of_number(strb); */
11068: 	dval=strtod(strb,&endptr);
11069: 	/* if(strb != endptr && *endptr == '\0') */
11070: 	/*   dval=dlval; */
11071: 	/* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
11072: 	if( strb[0]=='\0' || (*endptr != '\0')){
11073: 	  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);
11074: 	  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);
11075: 	  return 1;
11076: 	}
11077: 	coqvar[iv][i]=dval; 
11078: 	covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
11079:       }
11080:       strcpy(line,stra);
11081:     }/* end loop nqv */
11082:     
11083:     /* Covariate values */
11084:     for (j=ncovcol;j>=1;j--){
11085:       cutv(stra, strb,line,' '); 
11086:       if(strb[0]=='.') { /* Missing covariate value */
11087: 	lval=-1;
11088:       }else{
11089: 	errno=0;
11090: 	lval=strtol(strb,&endptr,10); 
11091: 	if( strb[0]=='\0' || (*endptr != '\0')){
11092: 	  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);
11093: 	  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);
11094: 	  return 1;
11095: 	}
11096:       }
11097:       if(lval <-1 || lval >1){
11098: 	printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
11099:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
11100:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
11101:  For example, for multinomial values like 1, 2 and 3,\n			\
11102:  build V1=0 V2=0 for the reference value (1),\n				\
11103:         V1=1 V2=0 for (2) \n						\
11104:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
11105:  output of IMaCh is often meaningless.\n				\
11106:  Exiting.\n",lval,linei, i,line,j);
11107: 	fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
11108:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
11109:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
11110:  For example, for multinomial values like 1, 2 and 3,\n			\
11111:  build V1=0 V2=0 for the reference value (1),\n				\
11112:         V1=1 V2=0 for (2) \n						\
11113:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
11114:  output of IMaCh is often meaningless.\n				\
11115:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
11116: 	return 1;
11117:       }
11118:       covar[j][i]=(double)(lval);
11119:       strcpy(line,stra);
11120:     }  
11121:     lstra=strlen(stra);
11122:     
11123:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
11124:       stratrunc = &(stra[lstra-9]);
11125:       num[i]=atol(stratrunc);
11126:     }
11127:     else
11128:       num[i]=atol(stra);
11129:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
11130:       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;}*/
11131:     
11132:     i=i+1;
11133:   } /* End loop reading  data */
11134:   
11135:   *imax=i-1; /* Number of individuals */
11136:   fclose(fic);
11137:   
11138:   return (0);
11139:   /* endread: */
11140:   printf("Exiting readdata: ");
11141:   fclose(fic);
11142:   return (1);
11143: }
11144: 
11145: void removefirstspace(char **stri){/*, char stro[]) {*/
11146:   char *p1 = *stri, *p2 = *stri;
11147:   while (*p2 == ' ')
11148:     p2++; 
11149:   /* while ((*p1++ = *p2++) !=0) */
11150:   /*   ; */
11151:   /* do */
11152:   /*   while (*p2 == ' ') */
11153:   /*     p2++; */
11154:   /* while (*p1++ == *p2++); */
11155:   *stri=p2; 
11156: }
11157: 
11158: int decoderesult( char resultline[], int nres)
11159: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
11160: {
11161:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
11162:   char resultsav[MAXLINE];
11163:   /* int resultmodel[MAXLINE]; */
11164:   /* int modelresult[MAXLINE]; */
11165:   char stra[80], strb[80], strc[80], strd[80],stre[80];
11166: 
11167:   removefirstspace(&resultline);
11168:   printf("decoderesult:%s\n",resultline);
11169: 
11170:   strcpy(resultsav,resultline);
11171:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
11172:   if (strlen(resultsav) >1){
11173:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
11174:   }
11175:   if(j == 0 && cptcovs== 0){ /* Resultline but no =  and no covariate in the model */
11176:     TKresult[nres]=0; /* Combination for the nresult and the model */
11177:     return (0);
11178:   }
11179:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
11180:     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);
11181:     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);
11182:     if(j==0)
11183:       return 1;
11184:   }
11185:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
11186:     if(nbocc(resultsav,'=') >1){
11187:       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" */
11188:       /* If resultsav= "V4= 1 V5=25.1 V3=0" with a blank then strb="V4=" and stra="1 V5=25.1 V3=0" */
11189:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
11190:       /* If a blank, then strc="V4=" and strd='\0' */
11191:       if(strc[0]=='\0'){
11192:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
11193: 	fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
11194: 	return 1;
11195:       }
11196:     }else
11197:       cutl(strc,strd,resultsav,'=');
11198:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
11199:     
11200:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
11201:     Tvarsel[k]=atoi(strc);  /* 4 */ /* Tvarsel is the id of the kth covariate in the result line Tvarsel[1] in "V4=1.." is 4.*/
11202:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
11203:     /* cptcovsel++;     */
11204:     if (nbocc(stra,'=') >0)
11205:       strcpy(resultsav,stra); /* and analyzes it */
11206:   }
11207:   /* Checking for missing or useless values in comparison of current model needs */
11208:   /* Feeds resultmodel[nres][k1]=k2 for k1th product covariate with age in the model equation fed by the index k2 of the resutline*/
11209:   for(k1=1; k1<= cptcovt ;k1++){ /* Loop on MODEL LINE V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
11210:     if(Typevar[k1]==0){ /* Single covariate in model */
11211:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
11212:       match=0;
11213:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
11214: 	if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
11215: 	  modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
11216: 	  match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
11217: 	  break;
11218: 	}
11219:       }
11220:       if(match == 0){
11221: 	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]);
11222: 	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);
11223: 	return 1;
11224:       }
11225:     }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*/
11226:       /* We feed resultmodel[k1]=k2; */
11227:       match=0;
11228:       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 */
11229: 	if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
11230: 	  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 */
11231: 	  resultmodel[nres][k1]=k2; /* Added here */
11232: 	  /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
11233: 	  match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
11234: 	  break;
11235: 	}
11236:       }
11237:       if(match == 0){
11238: 	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]);
11239: 	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]);
11240:       return 1;
11241:       }
11242:     }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*/
11243:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
11244:       match=0;
11245:       /* 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]); */
11246:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
11247: 	if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
11248: 	  /* modelresult[k2]=k1; */
11249: 	  /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
11250: 	  match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
11251: 	}
11252:       }
11253:       if(match == 0){
11254: 	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);
11255: 	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);
11256: 	return 1;
11257:       }
11258:       match=0;
11259:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
11260: 	if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
11261: 	  /* modelresult[k2]=k1;*/
11262: 	  /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
11263: 	  match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
11264: 	  break;
11265: 	}
11266:       }
11267:       if(match == 0){
11268: 	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);
11269: 	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);
11270: 	return 1;
11271:       }
11272:     }/* End of testing */
11273:   }/* End loop cptcovt */
11274:   /* Checking for missing or useless values in comparison of current model needs */
11275:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
11276:   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)
11277: 			   * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
11278:     match=0;
11279:     for(k1=1; k1<= cptcovt ;k1++){ /* loop on model: model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
11280:       if(Typevar[k1]==0){ /* Single only */
11281: 	if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4  What if a product?  */
11282: 	  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 */
11283: 	  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 */
11284: 	  ++match;
11285: 	}
11286:       }
11287:     }
11288:     if(match == 0){
11289:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
11290:       fprintf(ficlog,"Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
11291:       return 1;
11292:     }else if(match > 1){
11293:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
11294:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
11295:       return 1;
11296:     }
11297:   }
11298:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
11299:   /* We need to deduce which combination number is chosen and save quantitative values */
11300:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
11301:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
11302:   /* 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*/
11303:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
11304:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
11305:   /*    1 0 0 0 */
11306:   /*    2 1 0 0 */
11307:   /*    3 0 1 0 */ 
11308:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
11309:   /*    5 0 0 1 */
11310:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
11311:   /*    7 0 1 1 */
11312:   /*    8 1 1 1 */
11313:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
11314:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
11315:   /* V5*age V5 known which value for nres?  */
11316:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
11317:   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.
11318: 						   * loop on position k1 in the MODEL LINE */
11319:     /* k counting number of combination of single dummies in the equation model */
11320:     /* k4 counting single dummies in the equation model */
11321:     /* k4q counting single quantitatives in the equation model */
11322:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Dummy and Single, fixed or timevarying, k1 is sorting according to MODEL, but k3 to resultline */
11323:        /* 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) */
11324:       /* modelresult[k3]=k1: k3th position in the result line corresponds to the k1 position in the model line (doesn't work with products)*/
11325:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
11326:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
11327:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
11328:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
11329:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
11330:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
11331:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
11332:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
11333:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
11334:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
11335:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
11336:       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)*/
11337:       k+=Tvalsel[k3]*pow(2,k4);  /* nres=1 k1=2 Tvalsel[1]=1 (V4=1); k1=3 k3=2 Tvalsel[2]=0 (V3=0) */
11338:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
11339:       /* Tinvresult[nres][4]=1 */
11340:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
11341:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
11342:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
11343:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
11344:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
11345:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
11346:       /* 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); */
11347:       k4++;;
11348:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
11349:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
11350:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
11351:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
11352:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
11353:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
11354:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
11355:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
11356:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
11357:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
11358:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
11359:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
11360:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
11361:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
11362:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
11363:       precov[nres][k1]=Tvalsel[k3q];
11364:       /* 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]); */
11365:       k4q++;;
11366:     }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"*/
11367:       /* Tvar[k1]; */ /* Age variable */ /* 17 age*V6*V2 ?*/
11368:       /* Wrong we want the value of variable name Tvar[k1] */
11369:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
11370: 	precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
11371:       /* 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]]); */
11372:       }else{
11373: 	k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
11374: 	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)*/
11375: 	TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
11376: 	precov[nres][k1]=Tvalsel[k3];
11377:       }
11378:       /* 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]); */
11379:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
11380:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
11381: 	precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
11382:       /* 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]]); */
11383:       }else{
11384: 	k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
11385: 	k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
11386: 	TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
11387: 	precov[nres][k1]=Tvalsel[k3q];
11388:       }
11389:       /* 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]); */
11390:     }else if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
11391:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
11392:       /* 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]]); */
11393:     }else{
11394:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
11395:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
11396:     }
11397:   }
11398:   
11399:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
11400:   return (0);
11401: }
11402: 
11403: int decodemodel( char model[], int lastobs)
11404:  /**< This routine decodes the model and returns:
11405: 	* Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
11406: 	* - nagesqr = 1 if age*age in the model, otherwise 0.
11407: 	* - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
11408: 	* - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
11409: 	* - cptcovage number of covariates with age*products =2
11410: 	* - cptcovs number of simple covariates
11411: 	* ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
11412: 	* - 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
11413: 	*     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
11414: 	* - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
11415: 	* - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
11416: 	*    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
11417: 	* - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
11418: 	*/
11419: /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 */
11420: {
11421:   int i, j, k, ks, v;
11422:   int n,m;
11423:   int  j1, k1, k11, k12, k2, k3, k4;
11424:   char modelsav[300];
11425:   char stra[300], strb[300], strc[300], strd[300],stre[300],strf[300];
11426:   char *strpt;
11427:   int  **existcomb;
11428:   
11429:   existcomb=imatrix(1,NCOVMAX,1,NCOVMAX);
11430:   for(i=1;i<=NCOVMAX;i++)
11431:     for(j=1;j<=NCOVMAX;j++)
11432:       existcomb[i][j]=0;
11433:     
11434:   /*removespace(model);*/
11435:   if (strlen(model) >1){ /* If there is at least 1 covariate */
11436:     j=0, j1=0, k1=0, k12=0, k2=-1, ks=0, cptcovn=0;
11437:     if (strstr(model,"AGE") !=0){
11438:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
11439:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
11440:       return 1;
11441:     }
11442:     if (strstr(model,"v") !=0){
11443:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
11444:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
11445:       return 1;
11446:     }
11447:     strcpy(modelsav,model); 
11448:     if ((strpt=strstr(model,"age*age")) !=0){
11449:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
11450:       if(strpt != model){
11451: 	printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
11452:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
11453:  corresponding column of parameters.\n",model);
11454: 	fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
11455:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
11456:  corresponding column of parameters.\n",model); fflush(ficlog);
11457: 	return 1;
11458:       }
11459:       nagesqr=1;
11460:       if (strstr(model,"+age*age") !=0)
11461: 	substrchaine(modelsav, model, "+age*age");
11462:       else if (strstr(model,"age*age+") !=0)
11463: 	substrchaine(modelsav, model, "age*age+");
11464:       else 
11465: 	substrchaine(modelsav, model, "age*age");
11466:     }else
11467:       nagesqr=0;
11468:     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 */
11469:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
11470:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
11471:       cptcovs=0; /**<  Number of simple covariates V1 +V1*age +V3 +V3*V4 +age*age => V1 + V3 =4+1-3=2  Wrong */
11472:       cptcovt= j+1; /* Number of total covariates in the model, not including
11473: 		     * cst, age and age*age 
11474: 		     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
11475:       /* including age products which are counted in cptcovage.
11476:        * but the covariates which are products must be treated 
11477:        * separately: ncovn=4- 2=2 (V1+V3). */
11478:       cptcovprod=0; /**< Number of products  V1*V2 +v3*age = 2 */
11479:       cptcovdageprod=0; /* Number of doouble products with age age*Vn*VM or Vn*age*Vm or Vn*Vm*age */
11480:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
11481:       cptcovprodage=0;
11482:       /* cptcovprodage=nboccstr(modelsav,"age");*/
11483:       
11484:       /*   Design
11485:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
11486:        *  <          ncovcol=8                >
11487:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
11488:        *   k=  1    2      3       4     5       6      7        8
11489:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
11490:        *  covar[k,i], are for fixed covariates, value of kth covariate if not including age for individual i:
11491:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
11492:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
11493:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
11494:        *  Tage[++cptcovage]=k
11495:        *       if products, new covar are created after ncovcol + nqv (quanti fixed) with k1
11496:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
11497:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
11498:        *  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
11499:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
11500:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
11501:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
11502:        *  <          ncovcol=8  8 fixed covariate. Additional starts at 9 (V5*V6) and 10(V7*V8)              >
11503:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
11504:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
11505:        *     Tvard[k]= 2    1      3       3    10      11      8        8    5    6    7   8
11506:        * p Tvar[1]@12={2,   1,     3,      3,   9,     10,     8,       8}
11507:        * p Tprod[1]@2={                         6, 5}
11508:        *p Tvard[1][1]@4= {7, 8, 5, 6}
11509:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
11510:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
11511:        *How to reorganize? Tvars(orted)
11512:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
11513:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
11514:        *       {2,   1,     4,      8,    5,      6,     3,       7}
11515:        * Struct []
11516:        */
11517:       
11518:       /* This loop fills the array Tvar from the string 'model'.*/
11519:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
11520:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
11521:       /* 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
11522:       /* 	k=3 V4 Tvar[k=3]= 4 (from V4) */
11523:       /* 	k=2 V1 Tvar[k=2]= 1 (from V1) */
11524:       /* 	k=1 Tvar[1]=2 (from V2) */
11525:       /* 	k=5 Tvar[5] */
11526:       /* for (k=1; k<=cptcovn;k++) { */
11527:       /* 	cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
11528:       /* 	} */
11529:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
11530:       /*
11531:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
11532:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
11533:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
11534:       }
11535:       cptcovage=0;
11536: 
11537:       /* First loop in order to calculate */
11538:       /* for age*VN*Vm
11539:        * Provides, Typevar[k], Tage[cptcovage], existcomb[n][m], FixedV[ncovcolt+k12]
11540:        * Tprod[k1]=k  Tposprod[k]=k1;    Tvard[k1][1] =m;
11541:       */
11542:       /* Needs  FixedV[Tvardk[k][1]] */
11543:       /* For others:
11544:        * Sets 	Typevar[k];
11545:        * Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
11546:        *	Tposprod[k]=k11;
11547:        *	Tprod[k11]=k;
11548:        *	Tvardk[k][1] =m;
11549:        * Needs FixedV[Tvardk[k][1]] == 0
11550:       */
11551:       
11552:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
11553: 	cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
11554: 					 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" */
11555: 	if (nbocc(modelsav,'+')==0)
11556: 	  strcpy(strb,modelsav); /* and analyzes it */
11557: 	/*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
11558: 	/*scanf("%d",i);*/
11559: 	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 */
11560: 	  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  */
11561: 	  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   */
11562: 	    Typevar[k]=3;  /* 3 for age and double product age*Vn*Vm varying of fixed */
11563:             if(strstr(strc,"age")!=0) { /* It means that strc=V2*age or age*V2 and thus that strd=Vn */
11564:               cutl(stre,strf,strc,'*') ; /* strf=age or Vm, stre=Vm or age. If strc=V6*V2 then strf=V6 and stre=V2 */
11565: 	      strcpy(strc,strb); /* save strb(=age*Vn*Vm) into strc */
11566: 	      /* We want strb=Vn*Vm */
11567:               if(strcmp(strf,"age")==0){ /* strf is "age" so that stre=Vm =V2 . */
11568:                 strcpy(strb,strd);
11569:                 strcat(strb,"*");
11570:                 strcat(strb,stre);
11571:               }else{  /* strf=Vm  If strf=V6 then stre=V2 */
11572:                 strcpy(strb,strf);
11573:                 strcat(strb,"*");
11574:                 strcat(strb,stre);
11575:                 strcpy(strd,strb); /* in order for strd to not be "age"  for next test (will be Vn*Vm */
11576:               }
11577: 	      /* 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]]]); */
11578: 	      /* FixedV[Tvar[Tage[k]]]=0; /\* HERY not sure if V7*V4*age Fixed might not exist  yet*\/ */
11579:             }else{  /* strc=Vn*Vm (and strd=age) and should be strb=Vn*Vm but want to keep original strb double product  */
11580: 	      strcpy(stre,strb); /* save full b in stre */
11581: 	      strcpy(strb,strc); /* save short c in new short b for next block strb=Vn*Vm*/
11582: 	      strcpy(strf,strc); /* save short c in new short f */
11583:               cutl(strc,strd,strf,'*'); /* We get strd=Vn and strc=Vm for next block (strb=Vn*Vm)*/
11584: 	      /* strcpy(strc,stre);*/ /* save full e in c for future */
11585:             }
11586:             cptcovdageprod++; /* double product with age  Which product is it? */
11587:             /* 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 *\/ */
11588:             /* cutl(strc,strd,strb,'*'); /\* strd=  V6    or   V2     or    age and  strc=  V2 or    age or    V2 *\/ */
11589: 	    cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
11590: 	    n=atoi(stre);
11591: 	    cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
11592: 	    m=atoi(strc);
11593: 	    cptcovage++; /* Counts the number of covariates which include age as a product */
11594: 	    Tage[cptcovage]=k; /* For age*V3*V2 gives the position in model of covariates associated with age Tage[1]=6 HERY too*/
11595: 	    if(existcomb[n][m] == 0){
11596: 	      /*  r /home/brouard/Documents/Recherches/REVES/Zachary/Zach-2022/Feinuo_Sun/Feinuo-threeway/femV12V15_3wayintNBe.imach */
11597: 	      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);
11598: 	      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);
11599: 	      fflush(ficlog);
11600: 	      k1++;  /* The combination Vn*Vm will be in the model so we create it at k1 */
11601: 	      k12++;
11602: 	      existcomb[n][m]=k1;
11603: 	      existcomb[m][n]=k1;
11604: 	      Tvar[k]=ncovcol+nqv+ntv+nqtv+k1;
11605: 	      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*/
11606: 	      Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 Gives the k1 double product  Vn*Vm or age*Vn*Vm at the k position */
11607: 	      Tvard[k1][1] =m; /* m 1 for V1*/
11608: 	      Tvardk[k][1] =m; /* m 1 for V1*/
11609: 	      Tvard[k1][2] =n; /* n 4 for V4*/
11610: 	      Tvardk[k][2] =n; /* n 4 for V4*/
11611: /*	      Tvar[Tage[cptcovage]]=k1;*/ /* Tvar[6=age*V3*V2]=9 (new fixed covariate) */ /* We don't know about Fixed yet HERE */
11612: 	      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 */
11613: 		for (i=1; i<=lastobs;i++){/* For fixed product */
11614: 		  /* Computes the new covariate which is a product of
11615: 		     covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
11616: 		  covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
11617: 		}
11618: 		cptcovprodage++; /* Counting the number of fixed covariate with age */
11619: 		FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
11620: 		k12++;
11621: 		FixedV[ncovcolt+k12]=0;
11622: 	      }else{ /*End of FixedV */
11623: 		cptcovprodvage++; /* Counting the number of varying covariate with age */
11624: 		FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
11625: 		k12++;
11626: 		FixedV[ncovcolt+k12]=1;
11627: 	      }
11628: 	    }else{  /* k1 Vn*Vm already exists */
11629: 	      k11=existcomb[n][m];
11630: 	      Tposprod[k]=k11; /* OK */
11631: 	      Tvar[k]=Tvar[Tprod[k11]]; /* HERY */
11632: 	      Tvardk[k][1]=m;
11633: 	      Tvardk[k][2]=n;
11634: 	      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 */
11635: 		/*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
11636: 		cptcovprodage++; /* Counting the number of fixed covariate with age */
11637: 		/*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
11638: 		Tvar[Tage[cptcovage]]=k1;
11639: 		FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
11640: 		k12++;
11641: 		FixedV[ncovcolt+k12]=0;
11642: 	      }else{ /* Already exists but time varying (and age) */
11643: 		/*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
11644: 		/*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
11645: 		/* Tvar[Tage[cptcovage]]=k1; */
11646: 		cptcovprodvage++;
11647: 		FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
11648: 		k12++;
11649: 		FixedV[ncovcolt+k12]=1;
11650: 	      }
11651: 	    }
11652: 	    /* Tage[cptcovage]=k;  /\*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
11653: 	    /* Tvar[k]=k11; /\* HERY *\/ */
11654: 	  } 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 */
11655:             cptcovprod++;
11656:             if (strcmp(strc,"age")==0) { /**< Model includes age: strb= Vn*age c=age d=Vn*/
11657:               /* covar is not filled and then is empty */
11658:               cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
11659:               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 */
11660:               Typevar[k]=1;  /* 1 for age product */
11661:               cptcovage++; /* Counts the number of covariates which include age as a product */
11662:               Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
11663: 	      if( FixedV[Tvar[k]] == 0){
11664: 		cptcovprodage++; /* Counting the number of fixed covariate with age */
11665: 	      }else{
11666: 		cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
11667: 	      }
11668:               /*printf("stre=%s ", stre);*/
11669:             } else if (strcmp(strd,"age")==0) { /* strb= age*Vn c=Vn */
11670:               cutl(stre,strb,strc,'V');
11671:               Tvar[k]=atoi(stre);
11672:               Typevar[k]=1;  /* 1 for age product */
11673:               cptcovage++;
11674:               Tage[cptcovage]=k;
11675: 	      if( FixedV[Tvar[k]] == 0){
11676: 		cptcovprodage++; /* Counting the number of fixed covariate with age */
11677: 	      }else{
11678: 		cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
11679: 	      }
11680:             }else{ /*  for product Vn*Vm */
11681: 	      Typevar[k]=2;  /* 2 for product Vn*Vm */
11682: 	      cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
11683: 	      n=atoi(stre);
11684: 	      cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
11685: 	      m=atoi(strc);
11686: 	      k1++;
11687: 	      cptcovprodnoage++;
11688: 	      if(existcomb[n][m] != 0 || existcomb[m][n] != 0){
11689: 		printf("Warning in model combination V%d*V%d already exists in the model in position k1=%d!\n",n,m,existcomb[n][m]);
11690: 		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]);
11691: 		fflush(ficlog);
11692: 		k11=existcomb[n][m];
11693: 		Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
11694: 		Tposprod[k]=k11;
11695: 		Tprod[k11]=k;
11696: 		Tvardk[k][1] =m; /* m 1 for V1*/
11697: 		/* Tvard[k11][1] =m; /\* n 4 for V4*\/ */
11698: 		Tvardk[k][2] =n; /* n 4 for V4*/		
11699: 		/* Tvard[k11][2] =n; /\* n 4 for V4*\/ */
11700: 	      }else{ /* combination Vn*Vm doesn't exist we create it (no age)*/
11701: 		existcomb[n][m]=k1;
11702: 		existcomb[m][n]=k1;
11703: 		Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
11704: 						    because this model-covariate is a construction we invent a new column
11705: 						    which is after existing variables ncovcol+nqv+ntv+nqtv + k1
11706: 						    If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
11707: 						    thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
11708: 						    Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
11709: 		/* Please remark that the new variables are model dependent */
11710: 		/* If we have 4 variable but the model uses only 3, like in
11711: 		 * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
11712: 		 *  k=     1     2      3   4     5        6        7       8
11713: 		 * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
11714: 		 * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
11715: 		 * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
11716: 		 */
11717: 		/* We need to feed some variables like TvarVV, but later on next loop because of ncovv (k2) is not correct */
11718: 		Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 +V6*V2*age  */
11719: 		Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
11720: 		Tvard[k1][1] =m; /* m 1 for V1*/
11721: 		Tvardk[k][1] =m; /* m 1 for V1*/
11722: 		Tvard[k1][2] =n; /* n 4 for V4*/
11723: 		Tvardk[k][2] =n; /* n 4 for V4*/
11724: 		k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
11725: 		/* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
11726: 		/* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
11727: 		/*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
11728: 		/*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
11729: 		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 */
11730: 		  for (i=1; i<=lastobs;i++){/* For fixed product */
11731: 		    /* Computes the new covariate which is a product of
11732: 		       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
11733: 		    covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
11734: 		  }
11735: 		  /* TvarVV[k2]=n; */
11736: 		  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
11737: 		  /* TvarVV[k2+1]=m; */
11738: 		  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
11739: 		}else{ /* not FixedV */
11740: 		  /* TvarVV[k2]=n; */
11741: 		  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
11742: 		  /* TvarVV[k2+1]=m; */
11743: 		  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
11744: 		}		  
11745: 	      }  /* End of creation of Vn*Vm if not created by age*Vn*Vm earlier  */
11746: 	    } /*  End of product Vn*Vm */
11747:           } /* End of age*double product or simple product */
11748: 	}else { /* not a product */
11749: 	  /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
11750: 	  /*  scanf("%d",i);*/
11751: 	  cutl(strd,strc,strb,'V');
11752: 	  ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
11753: 	  cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
11754: 	  Tvar[k]=atoi(strd);
11755: 	  Typevar[k]=0;  /* 0 for simple covariates */
11756: 	}
11757: 	strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
11758: 				/*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
11759: 				  scanf("%d",i);*/
11760:       } /* end of loop + on total covariates */
11761: 
11762:       
11763:     } /* end if strlen(modelsave == 0) age*age might exist */
11764:   } /* end if strlen(model == 0) */
11765:   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  */
11766: 
11767:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
11768:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
11769:   
11770:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
11771:      printf("cptcovprod=%d ", cptcovprod);
11772:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
11773:      scanf("%d ",i);*/
11774: 
11775: 
11776: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
11777:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
11778: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
11779:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
11780:    k =           1    2   3     4       5       6      7      8        9
11781:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
11782:    Typevar[k]=   0    0   0     2       1       0      2      1        0
11783:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
11784:    Dummy[k]      1    0   0     0       3       1      1      2        3
11785: 	  Tmodelind[combination of covar]=k;
11786: */  
11787: /* Dispatching between quantitative and time varying covariates */
11788:   /* If Tvar[k] >ncovcol it is a product */
11789:   /* Tvar[k] is the value n of Vn with n varying for 1 to nvcol, or p  Vp=Vn*Vm for product */
11790: 	/* Computing effective variables, ie used by the model, that is from the cptcovt variables */
11791:   printf("Model=1+age+%s\n\
11792: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product, 3 for double product with age \n\
11793: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
11794: 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);
11795:   fprintf(ficlog,"Model=1+age+%s\n\
11796: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product, 3 for double product with age  \n\
11797: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
11798: 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);
11799:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
11800:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
11801: 
11802: 
11803:   /* Second loop for calculating  Fixed[k], Dummy[k]*/
11804: 
11805:   
11806:   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 */
11807:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
11808:       Fixed[k]= 0;
11809:       Dummy[k]= 0;
11810:       ncoveff++;
11811:       ncovf++;
11812:       nsd++;
11813:       modell[k].maintype= FTYPE;
11814:       TvarsD[nsd]=Tvar[k];
11815:       TvarsDind[nsd]=k;
11816:       TnsdVar[Tvar[k]]=nsd;
11817:       TvarF[ncovf]=Tvar[k];
11818:       TvarFind[ncovf]=k;
11819:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
11820:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
11821:     /* }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /\* Product of fixed dummy (<=ncovcol) covariates For a fixed product k is higher than ncovcol *\/ */
11822:     }else if( Tvar[k] <=ncovcol+nqv && Typevar[k]==0){/* Remind that product Vn*Vm are added in k Only simple fixed quantitative variable */
11823:       Fixed[k]= 0;
11824:       Dummy[k]= 1;
11825:       nqfveff++;
11826:       modell[k].maintype= FTYPE;
11827:       modell[k].subtype= FQ;
11828:       nsq++;
11829:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
11830:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
11831:       ncovf++;
11832:       TvarF[ncovf]=Tvar[k];
11833:       TvarFind[ncovf]=k;
11834:       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 */
11835:       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 */
11836:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
11837:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
11838:       /* model V1+V3+age*V1+age*V3+V1*V3 */
11839:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
11840:       ncovvt++;
11841:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
11842:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
11843: 
11844:       Fixed[k]= 1;
11845:       Dummy[k]= 0;
11846:       ntveff++; /* Only simple time varying dummy variable */
11847:       modell[k].maintype= VTYPE;
11848:       modell[k].subtype= VD;
11849:       nsd++;
11850:       TvarsD[nsd]=Tvar[k];
11851:       TvarsDind[nsd]=k;
11852:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
11853:       ncovv++; /* Only simple time varying variables */
11854:       TvarV[ncovv]=Tvar[k];
11855:       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 */
11856:       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 */
11857:       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 */
11858:       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);
11859:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
11860:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
11861:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
11862:       /* model V1+V3+age*V1+age*V3+V1*V3 */
11863:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
11864:       ncovvt++;
11865:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
11866:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
11867:       
11868:       Fixed[k]= 1;
11869:       Dummy[k]= 1;
11870:       nqtveff++;
11871:       modell[k].maintype= VTYPE;
11872:       modell[k].subtype= VQ;
11873:       ncovv++; /* Only simple time varying variables */
11874:       nsq++;
11875:       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) */
11876:       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) */
11877:       TvarV[ncovv]=Tvar[k];
11878:       TvarVind[ncovv]=k; /* TvarVind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Any time varying singele */
11879:       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 */
11880:       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 */
11881:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
11882:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
11883:       /* 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); */
11884:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
11885:     }else if (Typevar[k] == 1) {  /* product with age */
11886:       ncova++;
11887:       TvarA[ncova]=Tvar[k];
11888:       TvarAind[ncova]=k;
11889:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
11890:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
11891:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
11892:       	Fixed[k]= 2;
11893:       	Dummy[k]= 2;
11894:       	modell[k].maintype= ATYPE;
11895:       	modell[k].subtype= APFD;
11896: 	ncovta++;
11897: 	TvarAVVA[ncovta]=Tvar[k]; /*  (2)age*V3 */
11898: 	TvarAVVAind[ncovta]=k;
11899:       	/* ncoveff++; */
11900:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
11901:       	Fixed[k]= 2;
11902:       	Dummy[k]= 3;
11903:       	modell[k].maintype= ATYPE;
11904:       	modell[k].subtype= APFQ;		/*	Product age * fixed quantitative */
11905: 	ncovta++;
11906: 	TvarAVVA[ncovta]=Tvar[k]; /*   */
11907: 	TvarAVVAind[ncovta]=k;
11908:       	/* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
11909:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
11910:       	Fixed[k]= 3;
11911:       	Dummy[k]= 2;
11912:       	modell[k].maintype= ATYPE;
11913:       	modell[k].subtype= APVD;		/*	Product age * varying dummy */
11914: 	ncovva++;
11915: 	TvarVVA[ncovva]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
11916: 	TvarVVAind[ncovva]=k;
11917: 	ncovta++;
11918: 	TvarAVVA[ncovta]=Tvar[k]; /*   */
11919: 	TvarAVVAind[ncovta]=k;
11920:       	/* ntveff++; /\* Only simple time varying dummy variable *\/ */
11921:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
11922:       	Fixed[k]= 3;
11923:       	Dummy[k]= 3;
11924:       	modell[k].maintype= ATYPE;
11925:       	modell[k].subtype= APVQ;		/*	Product age * varying quantitative */
11926: 	ncovva++;
11927: 	TvarVVA[ncovva]=Tvar[k]; /*   */
11928: 	TvarVVAind[ncovva]=k;
11929: 	ncovta++;
11930: 	TvarAVVA[ncovta]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
11931: 	TvarAVVAind[ncovta]=k;
11932:       	/* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
11933:       }
11934:     }else if( Tposprod[k]>0  &&  Typevar[k]==2){  /* Detects if fixed product no age Vm*Vn */
11935:       printf("MEMORY ERRORR k=%d  Tposprod[k]=%d, Typevar[k]=%d\n ",k, Tposprod[k], Typevar[k]);
11936:       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 */
11937:       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]]);
11938: 	Fixed[k]= 0;
11939: 	Dummy[k]= 0;
11940: 	ncoveff++;
11941: 	ncovf++;
11942: 	/* ncovv++; */
11943: 	/* TvarVV[ncovv]=Tvardk[k][1]; */
11944: 	/* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
11945: 	/* ncovv++; */
11946: 	/* TvarVV[ncovv]=Tvardk[k][2]; */
11947: 	/* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
11948: 	modell[k].maintype= FTYPE;
11949: 	TvarF[ncovf]=Tvar[k];
11950: 	/* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
11951: 	TvarFind[ncovf]=k;
11952: 	TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
11953: 	TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
11954:       }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  */
11955: 	/*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
11956: 	/* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
11957: 	/*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
11958: 	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 */
11959: 	ncovvt++;
11960: 	TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
11961: 	TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
11962: 	ncovvt++;
11963: 	TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
11964: 	TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
11965: 	
11966: 	/** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
11967: 	/** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
11968: 	
11969: 	if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
11970: 	  if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
11971: 	    Fixed[k]= 1;
11972: 	    Dummy[k]= 0;
11973: 	    modell[k].maintype= FTYPE;
11974: 	    modell[k].subtype= FPDD;		/*	Product fixed dummy * fixed dummy */
11975: 	    ncovf++; /* Fixed variables without age */
11976: 	    TvarF[ncovf]=Tvar[k];
11977: 	    TvarFind[ncovf]=k;
11978: 	  }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
11979: 	    Fixed[k]= 0;  /* Fixed product */
11980: 	    Dummy[k]= 1;
11981: 	    modell[k].maintype= FTYPE;
11982: 	    modell[k].subtype= FPDQ;		/*	Product fixed dummy * fixed quantitative */
11983: 	    ncovf++; /* Varying variables without age */
11984: 	    TvarF[ncovf]=Tvar[k];
11985: 	    TvarFind[ncovf]=k;
11986: 	  }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
11987: 	    Fixed[k]= 1;
11988: 	    Dummy[k]= 0;
11989: 	    modell[k].maintype= VTYPE;
11990: 	    modell[k].subtype= VPDD;		/*	Product fixed dummy * varying dummy */
11991: 	    ncovv++; /* Varying variables without age */
11992: 	    TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
11993: 	    TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
11994: 	  }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
11995: 	    Fixed[k]= 1;
11996: 	    Dummy[k]= 1;
11997: 	    modell[k].maintype= VTYPE;
11998: 	    modell[k].subtype= VPDQ;		/*	Product fixed dummy * varying quantitative */
11999: 	    ncovv++; /* Varying variables without age */
12000: 	    TvarV[ncovv]=Tvar[k];
12001: 	    TvarVind[ncovv]=k;
12002: 	  }
12003: 	}else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
12004: 	  if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
12005: 	    Fixed[k]= 0;  /*  Fixed product */
12006: 	    Dummy[k]= 1;
12007: 	    modell[k].maintype= FTYPE;
12008: 	    modell[k].subtype= FPDQ;		/*	Product fixed quantitative * fixed dummy */
12009: 	    ncovf++; /* Fixed variables without age */
12010: 	    TvarF[ncovf]=Tvar[k];
12011: 	    TvarFind[ncovf]=k;
12012: 	  }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
12013: 	    Fixed[k]= 1;
12014: 	    Dummy[k]= 1;
12015: 	    modell[k].maintype= VTYPE;
12016: 	    modell[k].subtype= VPDQ;		/*	Product fixed quantitative * varying dummy */
12017: 	    ncovv++; /* Varying variables without age */
12018: 	    TvarV[ncovv]=Tvar[k];
12019: 	    TvarVind[ncovv]=k;
12020: 	  }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
12021: 	    Fixed[k]= 1;
12022: 	    Dummy[k]= 1;
12023: 	    modell[k].maintype= VTYPE;
12024: 	    modell[k].subtype= VPQQ;		/*	Product fixed quantitative * varying quantitative */
12025: 	    ncovv++; /* Varying variables without age */
12026: 	    TvarV[ncovv]=Tvar[k];
12027: 	    TvarVind[ncovv]=k;
12028: 	    ncovv++; /* Varying variables without age */
12029: 	    TvarV[ncovv]=Tvar[k];
12030: 	    TvarVind[ncovv]=k;
12031: 	  }
12032: 	}else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
12033: 	  if(Tvard[k1][2] <=ncovcol){
12034: 	    Fixed[k]= 1;
12035: 	    Dummy[k]= 1;
12036: 	    modell[k].maintype= VTYPE;
12037: 	    modell[k].subtype= VPDD;		/*	Product time varying dummy * fixed dummy */
12038: 	    ncovv++; /* Varying variables without age */
12039: 	    TvarV[ncovv]=Tvar[k];
12040: 	    TvarVind[ncovv]=k;
12041: 	  }else if(Tvard[k1][2] <=ncovcol+nqv){
12042: 	    Fixed[k]= 1;
12043: 	    Dummy[k]= 1;
12044: 	    modell[k].maintype= VTYPE;
12045: 	    modell[k].subtype= VPDQ;		/*	Product time varying dummy * fixed quantitative */
12046: 	    ncovv++; /* Varying variables without age */
12047: 	    TvarV[ncovv]=Tvar[k];
12048: 	    TvarVind[ncovv]=k;
12049: 	  }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
12050: 	    Fixed[k]= 1;
12051: 	    Dummy[k]= 0;
12052: 	    modell[k].maintype= VTYPE;
12053: 	    modell[k].subtype= VPDD;		/*	Product time varying dummy * time varying dummy */
12054: 	    ncovv++; /* Varying variables without age */
12055: 	    TvarV[ncovv]=Tvar[k];
12056: 	    TvarVind[ncovv]=k;
12057: 	  }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
12058: 	    Fixed[k]= 1;
12059: 	    Dummy[k]= 1;
12060: 	    modell[k].maintype= VTYPE;
12061: 	    modell[k].subtype= VPDQ;		/*	Product time varying dummy * time varying quantitative */
12062: 	    ncovv++; /* Varying variables without age */
12063: 	    TvarV[ncovv]=Tvar[k];
12064: 	    TvarVind[ncovv]=k;
12065: 	  }
12066: 	}else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
12067: 	  if(Tvard[k1][2] <=ncovcol){
12068: 	    Fixed[k]= 1;
12069: 	    Dummy[k]= 1;
12070: 	    modell[k].maintype= VTYPE;
12071: 	    modell[k].subtype= VPDQ;		/*	Product time varying quantitative * fixed dummy */
12072: 	    ncovv++; /* Varying variables without age */
12073: 	    TvarV[ncovv]=Tvar[k];
12074: 	    TvarVind[ncovv]=k;
12075: 	  }else if(Tvard[k1][2] <=ncovcol+nqv){
12076: 	    Fixed[k]= 1;
12077: 	    Dummy[k]= 1;
12078: 	    modell[k].maintype= VTYPE;
12079: 	    modell[k].subtype= VPQQ;		/*	Product time varying quantitative * fixed quantitative */
12080: 	    ncovv++; /* Varying variables without age */
12081: 	    TvarV[ncovv]=Tvar[k];
12082: 	    TvarVind[ncovv]=k;
12083: 	  }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
12084: 	    Fixed[k]= 1;
12085: 	    Dummy[k]= 1;
12086: 	    modell[k].maintype= VTYPE;
12087: 	    modell[k].subtype= VPDQ;		/*	Product time varying quantitative * time varying dummy */
12088: 	    ncovv++; /* Varying variables without age */
12089: 	    TvarV[ncovv]=Tvar[k];
12090: 	    TvarVind[ncovv]=k;
12091: 	  }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
12092: 	    Fixed[k]= 1;
12093: 	    Dummy[k]= 1;
12094: 	    modell[k].maintype= VTYPE;
12095: 	    modell[k].subtype= VPQQ;		/*	Product time varying quantitative * time varying quantitative */
12096: 	    ncovv++; /* Varying variables without age */
12097: 	    TvarV[ncovv]=Tvar[k];
12098: 	    TvarVind[ncovv]=k;
12099: 	  }
12100: 	}else{
12101: 	  printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
12102: 	  fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
12103: 	} /*end k1*/
12104:       }
12105:     }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  */
12106:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
12107:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
12108:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
12109:       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 */
12110:       ncova++;
12111:       TvarA[ncova]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
12112:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
12113:       ncova++;
12114:       TvarA[ncova]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
12115:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
12116: 
12117:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
12118:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
12119:       if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){
12120: 	ncovta++;
12121: 	TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
12122: 	TvarAVVAind[ncovta]=k;
12123: 	ncovta++;
12124: 	TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
12125: 	TvarAVVAind[ncovta]=k;
12126:       }else{
12127: 	ncovva++;  /* HERY  reached */
12128: 	TvarVVA[ncovva]=Tvard[k1][1]; /*  age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4  */
12129: 	TvarVVAind[ncovva]=k;
12130: 	ncovva++;
12131: 	TvarVVA[ncovva]=Tvard[k1][2]; /*   */
12132: 	TvarVVAind[ncovva]=k;
12133: 	ncovta++;
12134: 	TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
12135: 	TvarAVVAind[ncovta]=k;
12136: 	ncovta++;
12137: 	TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
12138: 	TvarAVVAind[ncovta]=k;
12139:       }
12140:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
12141:     	if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
12142:     	  Fixed[k]= 2;
12143:     	  Dummy[k]= 2;
12144:     	  modell[k].maintype= FTYPE;
12145:     	  modell[k].subtype= FPDD;		/*	Product fixed dummy * fixed dummy */
12146:     	  /* TvarF[ncova]=Tvar[k];   /\* Problem to solve *\/ */
12147:     	  /* TvarFind[ncova]=k; */
12148:     	}else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
12149:     	  Fixed[k]= 2;  /* Fixed product */
12150:     	  Dummy[k]= 3;
12151:     	  modell[k].maintype= FTYPE;
12152:     	  modell[k].subtype= FPDQ;		/*	Product fixed dummy * fixed quantitative */
12153:     	  /* TvarF[ncova]=Tvar[k]; */
12154:     	  /* TvarFind[ncova]=k; */
12155:     	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
12156:     	  Fixed[k]= 3;
12157:     	  Dummy[k]= 2;
12158:     	  modell[k].maintype= VTYPE;
12159:     	  modell[k].subtype= VPDD;		/*	Product fixed dummy * varying dummy */
12160:     	  TvarV[ncova]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
12161:     	  TvarVind[ncova]=k;/* TvarVind[1]=5 */ 
12162:     	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
12163:     	  Fixed[k]= 3;
12164:     	  Dummy[k]= 3;
12165:     	  modell[k].maintype= VTYPE;
12166:     	  modell[k].subtype= VPDQ;		/*	Product fixed dummy * varying quantitative */
12167:     	  /* ncovv++; /\* Varying variables without age *\/ */
12168:     	  /* TvarV[ncovv]=Tvar[k]; */
12169:     	  /* TvarVind[ncovv]=k; */
12170:     	}
12171:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
12172:     	if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
12173:     	  Fixed[k]= 2;  /*  Fixed product */
12174:     	  Dummy[k]= 2;
12175:     	  modell[k].maintype= FTYPE;
12176:     	  modell[k].subtype= FPDQ;		/*	Product fixed quantitative * fixed dummy */
12177:     	  /* ncova++; /\* Fixed variables with age *\/ */
12178:     	  /* TvarF[ncovf]=Tvar[k]; */
12179:     	  /* TvarFind[ncovf]=k; */
12180:     	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
12181:     	  Fixed[k]= 2;
12182:     	  Dummy[k]= 3;
12183:     	  modell[k].maintype= VTYPE;
12184:     	  modell[k].subtype= VPDQ;		/*	Product fixed quantitative * varying dummy */
12185:     	  /* ncova++; /\* Varying variables with age *\/ */
12186:     	  /* TvarV[ncova]=Tvar[k]; */
12187:     	  /* TvarVind[ncova]=k; */
12188:     	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
12189:     	  Fixed[k]= 3;
12190:     	  Dummy[k]= 2;
12191:     	  modell[k].maintype= VTYPE;
12192:     	  modell[k].subtype= VPQQ;		/*	Product fixed quantitative * varying quantitative */
12193:     	  ncova++; /* Varying variables without age */
12194:     	  TvarV[ncova]=Tvar[k];
12195:     	  TvarVind[ncova]=k;
12196:     	  /* ncova++; /\* Varying variables without age *\/ */
12197:     	  /* TvarV[ncova]=Tvar[k]; */
12198:     	  /* TvarVind[ncova]=k; */
12199:     	}
12200:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
12201:     	if(Tvard[k1][2] <=ncovcol){
12202:     	  Fixed[k]= 2;
12203:     	  Dummy[k]= 2;
12204:     	  modell[k].maintype= VTYPE;
12205:     	  modell[k].subtype= VPDD;		/*	Product time varying dummy * fixed dummy */
12206:     	  /* ncova++; /\* Varying variables with age *\/ */
12207:     	  /* TvarV[ncova]=Tvar[k]; */
12208:     	  /* TvarVind[ncova]=k; */
12209:     	}else if(Tvard[k1][2] <=ncovcol+nqv){
12210:     	  Fixed[k]= 2;
12211:     	  Dummy[k]= 3;
12212:     	  modell[k].maintype= VTYPE;
12213:     	  modell[k].subtype= VPDQ;		/*	Product time varying dummy * fixed quantitative */
12214:     	  /* ncova++; /\* Varying variables with age *\/ */
12215:     	  /* TvarV[ncova]=Tvar[k]; */
12216:     	  /* TvarVind[ncova]=k; */
12217:     	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
12218:     	  Fixed[k]= 3;
12219:     	  Dummy[k]= 2;
12220:     	  modell[k].maintype= VTYPE;
12221:     	  modell[k].subtype= VPDD;		/*	Product time varying dummy * time varying dummy */
12222:     	  /* ncova++; /\* Varying variables with age *\/ */
12223:     	  /* TvarV[ncova]=Tvar[k]; */
12224:     	  /* TvarVind[ncova]=k; */
12225:     	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
12226:     	  Fixed[k]= 3;
12227:     	  Dummy[k]= 3;
12228:     	  modell[k].maintype= VTYPE;
12229:     	  modell[k].subtype= VPDQ;		/*	Product time varying dummy * time varying quantitative */
12230:     	  /* ncova++; /\* Varying variables with age *\/ */
12231:     	  /* TvarV[ncova]=Tvar[k]; */
12232:     	  /* TvarVind[ncova]=k; */
12233:     	}
12234:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
12235:     	if(Tvard[k1][2] <=ncovcol){
12236:     	  Fixed[k]= 2;
12237:     	  Dummy[k]= 2;
12238:     	  modell[k].maintype= VTYPE;
12239:     	  modell[k].subtype= VPDQ;		/*	Product time varying quantitative * fixed dummy */
12240:     	  /* ncova++; /\* Varying variables with age *\/ */
12241:     	  /* TvarV[ncova]=Tvar[k]; */
12242:     	  /* TvarVind[ncova]=k; */
12243:     	}else if(Tvard[k1][2] <=ncovcol+nqv){
12244:     	  Fixed[k]= 2;
12245:     	  Dummy[k]= 3;
12246:     	  modell[k].maintype= VTYPE;
12247:     	  modell[k].subtype= VPQQ;		/*	Product time varying quantitative * fixed quantitative */
12248:     	  /* ncova++; /\* Varying variables with age *\/ */
12249:     	  /* TvarV[ncova]=Tvar[k]; */
12250:     	  /* TvarVind[ncova]=k; */
12251:     	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
12252:     	  Fixed[k]= 3;
12253:     	  Dummy[k]= 2;
12254:     	  modell[k].maintype= VTYPE;
12255:     	  modell[k].subtype= VPDQ;		/*	Product time varying quantitative * time varying dummy */
12256:     	  /* ncova++; /\* Varying variables with age *\/ */
12257:     	  /* TvarV[ncova]=Tvar[k]; */
12258:     	  /* TvarVind[ncova]=k; */
12259:     	}else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
12260:     	  Fixed[k]= 3;
12261:     	  Dummy[k]= 3;
12262:     	  modell[k].maintype= VTYPE;
12263:     	  modell[k].subtype= VPQQ;		/*	Product time varying quantitative * time varying quantitative */
12264:     	  /* ncova++; /\* Varying variables with age *\/ */
12265:     	  /* TvarV[ncova]=Tvar[k]; */
12266:     	  /* TvarVind[ncova]=k; */
12267:     	}
12268:       }else{
12269:     	printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
12270:     	fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
12271:       } /*end k1*/
12272:     } else{
12273:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
12274:       fprintf(ficlog,"Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
12275:     }
12276:     /* 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]); */
12277:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
12278:     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]);
12279:   }
12280:   ncovvta=ncovva;
12281:   /* Searching for doublons in the model */
12282:   for(k1=1; k1<= cptcovt;k1++){
12283:     for(k2=1; k2 <k1;k2++){
12284:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
12285:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
12286: 	if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
12287: 	  if(Tvar[k1]==Tvar[k2]){
12288: 	    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]);
12289: 	    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);
12290: 	    return(1);
12291: 	  }
12292: 	}else if (Typevar[k1] ==2){
12293: 	  k3=Tposprod[k1];
12294: 	  k4=Tposprod[k2];
12295: 	  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])) ){
12296: 	    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]]);
12297: 	    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);
12298: 	    return(1);
12299: 	  }
12300: 	}
12301:       }
12302:     }
12303:   }
12304:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
12305:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
12306:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
12307:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
12308: 
12309:   free_imatrix(existcomb,1,NCOVMAX,1,NCOVMAX);
12310:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
12311:   /*endread:*/
12312:   printf("Exiting decodemodel: ");
12313:   return (1);
12314: }
12315: 
12316: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
12317: {/* Check ages at death */
12318:   int i, m;
12319:   int firstone=0;
12320:   
12321:   for (i=1; i<=imx; i++) {
12322:     for(m=2; (m<= maxwav); m++) {
12323:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
12324: 	anint[m][i]=9999;
12325: 	if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
12326: 	  s[m][i]=-1;
12327:       }
12328:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
12329: 	*nberr = *nberr + 1;
12330: 	if(firstone == 0){
12331: 	  firstone=1;
12332: 	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);
12333: 	}
12334: 	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);
12335: 	s[m][i]=-1;  /* Droping the death status */
12336:       }
12337:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
12338: 	(*nberr)++;
12339: 	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);
12340: 	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);
12341: 	s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
12342:       }
12343:     }
12344:   }
12345: 
12346:   for (i=1; i<=imx; i++)  {
12347:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
12348:     for(m=firstpass; (m<= lastpass); m++){
12349:       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 */
12350: 	if (s[m][i] >= nlstate+1) {
12351: 	  if(agedc[i]>0){
12352: 	    if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
12353: 	      agev[m][i]=agedc[i];
12354: 	      /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
12355: 	    }else {
12356: 	      if ((int)andc[i]!=9999){
12357: 		nbwarn++;
12358: 		printf("Warning negative age at death: %ld line:%d\n",num[i],i);
12359: 		fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
12360: 		agev[m][i]=-1;
12361: 	      }
12362: 	    }
12363: 	  } /* agedc > 0 */
12364: 	} /* end if */
12365: 	else if(s[m][i] !=9){ /* Standard case, age in fractional
12366: 				 years but with the precision of a month */
12367: 	  agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
12368: 	  if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
12369: 	    agev[m][i]=1;
12370: 	  else if(agev[m][i] < *agemin){ 
12371: 	    *agemin=agev[m][i];
12372: 	    printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
12373: 	  }
12374: 	  else if(agev[m][i] >*agemax){
12375: 	    *agemax=agev[m][i];
12376: 	    /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
12377: 	  }
12378: 	  /*agev[m][i]=anint[m][i]-annais[i];*/
12379: 	  /*	 agev[m][i] = age[i]+2*m;*/
12380: 	} /* en if 9*/
12381: 	else { /* =9 */
12382: 	  /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
12383: 	  agev[m][i]=1;
12384: 	  s[m][i]=-1;
12385: 	}
12386:       }
12387:       else if(s[m][i]==0) /*= 0 Unknown */
12388: 	agev[m][i]=1;
12389:       else{
12390: 	printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
12391: 	fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
12392: 	agev[m][i]=0;
12393:       }
12394:     } /* End for lastpass */
12395:   }
12396:     
12397:   for (i=1; i<=imx; i++)  {
12398:     for(m=firstpass; (m<=lastpass); m++){
12399:       if (s[m][i] > (nlstate+ndeath)) {
12400: 	(*nberr)++;
12401: 	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);	
12402: 	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);	
12403: 	return 1;
12404:       }
12405:     }
12406:   }
12407: 
12408:   /*for (i=1; i<=imx; i++){
12409:   for (m=firstpass; (m<lastpass); m++){
12410:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
12411: }
12412: 
12413: }*/
12414: 
12415: 
12416:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
12417:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
12418: 
12419:   return (0);
12420:  /* endread:*/
12421:     printf("Exiting calandcheckages: ");
12422:     return (1);
12423: }
12424: 
12425: #if defined(_MSC_VER)
12426: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
12427: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
12428: //#include "stdafx.h"
12429: //#include <stdio.h>
12430: //#include <tchar.h>
12431: //#include <windows.h>
12432: //#include <iostream>
12433: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
12434: 
12435: LPFN_ISWOW64PROCESS fnIsWow64Process;
12436: 
12437: BOOL IsWow64()
12438: {
12439: 	BOOL bIsWow64 = FALSE;
12440: 
12441: 	//typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
12442: 	//  (HANDLE, PBOOL);
12443: 
12444: 	//LPFN_ISWOW64PROCESS fnIsWow64Process;
12445: 
12446: 	HMODULE module = GetModuleHandle(_T("kernel32"));
12447: 	const char funcName[] = "IsWow64Process";
12448: 	fnIsWow64Process = (LPFN_ISWOW64PROCESS)
12449: 		GetProcAddress(module, funcName);
12450: 
12451: 	if (NULL != fnIsWow64Process)
12452: 	{
12453: 		if (!fnIsWow64Process(GetCurrentProcess(),
12454: 			&bIsWow64))
12455: 			//throw std::exception("Unknown error");
12456: 			printf("Unknown error\n");
12457: 	}
12458: 	return bIsWow64 != FALSE;
12459: }
12460: #endif
12461: 
12462: void syscompilerinfo(int logged)
12463: {
12464: #include <stdint.h>
12465: 
12466:   /* #include "syscompilerinfo.h"*/
12467:    /* command line Intel compiler 32bit windows, XP compatible:*/
12468:    /* /GS /W3 /Gy
12469:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
12470:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
12471:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
12472:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
12473:    */ 
12474:    /* 64 bits */
12475:    /*
12476:      /GS /W3 /Gy
12477:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
12478:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
12479:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
12480:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
12481:    /* Optimization are useless and O3 is slower than O2 */
12482:    /*
12483:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
12484:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
12485:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
12486:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
12487:    */
12488:    /* Link is */ /* /OUT:"visual studio
12489:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
12490:       /PDB:"visual studio
12491:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
12492:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
12493:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
12494:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
12495:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
12496:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
12497:       uiAccess='false'"
12498:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
12499:       /NOLOGO /TLBID:1
12500:    */
12501: 
12502: 
12503: #if defined __INTEL_COMPILER
12504: #if defined(__GNUC__)
12505: 	struct utsname sysInfo;  /* For Intel on Linux and OS/X */
12506: #endif
12507: #elif defined(__GNUC__) 
12508: #ifndef  __APPLE__
12509: #include <gnu/libc-version.h>  /* Only on gnu */
12510: #endif
12511:    struct utsname sysInfo;
12512:    int cross = CROSS;
12513:    if (cross){
12514: 	   printf("Cross-");
12515: 	   if(logged) fprintf(ficlog, "Cross-");
12516:    }
12517: #endif
12518: 
12519:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
12520: #if defined(__clang__)
12521:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");	/* Clang/LLVM. ---------------------------------------------- */
12522: #endif
12523: #if defined(__ICC) || defined(__INTEL_COMPILER)
12524:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
12525: #endif
12526: #if defined(__GNUC__) || defined(__GNUG__)
12527:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
12528: #endif
12529: #if defined(__HP_cc) || defined(__HP_aCC)
12530:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
12531: #endif
12532: #if defined(__IBMC__) || defined(__IBMCPP__)
12533:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
12534: #endif
12535: #if defined(_MSC_VER)
12536:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
12537: #endif
12538: #if defined(__PGI)
12539:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
12540: #endif
12541: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
12542:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
12543: #endif
12544:    printf(" for "); if (logged) fprintf(ficlog, " for ");
12545:    
12546: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
12547: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
12548:     // Windows (x64 and x86)
12549:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
12550: #elif __unix__ // all unices, not all compilers
12551:     // Unix
12552:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
12553: #elif __linux__
12554:     // linux
12555:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
12556: #elif __APPLE__
12557:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
12558:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
12559: #endif
12560: 
12561: /*  __MINGW32__	  */
12562: /*  __CYGWIN__	 */
12563: /* __MINGW64__  */
12564: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
12565: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
12566: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
12567: /* _WIN64  // Defined for applications for Win64. */
12568: /* _M_X64 // Defined for compilations that target x64 processors. */
12569: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
12570: 
12571: #if UINTPTR_MAX == 0xffffffff
12572:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
12573: #elif UINTPTR_MAX == 0xffffffffffffffff
12574:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
12575: #else
12576:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
12577: #endif
12578: 
12579: #if defined(__GNUC__)
12580: # if defined(__GNUC_PATCHLEVEL__)
12581: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
12582:                             + __GNUC_MINOR__ * 100 \
12583:                             + __GNUC_PATCHLEVEL__)
12584: # else
12585: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
12586:                             + __GNUC_MINOR__ * 100)
12587: # endif
12588:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
12589:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
12590: 
12591:    if (uname(&sysInfo) != -1) {
12592:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
12593: 	 if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
12594:    }
12595:    else
12596:       perror("uname() error");
12597:    //#ifndef __INTEL_COMPILER 
12598: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
12599:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
12600:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
12601: #endif
12602: #endif
12603: 
12604:    //   void main ()
12605:    //   {
12606: #if defined(_MSC_VER)
12607:    if (IsWow64()){
12608: 	   printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
12609: 	   if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
12610:    }
12611:    else{
12612: 	   printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
12613: 	   if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
12614:    }
12615:    //	   printf("\nPress Enter to continue...");
12616:    //	   getchar();
12617:    //   }
12618: 
12619: #endif
12620:    
12621: 
12622: }
12623: 
12624: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
12625:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
12626:   /* Computes the prevalence limit for each combination of the dummy covariates */
12627:   int i, j, k, i1, k4=0, nres=0 ;
12628:   /* double ftolpl = 1.e-10; */
12629:   double age, agebase, agelim;
12630:   double tot;
12631: 
12632:   strcpy(filerespl,"PL_");
12633:   strcat(filerespl,fileresu);
12634:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
12635:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
12636:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
12637:   }
12638:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
12639:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
12640:   pstamp(ficrespl);
12641:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
12642:   fprintf(ficrespl,"#Age ");
12643:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
12644:   fprintf(ficrespl,"\n");
12645:   
12646:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
12647: 
12648:   agebase=ageminpar;
12649:   agelim=agemaxpar;
12650: 
12651:   /* i1=pow(2,ncoveff); */
12652:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
12653:   if (cptcovn < 1){i1=1;}
12654: 
12655:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
12656:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
12657:       k=TKresult[nres];
12658:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
12659:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
12660:       /* 	continue; */
12661: 
12662:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
12663:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
12664:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
12665:       /* k=k+1; */
12666:       /* to clean */
12667:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
12668:       fprintf(ficrespl,"#******");
12669:       printf("#******");
12670:       fprintf(ficlog,"#******");
12671:       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) */
12672: 	/* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
12673: 	/* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
12674: 	/* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
12675: 	fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
12676: 	printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
12677: 	fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
12678:       }
12679:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
12680:       /* 	printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
12681:       /* 	fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
12682:       /* 	fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
12683:       /* } */
12684:       fprintf(ficrespl,"******\n");
12685:       printf("******\n");
12686:       fprintf(ficlog,"******\n");
12687:       if(invalidvarcomb[k]){
12688: 	printf("\nCombination (%d) ignored because no case \n",k); 
12689: 	fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
12690: 	fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
12691: 	continue;
12692:       }
12693: 
12694:       fprintf(ficrespl,"#Age ");
12695:       /* for(j=1;j<=cptcoveff;j++) { */
12696:       /* 	fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
12697:       /* } */
12698:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
12699: 	fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
12700:       }
12701:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
12702:       fprintf(ficrespl,"Total Years_to_converge\n");
12703:     
12704:       for (age=agebase; age<=agelim; age++){
12705: 	/* for (age=agebase; age<=agebase; age++){ */
12706: 	/**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
12707: 	prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
12708: 	fprintf(ficrespl,"%.0f ",age );
12709: 	/* for(j=1;j<=cptcoveff;j++) */
12710: 	/*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
12711: 	for(j=1;j<=cptcovs;j++)
12712: 	  fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
12713: 	tot=0.;
12714: 	for(i=1; i<=nlstate;i++){
12715: 	  tot +=  prlim[i][i];
12716: 	  fprintf(ficrespl," %.5f", prlim[i][i]);
12717: 	}
12718: 	fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
12719:       } /* Age */
12720:       /* was end of cptcod */
12721:     } /* nres */
12722:   /* } /\* for each combination *\/ */
12723:   return 0;
12724: }
12725: 
12726: 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){
12727: 	/*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
12728: 	
12729: 	/* Computes the back prevalence limit  for any combination	of covariate values 
12730:    * at any age between ageminpar and agemaxpar
12731: 	 */
12732:   int i, j, k, i1, nres=0 ;
12733:   /* double ftolpl = 1.e-10; */
12734:   double age, agebase, agelim;
12735:   double tot;
12736:   /* double ***mobaverage; */
12737:   /* double	 **dnewm, **doldm, **dsavm;  /\* for use *\/ */
12738: 
12739:   strcpy(fileresplb,"PLB_");
12740:   strcat(fileresplb,fileresu);
12741:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
12742:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
12743:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
12744:   }
12745:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
12746:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
12747:   pstamp(ficresplb);
12748:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
12749:   fprintf(ficresplb,"#Age ");
12750:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
12751:   fprintf(ficresplb,"\n");
12752:   
12753:   
12754:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
12755:   
12756:   agebase=ageminpar;
12757:   agelim=agemaxpar;
12758:   
12759:   
12760:   i1=pow(2,cptcoveff);
12761:   if (cptcovn < 1){i1=1;}
12762:   
12763:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
12764:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
12765:       k=TKresult[nres];
12766:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
12767:      /* if(i1 != 1 && TKresult[nres]!= k) */
12768:      /* 	continue; */
12769:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
12770:       fprintf(ficresplb,"#******");
12771:       printf("#******");
12772:       fprintf(ficlog,"#******");
12773:       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) */
12774: 	printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
12775: 	fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
12776: 	fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
12777:       }
12778:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
12779:       /* 	fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
12780:       /* 	printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
12781:       /* 	fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
12782:       /* } */
12783:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
12784:       /* 	printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
12785:       /* 	fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
12786:       /* 	fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
12787:       /* } */
12788:       fprintf(ficresplb,"******\n");
12789:       printf("******\n");
12790:       fprintf(ficlog,"******\n");
12791:       if(invalidvarcomb[k]){
12792: 	printf("\nCombination (%d) ignored because no cases \n",k); 
12793: 	fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
12794: 	fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
12795: 	continue;
12796:       }
12797:     
12798:       fprintf(ficresplb,"#Age ");
12799:       for(j=1;j<=cptcovs;j++) {
12800: 	fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
12801:       }
12802:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
12803:       fprintf(ficresplb,"Total Years_to_converge\n");
12804:     
12805:     
12806:       for (age=agebase; age<=agelim; age++){
12807: 	/* for (age=agebase; age<=agebase; age++){ */
12808: 	if(mobilavproj > 0){
12809: 	  /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
12810: 	  /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
12811: 	  bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
12812: 	}else if (mobilavproj == 0){
12813: 	  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);
12814: 	  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);
12815: 	  exit(1);
12816: 	}else{
12817: 	  /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
12818: 	  bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
12819: 	  /* printf("TOTOT\n"); */
12820:           /* exit(1); */
12821: 	}
12822: 	fprintf(ficresplb,"%.0f ",age );
12823: 	for(j=1;j<=cptcovs;j++)
12824: 	  fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
12825: 	tot=0.;
12826: 	for(i=1; i<=nlstate;i++){
12827: 	  tot +=  bprlim[i][i];
12828: 	  fprintf(ficresplb," %.5f", bprlim[i][i]);
12829: 	}
12830: 	fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
12831:       } /* Age */
12832:       /* was end of cptcod */
12833:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
12834:     /* } /\* end of any combination *\/ */
12835:   } /* end of nres */  
12836:   /* hBijx(p, bage, fage); */
12837:   /* fclose(ficrespijb); */
12838:   
12839:   return 0;
12840: }
12841:  
12842: int hPijx(double *p, int bage, int fage){
12843:     /*------------- h Pij x at various ages ------------*/
12844:   /* to be optimized with precov */
12845:   int stepsize;
12846:   int agelim;
12847:   int hstepm;
12848:   int nhstepm;
12849:   int h, i, i1, j, k, k4, nres=0;
12850: 
12851:   double agedeb;
12852:   double ***p3mat;
12853: 
12854:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
12855:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
12856:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
12857:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
12858:   }
12859:   printf("Computing pij: result on file '%s' \n", filerespij);
12860:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
12861:   
12862:   stepsize=(int) (stepm+YEARM-1)/YEARM;
12863:   /*if (stepm<=24) stepsize=2;*/
12864:   
12865:   agelim=AGESUP;
12866:   hstepm=stepsize*YEARM; /* Every year of age */
12867:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
12868:   
12869:   /* hstepm=1;   aff par mois*/
12870:   pstamp(ficrespij);
12871:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
12872:   i1= pow(2,cptcoveff);
12873:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
12874:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
12875:   /*  	k=k+1;  */
12876:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
12877:     k=TKresult[nres];
12878:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
12879:     /* for(k=1; k<=i1;k++){ */
12880:     /* if(i1 != 1 && TKresult[nres]!= k) */
12881:     /* 	continue; */
12882:     fprintf(ficrespij,"\n#****** ");
12883:     for(j=1;j<=cptcovs;j++){
12884:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
12885:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
12886:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
12887:       /* 	printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
12888:       /* 	fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
12889:     }
12890:     fprintf(ficrespij,"******\n");
12891:     
12892:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
12893:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
12894:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
12895:       
12896:       /*	  nhstepm=nhstepm*YEARM; aff par mois*/
12897:       
12898:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
12899:       oldm=oldms;savm=savms;
12900:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
12901:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
12902:       for(i=1; i<=nlstate;i++)
12903: 	for(j=1; j<=nlstate+ndeath;j++)
12904: 	  fprintf(ficrespij," %1d-%1d",i,j);
12905:       fprintf(ficrespij,"\n");
12906:       for (h=0; h<=nhstepm; h++){
12907: 	/*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
12908: 	fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
12909: 	for(i=1; i<=nlstate;i++)
12910: 	  for(j=1; j<=nlstate+ndeath;j++)
12911: 	    fprintf(ficrespij," %.5f", p3mat[i][j][h]);
12912: 	fprintf(ficrespij,"\n");
12913:       }
12914:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
12915:       fprintf(ficrespij,"\n");
12916:     }
12917:   }
12918:   /*}*/
12919:   return 0;
12920: }
12921:  
12922:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
12923:     /*------------- h Bij x at various ages ------------*/
12924:     /* To be optimized with precov */
12925:   int stepsize;
12926:   /* int agelim; */
12927: 	int ageminl;
12928:   int hstepm;
12929:   int nhstepm;
12930:   int h, i, i1, j, k, nres;
12931: 	
12932:   double agedeb;
12933:   double ***p3mat;
12934: 	
12935:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
12936:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
12937:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
12938:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
12939:   }
12940:   printf("Computing pij back: result on file '%s' \n", filerespijb);
12941:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
12942:   
12943:   stepsize=(int) (stepm+YEARM-1)/YEARM;
12944:   /*if (stepm<=24) stepsize=2;*/
12945:   
12946:   /* agelim=AGESUP; */
12947:   ageminl=AGEINF; /* was 30 */
12948:   hstepm=stepsize*YEARM; /* Every year of age */
12949:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
12950:   
12951:   /* hstepm=1;   aff par mois*/
12952:   pstamp(ficrespijb);
12953:   fprintf(ficrespijb,"#****** h Bij x Back probability to be in state i at age x-h being in j at x: B1j+B2j+...=1 ");
12954:   i1= pow(2,cptcoveff);
12955:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
12956:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
12957:   /*  	k=k+1;  */
12958:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
12959:     k=TKresult[nres];
12960:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
12961:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
12962:     /*    if(i1 != 1 && TKresult[nres]!= k) */
12963:     /* 	continue; */
12964:     fprintf(ficrespijb,"\n#****** ");
12965:     for(j=1;j<=cptcovs;j++){
12966:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
12967:       /* for(j=1;j<=cptcoveff;j++) */
12968:       /* 	fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
12969:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
12970:       /* 	fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
12971:     }
12972:     fprintf(ficrespijb,"******\n");
12973:     if(invalidvarcomb[k]){  /* Is it necessary here? */
12974:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
12975:       continue;
12976:     }
12977:     
12978:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
12979:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
12980:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
12981:       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 */
12982:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
12983:       
12984:       /*	  nhstepm=nhstepm*YEARM; aff par mois*/
12985:       
12986:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
12987:       /* and memory limitations if stepm is small */
12988:       
12989:       /* oldm=oldms;savm=savms; */
12990:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
12991:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
12992:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
12993:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
12994:       for(i=1; i<=nlstate;i++)
12995: 	for(j=1; j<=nlstate+ndeath;j++)
12996: 	  fprintf(ficrespijb," %1d-%1d",i,j);
12997:       fprintf(ficrespijb,"\n");
12998:       for (h=0; h<=nhstepm; h++){
12999: 	/*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
13000: 	fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
13001: 	/* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
13002: 	for(i=1; i<=nlstate;i++)
13003: 	  for(j=1; j<=nlstate+ndeath;j++)
13004: 	    fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
13005: 	fprintf(ficrespijb,"\n");
13006:       }
13007:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
13008:       fprintf(ficrespijb,"\n");
13009:     } /* end age deb */
13010:     /* } /\* end combination *\/ */
13011:   } /* end nres */
13012:   return 0;
13013:  } /*  hBijx */
13014: 
13015: 
13016: /***********************************************/
13017: /**************** Main Program *****************/
13018: /***********************************************/
13019: 
13020: int main(int argc, char *argv[])
13021: {
13022: #ifdef GSL
13023:   const gsl_multimin_fminimizer_type *T;
13024:   size_t iteri = 0, it;
13025:   int rval = GSL_CONTINUE;
13026:   int status = GSL_SUCCESS;
13027:   double ssval;
13028: #endif
13029:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
13030:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
13031:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
13032:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
13033:   int jj, ll, li, lj, lk;
13034:   int numlinepar=0; /* Current linenumber of parameter file */
13035:   int num_filled;
13036:   int itimes;
13037:   int NDIM=2;
13038:   int vpopbased=0;
13039:   int nres=0;
13040:   int endishere=0;
13041:   int noffset=0;
13042:   int ncurrv=0; /* Temporary variable */
13043:   
13044:   char ca[32], cb[32];
13045:   /*  FILE *fichtm; *//* Html File */
13046:   /* FILE *ficgp;*/ /*Gnuplot File */
13047:   struct stat info;
13048:   double agedeb=0.;
13049: 
13050:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
13051:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
13052: 
13053:   double fret;
13054:   double dum=0.; /* Dummy variable */
13055:   double ***p3mat;
13056:   /* double ***mobaverage; */
13057:   double wald;
13058: 
13059:   char line[MAXLINE], linetmp[MAXLINE];
13060:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
13061: 
13062:   char  modeltemp[MAXLINE];
13063:   char resultline[MAXLINE], resultlineori[MAXLINE];
13064:   
13065:   char pathr[MAXLINE], pathimach[MAXLINE]; 
13066:   char *tok, *val; /* pathtot */
13067:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
13068:   int c,  h , cpt, c2;
13069:   int jl=0;
13070:   int i1, j1, jk, stepsize=0;
13071:   int count=0;
13072: 
13073:   int *tab; 
13074:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
13075:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
13076:   /* double anprojf, mprojf, jprojf; */
13077:   /* double jintmean,mintmean,aintmean;   */
13078:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
13079:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
13080:   double yrfproj= 10.0; /* Number of years of forward projections */
13081:   double yrbproj= 10.0; /* Number of years of backward projections */
13082:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
13083:   int mobilav=0,popforecast=0;
13084:   int hstepm=0, nhstepm=0;
13085:   int agemortsup;
13086:   float  sumlpop=0.;
13087:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
13088:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
13089: 
13090:   double bage=0, fage=110., age, agelim=0., agebase=0.;
13091:   double ftolpl=FTOL;
13092:   double **prlim;
13093:   double **bprlim;
13094:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
13095:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
13096:   double ***paramstart; /* Matrix of starting parameter values */
13097:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
13098:   double **matcov; /* Matrix of covariance */
13099:   double **hess; /* Hessian matrix */
13100:   double ***delti3; /* Scale */
13101:   double *delti; /* Scale */
13102:   double ***eij, ***vareij;
13103:   double **varpl; /* Variances of prevalence limits by age */
13104: 
13105:   double *epj, vepp;
13106: 
13107:   double dateprev1, dateprev2;
13108:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
13109:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
13110: 
13111: 
13112:   double **ximort;
13113:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
13114:   int *dcwave;
13115: 
13116:   char z[1]="c";
13117: 
13118:   /*char  *strt;*/
13119:   char strtend[80];
13120: 
13121: 
13122: /*   setlocale (LC_ALL, ""); */
13123: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
13124: /*   textdomain (PACKAGE); */
13125: /*   setlocale (LC_CTYPE, ""); */
13126: /*   setlocale (LC_MESSAGES, ""); */
13127: 
13128:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
13129:   rstart_time = time(NULL);  
13130:   /*  (void) gettimeofday(&start_time,&tzp);*/
13131:   start_time = *localtime(&rstart_time);
13132:   curr_time=start_time;
13133:   /*tml = *localtime(&start_time.tm_sec);*/
13134:   /* strcpy(strstart,asctime(&tml)); */
13135:   strcpy(strstart,asctime(&start_time));
13136: 
13137: /*  printf("Localtime (at start)=%s",strstart); */
13138: /*  tp.tm_sec = tp.tm_sec +86400; */
13139: /*  tm = *localtime(&start_time.tm_sec); */
13140: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
13141: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
13142: /*   tmg.tm_hour=tmg.tm_hour + 1; */
13143: /*   tp.tm_sec = mktime(&tmg); */
13144: /*   strt=asctime(&tmg); */
13145: /*   printf("Time(after) =%s",strstart);  */
13146: /*  (void) time (&time_value);
13147: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
13148: *  tm = *localtime(&time_value);
13149: *  strstart=asctime(&tm);
13150: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
13151: */
13152: 
13153:   nberr=0; /* Number of errors and warnings */
13154:   nbwarn=0;
13155: #ifdef WIN32
13156:   _getcwd(pathcd, size);
13157: #else
13158:   getcwd(pathcd, size);
13159: #endif
13160:   syscompilerinfo(0);
13161:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
13162:   if(argc <=1){
13163:     printf("\nEnter the parameter file name: ");
13164:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
13165:       printf("ERROR Empty parameter file name\n");
13166:       goto end;
13167:     }
13168:     i=strlen(pathr);
13169:     if(pathr[i-1]=='\n')
13170:       pathr[i-1]='\0';
13171:     i=strlen(pathr);
13172:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
13173:       pathr[i-1]='\0';
13174:     }
13175:     i=strlen(pathr);
13176:     if( i==0 ){
13177:       printf("ERROR Empty parameter file name\n");
13178:       goto end;
13179:     }
13180:     for (tok = pathr; tok != NULL; ){
13181:       printf("Pathr |%s|\n",pathr);
13182:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
13183:       printf("val= |%s| pathr=%s\n",val,pathr);
13184:       strcpy (pathtot, val);
13185:       if(pathr[0] == '\0') break; /* Dirty */
13186:     }
13187:   }
13188:   else if (argc<=2){
13189:     strcpy(pathtot,argv[1]);
13190:   }
13191:   else{
13192:     strcpy(pathtot,argv[1]);
13193:     strcpy(z,argv[2]);
13194:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
13195:   }
13196:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
13197:   /*cygwin_split_path(pathtot,path,optionfile);
13198:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
13199:   /* cutv(path,optionfile,pathtot,'\\');*/
13200: 
13201:   /* Split argv[0], imach program to get pathimach */
13202:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
13203:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
13204:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
13205:  /*   strcpy(pathimach,argv[0]); */
13206:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
13207:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
13208:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
13209: #ifdef WIN32
13210:   _chdir(path); /* Can be a relative path */
13211:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
13212: #else
13213:   chdir(path); /* Can be a relative path */
13214:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
13215: #endif
13216:   printf("Current directory %s!\n",pathcd);
13217:   strcpy(command,"mkdir ");
13218:   strcat(command,optionfilefiname);
13219:   if((outcmd=system(command)) != 0){
13220:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
13221:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
13222:     /* fclose(ficlog); */
13223: /*     exit(1); */
13224:   }
13225: /*   if((imk=mkdir(optionfilefiname))<0){ */
13226: /*     perror("mkdir"); */
13227: /*   } */
13228: 
13229:   /*-------- arguments in the command line --------*/
13230: 
13231:   /* Main Log file */
13232:   strcat(filelog, optionfilefiname);
13233:   strcat(filelog,".log");    /* */
13234:   if((ficlog=fopen(filelog,"w"))==NULL)    {
13235:     printf("Problem with logfile %s\n",filelog);
13236:     goto end;
13237:   }
13238:   fprintf(ficlog,"Log filename:%s\n",filelog);
13239:   fprintf(ficlog,"Version %s %s",version,fullversion);
13240:   fprintf(ficlog,"\nEnter the parameter file name: \n");
13241:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
13242:  path=%s \n\
13243:  optionfile=%s\n\
13244:  optionfilext=%s\n\
13245:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
13246: 
13247:   syscompilerinfo(1);
13248: 
13249:   printf("Local time (at start):%s",strstart);
13250:   fprintf(ficlog,"Local time (at start): %s",strstart);
13251:   fflush(ficlog);
13252: /*   (void) gettimeofday(&curr_time,&tzp); */
13253: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
13254: 
13255:   /* */
13256:   strcpy(fileres,"r");
13257:   strcat(fileres, optionfilefiname);
13258:   strcat(fileresu, optionfilefiname); /* Without r in front */
13259:   strcat(fileres,".txt");    /* Other files have txt extension */
13260:   strcat(fileresu,".txt");    /* Other files have txt extension */
13261: 
13262:   /* Main ---------arguments file --------*/
13263: 
13264:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
13265:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
13266:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
13267:     fflush(ficlog);
13268:     /* goto end; */
13269:     exit(70); 
13270:   }
13271: 
13272:   strcpy(filereso,"o");
13273:   strcat(filereso,fileresu);
13274:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
13275:     printf("Problem with Output resultfile: %s\n", filereso);
13276:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
13277:     fflush(ficlog);
13278:     goto end;
13279:   }
13280:       /*-------- Rewriting parameter file ----------*/
13281:   strcpy(rfileres,"r");    /* "Rparameterfile */
13282:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
13283:   strcat(rfileres,".");    /* */
13284:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
13285:   if((ficres =fopen(rfileres,"w"))==NULL) {
13286:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
13287:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
13288:     fflush(ficlog);
13289:     goto end;
13290:   }
13291:   fprintf(ficres,"#IMaCh %s\n",version);
13292: 
13293: 				      
13294:   /* Reads comments: lines beginning with '#' */
13295:   numlinepar=0;
13296:   /* Is it a BOM UTF-8 Windows file? */
13297:   /* First parameter line */
13298:   while(fgets(line, MAXLINE, ficpar)) {
13299:     noffset=0;
13300:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
13301:     {
13302:       noffset=noffset+3;
13303:       printf("# File is an UTF8 Bom.\n"); // 0xBF
13304:     }
13305: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
13306:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
13307:     {
13308:       noffset=noffset+2;
13309:       printf("# File is an UTF16BE BOM file\n");
13310:     }
13311:     else if( line[0] == 0 && line[1] == 0)
13312:     {
13313:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
13314: 	noffset=noffset+4;
13315: 	printf("# File is an UTF16BE BOM file\n");
13316:       }
13317:     } else{
13318:       ;/*printf(" Not a BOM file\n");*/
13319:     }
13320:   
13321:     /* If line starts with a # it is a comment */
13322:     if (line[noffset] == '#') {
13323:       numlinepar++;
13324:       fputs(line,stdout);
13325:       fputs(line,ficparo);
13326:       fputs(line,ficres);
13327:       fputs(line,ficlog);
13328:       continue;
13329:     }else
13330:       break;
13331:   }
13332:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
13333: 			title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
13334:     if (num_filled != 5) {
13335:       printf("Should be 5 parameters\n");
13336:       fprintf(ficlog,"Should be 5 parameters\n");
13337:     }
13338:     numlinepar++;
13339:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
13340:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
13341:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
13342:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
13343:   }
13344:   /* Second parameter line */
13345:   while(fgets(line, MAXLINE, ficpar)) {
13346:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
13347:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
13348:     if (line[0] == '#') {
13349:       numlinepar++;
13350:       printf("%s",line);
13351:       fprintf(ficres,"%s",line);
13352:       fprintf(ficparo,"%s",line);
13353:       fprintf(ficlog,"%s",line);
13354:       continue;
13355:     }else
13356:       break;
13357:   }
13358:   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", \
13359: 			&ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
13360:     if (num_filled != 11) {
13361:       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");
13362:       printf("but line=%s\n",line);
13363:       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");
13364:       fprintf(ficlog,"but line=%s\n",line);
13365:     }
13366:     if( lastpass > maxwav){
13367:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
13368:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
13369:       fflush(ficlog);
13370:       goto end;
13371:     }
13372:       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);
13373:     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);
13374:     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);
13375:     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);
13376:   }
13377:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
13378:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
13379:   /* Third parameter line */
13380:   while(fgets(line, MAXLINE, ficpar)) {
13381:     /* If line starts with a # it is a comment */
13382:     if (line[0] == '#') {
13383:       numlinepar++;
13384:       printf("%s",line);
13385:       fprintf(ficres,"%s",line);
13386:       fprintf(ficparo,"%s",line);
13387:       fprintf(ficlog,"%s",line);
13388:       continue;
13389:     }else
13390:       break;
13391:   }
13392:   if((num_filled=sscanf(line,"model=%[^.\n]", model)) !=EOF){ /* Every character after model but dot and  return */
13393:     if (num_filled != 1){
13394:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
13395:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
13396:       model[0]='\0';
13397:       goto end;
13398:     }else{
13399:       trimbtab(linetmp,line); /* Trims multiple blanks in line */
13400:       strcpy(line, linetmp);
13401:     }
13402:   }
13403:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){ /* Every character after 1+age but dot and  return */
13404:     if (num_filled != 1){
13405:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
13406:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
13407:       model[0]='\0';
13408:       goto end;
13409:     }
13410:     else{
13411:       if (model[0]=='+'){
13412: 	for(i=1; i<=strlen(model);i++)
13413: 	  modeltemp[i-1]=model[i];
13414: 	strcpy(model,modeltemp); 
13415:       }
13416:     }
13417:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
13418:     printf("model=1+age+%s\n",model);fflush(stdout);
13419:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
13420:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
13421:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
13422:   }
13423:   /* 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); */
13424:   /* numlinepar=numlinepar+3; /\* In general *\/ */
13425:   /* 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); */
13426:   /* 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); */
13427:   /* 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); */
13428:   fflush(ficlog);
13429:   /* if(model[0]=='#'|| model[0]== '\0'){ */
13430:   if(model[0]=='#'){
13431:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
13432:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
13433:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");		\
13434:     if(mle != -1){
13435:       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");
13436:       exit(1);
13437:     }
13438:   }
13439:   while((c=getc(ficpar))=='#' && c!= EOF){
13440:     ungetc(c,ficpar);
13441:     fgets(line, MAXLINE, ficpar);
13442:     numlinepar++;
13443:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
13444:       z[0]=line[1];
13445:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
13446:       debugILK=1;printf("DebugILK\n");
13447:     }
13448:     /* printf("****line [1] = %c \n",line[1]); */
13449:     fputs(line, stdout);
13450:     //puts(line);
13451:     fputs(line,ficparo);
13452:     fputs(line,ficlog);
13453:   }
13454:   ungetc(c,ficpar);
13455: 
13456:    
13457:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
13458:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
13459:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
13460:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
13461:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
13462:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
13463:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
13464:      v1+v2*age+v2*v3 makes cptcovn = 3
13465:   */
13466:   if (strlen(model)>1) 
13467:     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*/
13468:   else
13469:     ncovmodel=2; /* Constant and age */
13470:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
13471:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
13472:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
13473:     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);
13474:     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);
13475:     fflush(stdout);
13476:     fclose (ficlog);
13477:     goto end;
13478:   }
13479:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
13480:   delti=delti3[1][1];
13481:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
13482:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
13483: /* We could also provide initial parameters values giving by simple logistic regression 
13484:  * only one way, that is without matrix product. We will have nlstate maximizations */
13485:       /* for(i=1;i<nlstate;i++){ */
13486:       /* 	/\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
13487:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
13488:       /* } */
13489:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
13490:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
13491:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
13492:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
13493:     fclose (ficparo);
13494:     fclose (ficlog);
13495:     goto end;
13496:     exit(0);
13497:   }  else if(mle==-5) { /* Main Wizard */
13498:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
13499:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
13500:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
13501:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
13502:     matcov=matrix(1,npar,1,npar);
13503:     hess=matrix(1,npar,1,npar);
13504:   }  else{ /* Begin of mle != -1 or -5 */
13505:     /* Read guessed parameters */
13506:     /* Reads comments: lines beginning with '#' */
13507:     while((c=getc(ficpar))=='#' && c!= EOF){
13508:       ungetc(c,ficpar);
13509:       fgets(line, MAXLINE, ficpar);
13510:       numlinepar++;
13511:       fputs(line,stdout);
13512:       fputs(line,ficparo);
13513:       fputs(line,ficlog);
13514:     }
13515:     ungetc(c,ficpar);
13516:     
13517:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
13518:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
13519:     for(i=1; i <=nlstate; i++){
13520:       j=0;
13521:       for(jj=1; jj <=nlstate+ndeath; jj++){
13522: 	if(jj==i) continue;
13523: 	j++;
13524: 	while((c=getc(ficpar))=='#' && c!= EOF){
13525: 	  ungetc(c,ficpar);
13526: 	  fgets(line, MAXLINE, ficpar);
13527: 	  numlinepar++;
13528: 	  fputs(line,stdout);
13529: 	  fputs(line,ficparo);
13530: 	  fputs(line,ficlog);
13531: 	}
13532: 	ungetc(c,ficpar);
13533: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
13534: 	if ((i1 != i) || (j1 != jj)){
13535: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
13536: It might be a problem of design; if ncovcol and the model are correct\n \
13537: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
13538: 	  exit(1);
13539: 	}
13540: 	fprintf(ficparo,"%1d%1d",i1,j1);
13541: 	if(mle==1)
13542: 	  printf("%1d%1d",i,jj);
13543: 	fprintf(ficlog,"%1d%1d",i,jj);
13544: 	for(k=1; k<=ncovmodel;k++){
13545: 	  fscanf(ficpar," %lf",&param[i][j][k]);
13546: 	  if(mle==1){
13547: 	    printf(" %lf",param[i][j][k]);
13548: 	    fprintf(ficlog," %lf",param[i][j][k]);
13549: 	  }
13550: 	  else
13551: 	    fprintf(ficlog," %lf",param[i][j][k]);
13552: 	  fprintf(ficparo," %lf",param[i][j][k]);
13553: 	}
13554: 	fscanf(ficpar,"\n");
13555: 	numlinepar++;
13556: 	if(mle==1)
13557: 	  printf("\n");
13558: 	fprintf(ficlog,"\n");
13559: 	fprintf(ficparo,"\n");
13560:       }
13561:     }  
13562:     fflush(ficlog);
13563:     
13564:     /* Reads parameters values */
13565:     p=param[1][1];
13566:     pstart=paramstart[1][1];
13567:     
13568:     /* Reads comments: lines beginning with '#' */
13569:     while((c=getc(ficpar))=='#' && c!= EOF){
13570:       ungetc(c,ficpar);
13571:       fgets(line, MAXLINE, ficpar);
13572:       numlinepar++;
13573:       fputs(line,stdout);
13574:       fputs(line,ficparo);
13575:       fputs(line,ficlog);
13576:     }
13577:     ungetc(c,ficpar);
13578: 
13579:     for(i=1; i <=nlstate; i++){
13580:       for(j=1; j <=nlstate+ndeath-1; j++){
13581: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
13582: 	if ( (i1-i) * (j1-j) != 0){
13583: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
13584: 	  exit(1);
13585: 	}
13586: 	printf("%1d%1d",i,j);
13587: 	fprintf(ficparo,"%1d%1d",i1,j1);
13588: 	fprintf(ficlog,"%1d%1d",i1,j1);
13589: 	for(k=1; k<=ncovmodel;k++){
13590: 	  fscanf(ficpar,"%le",&delti3[i][j][k]);
13591: 	  printf(" %le",delti3[i][j][k]);
13592: 	  fprintf(ficparo," %le",delti3[i][j][k]);
13593: 	  fprintf(ficlog," %le",delti3[i][j][k]);
13594: 	}
13595: 	fscanf(ficpar,"\n");
13596: 	numlinepar++;
13597: 	printf("\n");
13598: 	fprintf(ficparo,"\n");
13599: 	fprintf(ficlog,"\n");
13600:       }
13601:     }
13602:     fflush(ficlog);
13603:     
13604:     /* Reads covariance matrix */
13605:     delti=delti3[1][1];
13606: 		
13607: 		
13608:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
13609: 		
13610:     /* Reads comments: lines beginning with '#' */
13611:     while((c=getc(ficpar))=='#' && c!= EOF){
13612:       ungetc(c,ficpar);
13613:       fgets(line, MAXLINE, ficpar);
13614:       numlinepar++;
13615:       fputs(line,stdout);
13616:       fputs(line,ficparo);
13617:       fputs(line,ficlog);
13618:     }
13619:     ungetc(c,ficpar);
13620: 		
13621:     matcov=matrix(1,npar,1,npar);
13622:     hess=matrix(1,npar,1,npar);
13623:     for(i=1; i <=npar; i++)
13624:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
13625: 		
13626:     /* Scans npar lines */
13627:     for(i=1; i <=npar; i++){
13628:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
13629:       if(count != 3){
13630: 	printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
13631: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
13632: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
13633: 	fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
13634: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
13635: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
13636: 	exit(1);
13637:       }else{
13638: 	if(mle==1)
13639: 	  printf("%1d%1d%d",i1,j1,jk);
13640:       }
13641:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
13642:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
13643:       for(j=1; j <=i; j++){
13644: 	fscanf(ficpar," %le",&matcov[i][j]);
13645: 	if(mle==1){
13646: 	  printf(" %.5le",matcov[i][j]);
13647: 	}
13648: 	fprintf(ficlog," %.5le",matcov[i][j]);
13649: 	fprintf(ficparo," %.5le",matcov[i][j]);
13650:       }
13651:       fscanf(ficpar,"\n");
13652:       numlinepar++;
13653:       if(mle==1)
13654: 				printf("\n");
13655:       fprintf(ficlog,"\n");
13656:       fprintf(ficparo,"\n");
13657:     }
13658:     /* End of read covariance matrix npar lines */
13659:     for(i=1; i <=npar; i++)
13660:       for(j=i+1;j<=npar;j++)
13661: 	matcov[i][j]=matcov[j][i];
13662:     
13663:     if(mle==1)
13664:       printf("\n");
13665:     fprintf(ficlog,"\n");
13666:     
13667:     fflush(ficlog);
13668:     
13669:   }    /* End of mle != -3 */
13670:   
13671:   /*  Main data
13672:    */
13673:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
13674:   /* num=lvector(1,n); */
13675:   /* moisnais=vector(1,n); */
13676:   /* annais=vector(1,n); */
13677:   /* moisdc=vector(1,n); */
13678:   /* andc=vector(1,n); */
13679:   /* weight=vector(1,n); */
13680:   /* agedc=vector(1,n); */
13681:   /* cod=ivector(1,n); */
13682:   /* for(i=1;i<=n;i++){ */
13683:   num=lvector(firstobs,lastobs);
13684:   moisnais=vector(firstobs,lastobs);
13685:   annais=vector(firstobs,lastobs);
13686:   moisdc=vector(firstobs,lastobs);
13687:   andc=vector(firstobs,lastobs);
13688:   weight=vector(firstobs,lastobs);
13689:   agedc=vector(firstobs,lastobs);
13690:   cod=ivector(firstobs,lastobs);
13691:   for(i=firstobs;i<=lastobs;i++){
13692:     num[i]=0;
13693:     moisnais[i]=0;
13694:     annais[i]=0;
13695:     moisdc[i]=0;
13696:     andc[i]=0;
13697:     agedc[i]=0;
13698:     cod[i]=0;
13699:     weight[i]=1.0; /* Equal weights, 1 by default */
13700:   }
13701:   mint=matrix(1,maxwav,firstobs,lastobs);
13702:   anint=matrix(1,maxwav,firstobs,lastobs);
13703:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
13704:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
13705:   tab=ivector(1,NCOVMAX);
13706:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
13707:   ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
13708: 
13709:   /* Reads data from file datafile */
13710:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
13711:     goto end;
13712: 
13713:   /* Calculation of the number of parameters from char model */
13714:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
13715: 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
13716: 	k=3 V4 Tvar[k=3]= 4 (from V4)
13717: 	k=2 V1 Tvar[k=2]= 1 (from V1)
13718: 	k=1 Tvar[1]=2 (from V2)
13719:   */
13720:   
13721:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
13722:   TvarsDind=ivector(1,NCOVMAX); /*  */
13723:   TnsdVar=ivector(1,NCOVMAX); /*  */
13724:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
13725:   TvarsD=ivector(1,NCOVMAX); /*  */
13726:   TvarsQind=ivector(1,NCOVMAX); /*  */
13727:   TvarsQ=ivector(1,NCOVMAX); /*  */
13728:   TvarF=ivector(1,NCOVMAX); /*  */
13729:   TvarFind=ivector(1,NCOVMAX); /*  */
13730:   TvarV=ivector(1,NCOVMAX); /*  */
13731:   TvarVind=ivector(1,NCOVMAX); /*  */
13732:   TvarA=ivector(1,NCOVMAX); /*  */
13733:   TvarAind=ivector(1,NCOVMAX); /*  */
13734:   TvarFD=ivector(1,NCOVMAX); /*  */
13735:   TvarFDind=ivector(1,NCOVMAX); /*  */
13736:   TvarFQ=ivector(1,NCOVMAX); /*  */
13737:   TvarFQind=ivector(1,NCOVMAX); /*  */
13738:   TvarVD=ivector(1,NCOVMAX); /*  */
13739:   TvarVDind=ivector(1,NCOVMAX); /*  */
13740:   TvarVQ=ivector(1,NCOVMAX); /*  */
13741:   TvarVQind=ivector(1,NCOVMAX); /*  */
13742:   TvarVV=ivector(1,NCOVMAX); /*  */
13743:   TvarVVind=ivector(1,NCOVMAX); /*  */
13744:   TvarVVA=ivector(1,NCOVMAX); /*  */
13745:   TvarVVAind=ivector(1,NCOVMAX); /*  */
13746:   TvarAVVA=ivector(1,NCOVMAX); /*  */
13747:   TvarAVVAind=ivector(1,NCOVMAX); /*  */
13748: 
13749:   Tvalsel=vector(1,NCOVMAX); /*  */
13750:   Tvarsel=ivector(1,NCOVMAX); /*  */
13751:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
13752:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
13753:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
13754:   DummyV=ivector(-1,NCOVMAX); /* 1 to 3 */
13755:   FixedV=ivector(-1,NCOVMAX); /* 1 to 3 */
13756: 
13757:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
13758:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
13759:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
13760:   */
13761:   /* For model-covariate k tells which data-covariate to use but
13762:     because this model-covariate is a construction we invent a new column
13763:     ncovcol + k1
13764:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
13765:     Tvar[3=V1*V4]=4+1 etc */
13766:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
13767:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
13768:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
13769:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
13770:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
13771:   */
13772:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
13773:   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
13774: 			    * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
13775: 			    * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
13776:   Tvardk=imatrix(0,NCOVMAX,1,2);
13777:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
13778: 			 4 covariates (3 plus signs)
13779: 			 Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
13780: 			   */  
13781:   for(i=1;i<NCOVMAX;i++)
13782:     Tage[i]=0;
13783:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
13784: 				* individual dummy, fixed or varying:
13785: 				* Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
13786: 				* 3, 1, 0, 0, 0, 0, 0, 0},
13787: 				* model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
13788: 				* V1 df, V2 qf, V3 & V4 dv, V5 qv
13789: 				* Tmodelind[1]@9={9,0,3,2,}*/
13790:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
13791:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
13792: 				* individual quantitative, fixed or varying:
13793: 				* Tmodelqind[1]=1,Tvaraff[1]@9={4,
13794: 				* 3, 1, 0, 0, 0, 0, 0, 0},
13795: 				* model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
13796: 
13797: /* Probably useless zeroes */
13798:   for(i=1;i<NCOVMAX;i++){
13799:     DummyV[i]=0;
13800:     FixedV[i]=0;
13801:   }
13802: 
13803:   for(i=1; i <=ncovcol;i++){
13804:     DummyV[i]=0;
13805:     FixedV[i]=0;
13806:   }
13807:   for(i=ncovcol+1; i <=ncovcol+nqv;i++){
13808:     DummyV[i]=1;
13809:     FixedV[i]=0;
13810:   }
13811:   for(i=ncovcol+nqv+1; i <=ncovcol+nqv+ntv;i++){
13812:     DummyV[i]=0;
13813:     FixedV[i]=1;
13814:   }
13815:   for(i=ncovcol+nqv+ntv+1; i <=ncovcol+nqv+ntv+nqtv;i++){
13816:     DummyV[i]=1;
13817:     FixedV[i]=1;
13818:   }
13819:   for(i=1; i <=ncovcol+nqv+ntv+nqtv;i++){
13820:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",i,i,DummyV[i],i,FixedV[i]);
13821:     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]);
13822:   }
13823: 
13824: 
13825: 
13826: /* Main decodemodel */
13827: 
13828: 
13829:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
13830:     goto end;
13831: 
13832:   if((double)(lastobs-imx)/(double)imx > 1.10){
13833:     nbwarn++;
13834:     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); 
13835:     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); 
13836:   }
13837:     /*  if(mle==1){*/
13838:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
13839:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
13840:   }
13841: 
13842:     /*-calculation of age at interview from date of interview and age at death -*/
13843:   agev=matrix(1,maxwav,1,imx);
13844: 
13845:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
13846:     goto end;
13847: 
13848: 
13849:   agegomp=(int)agemin;
13850:   free_vector(moisnais,firstobs,lastobs);
13851:   free_vector(annais,firstobs,lastobs);
13852:   /* free_matrix(mint,1,maxwav,1,n);
13853:      free_matrix(anint,1,maxwav,1,n);*/
13854:   /* free_vector(moisdc,1,n); */
13855:   /* free_vector(andc,1,n); */
13856:   /* */
13857:   
13858:   wav=ivector(1,imx);
13859:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
13860:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
13861:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
13862:   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.*/
13863:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
13864:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
13865:    
13866:   /* Concatenates waves */
13867:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
13868:      Death is a valid wave (if date is known).
13869:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
13870:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
13871:      and mw[mi+1][i]. dh depends on stepm.
13872:   */
13873: 
13874:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
13875:   /* Concatenates waves */
13876:  
13877:   free_vector(moisdc,firstobs,lastobs);
13878:   free_vector(andc,firstobs,lastobs);
13879: 
13880:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
13881:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
13882:   ncodemax[1]=1;
13883:   Ndum =ivector(-1,NCOVMAX);  
13884:   cptcoveff=0;
13885:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
13886:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; as well as calculate cptcoveff or number of total effective dummy covariates*/
13887:   }
13888:   
13889:   ncovcombmax=pow(2,cptcoveff);
13890:   invalidvarcomb=ivector(0, ncovcombmax); 
13891:   for(i=0;i<ncovcombmax;i++)
13892:     invalidvarcomb[i]=0;
13893:   
13894:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
13895:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
13896:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
13897:   
13898:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
13899:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
13900:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
13901:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
13902:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
13903:    * (currently 0 or 1) in the data.
13904:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
13905:    * corresponding modality (h,j).
13906:    */
13907: 
13908:   h=0;
13909:   /*if (cptcovn > 0) */
13910:   m=pow(2,cptcoveff);
13911:  
13912: 	  /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
13913: 	   * For k=4 covariates, h goes from 1 to m=2**k
13914: 	   * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
13915:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
13916: 	   *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
13917: 	   *______________________________   *______________________
13918: 	   *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
13919: 	   *     2     2     1     1     1   *     1     0  0  0  1 
13920: 	   *     3 i=2 1     2     1     1   *     2     0  0  1  0 
13921: 	   *     4     2     2     1     1   *     3     0  0  1  1 
13922: 	   *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
13923: 	   *     6     2     1     2     1   *     5     0  1  0  1 
13924: 	   *     7 i=4 1     2     2     1   *     6     0  1  1  0 
13925: 	   *     8     2     2     2     1   *     7     0  1  1  1 
13926: 	   *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
13927: 	   *    10     2     1     1     2   *     9     1  0  0  1 
13928: 	   *    11 i=6 1     2     1     2   *    10     1  0  1  0 
13929: 	   *    12     2     2     1     2   *    11     1  0  1  1 
13930: 	   *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
13931: 	   *    14     2     1     2     2   *    13     1  1  0  1 
13932: 	   *    15 i=8 1     2     2     2   *    14     1  1  1  0 
13933: 	   *    16     2     2     2     2   *    15     1  1  1  1          
13934: 	   */					  
13935:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
13936:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
13937:      * and the value of each covariate?
13938:      * V1=1, V2=1, V3=2, V4=1 ?
13939:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
13940:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
13941:      * In order to get the real value in the data, we use nbcode
13942:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
13943:      * We are keeping this crazy system in order to be able (in the future?) 
13944:      * to have more than 2 values (0 or 1) for a covariate.
13945:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
13946:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
13947:      *              bbbbbbbb
13948:      *              76543210     
13949:      *   h-1        00000101 (6-1=5)
13950:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
13951:      *           &
13952:      *     1        00000001 (1)
13953:      *              00000000        = 1 & ((h-1) >> (k-1))
13954:      *          +1= 00000001 =1 
13955:      *
13956:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
13957:      *          h'      1101 =2^3+2^2+0x2^1+2^0
13958:      *    >>k'            11
13959:      *          &   00000001
13960:      *            = 00000001
13961:      *      +1    = 00000010=2    =  codtabm(14,3)   
13962:      * Reverse h=6 and m=16?
13963:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
13964:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
13965:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
13966:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
13967:      * V3=decodtabm(14,3,2**4)=2
13968:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
13969:      *(h-1) >> (j-1)    0011 =13 >> 2
13970:      *          &1 000000001
13971:      *           = 000000001
13972:      *         +1= 000000010 =2
13973:      *                  2211
13974:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
13975:      *                  V3=2
13976: 		 * codtabm and decodtabm are identical
13977:      */
13978: 
13979: 
13980:  free_ivector(Ndum,-1,NCOVMAX);
13981: 
13982: 
13983:     
13984:   /* Initialisation of ----------- gnuplot -------------*/
13985:   strcpy(optionfilegnuplot,optionfilefiname);
13986:   if(mle==-3)
13987:     strcat(optionfilegnuplot,"-MORT_");
13988:   strcat(optionfilegnuplot,".gp");
13989: 
13990:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
13991:     printf("Problem with file %s",optionfilegnuplot);
13992:   }
13993:   else{
13994:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
13995:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
13996:     //fprintf(ficgp,"set missing 'NaNq'\n");
13997:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
13998:   }
13999:   /*  fclose(ficgp);*/
14000: 
14001: 
14002:   /* Initialisation of --------- index.htm --------*/
14003: 
14004:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
14005:   if(mle==-3)
14006:     strcat(optionfilehtm,"-MORT_");
14007:   strcat(optionfilehtm,".htm");
14008:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
14009:     printf("Problem with %s \n",optionfilehtm);
14010:     exit(0);
14011:   }
14012: 
14013:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
14014:   strcat(optionfilehtmcov,"-cov.htm");
14015:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
14016:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
14017:   }
14018:   else{
14019:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
14020: <hr size=\"2\" color=\"#EC5E5E\"> \n\
14021: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
14022: 	  optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
14023:   }
14024: 
14025:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
14026: <title>IMaCh %s</title></head>\n\
14027:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
14028: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
14029: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
14030: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
14031: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
14032:   
14033:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
14034: <font size=\"2\">IMaCh-%s <br> %s</font> \
14035: <hr size=\"2\" color=\"#EC5E5E\"> \n\
14036: 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\
14037: \n\
14038: <hr  size=\"2\" color=\"#EC5E5E\">\
14039:  <ul><li><h4>Parameter files</h4>\n\
14040:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
14041:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
14042:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
14043:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
14044:  - Date and time at start: %s</ul>\n",\
14045: 	  version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
14046: 	  optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
14047: 	  fileres,fileres,\
14048: 	  filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
14049:   fflush(fichtm);
14050: 
14051:   strcpy(pathr,path);
14052:   strcat(pathr,optionfilefiname);
14053: #ifdef WIN32
14054:   _chdir(optionfilefiname); /* Move to directory named optionfile */
14055: #else
14056:   chdir(optionfilefiname); /* Move to directory named optionfile */
14057: #endif
14058: 	  
14059:   
14060:   /* Calculates basic frequencies. Computes observed prevalence at single age 
14061: 		 and for any valid combination of covariates
14062:      and prints on file fileres'p'. */
14063:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
14064: 	      firstpass, lastpass,  stepm,  weightopt, model);
14065: 
14066:   fprintf(fichtm,"\n");
14067:   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",\
14068: 	  ftol, stepm);
14069:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
14070:   ncurrv=1;
14071:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
14072:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
14073:   ncurrv=i;
14074:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
14075:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
14076:   ncurrv=i;
14077:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
14078:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
14079:   ncurrv=i;
14080:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
14081:   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", \
14082: 	   nlstate, ndeath, maxwav, mle, weightopt);
14083: 
14084:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
14085: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
14086: 
14087:   
14088:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
14089: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
14090: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
14091:   imx,agemin,agemax,jmin,jmax,jmean);
14092:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
14093:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
14094:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
14095:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
14096:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
14097: 
14098:   /* For Powell, parameters are in a vector p[] starting at p[1]
14099:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
14100:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
14101: 
14102:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
14103:   /* For mortality only */
14104:   if (mle==-3){
14105:     ximort=matrix(1,NDIM,1,NDIM); 
14106:     for(i=1;i<=NDIM;i++)
14107:       for(j=1;j<=NDIM;j++)
14108: 	ximort[i][j]=0.;
14109:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
14110:     cens=ivector(firstobs,lastobs);
14111:     ageexmed=vector(firstobs,lastobs);
14112:     agecens=vector(firstobs,lastobs);
14113:     dcwave=ivector(firstobs,lastobs);
14114: 		
14115:     for (i=1; i<=imx; i++){
14116:       dcwave[i]=-1;
14117:       for (m=firstpass; m<=lastpass; m++)
14118: 	if (s[m][i]>nlstate) {
14119: 	  dcwave[i]=m;
14120: 	  /*	printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
14121: 	  break;
14122: 	}
14123:     }
14124:     
14125:     for (i=1; i<=imx; i++) {
14126:       if (wav[i]>0){
14127: 	ageexmed[i]=agev[mw[1][i]][i];
14128: 	j=wav[i];
14129: 	agecens[i]=1.; 
14130: 	
14131: 	if (ageexmed[i]> 1 && wav[i] > 0){
14132: 	  agecens[i]=agev[mw[j][i]][i];
14133: 	  cens[i]= 1;
14134: 	}else if (ageexmed[i]< 1) 
14135: 	  cens[i]= -1;
14136: 	if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
14137: 	  cens[i]=0 ;
14138:       }
14139:       else cens[i]=-1;
14140:     }
14141:     
14142:     for (i=1;i<=NDIM;i++) {
14143:       for (j=1;j<=NDIM;j++)
14144: 	ximort[i][j]=(i == j ? 1.0 : 0.0);
14145:     }
14146:     
14147:     p[1]=0.0268; p[NDIM]=0.083;
14148:     /* printf("%lf %lf", p[1], p[2]); */
14149:     
14150:     
14151: #ifdef GSL
14152:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
14153: #else
14154:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
14155: #endif
14156:     strcpy(filerespow,"POW-MORT_"); 
14157:     strcat(filerespow,fileresu);
14158:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
14159:       printf("Problem with resultfile: %s\n", filerespow);
14160:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
14161:     }
14162: #ifdef GSL
14163:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
14164: #else
14165:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
14166: #endif
14167:     /*  for (i=1;i<=nlstate;i++)
14168: 	for(j=1;j<=nlstate+ndeath;j++)
14169: 	if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
14170:     */
14171:     fprintf(ficrespow,"\n");
14172: #ifdef GSL
14173:     /* gsl starts here */ 
14174:     T = gsl_multimin_fminimizer_nmsimplex;
14175:     gsl_multimin_fminimizer *sfm = NULL;
14176:     gsl_vector *ss, *x;
14177:     gsl_multimin_function minex_func;
14178: 
14179:     /* Initial vertex size vector */
14180:     ss = gsl_vector_alloc (NDIM);
14181:     
14182:     if (ss == NULL){
14183:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
14184:     }
14185:     /* Set all step sizes to 1 */
14186:     gsl_vector_set_all (ss, 0.001);
14187: 
14188:     /* Starting point */
14189:     
14190:     x = gsl_vector_alloc (NDIM);
14191:     
14192:     if (x == NULL){
14193:       gsl_vector_free(ss);
14194:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
14195:     }
14196:   
14197:     /* Initialize method and iterate */
14198:     /*     p[1]=0.0268; p[NDIM]=0.083; */
14199:     /*     gsl_vector_set(x, 0, 0.0268); */
14200:     /*     gsl_vector_set(x, 1, 0.083); */
14201:     gsl_vector_set(x, 0, p[1]);
14202:     gsl_vector_set(x, 1, p[2]);
14203: 
14204:     minex_func.f = &gompertz_f;
14205:     minex_func.n = NDIM;
14206:     minex_func.params = (void *)&p; /* ??? */
14207:     
14208:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
14209:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
14210:     
14211:     printf("Iterations beginning .....\n\n");
14212:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
14213: 
14214:     iteri=0;
14215:     while (rval == GSL_CONTINUE){
14216:       iteri++;
14217:       status = gsl_multimin_fminimizer_iterate(sfm);
14218:       
14219:       if (status) printf("error: %s\n", gsl_strerror (status));
14220:       fflush(0);
14221:       
14222:       if (status) 
14223:         break;
14224:       
14225:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
14226:       ssval = gsl_multimin_fminimizer_size (sfm);
14227:       
14228:       if (rval == GSL_SUCCESS)
14229:         printf ("converged to a local maximum at\n");
14230:       
14231:       printf("%5d ", iteri);
14232:       for (it = 0; it < NDIM; it++){
14233: 	printf ("%10.5f ", gsl_vector_get (sfm->x, it));
14234:       }
14235:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
14236:     }
14237:     
14238:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
14239:     
14240:     gsl_vector_free(x); /* initial values */
14241:     gsl_vector_free(ss); /* inital step size */
14242:     for (it=0; it<NDIM; it++){
14243:       p[it+1]=gsl_vector_get(sfm->x,it);
14244:       fprintf(ficrespow," %.12lf", p[it]);
14245:     }
14246:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
14247: #endif
14248: #ifdef POWELL
14249:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
14250: #endif  
14251:     fclose(ficrespow);
14252:     
14253:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
14254: 
14255:     for(i=1; i <=NDIM; i++)
14256:       for(j=i+1;j<=NDIM;j++)
14257: 				matcov[i][j]=matcov[j][i];
14258:     
14259:     printf("\nCovariance matrix\n ");
14260:     fprintf(ficlog,"\nCovariance matrix\n ");
14261:     for(i=1; i <=NDIM; i++) {
14262:       for(j=1;j<=NDIM;j++){ 
14263: 				printf("%f ",matcov[i][j]);
14264: 				fprintf(ficlog,"%f ",matcov[i][j]);
14265:       }
14266:       printf("\n ");  fprintf(ficlog,"\n ");
14267:     }
14268:     
14269:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
14270:     for (i=1;i<=NDIM;i++) {
14271:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
14272:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
14273:     }
14274:     lsurv=vector(agegomp,AGESUP);
14275:     lpop=vector(agegomp,AGESUP);
14276:     tpop=vector(agegomp,AGESUP);
14277:     lsurv[agegomp]=100000;
14278:     
14279:     for (k=agegomp;k<=AGESUP;k++) {
14280:       agemortsup=k;
14281:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
14282:     }
14283:     
14284:     for (k=agegomp;k<agemortsup;k++)
14285:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
14286:     
14287:     for (k=agegomp;k<agemortsup;k++){
14288:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
14289:       sumlpop=sumlpop+lpop[k];
14290:     }
14291:     
14292:     tpop[agegomp]=sumlpop;
14293:     for (k=agegomp;k<(agemortsup-3);k++){
14294:       /*  tpop[k+1]=2;*/
14295:       tpop[k+1]=tpop[k]-lpop[k];
14296:     }
14297:     
14298:     
14299:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
14300:     for (k=agegomp;k<(agemortsup-2);k++) 
14301:       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]);
14302:     
14303:     
14304:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
14305: 		ageminpar=50;
14306: 		agemaxpar=100;
14307:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
14308:       	printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
14309: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
14310: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
14311:       	fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
14312: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
14313: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
14314:     }else{
14315: 			printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
14316: 			fprintf(ficlog,"Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
14317:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
14318: 		}
14319:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
14320: 		     stepm, weightopt,\
14321: 		     model,imx,p,matcov,agemortsup);
14322:     
14323:     free_vector(lsurv,agegomp,AGESUP);
14324:     free_vector(lpop,agegomp,AGESUP);
14325:     free_vector(tpop,agegomp,AGESUP);
14326:     free_matrix(ximort,1,NDIM,1,NDIM);
14327:     free_ivector(dcwave,firstobs,lastobs);
14328:     free_vector(agecens,firstobs,lastobs);
14329:     free_vector(ageexmed,firstobs,lastobs);
14330:     free_ivector(cens,firstobs,lastobs);
14331: #ifdef GSL
14332: #endif
14333:   } /* Endof if mle==-3 mortality only */
14334:   /* Standard  */
14335:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
14336:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
14337:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
14338:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
14339:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
14340:     for (k=1; k<=npar;k++)
14341:       printf(" %d %8.5f",k,p[k]);
14342:     printf("\n");
14343:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
14344:       /* mlikeli uses func not funcone */
14345:       /* for(i=1;i<nlstate;i++){ */
14346:       /* 	/\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
14347:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
14348:       /* } */
14349:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
14350:     }
14351:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
14352:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
14353:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
14354:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
14355:     }
14356:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
14357:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
14358:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
14359:           /* exit(0); */
14360:     for (k=1; k<=npar;k++)
14361:       printf(" %d %8.5f",k,p[k]);
14362:     printf("\n");
14363:     
14364:     /*--------- results files --------------*/
14365:     /* 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); */
14366:     
14367:     
14368:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
14369:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
14370:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
14371: 
14372:     printf("#model=  1      +     age ");
14373:     fprintf(ficres,"#model=  1      +     age ");
14374:     fprintf(ficlog,"#model=  1      +     age ");
14375:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
14376: </ul>", model);
14377: 
14378:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
14379:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
14380:     if(nagesqr==1){
14381:       printf("  + age*age  ");
14382:       fprintf(ficres,"  + age*age  ");
14383:       fprintf(ficlog,"  + age*age  ");
14384:       fprintf(fichtm, "<th>+ age*age</th>");
14385:     }
14386:     for(j=1;j <=ncovmodel-2;j++){
14387:       if(Typevar[j]==0) {
14388: 	printf("  +      V%d  ",Tvar[j]);
14389: 	fprintf(ficres,"  +      V%d  ",Tvar[j]);
14390: 	fprintf(ficlog,"  +      V%d  ",Tvar[j]);
14391: 	fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
14392:       }else if(Typevar[j]==1) {
14393: 	printf("  +    V%d*age ",Tvar[j]);
14394: 	fprintf(ficres,"  +    V%d*age ",Tvar[j]);
14395: 	fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
14396: 	fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
14397:       }else if(Typevar[j]==2) {
14398: 	printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
14399: 	fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
14400: 	fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
14401: 	fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
14402:       }else if(Typevar[j]==3) { /* TO VERIFY */
14403: 	printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
14404: 	fprintf(ficres,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
14405: 	fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
14406: 	fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
14407:       }
14408:     }
14409:     printf("\n");
14410:     fprintf(ficres,"\n");
14411:     fprintf(ficlog,"\n");
14412:     fprintf(fichtm, "</tr>");
14413:     fprintf(fichtm, "\n");
14414:     
14415:     
14416:     for(i=1,jk=1; i <=nlstate; i++){
14417:       for(k=1; k <=(nlstate+ndeath); k++){
14418: 	if (k != i) {
14419: 	  fprintf(fichtm, "<tr>");
14420: 	  printf("%d%d ",i,k);
14421: 	  fprintf(ficlog,"%d%d ",i,k);
14422: 	  fprintf(ficres,"%1d%1d ",i,k);
14423: 	  fprintf(fichtm, "<td>%1d%1d</td>",i,k);
14424: 	  for(j=1; j <=ncovmodel; j++){
14425: 	    printf("%12.7f ",p[jk]);
14426: 	    fprintf(ficlog,"%12.7f ",p[jk]);
14427: 	    fprintf(ficres,"%12.7f ",p[jk]);
14428: 	    fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
14429: 	    jk++; 
14430: 	  }
14431: 	  printf("\n");
14432: 	  fprintf(ficlog,"\n");
14433: 	  fprintf(ficres,"\n");
14434: 	  fprintf(fichtm, "</tr>\n");
14435: 	}
14436:       }
14437:     }
14438:     /* fprintf(fichtm,"</tr>\n"); */
14439:     fprintf(fichtm,"</table>\n");
14440:     fprintf(fichtm, "\n");
14441: 
14442:     if(mle != 0){
14443:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
14444:       ftolhess=ftol; /* Usually correct */
14445:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
14446:       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");
14447:       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");
14448:       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);
14449:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
14450:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
14451:       if(nagesqr==1){
14452: 	printf("  + age*age  ");
14453: 	fprintf(ficres,"  + age*age  ");
14454: 	fprintf(ficlog,"  + age*age  ");
14455: 	fprintf(fichtm, "<th>+ age*age</th>");
14456:       }
14457:       for(j=1;j <=ncovmodel-2;j++){
14458: 	if(Typevar[j]==0) {
14459: 	  printf("  +      V%d  ",Tvar[j]);
14460: 	  fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
14461: 	}else if(Typevar[j]==1) {
14462: 	  printf("  +    V%d*age ",Tvar[j]);
14463: 	  fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
14464: 	}else if(Typevar[j]==2) {
14465: 	  fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
14466: 	}else if(Typevar[j]==3) { /* TO VERIFY */
14467: 	  fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
14468: 	}
14469:       }
14470:       fprintf(fichtm, "</tr>\n");
14471:  
14472:       for(i=1,jk=1; i <=nlstate; i++){
14473: 	for(k=1; k <=(nlstate+ndeath); k++){
14474: 	  if (k != i) {
14475: 	    fprintf(fichtm, "<tr valign=top>");
14476: 	    printf("%d%d ",i,k);
14477: 	    fprintf(ficlog,"%d%d ",i,k);
14478: 	    fprintf(fichtm, "<td>%1d%1d</td>",i,k);
14479: 	    for(j=1; j <=ncovmodel; j++){
14480: 	      wald=p[jk]/sqrt(matcov[jk][jk]);
14481: 	      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]));
14482: 	      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]));
14483: 	      if(fabs(wald) > 1.96){
14484: 		fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
14485: 	      }else{
14486: 		fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
14487: 	      }
14488: 	      fprintf(fichtm,"W=%8.3f</br>",wald);
14489: 	      fprintf(fichtm,"[%12.7f;%12.7f]</br></td>", p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
14490: 	      jk++; 
14491: 	    }
14492: 	    printf("\n");
14493: 	    fprintf(ficlog,"\n");
14494: 	    fprintf(fichtm, "</tr>\n");
14495: 	  }
14496: 	}
14497:       }
14498:     } /* end of hesscov and Wald tests */
14499:     fprintf(fichtm,"</table>\n");
14500:     
14501:     /*  */
14502:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
14503:     printf("# Scales (for hessian or gradient estimation)\n");
14504:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
14505:     for(i=1,jk=1; i <=nlstate; i++){
14506:       for(j=1; j <=nlstate+ndeath; j++){
14507: 	if (j!=i) {
14508: 	  fprintf(ficres,"%1d%1d",i,j);
14509: 	  printf("%1d%1d",i,j);
14510: 	  fprintf(ficlog,"%1d%1d",i,j);
14511: 	  for(k=1; k<=ncovmodel;k++){
14512: 	    printf(" %.5e",delti[jk]);
14513: 	    fprintf(ficlog," %.5e",delti[jk]);
14514: 	    fprintf(ficres," %.5e",delti[jk]);
14515: 	    jk++;
14516: 	  }
14517: 	  printf("\n");
14518: 	  fprintf(ficlog,"\n");
14519: 	  fprintf(ficres,"\n");
14520: 	}
14521:       }
14522:     }
14523:     
14524:     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");
14525:     if(mle >= 1) /* Too big for the screen */
14526:       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");
14527:     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");
14528:     /* # 121 Var(a12)\n\ */
14529:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
14530:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
14531:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
14532:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
14533:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
14534:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
14535:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
14536:     
14537:     
14538:     /* Just to have a covariance matrix which will be more understandable
14539:        even is we still don't want to manage dictionary of variables
14540:     */
14541:     for(itimes=1;itimes<=2;itimes++){
14542:       jj=0;
14543:       for(i=1; i <=nlstate; i++){
14544: 	for(j=1; j <=nlstate+ndeath; j++){
14545: 	  if(j==i) continue;
14546: 	  for(k=1; k<=ncovmodel;k++){
14547: 	    jj++;
14548: 	    ca[0]= k+'a'-1;ca[1]='\0';
14549: 	    if(itimes==1){
14550: 	      if(mle>=1)
14551: 		printf("#%1d%1d%d",i,j,k);
14552: 	      fprintf(ficlog,"#%1d%1d%d",i,j,k);
14553: 	      fprintf(ficres,"#%1d%1d%d",i,j,k);
14554: 	    }else{
14555: 	      if(mle>=1)
14556: 		printf("%1d%1d%d",i,j,k);
14557: 	      fprintf(ficlog,"%1d%1d%d",i,j,k);
14558: 	      fprintf(ficres,"%1d%1d%d",i,j,k);
14559: 	    }
14560: 	    ll=0;
14561: 	    for(li=1;li <=nlstate; li++){
14562: 	      for(lj=1;lj <=nlstate+ndeath; lj++){
14563: 		if(lj==li) continue;
14564: 		for(lk=1;lk<=ncovmodel;lk++){
14565: 		  ll++;
14566: 		  if(ll<=jj){
14567: 		    cb[0]= lk +'a'-1;cb[1]='\0';
14568: 		    if(ll<jj){
14569: 		      if(itimes==1){
14570: 			if(mle>=1)
14571: 			  printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
14572: 			fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
14573: 			fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
14574: 		      }else{
14575: 			if(mle>=1)
14576: 			  printf(" %.5e",matcov[jj][ll]); 
14577: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
14578: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
14579: 		      }
14580: 		    }else{
14581: 		      if(itimes==1){
14582: 			if(mle>=1)
14583: 			  printf(" Var(%s%1d%1d)",ca,i,j);
14584: 			fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
14585: 			fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
14586: 		      }else{
14587: 			if(mle>=1)
14588: 			  printf(" %.7e",matcov[jj][ll]); 
14589: 			fprintf(ficlog," %.7e",matcov[jj][ll]); 
14590: 			fprintf(ficres," %.7e",matcov[jj][ll]); 
14591: 		      }
14592: 		    }
14593: 		  }
14594: 		} /* end lk */
14595: 	      } /* end lj */
14596: 	    } /* end li */
14597: 	    if(mle>=1)
14598: 	      printf("\n");
14599: 	    fprintf(ficlog,"\n");
14600: 	    fprintf(ficres,"\n");
14601: 	    numlinepar++;
14602: 	  } /* end k*/
14603: 	} /*end j */
14604:       } /* end i */
14605:     } /* end itimes */
14606:     
14607:     fflush(ficlog);
14608:     fflush(ficres);
14609:     while(fgets(line, MAXLINE, ficpar)) {
14610:       /* If line starts with a # it is a comment */
14611:       if (line[0] == '#') {
14612: 	numlinepar++;
14613: 	fputs(line,stdout);
14614: 	fputs(line,ficparo);
14615: 	fputs(line,ficlog);
14616: 	fputs(line,ficres);
14617: 	continue;
14618:       }else
14619: 	break;
14620:     }
14621:     
14622:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
14623:     /*   ungetc(c,ficpar); */
14624:     /*   fgets(line, MAXLINE, ficpar); */
14625:     /*   fputs(line,stdout); */
14626:     /*   fputs(line,ficparo); */
14627:     /* } */
14628:     /* ungetc(c,ficpar); */
14629:     
14630:     estepm=0;
14631:     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){
14632:       
14633:       if (num_filled != 6) {
14634: 	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);
14635: 	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);
14636: 	goto end;
14637:       }
14638:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
14639:     }
14640:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
14641:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
14642:     
14643:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
14644:     if (estepm==0 || estepm < stepm) estepm=stepm;
14645:     if (fage <= 2) {
14646:       bage = ageminpar;
14647:       fage = agemaxpar;
14648:     }
14649:     
14650:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
14651:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
14652:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
14653: 		
14654:     /* Other stuffs, more or less useful */    
14655:     while(fgets(line, MAXLINE, ficpar)) {
14656:       /* If line starts with a # it is a comment */
14657:       if (line[0] == '#') {
14658: 	numlinepar++;
14659: 	fputs(line,stdout);
14660: 	fputs(line,ficparo);
14661: 	fputs(line,ficlog);
14662: 	fputs(line,ficres);
14663: 	continue;
14664:       }else
14665: 	break;
14666:     }
14667: 
14668:     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){
14669:       
14670:       if (num_filled != 7) {
14671: 	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);
14672: 	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);
14673: 	goto end;
14674:       }
14675:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
14676:       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);
14677:       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);
14678:       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);
14679:     }
14680: 
14681:     while(fgets(line, MAXLINE, ficpar)) {
14682:       /* If line starts with a # it is a comment */
14683:       if (line[0] == '#') {
14684: 	numlinepar++;
14685: 	fputs(line,stdout);
14686: 	fputs(line,ficparo);
14687: 	fputs(line,ficlog);
14688: 	fputs(line,ficres);
14689: 	continue;
14690:       }else
14691: 	break;
14692:     }
14693:     
14694:     
14695:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
14696:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
14697:     
14698:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
14699:       if (num_filled != 1) {
14700: 	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);
14701: 	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);
14702: 	goto end;
14703:       }
14704:       printf("pop_based=%d\n",popbased);
14705:       fprintf(ficlog,"pop_based=%d\n",popbased);
14706:       fprintf(ficparo,"pop_based=%d\n",popbased);   
14707:       fprintf(ficres,"pop_based=%d\n",popbased);   
14708:     }
14709:      
14710:     /* Results */
14711:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
14712:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
14713:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
14714:     endishere=0;
14715:     nresult=0;
14716:     parameterline=0;
14717:     do{
14718:       if(!fgets(line, MAXLINE, ficpar)){
14719: 	endishere=1;
14720: 	parameterline=15;
14721:       }else if (line[0] == '#') {
14722: 	/* If line starts with a # it is a comment */
14723: 	numlinepar++;
14724: 	fputs(line,stdout);
14725: 	fputs(line,ficparo);
14726: 	fputs(line,ficlog);
14727: 	fputs(line,ficres);
14728: 	continue;
14729:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
14730: 	parameterline=11;
14731:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
14732: 	parameterline=12;
14733:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
14734: 	parameterline=13;
14735:       }
14736:       else{
14737: 	parameterline=14;
14738:       }
14739:       switch (parameterline){ /* =0 only if only comments */
14740:       case 11:
14741: 	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)){
14742: 	  	  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);
14743: 	  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);
14744: 	  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);
14745: 	  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);
14746: 	  /* day and month of proj2 are not used but only year anproj2.*/
14747: 	  dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
14748: 	  dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
14749:           prvforecast = 1;
14750: 	} 
14751: 	else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
14752: 	  printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
14753: 	  fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
14754: 	  fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
14755:           prvforecast = 2;
14756: 	}
14757: 	else {
14758: 	  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);
14759: 	  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);
14760: 	  goto end;
14761: 	}
14762: 	break;
14763:       case 12:
14764: 	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)){
14765:           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);
14766: 	  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);
14767: 	  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);
14768: 	  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);
14769: 	  /* day and month of back2 are not used but only year anback2.*/
14770: 	  dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
14771: 	  dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
14772:           prvbackcast = 1;
14773: 	} 
14774: 	else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
14775: 	  printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
14776: 	  fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
14777: 	  fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
14778:           prvbackcast = 2;
14779: 	}
14780: 	else {
14781: 	  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);
14782: 	  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);
14783: 	  goto end;
14784: 	}
14785: 	break;
14786:       case 13:
14787: 	num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
14788: 	nresult++; /* Sum of resultlines */
14789: 	/* printf("Result %d: result:%s\n",nresult, resultlineori); */
14790: 	/* removefirstspace(&resultlineori); */
14791: 	
14792: 	if(strstr(resultlineori,"v") !=0){
14793: 	  printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
14794: 	  fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
14795: 	  return 1;
14796: 	}
14797: 	trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
14798: 	/* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
14799: 	if(nresult > MAXRESULTLINESPONE-1){
14800: 	  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);
14801: 	  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);
14802: 	  goto end;
14803: 	}
14804: 	
14805: 	if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
14806: 	  fprintf(ficparo,"result: %s\n",resultline);
14807: 	  fprintf(ficres,"result: %s\n",resultline);
14808: 	  fprintf(ficlog,"result: %s\n",resultline);
14809: 	} else
14810: 	  goto end;
14811: 	break;
14812:       case 14:
14813: 	printf("Error: Unknown command '%s'\n",line);
14814: 	fprintf(ficlog,"Error: Unknown command '%s'\n",line);
14815: 	if(line[0] == ' ' || line[0] == '\n'){
14816: 	  printf("It should not be an empty line '%s'\n",line);
14817: 	  fprintf(ficlog,"It should not be an empty line '%s'\n",line);
14818: 	}	  
14819: 	if(ncovmodel >=2 && nresult==0 ){
14820: 	  printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
14821: 	  fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
14822: 	}
14823: 	/* goto end; */
14824: 	break;
14825:       case 15:
14826: 	printf("End of resultlines.\n");
14827: 	fprintf(ficlog,"End of resultlines.\n");
14828: 	break;
14829:       default: /* parameterline =0 */
14830: 	nresult=1;
14831: 	decoderesult(".",nresult ); /* No covariate */
14832:       } /* End switch parameterline */
14833:     }while(endishere==0); /* End do */
14834:     
14835:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
14836:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
14837:     
14838:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
14839:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
14840:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
14841: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
14842: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
14843:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
14844: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
14845: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
14846:     }else{
14847:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
14848:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
14849:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
14850:       if(prvforecast==1){
14851:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
14852:         jprojd=jproj1;
14853:         mprojd=mproj1;
14854:         anprojd=anproj1;
14855:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
14856:         jprojf=jproj2;
14857:         mprojf=mproj2;
14858:         anprojf=anproj2;
14859:       } else if(prvforecast == 2){
14860:         dateprojd=dateintmean;
14861:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
14862:         dateprojf=dateintmean+yrfproj;
14863:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
14864:       }
14865:       if(prvbackcast==1){
14866:         datebackd=(jback1+12*mback1+365*anback1)/365;
14867:         jbackd=jback1;
14868:         mbackd=mback1;
14869:         anbackd=anback1;
14870:         datebackf=(jback2+12*mback2+365*anback2)/365;
14871:         jbackf=jback2;
14872:         mbackf=mback2;
14873:         anbackf=anback2;
14874:       } else if(prvbackcast == 2){
14875:         datebackd=dateintmean;
14876:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
14877:         datebackf=dateintmean-yrbproj;
14878:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
14879:       }
14880:       
14881:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);/* HERE valgrind Tvard*/
14882:     }
14883:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
14884: 		 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
14885: 		 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
14886: 		
14887:     /*------------ free_vector  -------------*/
14888:     /*  chdir(path); */
14889: 		
14890:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
14891:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
14892:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
14893:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
14894:     free_lvector(num,firstobs,lastobs);
14895:     free_vector(agedc,firstobs,lastobs);
14896:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
14897:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
14898:     fclose(ficparo);
14899:     fclose(ficres);
14900: 		
14901: 		
14902:     /* Other results (useful)*/
14903: 		
14904: 		
14905:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
14906:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
14907:     prlim=matrix(1,nlstate,1,nlstate);
14908:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
14909:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
14910:     fclose(ficrespl);
14911: 
14912:     /*------------- h Pij x at various ages ------------*/
14913:     /*#include "hpijx.h"*/
14914:     /** 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?*/
14915:     /* calls hpxij with combination k */
14916:     hPijx(p, bage, fage);
14917:     fclose(ficrespij);
14918:     
14919:     /* ncovcombmax=  pow(2,cptcoveff); */
14920:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
14921:     k=1;
14922:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
14923:     
14924:     /* Prevalence for each covariate combination in probs[age][status][cov] */
14925:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
14926:     for(i=AGEINF;i<=AGESUP;i++)
14927:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
14928: 	for(k=1;k<=ncovcombmax;k++)
14929: 	  probs[i][j][k]=0.;
14930:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
14931: 	       ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
14932:     if (mobilav!=0 ||mobilavproj !=0 ) {
14933:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
14934:       for(i=AGEINF;i<=AGESUP;i++)
14935: 	for(j=1;j<=nlstate+ndeath;j++)
14936: 	  for(k=1;k<=ncovcombmax;k++)
14937: 	    mobaverages[i][j][k]=0.;
14938:       mobaverage=mobaverages;
14939:       if (mobilav!=0) {
14940: 	printf("Movingaveraging observed prevalence\n");
14941: 	fprintf(ficlog,"Movingaveraging observed prevalence\n");
14942: 	if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
14943: 	  fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
14944: 	  printf(" Error in movingaverage mobilav=%d\n",mobilav);
14945: 	}
14946:       } else if (mobilavproj !=0) {
14947: 	printf("Movingaveraging projected observed prevalence\n");
14948: 	fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
14949: 	if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
14950: 	  fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
14951: 	  printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
14952: 	}
14953:       }else{
14954: 	printf("Internal error moving average\n");
14955: 	fflush(stdout);
14956: 	exit(1);
14957:       }
14958:     }/* end if moving average */
14959:     
14960:     /*---------- Forecasting ------------------*/
14961:     if(prevfcast==1){ 
14962:       /*   /\*    if(stepm ==1){*\/ */
14963:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
14964:       /*This done previously after freqsummary.*/
14965:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
14966:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
14967:       
14968:       /* } else if (prvforecast==2){ */
14969:       /*   /\*    if(stepm ==1){*\/ */
14970:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
14971:       /* } */
14972:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
14973:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
14974:     }
14975: 
14976:     /* Prevbcasting */
14977:     if(prevbcast==1){
14978:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath); 	
14979:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath); 	
14980:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
14981: 
14982:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
14983: 
14984:       bprlim=matrix(1,nlstate,1,nlstate);
14985: 
14986:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
14987:       fclose(ficresplb);
14988: 
14989:       hBijx(p, bage, fage, mobaverage);
14990:       fclose(ficrespijb);
14991: 
14992:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
14993:       /* /\* 		       mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
14994:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
14995:       /* 		       mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
14996:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
14997:       		       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
14998: 
14999:       
15000:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
15001: 
15002:       
15003:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
15004:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
15005:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
15006:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
15007:     }    /* end  Prevbcasting */
15008:  
15009:  
15010:     /* ------ Other prevalence ratios------------ */
15011: 
15012:     free_ivector(wav,1,imx);
15013:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
15014:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
15015:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
15016: 		
15017: 		
15018:     /*---------- Health expectancies, no variances ------------*/
15019: 		
15020:     strcpy(filerese,"E_");
15021:     strcat(filerese,fileresu);
15022:     if((ficreseij=fopen(filerese,"w"))==NULL) {
15023:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
15024:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
15025:     }
15026:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
15027:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
15028: 
15029:     pstamp(ficreseij);
15030:  		
15031:     /* i1=pow(2,cptcoveff); /\* Number of combination of dummy covariates *\/ */
15032:     /* if (cptcovn < 1){i1=1;} */
15033:     
15034:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
15035:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
15036:       /* if(i1 != 1 && TKresult[nres]!= k) */
15037:       /* 	continue; */
15038:       fprintf(ficreseij,"\n#****** ");
15039:       printf("\n#****** ");
15040:       for(j=1;j<=cptcovs;j++){
15041:       /* for(j=1;j<=cptcoveff;j++) { */
15042: 	/* fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
15043: 	fprintf(ficreseij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
15044: 	printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
15045: 	/* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
15046:       }
15047:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
15048: 	printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
15049: 	fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
15050:       }
15051:       fprintf(ficreseij,"******\n");
15052:       printf("******\n");
15053:       
15054:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
15055:       oldm=oldms;savm=savms;
15056:       /* printf("HELLO Entering evsij bage=%d fage=%d k=%d estepm=%d nres=%d\n",(int) bage, (int)fage, k, estepm, nres); */
15057:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
15058:       
15059:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
15060:     }
15061:     fclose(ficreseij);
15062:     printf("done evsij\n");fflush(stdout);
15063:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
15064: 
15065: 		
15066:     /*---------- State-specific expectancies and variances ------------*/
15067:     /* Should be moved in a function */		
15068:     strcpy(filerest,"T_");
15069:     strcat(filerest,fileresu);
15070:     if((ficrest=fopen(filerest,"w"))==NULL) {
15071:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
15072:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
15073:     }
15074:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
15075:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
15076:     strcpy(fileresstde,"STDE_");
15077:     strcat(fileresstde,fileresu);
15078:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
15079:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
15080:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
15081:     }
15082:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
15083:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
15084: 
15085:     strcpy(filerescve,"CVE_");
15086:     strcat(filerescve,fileresu);
15087:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
15088:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
15089:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
15090:     }
15091:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
15092:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
15093: 
15094:     strcpy(fileresv,"V_");
15095:     strcat(fileresv,fileresu);
15096:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
15097:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
15098:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
15099:     }
15100:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
15101:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
15102: 
15103:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
15104:     if (cptcovn < 1){i1=1;}
15105:     
15106:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
15107:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
15108: 			  * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
15109: 			  * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
15110: 			  * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
15111:       /* */
15112:       if(i1 != 1 && TKresult[nres]!= k) /* TKresult[nres] is the combination of this nres resultline. All the i1 combinations are not output */
15113: 	continue;
15114:       printf("\n# model %s \n#****** Result for:", model);  /* HERE model is empty */
15115:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
15116:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
15117:       /* It might not be a good idea to mix dummies and quantitative */
15118:       /* 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 *\/ */
15119:       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 */
15120: 	/* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
15121: 	/* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
15122: 	 * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
15123: 	 * (V5 is quanti) V4 and V3 are dummies
15124: 	 * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
15125: 	 *                                                              l=1 l=2
15126: 	 *                                                           k=1  1   1   0   0
15127: 	 *                                                           k=2  2   1   1   0
15128: 	 *                                                           k=3 [1] [2]  0   1
15129: 	 *                                                           k=4  2   2   1   1
15130: 	 * If nres=1 result: V3=1 V4=0 then k=3 and outputs
15131: 	 * If nres=2 result: V4=1 V3=0 then k=2 and outputs
15132: 	 * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
15133: 	 * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
15134: 	 */
15135: 	/* Tvresult[nres][j] Name of the variable at position j in this resultline */
15136: 	/* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
15137: /* We give up with the combinations!! */
15138: 	/* if(debugILK) */
15139: 	/*   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 *\/ */
15140: 
15141: 	if(Dummy[modelresult[nres][j]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to j in resultline  */
15142: 	  /* 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] */
15143: 	  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  */
15144: 	  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  */
15145: 	  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  */
15146: 	  if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
15147: 	    printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
15148: 	  }else{
15149: 	    printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
15150: 	  }
15151: 	  /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
15152: 	  /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
15153: 	}else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
15154: 	  /* For each selected (single) quantitative value */
15155: 	  printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
15156: 	  fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
15157: 	  fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
15158: 	  if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
15159: 	    printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
15160: 	  }else{
15161: 	    printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
15162: 	  }
15163: 	}else{
15164: 	  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 */
15165: 	  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 */
15166: 	  exit(1);
15167: 	}
15168:       } /* End loop for each variable in the resultline */
15169:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
15170:       /* 	printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
15171:       /* 	fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
15172:       /* 	fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
15173:       /* }	 */
15174:       fprintf(ficrest,"******\n");
15175:       fprintf(ficlog,"******\n");
15176:       printf("******\n");
15177:       
15178:       fprintf(ficresstdeij,"\n#****** ");
15179:       fprintf(ficrescveij,"\n#****** ");
15180:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
15181:       /* But it won't be sorted and depends on how the resultline is ordered */
15182:       for(j=1;j<=cptcoveff;j++) {
15183: 	fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
15184: 	/* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
15185: 	/* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
15186:       }
15187:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value, TvarsQind gives the position of a quantitative in model equation  */
15188: 	fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
15189: 	fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
15190:       }	
15191:       fprintf(ficresstdeij,"******\n");
15192:       fprintf(ficrescveij,"******\n");
15193:       
15194:       fprintf(ficresvij,"\n#****** ");
15195:       /* pstamp(ficresvij); */
15196:       for(j=1;j<=cptcoveff;j++) 
15197: 	fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
15198: 	/* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
15199:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
15200: 	/* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
15201: 	fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
15202:       }	
15203:       fprintf(ficresvij,"******\n");
15204:       
15205:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
15206:       oldm=oldms;savm=savms;
15207:       printf(" cvevsij ");
15208:       fprintf(ficlog, " cvevsij ");
15209:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
15210:       printf(" end cvevsij \n ");
15211:       fprintf(ficlog, " end cvevsij \n ");
15212:       
15213:       /*
15214:        */
15215:       /* goto endfree; */
15216:       
15217:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
15218:       pstamp(ficrest);
15219:       
15220:       epj=vector(1,nlstate+1);
15221:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
15222: 	oldm=oldms;savm=savms; /* ZZ Segmentation fault */
15223: 	cptcod= 0; /* To be deleted */
15224: 	printf("varevsij vpopbased=%d \n",vpopbased);
15225: 	fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
15226: 	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 */
15227: 	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 ");
15228: 	if(vpopbased==1)
15229: 	  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);
15230: 	else
15231: 	  fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
15232: 	fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
15233: 	for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
15234: 	fprintf(ficrest,"\n");
15235: 	/* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
15236: 	printf("Computing age specific forward period (stable) prevalences in each health state \n");
15237: 	fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
15238: 	for(age=bage; age <=fage ;age++){
15239: 	  prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
15240: 	  if (vpopbased==1) {
15241: 	    if(mobilav ==0){
15242: 	      for(i=1; i<=nlstate;i++)
15243: 		prlim[i][i]=probs[(int)age][i][k];
15244: 	    }else{ /* mobilav */ 
15245: 	      for(i=1; i<=nlstate;i++)
15246: 		prlim[i][i]=mobaverage[(int)age][i][k];
15247: 	    }
15248: 	  }
15249: 	  
15250: 	  fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
15251: 	  /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
15252: 	  /* printf(" age %4.0f ",age); */
15253: 	  for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
15254: 	    for(i=1, epj[j]=0.;i <=nlstate;i++) {
15255: 	      epj[j] += prlim[i][i]*eij[i][j][(int)age];
15256: 	      /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
15257: 	      /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
15258: 	    }
15259: 	    epj[nlstate+1] +=epj[j];
15260: 	  }
15261: 	  /* printf(" age %4.0f \n",age); */
15262: 	  
15263: 	  for(i=1, vepp=0.;i <=nlstate;i++)
15264: 	    for(j=1;j <=nlstate;j++)
15265: 	      vepp += vareij[i][j][(int)age];
15266: 	  fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
15267: 	  for(j=1;j <=nlstate;j++){
15268: 	    fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
15269: 	  }
15270: 	  fprintf(ficrest,"\n");
15271: 	}
15272:       } /* End vpopbased */
15273:       free_vector(epj,1,nlstate+1);
15274:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
15275:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
15276:       printf("done selection\n");fflush(stdout);
15277:       fprintf(ficlog,"done selection\n");fflush(ficlog);
15278:       
15279:     } /* End k selection or end covariate selection for nres */
15280: 
15281:     printf("done State-specific expectancies\n");fflush(stdout);
15282:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
15283: 
15284:     /* variance-covariance of forward period prevalence */
15285:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
15286: 
15287:     
15288:     free_vector(weight,firstobs,lastobs);
15289:     free_imatrix(Tvardk,0,NCOVMAX,1,2);
15290:     free_imatrix(Tvard,1,NCOVMAX,1,2);
15291:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
15292:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
15293:     free_matrix(mint,1,maxwav,firstobs,lastobs);
15294:     free_ivector(cod,firstobs,lastobs);
15295:     free_ivector(tab,1,NCOVMAX);
15296:     fclose(ficresstdeij);
15297:     fclose(ficrescveij);
15298:     fclose(ficresvij);
15299:     fclose(ficrest);
15300:     fclose(ficpar);
15301:     
15302:     
15303:     /*---------- End : free ----------------*/
15304:     if (mobilav!=0 ||mobilavproj !=0)
15305:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
15306:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
15307:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
15308:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
15309:   }  /* mle==-3 arrives here for freeing */
15310:   /* endfree:*/
15311:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
15312:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
15313:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
15314:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
15315:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
15316:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
15317:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
15318:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
15319:   free_matrix(matcov,1,npar,1,npar);
15320:   free_matrix(hess,1,npar,1,npar);
15321:   /*free_vector(delti,1,npar);*/
15322:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
15323:   free_matrix(agev,1,maxwav,1,imx);
15324:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
15325:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
15326:   
15327:   free_ivector(ncodemax,1,NCOVMAX);
15328:   free_ivector(ncodemaxwundef,1,NCOVMAX);
15329:   free_ivector(Dummy,-1,NCOVMAX);
15330:   free_ivector(Fixed,-1,NCOVMAX);
15331:   free_ivector(DummyV,-1,NCOVMAX);
15332:   free_ivector(FixedV,-1,NCOVMAX);
15333:   free_ivector(Typevar,-1,NCOVMAX);
15334:   free_ivector(Tvar,1,NCOVMAX);
15335:   free_ivector(TvarsQ,1,NCOVMAX);
15336:   free_ivector(TvarsQind,1,NCOVMAX);
15337:   free_ivector(TvarsD,1,NCOVMAX);
15338:   free_ivector(TnsdVar,1,NCOVMAX);
15339:   free_ivector(TvarsDind,1,NCOVMAX);
15340:   free_ivector(TvarFD,1,NCOVMAX);
15341:   free_ivector(TvarFDind,1,NCOVMAX);
15342:   free_ivector(TvarF,1,NCOVMAX);
15343:   free_ivector(TvarFind,1,NCOVMAX);
15344:   free_ivector(TvarV,1,NCOVMAX);
15345:   free_ivector(TvarVind,1,NCOVMAX);
15346:   free_ivector(TvarA,1,NCOVMAX);
15347:   free_ivector(TvarAind,1,NCOVMAX);
15348:   free_ivector(TvarFQ,1,NCOVMAX);
15349:   free_ivector(TvarFQind,1,NCOVMAX);
15350:   free_ivector(TvarVD,1,NCOVMAX);
15351:   free_ivector(TvarVDind,1,NCOVMAX);
15352:   free_ivector(TvarVQ,1,NCOVMAX);
15353:   free_ivector(TvarVQind,1,NCOVMAX);
15354:   free_ivector(TvarAVVA,1,NCOVMAX);
15355:   free_ivector(TvarAVVAind,1,NCOVMAX);
15356:   free_ivector(TvarVVA,1,NCOVMAX);
15357:   free_ivector(TvarVVAind,1,NCOVMAX);
15358:   free_ivector(TvarVV,1,NCOVMAX);
15359:   free_ivector(TvarVVind,1,NCOVMAX);
15360:   
15361:   free_ivector(Tvarsel,1,NCOVMAX);
15362:   free_vector(Tvalsel,1,NCOVMAX);
15363:   free_ivector(Tposprod,1,NCOVMAX);
15364:   free_ivector(Tprod,1,NCOVMAX);
15365:   free_ivector(Tvaraff,1,NCOVMAX);
15366:   free_ivector(invalidvarcomb,0,ncovcombmax);
15367:   free_ivector(Tage,1,NCOVMAX);
15368:   free_ivector(Tmodelind,1,NCOVMAX);
15369:   free_ivector(TmodelInvind,1,NCOVMAX);
15370:   free_ivector(TmodelInvQind,1,NCOVMAX);
15371: 
15372:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
15373: 
15374:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
15375:   /* free_imatrix(codtab,1,100,1,10); */
15376:   fflush(fichtm);
15377:   fflush(ficgp);
15378:   
15379:   
15380:   if((nberr >0) || (nbwarn>0)){
15381:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
15382:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d. Please look at the log file for details.\n",nberr,nbwarn);
15383:   }else{
15384:     printf("End of Imach\n");
15385:     fprintf(ficlog,"End of Imach\n");
15386:   }
15387:   printf("See log file on %s\n",filelog);
15388:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
15389:   /*(void) gettimeofday(&end_time,&tzp);*/
15390:   rend_time = time(NULL);  
15391:   end_time = *localtime(&rend_time);
15392:   /* tml = *localtime(&end_time.tm_sec); */
15393:   strcpy(strtend,asctime(&end_time));
15394:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
15395:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
15396:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
15397:   
15398:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
15399:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
15400:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
15401:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
15402: /*   if(fileappend(fichtm,optionfilehtm)){ */
15403:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
15404:   fclose(fichtm);
15405:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
15406:   fclose(fichtmcov);
15407:   fclose(ficgp);
15408:   fclose(ficlog);
15409:   /*------ End -----------*/
15410:   
15411: 
15412: /* Executes gnuplot */
15413:   
15414:   printf("Before Current directory %s!\n",pathcd);
15415: #ifdef WIN32
15416:   if (_chdir(pathcd) != 0)
15417:     printf("Can't move to directory %s!\n",path);
15418:   if(_getcwd(pathcd,MAXLINE) > 0)
15419: #else
15420:     if(chdir(pathcd) != 0)
15421:       printf("Can't move to directory %s!\n", path);
15422:   if (getcwd(pathcd, MAXLINE) > 0)
15423: #endif 
15424:     printf("Current directory %s!\n",pathcd);
15425:   /*strcat(plotcmd,CHARSEPARATOR);*/
15426:   sprintf(plotcmd,"gnuplot");
15427: #ifdef _WIN32
15428:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
15429: #endif
15430:   if(!stat(plotcmd,&info)){
15431:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
15432:     if(!stat(getenv("GNUPLOTBIN"),&info)){
15433:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
15434:     }else
15435:       strcpy(pplotcmd,plotcmd);
15436: #ifdef __unix
15437:     strcpy(plotcmd,GNUPLOTPROGRAM);
15438:     if(!stat(plotcmd,&info)){
15439:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
15440:     }else
15441:       strcpy(pplotcmd,plotcmd);
15442: #endif
15443:   }else
15444:     strcpy(pplotcmd,plotcmd);
15445:   
15446:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
15447:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
15448:   strcpy(pplotcmd,plotcmd);
15449:   
15450:   if((outcmd=system(plotcmd)) != 0){
15451:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
15452:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
15453:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
15454:     if((outcmd=system(plotcmd)) != 0){
15455:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
15456:       strcpy(plotcmd,pplotcmd);
15457:     }
15458:   }
15459:   printf(" Successful, please wait...");
15460:   while (z[0] != 'q') {
15461:     /* chdir(path); */
15462:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
15463:     scanf("%s",z);
15464: /*     if (z[0] == 'c') system("./imach"); */
15465:     if (z[0] == 'e') {
15466: #ifdef __APPLE__
15467:       sprintf(pplotcmd, "open %s", optionfilehtm);
15468: #elif __linux
15469:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
15470: #else
15471:       sprintf(pplotcmd, "%s", optionfilehtm);
15472: #endif
15473:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
15474:       system(pplotcmd);
15475:     }
15476:     else if (z[0] == 'g') system(plotcmd);
15477:     else if (z[0] == 'q') exit(0);
15478:   }
15479: end:
15480:   while (z[0] != 'q') {
15481:     printf("\nType  q for exiting: "); fflush(stdout);
15482:     scanf("%s",z);
15483:   }
15484:   printf("End\n");
15485:   exit(0);
15486: }

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