Annotation of imach/src/imachprax.c, revision 1.2

1.2     ! brouard     1: /* $Id: imach.c,v 1.353 2023/05/08 18:48:22 brouard Exp $
1.1       brouard     2:   $State: Exp $
                      3:   $Log: imach.c,v $
1.2     ! brouard     4:   Revision 1.353  2023/05/08 18:48:22  brouard
        !             5:   *** empty log message ***
        !             6: 
        !             7:   Revision 1.352  2023/04/29 10:46:21  brouard
        !             8:   *** empty log message ***
        !             9: 
        !            10:   Revision 1.351  2023/04/29 10:43:47  brouard
        !            11:   Summary: 099r45
        !            12: 
        !            13:   Revision 1.350  2023/04/24 11:38:06  brouard
        !            14:   *** empty log message ***
        !            15: 
        !            16:   Revision 1.349  2023/01/31 09:19:37  brouard
        !            17:   Summary: Improvements in models with age*Vn*Vm
        !            18: 
1.1       brouard    19:   Revision 1.347  2022/09/18 14:36:44  brouard
                     20:   Summary: version 0.99r42
                     21: 
                     22:   Revision 1.346  2022/09/16 13:52:36  brouard
                     23:   * src/imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     24: 
                     25:   Revision 1.345  2022/09/16 13:40:11  brouard
                     26:   Summary: Version 0.99r41
                     27: 
                     28:   * imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     29: 
                     30:   Revision 1.344  2022/09/14 19:33:30  brouard
                     31:   Summary: version 0.99r40
                     32: 
                     33:   * imach.c (Module): Fixing names of variables in T_ (thanks to Feinuo)
                     34: 
                     35:   Revision 1.343  2022/09/14 14:22:16  brouard
                     36:   Summary: version 0.99r39
                     37: 
                     38:   * imach.c (Module): Version 0.99r39 with colored dummy covariates
                     39:   (fixed or time varying), using new last columns of
                     40:   ILK_parameter.txt file.
                     41: 
                     42:   Revision 1.342  2022/09/11 19:54:09  brouard
                     43:   Summary: 0.99r38
                     44: 
                     45:   * imach.c (Module): Adding timevarying products of any kinds,
                     46:   should work before shifting cotvar from ncovcol+nqv columns in
                     47:   order to have a correspondance between the column of cotvar and
                     48:   the id of column.
                     49:   (Module): Some cleaning and adding covariates in ILK.txt
                     50: 
                     51:   Revision 1.341  2022/09/11 07:58:42  brouard
                     52:   Summary: Version 0.99r38
                     53: 
                     54:   After adding change in cotvar.
                     55: 
                     56:   Revision 1.340  2022/09/11 07:53:11  brouard
                     57:   Summary: Version imach 0.99r37
                     58: 
                     59:   * imach.c (Module): Adding timevarying products of any kinds,
                     60:   should work before shifting cotvar from ncovcol+nqv columns in
                     61:   order to have a correspondance between the column of cotvar and
                     62:   the id of column.
                     63: 
                     64:   Revision 1.339  2022/09/09 17:55:22  brouard
                     65:   Summary: version 0.99r37
                     66: 
                     67:   * imach.c (Module): Many improvements for fixing products of fixed
                     68:   timevarying as well as fixed * fixed, and test with quantitative
                     69:   covariate.
                     70: 
                     71:   Revision 1.338  2022/09/04 17:40:33  brouard
                     72:   Summary: 0.99r36
                     73: 
                     74:   * imach.c (Module): Now the easy runs i.e. without result or
                     75:   model=1+age only did not work. The defautl combination should be 1
                     76:   and not 0 because everything hasn't been tranformed yet.
                     77: 
                     78:   Revision 1.337  2022/09/02 14:26:02  brouard
                     79:   Summary: version 0.99r35
                     80: 
                     81:   * src/imach.c: Version 0.99r35 because it outputs same results with
                     82:   1+age+V1+V1*age for females and 1+age for females only
                     83:   (education=1 noweight)
                     84: 
                     85:   Revision 1.336  2022/08/31 09:52:36  brouard
                     86:   *** empty log message ***
                     87: 
                     88:   Revision 1.335  2022/08/31 08:23:16  brouard
                     89:   Summary: improvements...
                     90: 
                     91:   Revision 1.334  2022/08/25 09:08:41  brouard
                     92:   Summary: In progress for quantitative
                     93: 
                     94:   Revision 1.333  2022/08/21 09:10:30  brouard
                     95:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     96:   reassigning covariates: my first idea was that people will always
                     97:   use the first covariate V1 into the model but in fact they are
                     98:   producing data with many covariates and can use an equation model
                     99:   with some of the covariate; it means that in a model V2+V3 instead
                    100:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    101:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    102:   the equation model is restricted to two variables only (V2, V3)
                    103:   and the combination for V2 should be codtabm(k,1) instead of
                    104:   (codtabm(k,2), and the code should be
                    105:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    106:   made. All of these should be simplified once a day like we did in
                    107:   hpxij() for example by using precov[nres] which is computed in
                    108:   decoderesult for each nres of each resultline. Loop should be done
                    109:   on the equation model globally by distinguishing only product with
                    110:   age (which are changing with age) and no more on type of
                    111:   covariates, single dummies, single covariates.
                    112: 
                    113:   Revision 1.332  2022/08/21 09:06:25  brouard
                    114:   Summary: Version 0.99r33
                    115: 
                    116:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    117:   reassigning covariates: my first idea was that people will always
                    118:   use the first covariate V1 into the model but in fact they are
                    119:   producing data with many covariates and can use an equation model
                    120:   with some of the covariate; it means that in a model V2+V3 instead
                    121:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    122:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    123:   the equation model is restricted to two variables only (V2, V3)
                    124:   and the combination for V2 should be codtabm(k,1) instead of
                    125:   (codtabm(k,2), and the code should be
                    126:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    127:   made. All of these should be simplified once a day like we did in
                    128:   hpxij() for example by using precov[nres] which is computed in
                    129:   decoderesult for each nres of each resultline. Loop should be done
                    130:   on the equation model globally by distinguishing only product with
                    131:   age (which are changing with age) and no more on type of
                    132:   covariates, single dummies, single covariates.
                    133: 
                    134:   Revision 1.331  2022/08/07 05:40:09  brouard
                    135:   *** empty log message ***
                    136: 
                    137:   Revision 1.330  2022/08/06 07:18:25  brouard
                    138:   Summary: last 0.99r31
                    139: 
                    140:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                    141: 
                    142:   Revision 1.329  2022/08/03 17:29:54  brouard
                    143:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                    144: 
                    145:   Revision 1.328  2022/07/27 17:40:48  brouard
                    146:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                    147: 
                    148:   Revision 1.327  2022/07/27 14:47:35  brouard
                    149:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                    150: 
                    151:   Revision 1.326  2022/07/26 17:33:55  brouard
                    152:   Summary: some test with nres=1
                    153: 
                    154:   Revision 1.325  2022/07/25 14:27:23  brouard
                    155:   Summary: r30
                    156: 
                    157:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                    158:   coredumped, revealed by Feiuno, thank you.
                    159: 
                    160:   Revision 1.324  2022/07/23 17:44:26  brouard
                    161:   *** empty log message ***
                    162: 
                    163:   Revision 1.323  2022/07/22 12:30:08  brouard
                    164:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    165: 
                    166:   Revision 1.322  2022/07/22 12:27:48  brouard
                    167:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    168: 
                    169:   Revision 1.321  2022/07/22 12:04:24  brouard
                    170:   Summary: r28
                    171: 
                    172:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    173: 
                    174:   Revision 1.320  2022/06/02 05:10:11  brouard
                    175:   *** empty log message ***
                    176: 
                    177:   Revision 1.319  2022/06/02 04:45:11  brouard
                    178:   * imach.c (Module): Adding the Wald tests from the log to the main
                    179:   htm for better display of the maximum likelihood estimators.
                    180: 
                    181:   Revision 1.318  2022/05/24 08:10:59  brouard
                    182:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    183:   of confidencce intervals with product in the equation modelC
                    184: 
                    185:   Revision 1.317  2022/05/15 15:06:23  brouard
                    186:   * imach.c (Module):  Some minor improvements
                    187: 
                    188:   Revision 1.316  2022/05/11 15:11:31  brouard
                    189:   Summary: r27
                    190: 
                    191:   Revision 1.315  2022/05/11 15:06:32  brouard
                    192:   *** empty log message ***
                    193: 
                    194:   Revision 1.314  2022/04/13 17:43:09  brouard
                    195:   * imach.c (Module): Adding link to text data files
                    196: 
                    197:   Revision 1.313  2022/04/11 15:57:42  brouard
                    198:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    199: 
                    200:   Revision 1.312  2022/04/05 21:24:39  brouard
                    201:   *** empty log message ***
                    202: 
                    203:   Revision 1.311  2022/04/05 21:03:51  brouard
                    204:   Summary: Fixed quantitative covariates
                    205: 
                    206:          Fixed covariates (dummy or quantitative)
                    207:        with missing values have never been allowed but are ERRORS and
                    208:        program quits. Standard deviations of fixed covariates were
                    209:        wrongly computed. Mean and standard deviations of time varying
                    210:        covariates are still not computed.
                    211: 
                    212:   Revision 1.310  2022/03/17 08:45:53  brouard
                    213:   Summary: 99r25
                    214: 
                    215:   Improving detection of errors: result lines should be compatible with
                    216:   the model.
                    217: 
                    218:   Revision 1.309  2021/05/20 12:39:14  brouard
                    219:   Summary: Version 0.99r24
                    220: 
                    221:   Revision 1.308  2021/03/31 13:11:57  brouard
                    222:   Summary: Version 0.99r23
                    223: 
                    224: 
                    225:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    226: 
                    227:   Revision 1.307  2021/03/08 18:11:32  brouard
                    228:   Summary: 0.99r22 fixed bug on result:
                    229: 
                    230:   Revision 1.306  2021/02/20 15:44:02  brouard
                    231:   Summary: Version 0.99r21
                    232: 
                    233:   * imach.c (Module): Fix bug on quitting after result lines!
                    234:   (Module): Version 0.99r21
                    235: 
                    236:   Revision 1.305  2021/02/20 15:28:30  brouard
                    237:   * imach.c (Module): Fix bug on quitting after result lines!
                    238: 
                    239:   Revision 1.304  2021/02/12 11:34:20  brouard
                    240:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    241: 
                    242:   Revision 1.303  2021/02/11 19:50:15  brouard
                    243:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    244: 
                    245:   Revision 1.302  2020/02/22 21:00:05  brouard
                    246:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    247:   and life table from the data without any state)
                    248: 
                    249:   Revision 1.301  2019/06/04 13:51:20  brouard
                    250:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    251: 
                    252:   Revision 1.300  2019/05/22 19:09:45  brouard
                    253:   Summary: version 0.99r19 of May 2019
                    254: 
                    255:   Revision 1.299  2019/05/22 18:37:08  brouard
                    256:   Summary: Cleaned 0.99r19
                    257: 
                    258:   Revision 1.298  2019/05/22 18:19:56  brouard
                    259:   *** empty log message ***
                    260: 
                    261:   Revision 1.297  2019/05/22 17:56:10  brouard
                    262:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    263: 
                    264:   Revision 1.296  2019/05/20 13:03:18  brouard
                    265:   Summary: Projection syntax simplified
                    266: 
                    267: 
                    268:   We can now start projections, forward or backward, from the mean date
                    269:   of inteviews up to or down to a number of years of projection:
                    270:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    271:   or
                    272:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    273:   or
                    274:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    275:   or
                    276:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    277: 
                    278:   Revision 1.295  2019/05/18 09:52:50  brouard
                    279:   Summary: doxygen tex bug
                    280: 
                    281:   Revision 1.294  2019/05/16 14:54:33  brouard
                    282:   Summary: There was some wrong lines added
                    283: 
                    284:   Revision 1.293  2019/05/09 15:17:34  brouard
                    285:   *** empty log message ***
                    286: 
                    287:   Revision 1.292  2019/05/09 14:17:20  brouard
                    288:   Summary: Some updates
                    289: 
                    290:   Revision 1.291  2019/05/09 13:44:18  brouard
                    291:   Summary: Before ncovmax
                    292: 
                    293:   Revision 1.290  2019/05/09 13:39:37  brouard
                    294:   Summary: 0.99r18 unlimited number of individuals
                    295: 
                    296:   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.
                    297: 
                    298:   Revision 1.289  2018/12/13 09:16:26  brouard
                    299:   Summary: Bug for young ages (<-30) will be in r17
                    300: 
                    301:   Revision 1.288  2018/05/02 20:58:27  brouard
                    302:   Summary: Some bugs fixed
                    303: 
                    304:   Revision 1.287  2018/05/01 17:57:25  brouard
                    305:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    306: 
                    307:   Revision 1.286  2018/04/27 14:27:04  brouard
                    308:   Summary: some minor bugs
                    309: 
                    310:   Revision 1.285  2018/04/21 21:02:16  brouard
                    311:   Summary: Some bugs fixed, valgrind tested
                    312: 
                    313:   Revision 1.284  2018/04/20 05:22:13  brouard
                    314:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    315: 
                    316:   Revision 1.283  2018/04/19 14:49:16  brouard
                    317:   Summary: Some minor bugs fixed
                    318: 
                    319:   Revision 1.282  2018/02/27 22:50:02  brouard
                    320:   *** empty log message ***
                    321: 
                    322:   Revision 1.281  2018/02/27 19:25:23  brouard
                    323:   Summary: Adding second argument for quitting
                    324: 
                    325:   Revision 1.280  2018/02/21 07:58:13  brouard
                    326:   Summary: 0.99r15
                    327: 
                    328:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    329: 
                    330:   Revision 1.279  2017/07/20 13:35:01  brouard
                    331:   Summary: temporary working
                    332: 
                    333:   Revision 1.278  2017/07/19 14:09:02  brouard
                    334:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    335: 
                    336:   Revision 1.277  2017/07/17 08:53:49  brouard
                    337:   Summary: BOM files can be read now
                    338: 
                    339:   Revision 1.276  2017/06/30 15:48:31  brouard
                    340:   Summary: Graphs improvements
                    341: 
                    342:   Revision 1.275  2017/06/30 13:39:33  brouard
                    343:   Summary: Saito's color
                    344: 
                    345:   Revision 1.274  2017/06/29 09:47:08  brouard
                    346:   Summary: Version 0.99r14
                    347: 
                    348:   Revision 1.273  2017/06/27 11:06:02  brouard
                    349:   Summary: More documentation on projections
                    350: 
                    351:   Revision 1.272  2017/06/27 10:22:40  brouard
                    352:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    353: 
                    354:   Revision 1.271  2017/06/27 10:17:50  brouard
                    355:   Summary: Some bug with rint
                    356: 
                    357:   Revision 1.270  2017/05/24 05:45:29  brouard
                    358:   *** empty log message ***
                    359: 
                    360:   Revision 1.269  2017/05/23 08:39:25  brouard
                    361:   Summary: Code into subroutine, cleanings
                    362: 
                    363:   Revision 1.268  2017/05/18 20:09:32  brouard
                    364:   Summary: backprojection and confidence intervals of backprevalence
                    365: 
                    366:   Revision 1.267  2017/05/13 10:25:05  brouard
                    367:   Summary: temporary save for backprojection
                    368: 
                    369:   Revision 1.266  2017/05/13 07:26:12  brouard
                    370:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    371: 
                    372:   Revision 1.265  2017/04/26 16:22:11  brouard
                    373:   Summary: imach 0.99r13 Some bugs fixed
                    374: 
                    375:   Revision 1.264  2017/04/26 06:01:29  brouard
                    376:   Summary: Labels in graphs
                    377: 
                    378:   Revision 1.263  2017/04/24 15:23:15  brouard
                    379:   Summary: to save
                    380: 
                    381:   Revision 1.262  2017/04/18 16:48:12  brouard
                    382:   *** empty log message ***
                    383: 
                    384:   Revision 1.261  2017/04/05 10:14:09  brouard
                    385:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    386: 
                    387:   Revision 1.260  2017/04/04 17:46:59  brouard
                    388:   Summary: Gnuplot indexations fixed (humm)
                    389: 
                    390:   Revision 1.259  2017/04/04 13:01:16  brouard
                    391:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    392: 
                    393:   Revision 1.258  2017/04/03 10:17:47  brouard
                    394:   Summary: Version 0.99r12
                    395: 
                    396:   Some cleanings, conformed with updated documentation.
                    397: 
                    398:   Revision 1.257  2017/03/29 16:53:30  brouard
                    399:   Summary: Temp
                    400: 
                    401:   Revision 1.256  2017/03/27 05:50:23  brouard
                    402:   Summary: Temporary
                    403: 
                    404:   Revision 1.255  2017/03/08 16:02:28  brouard
                    405:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    406: 
                    407:   Revision 1.254  2017/03/08 07:13:00  brouard
                    408:   Summary: Fixing data parameter line
                    409: 
                    410:   Revision 1.253  2016/12/15 11:59:41  brouard
                    411:   Summary: 0.99 in progress
                    412: 
                    413:   Revision 1.252  2016/09/15 21:15:37  brouard
                    414:   *** empty log message ***
                    415: 
                    416:   Revision 1.251  2016/09/15 15:01:13  brouard
                    417:   Summary: not working
                    418: 
                    419:   Revision 1.250  2016/09/08 16:07:27  brouard
                    420:   Summary: continue
                    421: 
                    422:   Revision 1.249  2016/09/07 17:14:18  brouard
                    423:   Summary: Starting values from frequencies
                    424: 
                    425:   Revision 1.248  2016/09/07 14:10:18  brouard
                    426:   *** empty log message ***
                    427: 
                    428:   Revision 1.247  2016/09/02 11:11:21  brouard
                    429:   *** empty log message ***
                    430: 
                    431:   Revision 1.246  2016/09/02 08:49:22  brouard
                    432:   *** empty log message ***
                    433: 
                    434:   Revision 1.245  2016/09/02 07:25:01  brouard
                    435:   *** empty log message ***
                    436: 
                    437:   Revision 1.244  2016/09/02 07:17:34  brouard
                    438:   *** empty log message ***
                    439: 
                    440:   Revision 1.243  2016/09/02 06:45:35  brouard
                    441:   *** empty log message ***
                    442: 
                    443:   Revision 1.242  2016/08/30 15:01:20  brouard
                    444:   Summary: Fixing a lots
                    445: 
                    446:   Revision 1.241  2016/08/29 17:17:25  brouard
                    447:   Summary: gnuplot problem in Back projection to fix
                    448: 
                    449:   Revision 1.240  2016/08/29 07:53:18  brouard
                    450:   Summary: Better
                    451: 
                    452:   Revision 1.239  2016/08/26 15:51:03  brouard
                    453:   Summary: Improvement in Powell output in order to copy and paste
                    454: 
                    455:   Author:
                    456: 
                    457:   Revision 1.238  2016/08/26 14:23:35  brouard
                    458:   Summary: Starting tests of 0.99
                    459: 
                    460:   Revision 1.237  2016/08/26 09:20:19  brouard
                    461:   Summary: to valgrind
                    462: 
                    463:   Revision 1.236  2016/08/25 10:50:18  brouard
                    464:   *** empty log message ***
                    465: 
                    466:   Revision 1.235  2016/08/25 06:59:23  brouard
                    467:   *** empty log message ***
                    468: 
                    469:   Revision 1.234  2016/08/23 16:51:20  brouard
                    470:   *** empty log message ***
                    471: 
                    472:   Revision 1.233  2016/08/23 07:40:50  brouard
                    473:   Summary: not working
                    474: 
                    475:   Revision 1.232  2016/08/22 14:20:21  brouard
                    476:   Summary: not working
                    477: 
                    478:   Revision 1.231  2016/08/22 07:17:15  brouard
                    479:   Summary: not working
                    480: 
                    481:   Revision 1.230  2016/08/22 06:55:53  brouard
                    482:   Summary: Not working
                    483: 
                    484:   Revision 1.229  2016/07/23 09:45:53  brouard
                    485:   Summary: Completing for func too
                    486: 
                    487:   Revision 1.228  2016/07/22 17:45:30  brouard
                    488:   Summary: Fixing some arrays, still debugging
                    489: 
                    490:   Revision 1.226  2016/07/12 18:42:34  brouard
                    491:   Summary: temp
                    492: 
                    493:   Revision 1.225  2016/07/12 08:40:03  brouard
                    494:   Summary: saving but not running
                    495: 
                    496:   Revision 1.224  2016/07/01 13:16:01  brouard
                    497:   Summary: Fixes
                    498: 
                    499:   Revision 1.223  2016/02/19 09:23:35  brouard
                    500:   Summary: temporary
                    501: 
                    502:   Revision 1.222  2016/02/17 08:14:50  brouard
                    503:   Summary: Probably last 0.98 stable version 0.98r6
                    504: 
                    505:   Revision 1.221  2016/02/15 23:35:36  brouard
                    506:   Summary: minor bug
                    507: 
                    508:   Revision 1.219  2016/02/15 00:48:12  brouard
                    509:   *** empty log message ***
                    510: 
                    511:   Revision 1.218  2016/02/12 11:29:23  brouard
                    512:   Summary: 0.99 Back projections
                    513: 
                    514:   Revision 1.217  2015/12/23 17:18:31  brouard
                    515:   Summary: Experimental backcast
                    516: 
                    517:   Revision 1.216  2015/12/18 17:32:11  brouard
                    518:   Summary: 0.98r4 Warning and status=-2
                    519: 
                    520:   Version 0.98r4 is now:
                    521:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    522:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    523:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    524: 
                    525:   Revision 1.215  2015/12/16 08:52:24  brouard
                    526:   Summary: 0.98r4 working
                    527: 
                    528:   Revision 1.214  2015/12/16 06:57:54  brouard
                    529:   Summary: temporary not working
                    530: 
                    531:   Revision 1.213  2015/12/11 18:22:17  brouard
                    532:   Summary: 0.98r4
                    533: 
                    534:   Revision 1.212  2015/11/21 12:47:24  brouard
                    535:   Summary: minor typo
                    536: 
                    537:   Revision 1.211  2015/11/21 12:41:11  brouard
                    538:   Summary: 0.98r3 with some graph of projected cross-sectional
                    539: 
                    540:   Author: Nicolas Brouard
                    541: 
                    542:   Revision 1.210  2015/11/18 17:41:20  brouard
                    543:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
                    544:   Summary: Adding ftolpl parameter
                    545:   Author: N Brouard
                    546: 
                    547:   We had difficulties to get smoothed confidence intervals. It was due
                    548:   to the period prevalence which wasn't computed accurately. The inner
                    549:   parameter ftolpl is now an outer parameter of the .imach parameter
                    550:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    551:   computation are long.
                    552: 
                    553:   Revision 1.208  2015/11/17 14:31:57  brouard
                    554:   Summary: temporary
                    555: 
                    556:   Revision 1.207  2015/10/27 17:36:57  brouard
                    557:   *** empty log message ***
                    558: 
                    559:   Revision 1.206  2015/10/24 07:14:11  brouard
                    560:   *** empty log message ***
                    561: 
                    562:   Revision 1.205  2015/10/23 15:50:53  brouard
                    563:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    564: 
                    565:   Revision 1.204  2015/10/01 16:20:26  brouard
                    566:   Summary: Some new graphs of contribution to likelihood
                    567: 
                    568:   Revision 1.203  2015/09/30 17:45:14  brouard
                    569:   Summary: looking at better estimation of the hessian
                    570: 
                    571:   Also a better criteria for convergence to the period prevalence And
                    572:   therefore adding the number of years needed to converge. (The
                    573:   prevalence in any alive state shold sum to one
                    574: 
                    575:   Revision 1.202  2015/09/22 19:45:16  brouard
                    576:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    577: 
                    578:   Revision 1.201  2015/09/15 17:34:58  brouard
                    579:   Summary: 0.98r0
                    580: 
                    581:   - Some new graphs like suvival functions
                    582:   - Some bugs fixed like model=1+age+V2.
                    583: 
                    584:   Revision 1.200  2015/09/09 16:53:55  brouard
                    585:   Summary: Big bug thanks to Flavia
                    586: 
                    587:   Even model=1+age+V2. did not work anymore
                    588: 
                    589:   Revision 1.199  2015/09/07 14:09:23  brouard
                    590:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    591: 
                    592:   Revision 1.198  2015/09/03 07:14:39  brouard
                    593:   Summary: 0.98q5 Flavia
                    594: 
                    595:   Revision 1.197  2015/09/01 18:24:39  brouard
                    596:   *** empty log message ***
                    597: 
                    598:   Revision 1.196  2015/08/18 23:17:52  brouard
                    599:   Summary: 0.98q5
                    600: 
                    601:   Revision 1.195  2015/08/18 16:28:39  brouard
                    602:   Summary: Adding a hack for testing purpose
                    603: 
                    604:   After reading the title, ftol and model lines, if the comment line has
                    605:   a q, starting with #q, the answer at the end of the run is quit. It
                    606:   permits to run test files in batch with ctest. The former workaround was
                    607:   $ echo q | imach foo.imach
                    608: 
                    609:   Revision 1.194  2015/08/18 13:32:00  brouard
                    610:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    611: 
                    612:   Revision 1.193  2015/08/04 07:17:42  brouard
                    613:   Summary: 0.98q4
                    614: 
                    615:   Revision 1.192  2015/07/16 16:49:02  brouard
                    616:   Summary: Fixing some outputs
                    617: 
                    618:   Revision 1.191  2015/07/14 10:00:33  brouard
                    619:   Summary: Some fixes
                    620: 
                    621:   Revision 1.190  2015/05/05 08:51:13  brouard
                    622:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    623: 
                    624:   Fix 1+age+.
                    625: 
                    626:   Revision 1.189  2015/04/30 14:45:16  brouard
                    627:   Summary: 0.98q2
                    628: 
                    629:   Revision 1.188  2015/04/30 08:27:53  brouard
                    630:   *** empty log message ***
                    631: 
                    632:   Revision 1.187  2015/04/29 09:11:15  brouard
                    633:   *** empty log message ***
                    634: 
                    635:   Revision 1.186  2015/04/23 12:01:52  brouard
                    636:   Summary: V1*age is working now, version 0.98q1
                    637: 
                    638:   Some codes had been disabled in order to simplify and Vn*age was
                    639:   working in the optimization phase, ie, giving correct MLE parameters,
                    640:   but, as usual, outputs were not correct and program core dumped.
                    641: 
                    642:   Revision 1.185  2015/03/11 13:26:42  brouard
                    643:   Summary: Inclusion of compile and links command line for Intel Compiler
                    644: 
                    645:   Revision 1.184  2015/03/11 11:52:39  brouard
                    646:   Summary: Back from Windows 8. Intel Compiler
                    647: 
                    648:   Revision 1.183  2015/03/10 20:34:32  brouard
                    649:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    650: 
                    651:   We use directest instead of original Powell test; probably no
                    652:   incidence on the results, but better justifications;
                    653:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    654:   wrong results.
                    655: 
                    656:   Revision 1.182  2015/02/12 08:19:57  brouard
                    657:   Summary: Trying to keep directest which seems simpler and more general
                    658:   Author: Nicolas Brouard
                    659: 
                    660:   Revision 1.181  2015/02/11 23:22:24  brouard
                    661:   Summary: Comments on Powell added
                    662: 
                    663:   Author:
                    664: 
                    665:   Revision 1.180  2015/02/11 17:33:45  brouard
                    666:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    667: 
                    668:   Revision 1.179  2015/01/04 09:57:06  brouard
                    669:   Summary: back to OS/X
                    670: 
                    671:   Revision 1.178  2015/01/04 09:35:48  brouard
                    672:   *** empty log message ***
                    673: 
                    674:   Revision 1.177  2015/01/03 18:40:56  brouard
                    675:   Summary: Still testing ilc32 on OSX
                    676: 
                    677:   Revision 1.176  2015/01/03 16:45:04  brouard
                    678:   *** empty log message ***
                    679: 
                    680:   Revision 1.175  2015/01/03 16:33:42  brouard
                    681:   *** empty log message ***
                    682: 
                    683:   Revision 1.174  2015/01/03 16:15:49  brouard
                    684:   Summary: Still in cross-compilation
                    685: 
                    686:   Revision 1.173  2015/01/03 12:06:26  brouard
                    687:   Summary: trying to detect cross-compilation
                    688: 
                    689:   Revision 1.172  2014/12/27 12:07:47  brouard
                    690:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    691: 
                    692:   Revision 1.171  2014/12/23 13:26:59  brouard
                    693:   Summary: Back from Visual C
                    694: 
                    695:   Still problem with utsname.h on Windows
                    696: 
                    697:   Revision 1.170  2014/12/23 11:17:12  brouard
                    698:   Summary: Cleaning some \%% back to %%
                    699: 
                    700:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    701: 
                    702:   Revision 1.169  2014/12/22 23:08:31  brouard
                    703:   Summary: 0.98p
                    704: 
                    705:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    706: 
                    707:   Revision 1.168  2014/12/22 15:17:42  brouard
                    708:   Summary: update
                    709: 
                    710:   Revision 1.167  2014/12/22 13:50:56  brouard
                    711:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    712: 
                    713:   Testing on Linux 64
                    714: 
                    715:   Revision 1.166  2014/12/22 11:40:47  brouard
                    716:   *** empty log message ***
                    717: 
                    718:   Revision 1.165  2014/12/16 11:20:36  brouard
                    719:   Summary: After compiling on Visual C
                    720: 
                    721:   * imach.c (Module): Merging 1.61 to 1.162
                    722: 
                    723:   Revision 1.164  2014/12/16 10:52:11  brouard
                    724:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    725: 
                    726:   * imach.c (Module): Merging 1.61 to 1.162
                    727: 
                    728:   Revision 1.163  2014/12/16 10:30:11  brouard
                    729:   * imach.c (Module): Merging 1.61 to 1.162
                    730: 
                    731:   Revision 1.162  2014/09/25 11:43:39  brouard
                    732:   Summary: temporary backup 0.99!
                    733: 
                    734:   Revision 1.1  2014/09/16 11:06:58  brouard
                    735:   Summary: With some code (wrong) for nlopt
                    736: 
                    737:   Author:
                    738: 
                    739:   Revision 1.161  2014/09/15 20:41:41  brouard
                    740:   Summary: Problem with macro SQR on Intel compiler
                    741: 
                    742:   Revision 1.160  2014/09/02 09:24:05  brouard
                    743:   *** empty log message ***
                    744: 
                    745:   Revision 1.159  2014/09/01 10:34:10  brouard
                    746:   Summary: WIN32
                    747:   Author: Brouard
                    748: 
                    749:   Revision 1.158  2014/08/27 17:11:51  brouard
                    750:   *** empty log message ***
                    751: 
                    752:   Revision 1.157  2014/08/27 16:26:55  brouard
                    753:   Summary: Preparing windows Visual studio version
                    754:   Author: Brouard
                    755: 
                    756:   In order to compile on Visual studio, time.h is now correct and time_t
                    757:   and tm struct should be used. difftime should be used but sometimes I
                    758:   just make the differences in raw time format (time(&now).
                    759:   Trying to suppress #ifdef LINUX
                    760:   Add xdg-open for __linux in order to open default browser.
                    761: 
                    762:   Revision 1.156  2014/08/25 20:10:10  brouard
                    763:   *** empty log message ***
                    764: 
                    765:   Revision 1.155  2014/08/25 18:32:34  brouard
                    766:   Summary: New compile, minor changes
                    767:   Author: Brouard
                    768: 
                    769:   Revision 1.154  2014/06/20 17:32:08  brouard
                    770:   Summary: Outputs now all graphs of convergence to period prevalence
                    771: 
                    772:   Revision 1.153  2014/06/20 16:45:46  brouard
                    773:   Summary: If 3 live state, convergence to period prevalence on same graph
                    774:   Author: Brouard
                    775: 
                    776:   Revision 1.152  2014/06/18 17:54:09  brouard
                    777:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    778: 
                    779:   Revision 1.151  2014/06/18 16:43:30  brouard
                    780:   *** empty log message ***
                    781: 
                    782:   Revision 1.150  2014/06/18 16:42:35  brouard
                    783:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    784:   Author: brouard
                    785: 
                    786:   Revision 1.149  2014/06/18 15:51:14  brouard
                    787:   Summary: Some fixes in parameter files errors
                    788:   Author: Nicolas Brouard
                    789: 
                    790:   Revision 1.148  2014/06/17 17:38:48  brouard
                    791:   Summary: Nothing new
                    792:   Author: Brouard
                    793: 
                    794:   Just a new packaging for OS/X version 0.98nS
                    795: 
                    796:   Revision 1.147  2014/06/16 10:33:11  brouard
                    797:   *** empty log message ***
                    798: 
                    799:   Revision 1.146  2014/06/16 10:20:28  brouard
                    800:   Summary: Merge
                    801:   Author: Brouard
                    802: 
                    803:   Merge, before building revised version.
                    804: 
                    805:   Revision 1.145  2014/06/10 21:23:15  brouard
                    806:   Summary: Debugging with valgrind
                    807:   Author: Nicolas Brouard
                    808: 
                    809:   Lot of changes in order to output the results with some covariates
                    810:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    811:   improve the code.
                    812:   No more memory valgrind error but a lot has to be done in order to
                    813:   continue the work of splitting the code into subroutines.
                    814:   Also, decodemodel has been improved. Tricode is still not
                    815:   optimal. nbcode should be improved. Documentation has been added in
                    816:   the source code.
                    817: 
                    818:   Revision 1.143  2014/01/26 09:45:38  brouard
                    819:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    820: 
                    821:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    822:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    823: 
                    824:   Revision 1.142  2014/01/26 03:57:36  brouard
                    825:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    826: 
                    827:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    828: 
                    829:   Revision 1.141  2014/01/26 02:42:01  brouard
                    830:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    831: 
                    832:   Revision 1.140  2011/09/02 10:37:54  brouard
                    833:   Summary: times.h is ok with mingw32 now.
                    834: 
                    835:   Revision 1.139  2010/06/14 07:50:17  brouard
                    836:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    837:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    838: 
                    839:   Revision 1.138  2010/04/30 18:19:40  brouard
                    840:   *** empty log message ***
                    841: 
                    842:   Revision 1.137  2010/04/29 18:11:38  brouard
                    843:   (Module): Checking covariates for more complex models
                    844:   than V1+V2. A lot of change to be done. Unstable.
                    845: 
                    846:   Revision 1.136  2010/04/26 20:30:53  brouard
                    847:   (Module): merging some libgsl code. Fixing computation
                    848:   of likelione (using inter/intrapolation if mle = 0) in order to
                    849:   get same likelihood as if mle=1.
                    850:   Some cleaning of code and comments added.
                    851: 
                    852:   Revision 1.135  2009/10/29 15:33:14  brouard
                    853:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    854: 
                    855:   Revision 1.134  2009/10/29 13:18:53  brouard
                    856:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    857: 
                    858:   Revision 1.133  2009/07/06 10:21:25  brouard
                    859:   just nforces
                    860: 
                    861:   Revision 1.132  2009/07/06 08:22:05  brouard
                    862:   Many tings
                    863: 
                    864:   Revision 1.131  2009/06/20 16:22:47  brouard
                    865:   Some dimensions resccaled
                    866: 
                    867:   Revision 1.130  2009/05/26 06:44:34  brouard
                    868:   (Module): Max Covariate is now set to 20 instead of 8. A
                    869:   lot of cleaning with variables initialized to 0. Trying to make
                    870:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    871: 
                    872:   Revision 1.129  2007/08/31 13:49:27  lievre
                    873:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    874: 
                    875:   Revision 1.128  2006/06/30 13:02:05  brouard
                    876:   (Module): Clarifications on computing e.j
                    877: 
                    878:   Revision 1.127  2006/04/28 18:11:50  brouard
                    879:   (Module): Yes the sum of survivors was wrong since
                    880:   imach-114 because nhstepm was no more computed in the age
                    881:   loop. Now we define nhstepma in the age loop.
                    882:   (Module): In order to speed up (in case of numerous covariates) we
                    883:   compute health expectancies (without variances) in a first step
                    884:   and then all the health expectancies with variances or standard
                    885:   deviation (needs data from the Hessian matrices) which slows the
                    886:   computation.
                    887:   In the future we should be able to stop the program is only health
                    888:   expectancies and graph are needed without standard deviations.
                    889: 
                    890:   Revision 1.126  2006/04/28 17:23:28  brouard
                    891:   (Module): Yes the sum of survivors was wrong since
                    892:   imach-114 because nhstepm was no more computed in the age
                    893:   loop. Now we define nhstepma in the age loop.
                    894:   Version 0.98h
                    895: 
                    896:   Revision 1.125  2006/04/04 15:20:31  lievre
                    897:   Errors in calculation of health expectancies. Age was not initialized.
                    898:   Forecasting file added.
                    899: 
                    900:   Revision 1.124  2006/03/22 17:13:53  lievre
                    901:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    902:   The log-likelihood is printed in the log file
                    903: 
                    904:   Revision 1.123  2006/03/20 10:52:43  brouard
                    905:   * imach.c (Module): <title> changed, corresponds to .htm file
                    906:   name. <head> headers where missing.
                    907: 
                    908:   * imach.c (Module): Weights can have a decimal point as for
                    909:   English (a comma might work with a correct LC_NUMERIC environment,
                    910:   otherwise the weight is truncated).
                    911:   Modification of warning when the covariates values are not 0 or
                    912:   1.
                    913:   Version 0.98g
                    914: 
                    915:   Revision 1.122  2006/03/20 09:45:41  brouard
                    916:   (Module): Weights can have a decimal point as for
                    917:   English (a comma might work with a correct LC_NUMERIC environment,
                    918:   otherwise the weight is truncated).
                    919:   Modification of warning when the covariates values are not 0 or
                    920:   1.
                    921:   Version 0.98g
                    922: 
                    923:   Revision 1.121  2006/03/16 17:45:01  lievre
                    924:   * imach.c (Module): Comments concerning covariates added
                    925: 
                    926:   * imach.c (Module): refinements in the computation of lli if
                    927:   status=-2 in order to have more reliable computation if stepm is
                    928:   not 1 month. Version 0.98f
                    929: 
                    930:   Revision 1.120  2006/03/16 15:10:38  lievre
                    931:   (Module): refinements in the computation of lli if
                    932:   status=-2 in order to have more reliable computation if stepm is
                    933:   not 1 month. Version 0.98f
                    934: 
                    935:   Revision 1.119  2006/03/15 17:42:26  brouard
                    936:   (Module): Bug if status = -2, the loglikelihood was
                    937:   computed as likelihood omitting the logarithm. Version O.98e
                    938: 
                    939:   Revision 1.118  2006/03/14 18:20:07  brouard
                    940:   (Module): varevsij Comments added explaining the second
                    941:   table of variances if popbased=1 .
                    942:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    943:   (Module): Function pstamp added
                    944:   (Module): Version 0.98d
                    945: 
                    946:   Revision 1.117  2006/03/14 17:16:22  brouard
                    947:   (Module): varevsij Comments added explaining the second
                    948:   table of variances if popbased=1 .
                    949:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    950:   (Module): Function pstamp added
                    951:   (Module): Version 0.98d
                    952: 
                    953:   Revision 1.116  2006/03/06 10:29:27  brouard
                    954:   (Module): Variance-covariance wrong links and
                    955:   varian-covariance of ej. is needed (Saito).
                    956: 
                    957:   Revision 1.115  2006/02/27 12:17:45  brouard
                    958:   (Module): One freematrix added in mlikeli! 0.98c
                    959: 
                    960:   Revision 1.114  2006/02/26 12:57:58  brouard
                    961:   (Module): Some improvements in processing parameter
                    962:   filename with strsep.
                    963: 
                    964:   Revision 1.113  2006/02/24 14:20:24  brouard
                    965:   (Module): Memory leaks checks with valgrind and:
                    966:   datafile was not closed, some imatrix were not freed and on matrix
                    967:   allocation too.
                    968: 
                    969:   Revision 1.112  2006/01/30 09:55:26  brouard
                    970:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    971: 
                    972:   Revision 1.111  2006/01/25 20:38:18  brouard
                    973:   (Module): Lots of cleaning and bugs added (Gompertz)
                    974:   (Module): Comments can be added in data file. Missing date values
                    975:   can be a simple dot '.'.
                    976: 
                    977:   Revision 1.110  2006/01/25 00:51:50  brouard
                    978:   (Module): Lots of cleaning and bugs added (Gompertz)
                    979: 
                    980:   Revision 1.109  2006/01/24 19:37:15  brouard
                    981:   (Module): Comments (lines starting with a #) are allowed in data.
                    982: 
                    983:   Revision 1.108  2006/01/19 18:05:42  lievre
                    984:   Gnuplot problem appeared...
                    985:   To be fixed
                    986: 
                    987:   Revision 1.107  2006/01/19 16:20:37  brouard
                    988:   Test existence of gnuplot in imach path
                    989: 
                    990:   Revision 1.106  2006/01/19 13:24:36  brouard
                    991:   Some cleaning and links added in html output
                    992: 
                    993:   Revision 1.105  2006/01/05 20:23:19  lievre
                    994:   *** empty log message ***
                    995: 
                    996:   Revision 1.104  2005/09/30 16:11:43  lievre
                    997:   (Module): sump fixed, loop imx fixed, and simplifications.
                    998:   (Module): If the status is missing at the last wave but we know
                    999:   that the person is alive, then we can code his/her status as -2
                   1000:   (instead of missing=-1 in earlier versions) and his/her
                   1001:   contributions to the likelihood is 1 - Prob of dying from last
                   1002:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                   1003:   the healthy state at last known wave). Version is 0.98
                   1004: 
                   1005:   Revision 1.103  2005/09/30 15:54:49  lievre
                   1006:   (Module): sump fixed, loop imx fixed, and simplifications.
                   1007: 
                   1008:   Revision 1.102  2004/09/15 17:31:30  brouard
                   1009:   Add the possibility to read data file including tab characters.
                   1010: 
                   1011:   Revision 1.101  2004/09/15 10:38:38  brouard
                   1012:   Fix on curr_time
                   1013: 
                   1014:   Revision 1.100  2004/07/12 18:29:06  brouard
                   1015:   Add version for Mac OS X. Just define UNIX in Makefile
                   1016: 
                   1017:   Revision 1.99  2004/06/05 08:57:40  brouard
                   1018:   *** empty log message ***
                   1019: 
                   1020:   Revision 1.98  2004/05/16 15:05:56  brouard
                   1021:   New version 0.97 . First attempt to estimate force of mortality
                   1022:   directly from the data i.e. without the need of knowing the health
                   1023:   state at each age, but using a Gompertz model: log u =a + b*age .
                   1024:   This is the basic analysis of mortality and should be done before any
                   1025:   other analysis, in order to test if the mortality estimated from the
                   1026:   cross-longitudinal survey is different from the mortality estimated
                   1027:   from other sources like vital statistic data.
                   1028: 
                   1029:   The same imach parameter file can be used but the option for mle should be -3.
                   1030: 
                   1031:   Agnès, who wrote this part of the code, tried to keep most of the
                   1032:   former routines in order to include the new code within the former code.
                   1033: 
                   1034:   The output is very simple: only an estimate of the intercept and of
                   1035:   the slope with 95% confident intervals.
                   1036: 
                   1037:   Current limitations:
                   1038:   A) Even if you enter covariates, i.e. with the
                   1039:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                   1040:   B) There is no computation of Life Expectancy nor Life Table.
                   1041: 
                   1042:   Revision 1.97  2004/02/20 13:25:42  lievre
                   1043:   Version 0.96d. Population forecasting command line is (temporarily)
                   1044:   suppressed.
                   1045: 
                   1046:   Revision 1.96  2003/07/15 15:38:55  brouard
                   1047:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                   1048:   rewritten within the same printf. Workaround: many printfs.
                   1049: 
                   1050:   Revision 1.95  2003/07/08 07:54:34  brouard
                   1051:   * imach.c (Repository):
                   1052:   (Repository): Using imachwizard code to output a more meaningful covariance
                   1053:   matrix (cov(a12,c31) instead of numbers.
                   1054: 
                   1055:   Revision 1.94  2003/06/27 13:00:02  brouard
                   1056:   Just cleaning
                   1057: 
                   1058:   Revision 1.93  2003/06/25 16:33:55  brouard
                   1059:   (Module): On windows (cygwin) function asctime_r doesn't
                   1060:   exist so I changed back to asctime which exists.
                   1061:   (Module): Version 0.96b
                   1062: 
                   1063:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1064:   (Module): On windows (cygwin) function asctime_r doesn't
                   1065:   exist so I changed back to asctime which exists.
                   1066: 
                   1067:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1068:   * imach.c (Repository): Duplicated warning errors corrected.
                   1069:   (Repository): Elapsed time after each iteration is now output. It
                   1070:   helps to forecast when convergence will be reached. Elapsed time
                   1071:   is stamped in powell.  We created a new html file for the graphs
                   1072:   concerning matrix of covariance. It has extension -cov.htm.
                   1073: 
                   1074:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1075:   (Module): Some bugs corrected for windows. Also, when
                   1076:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1077:   of the covariance matrix to be input.
                   1078: 
                   1079:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1080:   (Module): Some bugs corrected for windows. Also, when
                   1081:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1082:   of the covariance matrix to be input.
                   1083: 
                   1084:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1085:   * 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.
                   1086: 
                   1087:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1088:   Version 0.96
                   1089: 
                   1090:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1091:   (Module): Change position of html and gnuplot routines and added
                   1092:   routine fileappend.
                   1093: 
                   1094:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1095:   * imach.c (Repository): Check when date of death was earlier that
                   1096:   current date of interview. It may happen when the death was just
                   1097:   prior to the death. In this case, dh was negative and likelihood
                   1098:   was wrong (infinity). We still send an "Error" but patch by
                   1099:   assuming that the date of death was just one stepm after the
                   1100:   interview.
                   1101:   (Repository): Because some people have very long ID (first column)
                   1102:   we changed int to long in num[] and we added a new lvector for
                   1103:   memory allocation. But we also truncated to 8 characters (left
                   1104:   truncation)
                   1105:   (Repository): No more line truncation errors.
                   1106: 
                   1107:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1108:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1109:   place. It differs from routine "prevalence" which may be called
                   1110:   many times. Probs is memory consuming and must be used with
                   1111:   parcimony.
                   1112:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1113: 
                   1114:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1115:   *** empty log message ***
                   1116: 
                   1117:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1118:   Add log in  imach.c and  fullversion number is now printed.
                   1119: 
                   1120: */
                   1121: /*
                   1122:    Interpolated Markov Chain
                   1123: 
                   1124:   Short summary of the programme:
                   1125:   
                   1126:   This program computes Healthy Life Expectancies or State-specific
                   1127:   (if states aren't health statuses) Expectancies from
                   1128:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1129: 
                   1130:   -1- a first survey ("cross") where individuals from different ages
                   1131:   are interviewed on their health status or degree of disability (in
                   1132:   the case of a health survey which is our main interest)
                   1133: 
                   1134:   -2- at least a second wave of interviews ("longitudinal") which
                   1135:   measure each change (if any) in individual health status.  Health
                   1136:   expectancies are computed from the time spent in each health state
                   1137:   according to a model. More health states you consider, more time is
                   1138:   necessary to reach the Maximum Likelihood of the parameters involved
                   1139:   in the model.  The simplest model is the multinomial logistic model
                   1140:   where pij is the probability to be observed in state j at the second
                   1141:   wave conditional to be observed in state i at the first
                   1142:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1143:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1144:   have a more complex model than "constant and age", you should modify
                   1145:   the program where the markup *Covariates have to be included here
                   1146:   again* invites you to do it.  More covariates you add, slower the
                   1147:   convergence.
                   1148: 
                   1149:   The advantage of this computer programme, compared to a simple
                   1150:   multinomial logistic model, is clear when the delay between waves is not
                   1151:   identical for each individual. Also, if a individual missed an
                   1152:   intermediate interview, the information is lost, but taken into
                   1153:   account using an interpolation or extrapolation.  
                   1154: 
                   1155:   hPijx is the probability to be observed in state i at age x+h
                   1156:   conditional to the observed state i at age x. The delay 'h' can be
                   1157:   split into an exact number (nh*stepm) of unobserved intermediate
                   1158:   states. This elementary transition (by month, quarter,
                   1159:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1160:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1161:   and the contribution of each individual to the likelihood is simply
                   1162:   hPijx.
                   1163: 
                   1164:   Also this programme outputs the covariance matrix of the parameters but also
                   1165:   of the life expectancies. It also computes the period (stable) prevalence.
                   1166: 
                   1167: Back prevalence and projections:
                   1168: 
                   1169:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1170:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1171:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1172:    mobilavproj)
                   1173: 
                   1174:     Computes the back prevalence limit for any combination of
                   1175:     covariate values k at any age between ageminpar and agemaxpar and
                   1176:     returns it in **bprlim. In the loops,
                   1177: 
                   1178:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1179:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1180: 
                   1181:    - hBijx Back Probability to be in state i at age x-h being in j at x
                   1182:    Computes for any combination of covariates k and any age between bage and fage 
                   1183:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1184:                        oldm=oldms;savm=savms;
                   1185: 
                   1186:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
                   1187:      Computes the transition matrix starting at age 'age' over
                   1188:      'nhstepm*hstepm*stepm' months (i.e. until
                   1189:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   1190:      nhstepm*hstepm matrices. 
                   1191: 
                   1192:      Returns p3mat[i][j][h] after calling
                   1193:      p3mat[i][j][h]=matprod2(newm,
                   1194:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1195:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1196:      oldm);
                   1197: 
                   1198: Important routines
                   1199: 
                   1200: - func (or funcone), computes logit (pij) distinguishing
                   1201:   o fixed variables (single or product dummies or quantitative);
                   1202:   o varying variables by:
                   1203:    (1) wave (single, product dummies, quantitative), 
                   1204:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1205:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1206:        % varying dummy (not done) or quantitative (not done);
                   1207: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1208:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1209: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
                   1210:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
                   1211:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
                   1212: 
                   1213: 
                   1214:   
                   1215:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1216:            Institut national d'études démographiques, Paris.
                   1217:   This software have been partly granted by Euro-REVES, a concerted action
                   1218:   from the European Union.
                   1219:   It is copyrighted identically to a GNU software product, ie programme and
                   1220:   software can be distributed freely for non commercial use. Latest version
                   1221:   can be accessed at http://euroreves.ined.fr/imach .
                   1222: 
                   1223:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1224:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1225:   
                   1226:   **********************************************************************/
                   1227: /*
                   1228:   main
                   1229:   read parameterfile
                   1230:   read datafile
                   1231:   concatwav
                   1232:   freqsummary
                   1233:   if (mle >= 1)
                   1234:     mlikeli
                   1235:   print results files
                   1236:   if mle==1 
                   1237:      computes hessian
                   1238:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1239:       begin-prev-date,...
                   1240:   open gnuplot file
                   1241:   open html file
                   1242:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1243:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1244:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1245:     freexexit2 possible for memory heap.
                   1246: 
                   1247:   h Pij x                         | pij_nom  ficrestpij
                   1248:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1249:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1250:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1251: 
                   1252:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1253:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1254:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1255:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1256:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1257: 
                   1258:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1259:   health expectancies
                   1260:   Variance-covariance of DFLE
                   1261:   prevalence()
                   1262:    movingaverage()
                   1263:   varevsij() 
                   1264:   if popbased==1 varevsij(,popbased)
                   1265:   total life expectancies
                   1266:   Variance of period (stable) prevalence
                   1267:  end
                   1268: */
                   1269: 
                   1270: /* #define DEBUG */
                   1271: /* #define DEBUGBRENT */
                   1272: /* #define DEBUGLINMIN */
                   1273: /* #define DEBUGHESS */
                   1274: #define DEBUGHESSIJ
                   1275: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
                   1276: #define POWELL /* Instead of NLOPT */
                   1277: #define POWELLNOF3INFF1TEST /* Skip test */
                   1278: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1279: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
                   1280: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
                   1281: 
                   1282: #include <math.h>
                   1283: #include <stdio.h>
                   1284: #include <stdlib.h>
                   1285: #include <string.h>
                   1286: #include <ctype.h>
                   1287: 
                   1288: #ifdef _WIN32
                   1289: #include <io.h>
                   1290: #include <windows.h>
                   1291: #include <tchar.h>
                   1292: #else
                   1293: #include <unistd.h>
                   1294: #endif
                   1295: 
                   1296: #include <limits.h>
                   1297: #include <sys/types.h>
                   1298: 
                   1299: #if defined(__GNUC__)
                   1300: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1301: #endif
                   1302: 
                   1303: #include <sys/stat.h>
                   1304: #include <errno.h>
                   1305: /* extern int errno; */
                   1306: 
                   1307: /* #ifdef LINUX */
                   1308: /* #include <time.h> */
                   1309: /* #include "timeval.h" */
                   1310: /* #else */
                   1311: /* #include <sys/time.h> */
                   1312: /* #endif */
                   1313: 
                   1314: #include <time.h>
                   1315: 
                   1316: #ifdef GSL
                   1317: #include <gsl/gsl_errno.h>
                   1318: #include <gsl/gsl_multimin.h>
                   1319: #endif
                   1320: 
                   1321: 
                   1322: #ifdef NLOPT
                   1323: #include <nlopt.h>
                   1324: typedef struct {
                   1325:   double (* function)(double [] );
                   1326: } myfunc_data ;
                   1327: #endif
                   1328: 
                   1329: /* #include <libintl.h> */
                   1330: /* #define _(String) gettext (String) */
                   1331: 
                   1332: #define MAXLINE 16384 /* Was 256 and 1024 and 2048. Overflow with 312 with 2 states and 4 covariates. Should be ok */
                   1333: 
                   1334: #define GNUPLOTPROGRAM "gnuplot"
                   1335: #define GNUPLOTVERSION 5.1
                   1336: double gnuplotversion=GNUPLOTVERSION;
                   1337: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                   1338: #define FILENAMELENGTH 256
                   1339: 
                   1340: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1341: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1342: 
                   1343: #define MAXPARM 216 /**< Maximum number of parameters for the optimization was 128 */
                   1344: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
                   1345: 
                   1346: #define NINTERVMAX 8
                   1347: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1348: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                   1349: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
                   1350: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   1351: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1352: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
                   1353: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
                   1354: #define YEARM 12. /**< Number of months per year */
                   1355: /* #define AGESUP 130 */
                   1356: /* #define AGESUP 150 */
                   1357: #define AGESUP 200
                   1358: #define AGEINF 0
                   1359: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
                   1360: #define AGEBASE 40
                   1361: #define AGEOVERFLOW 1.e20
                   1362: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
                   1363: #ifdef _WIN32
                   1364: #define DIRSEPARATOR '\\'
                   1365: #define CHARSEPARATOR "\\"
                   1366: #define ODIRSEPARATOR '/'
                   1367: #else
                   1368: #define DIRSEPARATOR '/'
                   1369: #define CHARSEPARATOR "/"
                   1370: #define ODIRSEPARATOR '\\'
                   1371: #endif
                   1372: 
1.2     ! brouard  1373: /* $Id: imachprax.c,v 1.1 2023/01/31 09:24:19 brouard Exp $ */
1.1       brouard  1374: /* $State: Exp $ */
                   1375: #include "version.h"
                   1376: char version[]=__IMACH_VERSION__;
1.2     ! brouard  1377: char copyright[]="April 2023,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015-2020, Nihon University 2021-202, INED 2000-2022";
        !          1378: char fullversion[]="$Revision: 1.353 $ $Date: 2023/05/08 18:48:22 $"; 
1.1       brouard  1379: char strstart[80];
                   1380: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
                   1381: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
                   1382: int debugILK=0; /* debugILK is set by a #d in a comment line */
                   1383: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
                   1384: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1385: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   1386: int cptcovn=0; /**< cptcovn decodemodel: number of covariates k of the models excluding age*products =6 and age*age but including products */
                   1387: int cptcovt=0; /**< cptcovt: total number of covariates of the model (2) nbocc(+)+1 = 8 excepting constant and age and age*age */
                   1388: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1389: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
                   1390: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1391: int cptcovprodage=0; /**< Number of fixed covariates with age: V3*age or V2*V3*age 1 */
                   1392: int cptcovprodvage=0; /**< Number of varying covariates with age: V7*age or V7*V6*age */
                   1393: int cptcovdageprod=0; /**< Number of doubleproducts with age, since 0.99r44 only: age*Vn*Vm for gnuplot printing*/
                   1394: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                   1395: 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) */
                   1396: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1397: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
                   1398: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
                   1399: 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 */
                   1400: 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 */
                   1401: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (single or product, dummy or quantitative) in the model */
                   1402: 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 */
                   1403: int nsd=0; /**< Total number of single dummy variables (output) */
                   1404: int nsq=0; /**< Total number of single quantitative variables (output) */
                   1405: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
                   1406: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
                   1407: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1408: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
                   1409: int cptcov=0; /* Working variable */
                   1410: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
                   1411: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
                   1412: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
                   1413: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
                   1414: int nlstate=2; /* Number of live states */
                   1415: int ndeath=1; /* Number of dead states */
                   1416: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
                   1417: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1418: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
                   1419: int popbased=0;
                   1420: 
                   1421: int *wav; /* Number of waves for this individuual 0 is possible */
                   1422: int maxwav=0; /* Maxim number of waves */
                   1423: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1424: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1425: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
                   1426:                   to the likelihood and the sum of weights (done by funcone)*/
                   1427: int mle=1, weightopt=0;
                   1428: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1429: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1430: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1431:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
                   1432: int countcallfunc=0;  /* Count the number of calls to func */
                   1433: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1434: 
                   1435: double jmean=1; /* Mean space between 2 waves */
                   1436: double **matprod2(); /* test */
                   1437: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1438: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
                   1439: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1440: 
                   1441: /*FILE *fic ; */ /* Used in readdata only */
                   1442: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
                   1443: FILE *ficlog, *ficrespow;
                   1444: int globpr=0; /* Global variable for printing or not */
                   1445: double fretone; /* Only one call to likelihood */
                   1446: long ipmx=0; /* Number of contributions */
                   1447: double sw; /* Sum of weights */
                   1448: char filerespow[FILENAMELENGTH];
                   1449: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1450: FILE *ficresilk;
                   1451: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1452: FILE *ficresprobmorprev;
                   1453: FILE *fichtm, *fichtmcov; /* Html File */
                   1454: FILE *ficreseij;
                   1455: char filerese[FILENAMELENGTH];
                   1456: FILE *ficresstdeij;
                   1457: char fileresstde[FILENAMELENGTH];
                   1458: FILE *ficrescveij;
                   1459: char filerescve[FILENAMELENGTH];
                   1460: FILE  *ficresvij;
                   1461: char fileresv[FILENAMELENGTH];
                   1462: 
                   1463: char title[MAXLINE];
                   1464: char model[MAXLINE]; /**< The model line */
                   1465: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
                   1466: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1467: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1468: char command[FILENAMELENGTH];
                   1469: int  outcmd=0;
                   1470: 
                   1471: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
                   1472: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
                   1473: char filelog[FILENAMELENGTH]; /* Log file */
                   1474: char filerest[FILENAMELENGTH];
                   1475: char fileregp[FILENAMELENGTH];
                   1476: char popfile[FILENAMELENGTH];
                   1477: 
                   1478: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1479: 
                   1480: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1481: /* struct timezone tzp; */
                   1482: /* extern int gettimeofday(); */
                   1483: struct tm tml, *gmtime(), *localtime();
                   1484: 
                   1485: extern time_t time();
                   1486: 
                   1487: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1488: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
1.2     ! brouard  1489: time_t   rlast_btime; /* raw time */
1.1       brouard  1490: struct tm tm;
                   1491: 
                   1492: char strcurr[80], strfor[80];
                   1493: 
                   1494: char *endptr;
                   1495: long lval;
                   1496: double dval;
                   1497: 
                   1498: #define NR_END 1
                   1499: #define FREE_ARG char*
                   1500: #define FTOL 1.0e-10
                   1501: 
                   1502: #define NRANSI 
                   1503: #define ITMAX 200
                   1504: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
                   1505: 
                   1506: #define TOL 2.0e-4 
                   1507: 
                   1508: #define CGOLD 0.3819660 
                   1509: #define ZEPS 1.0e-10 
                   1510: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1511: 
                   1512: #define GOLD 1.618034 
                   1513: #define GLIMIT 100.0 
                   1514: #define TINY 1.0e-20 
                   1515: 
                   1516: static double maxarg1,maxarg2;
                   1517: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1518: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1519:   
                   1520: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1521: #define rint(a) floor(a+0.5)
                   1522: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
                   1523: #define mytinydouble 1.0e-16
                   1524: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1525: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1526: /* static double dsqrarg; */
                   1527: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
                   1528: static double sqrarg;
                   1529: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1530: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1531: int agegomp= AGEGOMP;
                   1532: 
                   1533: int imx; 
                   1534: int stepm=1;
                   1535: /* Stepm, step in month: minimum step interpolation*/
                   1536: 
                   1537: int estepm;
                   1538: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1539: 
                   1540: int m,nb;
                   1541: long *num;
                   1542: int firstpass=0, lastpass=4,*cod, *cens;
                   1543: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1544:                   covariate for which somebody answered excluding 
                   1545:                   undefined. Usually 2: 0 and 1. */
                   1546: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1547:                             covariate for which somebody answered including 
                   1548:                             undefined. Usually 3: -1, 0 and 1. */
                   1549: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                   1550: double **pmmij, ***probs; /* Global pointer */
                   1551: double ***mobaverage, ***mobaverages; /* New global variable */
                   1552: double **precov; /* New global variable to store for each resultline, values of model covariates given by the resultlines (in order to speed up)  */
                   1553: double *ageexmed,*agecens;
                   1554: double dateintmean=0;
                   1555:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1556:   double anprojf, mprojf, jprojf;
                   1557: 
                   1558:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1559:   double anbackf, mbackf, jbackf;
                   1560:   double jintmean,mintmean,aintmean;  
                   1561: double *weight;
                   1562: int **s; /* Status */
                   1563: double *agedc;
                   1564: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
                   1565:                  * covar=matrix(0,NCOVMAX,1,n); 
                   1566:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
                   1567: double **coqvar; /* Fixed quantitative covariate nqv */
                   1568: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
                   1569: double ***cotqvar; /* Time varying quantitative covariate itqv */
                   1570: double  idx; 
                   1571: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
                   1572: /* Some documentation */
                   1573:       /*   Design original data
                   1574:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1575:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1576:        *                                                             ntv=3     nqtv=1
                   1577:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
                   1578:        * For time varying covariate, quanti or dummies
                   1579:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
                   1580:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
                   1581:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1582:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
                   1583:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
                   1584:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1585:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1586:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1587:        */
                   1588: /* According to the model, more columns can be added to covar by the product of covariates */
                   1589: /* 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
                   1590:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1591:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1592: */
                   1593: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1+V4*V3*age */
                   1594: /*    kmodel  1  2   3    4     5     6    7     8     9    10 */
                   1595: /*Typevar[k]=  0  0   0   2     1    0    2     1     0    3 *//*0 for simple covariate (dummy, quantitative,*/
                   1596:                                                                /* fixed or varying), 1 for age product, 2 for*/
                   1597:                                                                /* product without age, 3 for age and double product   */
                   1598: /*Dummy[k]=    1  0   0   1     3    1    1     2     0     3  *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1599:                                                                 /*(single or product without age), 2 dummy*/
                   1600:                                                                /* with age product, 3 quant with age product*/
                   1601: /*Tvar[k]=     5  4   3   6     5    2    7     1     1     6 */
                   1602: /*    nsd         1   2                               3 */ /* Counting single dummies covar fixed or tv */
                   1603: /*TnsdVar[Tvar]   1   2                               3 */ 
                   1604: /*Tvaraff[nsd]    4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1605: /*TvarsD[nsd]     4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1606: /*TvarsDind[nsd]  2   3                               9 */ /* position K of single dummy cova */
                   1607: /*    nsq      1                     2                  */ /* Counting single quantit tv */
                   1608: /* TvarsQ[k]   5                     2                  */ /* Number of single quantitative cova */
                   1609: /* TvarsQind   1                     6                  */ /* position K of single quantitative cova */
                   1610: /* Tprod[i]=k             1               2             */ /* Position in model of the ith prod without age */
                   1611: /* cptcovage                    1               2         3 */ /* Counting cov*age in the model equation */
                   1612: /* Tage[cptcovage]=k            5               8         10 */ /* Position in the model of ith cov*age */
1.2     ! brouard  1613: /* 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"*/
        !          1614: /*  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}*/
        !          1615: /*  p Tvard[2][1]@21 = {7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0 <repeats 11 times>} */
        !          1616: /* 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}*/
        !          1617: /* 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} */
1.1       brouard  1618: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2               */ /* Position in model of the ith prod without age */
                   1619: /* 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*/
                   1620: /* 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 */
                   1621: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
                   1622: /* Type                    */
                   1623: /* V         1  2  3  4  5 */
                   1624: /*           F  F  V  V  V */
                   1625: /*           D  Q  D  D  Q */
                   1626: /*                         */
                   1627: int *TvarsD;
                   1628: int *TnsdVar;
                   1629: int *TvarsDind;
                   1630: int *TvarsQ;
                   1631: int *TvarsQind;
                   1632: 
                   1633: #define MAXRESULTLINESPONE 10+1
                   1634: int nresult=0;
                   1635: int parameterline=0; /* # of the parameter (type) line */
                   1636: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1637: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1638: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1639: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
                   1640: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1641: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
                   1642: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
                   1643: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   1644: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
                   1645: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
                   1646: 
                   1647: /* 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
                   1648:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1649:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1650: */
                   1651: /* 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 *\/ */
                   1652: 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 */
                   1653: 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 */
                   1654: 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 */
                   1655: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1656: 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 */
                   1657: int *TvarAind; /**< TvarindA[1]=5, TvarAind[2]=8  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1658: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1659: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1660: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1661: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1662: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1663: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1664: 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 */
                   1665: 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 */
                   1666: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1667: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1668: int *TvarVVA; /* We count ncovvt time varying covariates (single or products with age) and put their name into TvarVVA */
                   1669: int *TvarVVAind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1670: int *TvarAVVA; /* We count ALL ncovta time varying covariates (single or products with age) and put their name into TvarVVA */
                   1671: int *TvarAVVAind; /* We count ALL ncovta time varying covariates (single or products without age) and put their name into TvarVV */
                   1672:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   1673:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age */
                   1674:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1675:       /* TvarVV={3,1,3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */        
                   1676:       /* 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 */              
                   1677: int *Tvarsel; /**< Selected covariates for output */
                   1678: double *Tvalsel; /**< Selected modality value of covariate for output */
                   1679: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product, 3 age*Vn*Vm */
                   1680: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1681: 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 */ 
                   1682: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1683: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
                   1684: int *Tage;
                   1685: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
                   1686: 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*/
                   1687: 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*/ 
                   1688: 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  */
                   1689: int *Ndum; /** Freq of modality (tricode */
                   1690: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
                   1691: int **Tvard;
                   1692: int **Tvardk;
                   1693: int *Tprod;/**< Gives the k position of the k1 product */
                   1694: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
                   1695: int *Tposprod; /**< Gives the k1 product from the k position */
                   1696:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1697:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
                   1698: int cptcovprod, *Tvaraff, *invalidvarcomb;
                   1699: double *lsurv, *lpop, *tpop;
                   1700: 
                   1701: #define FD 1; /* Fixed dummy covariate */
                   1702: #define FQ 2; /* Fixed quantitative covariate */
                   1703: #define FP 3; /* Fixed product covariate */
                   1704: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1705: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1706: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1707: #define VD 10; /* Varying dummy covariate */
                   1708: #define VQ 11; /* Varying quantitative covariate */
                   1709: #define VP 12; /* Varying product covariate */
                   1710: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1711: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1712: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1713: #define APFD 16; /* Age product * fixed dummy covariate */
                   1714: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1715: #define APVD 18; /* Age product * varying dummy covariate */
                   1716: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1717: 
                   1718: #define FTYPE 1; /* Fixed covariate */
                   1719: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1720: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1721: 
                   1722: struct kmodel{
                   1723:        int maintype; /* main type */
                   1724:        int subtype; /* subtype */
                   1725: };
                   1726: struct kmodel modell[NCOVMAX];
                   1727: 
                   1728: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1729: double ftolhess; /**< Tolerance for computing hessian */
                   1730: 
                   1731: /**************** split *************************/
                   1732: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1733: {
                   1734:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1735:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1736:   */ 
                   1737:   char *ss;                            /* pointer */
                   1738:   int  l1=0, l2=0;                             /* length counters */
                   1739: 
                   1740:   l1 = strlen(path );                  /* length of path */
                   1741:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1742:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1743:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1744:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1745:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1746:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1747:     /* get current working directory */
                   1748:     /*    extern  char* getcwd ( char *buf , int len);*/
                   1749: #ifdef WIN32
                   1750:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1751: #else
                   1752:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1753: #endif
                   1754:       return( GLOCK_ERROR_GETCWD );
                   1755:     }
                   1756:     /* got dirc from getcwd*/
                   1757:     printf(" DIRC = %s \n",dirc);
                   1758:   } else {                             /* strip directory from path */
                   1759:     ss++;                              /* after this, the filename */
                   1760:     l2 = strlen( ss );                 /* length of filename */
                   1761:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1762:     strcpy( name, ss );                /* save file name */
                   1763:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
                   1764:     dirc[l1-l2] = '\0';                        /* add zero */
                   1765:     printf(" DIRC2 = %s \n",dirc);
                   1766:   }
                   1767:   /* We add a separator at the end of dirc if not exists */
                   1768:   l1 = strlen( dirc );                 /* length of directory */
                   1769:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1770:     dirc[l1] =  DIRSEPARATOR;
                   1771:     dirc[l1+1] = 0; 
                   1772:     printf(" DIRC3 = %s \n",dirc);
                   1773:   }
                   1774:   ss = strrchr( name, '.' );           /* find last / */
                   1775:   if (ss >0){
                   1776:     ss++;
                   1777:     strcpy(ext,ss);                    /* save extension */
                   1778:     l1= strlen( name);
                   1779:     l2= strlen(ss)+1;
                   1780:     strncpy( finame, name, l1-l2);
                   1781:     finame[l1-l2]= 0;
                   1782:   }
                   1783: 
                   1784:   return( 0 );                         /* we're done */
                   1785: }
                   1786: 
                   1787: 
                   1788: /******************************************/
                   1789: 
                   1790: void replace_back_to_slash(char *s, char*t)
                   1791: {
                   1792:   int i;
                   1793:   int lg=0;
                   1794:   i=0;
                   1795:   lg=strlen(t);
                   1796:   for(i=0; i<= lg; i++) {
                   1797:     (s[i] = t[i]);
                   1798:     if (t[i]== '\\') s[i]='/';
                   1799:   }
                   1800: }
                   1801: 
                   1802: char *trimbb(char *out, char *in)
                   1803: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
                   1804:   char *s;
                   1805:   s=out;
                   1806:   while (*in != '\0'){
                   1807:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
                   1808:       in++;
                   1809:     }
                   1810:     *out++ = *in++;
                   1811:   }
                   1812:   *out='\0';
                   1813:   return s;
                   1814: }
                   1815: 
1.2     ! brouard  1816: char *trimbtab(char *out, char *in)
        !          1817: { /* Trim  blanks or tabs in line but keeps first blanks if line starts with blanks */
        !          1818:   char *s;
        !          1819:   s=out;
        !          1820:   while (*in != '\0'){
        !          1821:     while( (*in == ' ' || *in == '\t')){ /* && *(in+1) != '\0'){*/
        !          1822:       in++;
        !          1823:     }
        !          1824:     *out++ = *in++;
        !          1825:   }
        !          1826:   *out='\0';
        !          1827:   return s;
        !          1828: }
        !          1829: 
1.1       brouard  1830: /* char *substrchaine(char *out, char *in, char *chain) */
                   1831: /* { */
                   1832: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1833: /*   char *s, *t; */
                   1834: /*   t=in;s=out; */
                   1835: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1836: /*     *out++ = *in++; */
                   1837: /*   } */
                   1838: 
                   1839: /*   /\* *in matches *chain *\/ */
                   1840: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1841: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1842: /*   } */
                   1843: /*   in--; chain--; */
                   1844: /*   while ( (*in != '\0')){ */
                   1845: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1846: /*     *out++ = *in++; */
                   1847: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1848: /*   } */
                   1849: /*   *out='\0'; */
                   1850: /*   out=s; */
                   1851: /*   return out; */
                   1852: /* } */
                   1853: char *substrchaine(char *out, char *in, char *chain)
                   1854: {
                   1855:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1856:   /* in="V1+V1*age+age*age+V2", chain="+age*age" out="V1+V1*age+V2" */
                   1857: 
                   1858:   char *strloc;
                   1859: 
                   1860:   strcpy (out, in);                   /* out="V1+V1*age+age*age+V2" */
                   1861:   strloc = strstr(out, chain); /* strloc points to out at "+age*age+V2"  */
                   1862:   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" */
                   1863:   if(strloc != NULL){ 
                   1864:     /* will affect out */ /* strloc+strlen(chain)=|+V2 = "V1+V1*age+age*age|+V2" */ /* Will also work in Unicodek */
                   1865:     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)*/
                   1866:     /* equivalent to strcpy (strloc, strloc +strlen(chain)) if no overlap; Copies from "+V2" to V1+V1*age+ */
                   1867:   }
                   1868:   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" */
                   1869:   return out;
                   1870: }
                   1871: 
                   1872: 
                   1873: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1874: {
                   1875:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
                   1876:      and alocc starts after first occurence of char 'occ' : ex cutl(blocc,alocc,"abcdef2ghi2j",'2')
                   1877:      gives alocc="abcdef" and blocc="ghi2j".
                   1878:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1879:   */
                   1880:   char *s, *t;
                   1881:   t=in;s=in;
                   1882:   while ((*in != occ) && (*in != '\0')){
                   1883:     *alocc++ = *in++;
                   1884:   }
                   1885:   if( *in == occ){
                   1886:     *(alocc)='\0';
                   1887:     s=++in;
                   1888:   }
                   1889:  
                   1890:   if (s == t) {/* occ not found */
                   1891:     *(alocc-(in-s))='\0';
                   1892:     in=s;
                   1893:   }
                   1894:   while ( *in != '\0'){
                   1895:     *blocc++ = *in++;
                   1896:   }
                   1897: 
                   1898:   *blocc='\0';
                   1899:   return t;
                   1900: }
                   1901: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1902: {
                   1903:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
                   1904:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1905:      gives blocc="abcdef2ghi" and alocc="j".
                   1906:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1907:   */
                   1908:   char *s, *t;
                   1909:   t=in;s=in;
                   1910:   while (*in != '\0'){
                   1911:     while( *in == occ){
                   1912:       *blocc++ = *in++;
                   1913:       s=in;
                   1914:     }
                   1915:     *blocc++ = *in++;
                   1916:   }
                   1917:   if (s == t) /* occ not found */
                   1918:     *(blocc-(in-s))='\0';
                   1919:   else
                   1920:     *(blocc-(in-s)-1)='\0';
                   1921:   in=s;
                   1922:   while ( *in != '\0'){
                   1923:     *alocc++ = *in++;
                   1924:   }
                   1925: 
                   1926:   *alocc='\0';
                   1927:   return s;
                   1928: }
                   1929: 
                   1930: int nbocc(char *s, char occ)
                   1931: {
                   1932:   int i,j=0;
                   1933:   int lg=20;
                   1934:   i=0;
                   1935:   lg=strlen(s);
                   1936:   for(i=0; i<= lg; i++) {
                   1937:     if  (s[i] == occ ) j++;
                   1938:   }
                   1939:   return j;
                   1940: }
                   1941: 
                   1942: int nboccstr(char *textin, char *chain)
                   1943: {
                   1944:   /* Counts the number of occurence of "chain"  in string textin */
                   1945:   /*  in="+V7*V4+age*V2+age*V3+age*V4"  chain="age" */
                   1946:   char *strloc;
                   1947:   
                   1948:   int i,j=0;
                   1949: 
                   1950:   i=0;
                   1951: 
                   1952:   strloc=textin; /* strloc points to "^+V7*V4+age+..." in textin */
                   1953:   for(;;) {
                   1954:     strloc= strstr(strloc,chain); /* strloc points to first character of chain in textin if found. Example strloc points^ to "+V7*V4+^age" in textin  */
                   1955:     if(strloc != NULL){
                   1956:       strloc = strloc+strlen(chain); /* strloc points to "+V7*V4+age^" in textin */
                   1957:       j++;
                   1958:     }else
                   1959:       break;
                   1960:   }
                   1961:   return j;
                   1962:   
                   1963: }
                   1964: /* void cutv(char *u,char *v, char*t, char occ) */
                   1965: /* { */
                   1966: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1967: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1968: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1969: /*   int i,lg,j,p=0; */
                   1970: /*   i=0; */
                   1971: /*   lg=strlen(t); */
                   1972: /*   for(j=0; j<=lg-1; j++) { */
                   1973: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1974: /*   } */
                   1975: 
                   1976: /*   for(j=0; j<p; j++) { */
                   1977: /*     (u[j] = t[j]); */
                   1978: /*   } */
                   1979: /*      u[p]='\0'; */
                   1980: 
                   1981: /*    for(j=0; j<= lg; j++) { */
                   1982: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1983: /*   } */
                   1984: /* } */
                   1985: 
                   1986: #ifdef _WIN32
                   1987: char * strsep(char **pp, const char *delim)
                   1988: {
                   1989:   char *p, *q;
                   1990:          
                   1991:   if ((p = *pp) == NULL)
                   1992:     return 0;
                   1993:   if ((q = strpbrk (p, delim)) != NULL)
                   1994:   {
                   1995:     *pp = q + 1;
                   1996:     *q = '\0';
                   1997:   }
                   1998:   else
                   1999:     *pp = 0;
                   2000:   return p;
                   2001: }
                   2002: #endif
                   2003: 
                   2004: /********************** nrerror ********************/
                   2005: 
                   2006: void nrerror(char error_text[])
                   2007: {
                   2008:   fprintf(stderr,"ERREUR ...\n");
                   2009:   fprintf(stderr,"%s\n",error_text);
                   2010:   exit(EXIT_FAILURE);
                   2011: }
                   2012: /*********************** vector *******************/
                   2013: double *vector(int nl, int nh)
                   2014: {
                   2015:   double *v;
                   2016:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   2017:   if (!v) nrerror("allocation failure in vector");
                   2018:   return v-nl+NR_END;
                   2019: }
                   2020: 
                   2021: /************************ free vector ******************/
                   2022: void free_vector(double*v, int nl, int nh)
                   2023: {
                   2024:   free((FREE_ARG)(v+nl-NR_END));
                   2025: }
                   2026: 
                   2027: /************************ivector *******************************/
                   2028: int *ivector(long nl,long nh)
                   2029: {
                   2030:   int *v;
                   2031:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   2032:   if (!v) nrerror("allocation failure in ivector");
                   2033:   return v-nl+NR_END;
                   2034: }
                   2035: 
                   2036: /******************free ivector **************************/
                   2037: void free_ivector(int *v, long nl, long nh)
                   2038: {
                   2039:   free((FREE_ARG)(v+nl-NR_END));
                   2040: }
                   2041: 
                   2042: /************************lvector *******************************/
                   2043: long *lvector(long nl,long nh)
                   2044: {
                   2045:   long *v;
                   2046:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   2047:   if (!v) nrerror("allocation failure in ivector");
                   2048:   return v-nl+NR_END;
                   2049: }
                   2050: 
                   2051: /******************free lvector **************************/
                   2052: void free_lvector(long *v, long nl, long nh)
                   2053: {
                   2054:   free((FREE_ARG)(v+nl-NR_END));
                   2055: }
                   2056: 
                   2057: /******************* imatrix *******************************/
                   2058: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   2059:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   2060: { 
                   2061:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   2062:   int **m; 
                   2063:   
                   2064:   /* allocate pointers to rows */ 
                   2065:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   2066:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   2067:   m += NR_END; 
                   2068:   m -= nrl; 
                   2069:   
                   2070:   
                   2071:   /* allocate rows and set pointers to them */ 
                   2072:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   2073:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   2074:   m[nrl] += NR_END; 
                   2075:   m[nrl] -= ncl; 
                   2076:   
                   2077:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   2078:   
                   2079:   /* return pointer to array of pointers to rows */ 
                   2080:   return m; 
                   2081: } 
                   2082: 
                   2083: /****************** free_imatrix *************************/
                   2084: void free_imatrix(m,nrl,nrh,ncl,nch)
                   2085:       int **m;
                   2086:       long nch,ncl,nrh,nrl; 
                   2087:      /* free an int matrix allocated by imatrix() */ 
                   2088: { 
                   2089:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   2090:   free((FREE_ARG) (m+nrl-NR_END)); 
                   2091: } 
                   2092: 
                   2093: /******************* matrix *******************************/
                   2094: double **matrix(long nrl, long nrh, long ncl, long nch)
                   2095: {
                   2096:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   2097:   double **m;
                   2098: 
                   2099:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2100:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2101:   m += NR_END;
                   2102:   m -= nrl;
                   2103: 
                   2104:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2105:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2106:   m[nrl] += NR_END;
                   2107:   m[nrl] -= ncl;
                   2108: 
                   2109:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2110:   return m;
                   2111:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2112: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2113: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
                   2114:    */
                   2115: }
                   2116: 
                   2117: /*************************free matrix ************************/
                   2118: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2119: {
                   2120:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2121:   free((FREE_ARG)(m+nrl-NR_END));
                   2122: }
                   2123: 
                   2124: /******************* ma3x *******************************/
                   2125: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2126: {
                   2127:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2128:   double ***m;
                   2129: 
                   2130:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2131:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2132:   m += NR_END;
                   2133:   m -= nrl;
                   2134: 
                   2135:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2136:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2137:   m[nrl] += NR_END;
                   2138:   m[nrl] -= ncl;
                   2139: 
                   2140:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2141: 
                   2142:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2143:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2144:   m[nrl][ncl] += NR_END;
                   2145:   m[nrl][ncl] -= nll;
                   2146:   for (j=ncl+1; j<=nch; j++) 
                   2147:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2148:   
                   2149:   for (i=nrl+1; i<=nrh; i++) {
                   2150:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2151:     for (j=ncl+1; j<=nch; j++) 
                   2152:       m[i][j]=m[i][j-1]+nlay;
                   2153:   }
                   2154:   return m; 
                   2155:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2156:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2157:   */
                   2158: }
                   2159: 
                   2160: /*************************free ma3x ************************/
                   2161: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2162: {
                   2163:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2164:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2165:   free((FREE_ARG)(m+nrl-NR_END));
                   2166: }
                   2167: 
                   2168: /*************** function subdirf ***********/
                   2169: char *subdirf(char fileres[])
                   2170: {
                   2171:   /* Caution optionfilefiname is hidden */
                   2172:   strcpy(tmpout,optionfilefiname);
                   2173:   strcat(tmpout,"/"); /* Add to the right */
                   2174:   strcat(tmpout,fileres);
                   2175:   return tmpout;
                   2176: }
                   2177: 
                   2178: /*************** function subdirf2 ***********/
                   2179: char *subdirf2(char fileres[], char *preop)
                   2180: {
                   2181:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2182:  Errors in subdirf, 2, 3 while printing tmpout is
                   2183:  rewritten within the same printf. Workaround: many printfs */
                   2184:   /* Caution optionfilefiname is hidden */
                   2185:   strcpy(tmpout,optionfilefiname);
                   2186:   strcat(tmpout,"/");
                   2187:   strcat(tmpout,preop);
                   2188:   strcat(tmpout,fileres);
                   2189:   return tmpout;
                   2190: }
                   2191: 
                   2192: /*************** function subdirf3 ***********/
                   2193: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2194: {
                   2195:   
                   2196:   /* Caution optionfilefiname is hidden */
                   2197:   strcpy(tmpout,optionfilefiname);
                   2198:   strcat(tmpout,"/");
                   2199:   strcat(tmpout,preop);
                   2200:   strcat(tmpout,preop2);
                   2201:   strcat(tmpout,fileres);
                   2202:   return tmpout;
                   2203: }
                   2204:  
                   2205: /*************** function subdirfext ***********/
                   2206: char *subdirfext(char fileres[], char *preop, char *postop)
                   2207: {
                   2208:   
                   2209:   strcpy(tmpout,preop);
                   2210:   strcat(tmpout,fileres);
                   2211:   strcat(tmpout,postop);
                   2212:   return tmpout;
                   2213: }
                   2214: 
                   2215: /*************** function subdirfext3 ***********/
                   2216: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2217: {
                   2218:   
                   2219:   /* Caution optionfilefiname is hidden */
                   2220:   strcpy(tmpout,optionfilefiname);
                   2221:   strcat(tmpout,"/");
                   2222:   strcat(tmpout,preop);
                   2223:   strcat(tmpout,fileres);
                   2224:   strcat(tmpout,postop);
                   2225:   return tmpout;
                   2226: }
                   2227:  
                   2228: char *asc_diff_time(long time_sec, char ascdiff[])
                   2229: {
                   2230:   long sec_left, days, hours, minutes;
                   2231:   days = (time_sec) / (60*60*24);
                   2232:   sec_left = (time_sec) % (60*60*24);
                   2233:   hours = (sec_left) / (60*60) ;
                   2234:   sec_left = (sec_left) %(60*60);
                   2235:   minutes = (sec_left) /60;
                   2236:   sec_left = (sec_left) % (60);
                   2237:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2238:   return ascdiff;
                   2239: }
                   2240: 
                   2241: /***************** f1dim *************************/
                   2242: extern int ncom; 
                   2243: extern double *pcom,*xicom;
                   2244: extern double (*nrfunc)(double []); 
                   2245:  
                   2246: double f1dim(double x) 
                   2247: { 
                   2248:   int j; 
                   2249:   double f;
                   2250:   double *xt; 
                   2251:  
                   2252:   xt=vector(1,ncom); 
                   2253:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2254:   f=(*nrfunc)(xt); 
                   2255:   free_vector(xt,1,ncom); 
                   2256:   return f; 
                   2257: } 
                   2258: 
                   2259: /*****************brent *************************/
                   2260: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
                   2261: {
                   2262:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2263:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2264:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2265:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2266:    * returned function value. 
                   2267:   */
                   2268:   int iter; 
                   2269:   double a,b,d,etemp;
                   2270:   double fu=0,fv,fw,fx;
                   2271:   double ftemp=0.;
                   2272:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2273:   double e=0.0; 
                   2274:  
                   2275:   a=(ax < cx ? ax : cx); 
                   2276:   b=(ax > cx ? ax : cx); 
                   2277:   x=w=v=bx; 
                   2278:   fw=fv=fx=(*f)(x); 
                   2279:   for (iter=1;iter<=ITMAX;iter++) { 
                   2280:     xm=0.5*(a+b); 
                   2281:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2282:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2283:     printf(".");fflush(stdout);
                   2284:     fprintf(ficlog,".");fflush(ficlog);
                   2285: #ifdef DEBUGBRENT
                   2286:     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);
                   2287:     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);
                   2288:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2289: #endif
                   2290:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2291:       *xmin=x; 
                   2292:       return fx; 
                   2293:     } 
                   2294:     ftemp=fu;
                   2295:     if (fabs(e) > tol1) { 
                   2296:       r=(x-w)*(fx-fv); 
                   2297:       q=(x-v)*(fx-fw); 
                   2298:       p=(x-v)*q-(x-w)*r; 
                   2299:       q=2.0*(q-r); 
                   2300:       if (q > 0.0) p = -p; 
                   2301:       q=fabs(q); 
                   2302:       etemp=e; 
                   2303:       e=d; 
                   2304:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   2305:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2306:       else { 
                   2307:                                d=p/q; 
                   2308:                                u=x+d; 
                   2309:                                if (u-a < tol2 || b-u < tol2) 
                   2310:                                        d=SIGN(tol1,xm-x); 
                   2311:       } 
                   2312:     } else { 
                   2313:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2314:     } 
                   2315:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2316:     fu=(*f)(u); 
                   2317:     if (fu <= fx) { 
                   2318:       if (u >= x) a=x; else b=x; 
                   2319:       SHFT(v,w,x,u) 
                   2320:       SHFT(fv,fw,fx,fu) 
                   2321:     } else { 
                   2322:       if (u < x) a=u; else b=u; 
                   2323:       if (fu <= fw || w == x) { 
                   2324:                                v=w; 
                   2325:                                w=u; 
                   2326:                                fv=fw; 
                   2327:                                fw=fu; 
                   2328:       } else if (fu <= fv || v == x || v == w) { 
                   2329:                                v=u; 
                   2330:                                fv=fu; 
                   2331:       } 
                   2332:     } 
                   2333:   } 
                   2334:   nrerror("Too many iterations in brent"); 
                   2335:   *xmin=x; 
                   2336:   return fx; 
                   2337: } 
                   2338: 
                   2339: /****************** mnbrak ***********************/
                   2340: 
                   2341: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2342:            double (*func)(double)) 
                   2343: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2344: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2345: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2346: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2347:    */
                   2348:   double ulim,u,r,q, dum;
                   2349:   double fu; 
                   2350: 
                   2351:   double scale=10.;
                   2352:   int iterscale=0;
                   2353: 
                   2354:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2355:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2356: 
                   2357: 
                   2358:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2359:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2360:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2361:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2362:   /* } */
                   2363: 
                   2364:   if (*fb > *fa) { 
                   2365:     SHFT(dum,*ax,*bx,dum) 
                   2366:     SHFT(dum,*fb,*fa,dum) 
                   2367:   } 
                   2368:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2369:   *fc=(*func)(*cx); 
                   2370: #ifdef DEBUG
                   2371:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2372:   fprintf(ficlog,"mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2373: #endif
                   2374:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc. If fc=inf it exits and if flat fb=fc it exits too.*/
                   2375:     r=(*bx-*ax)*(*fb-*fc); 
                   2376:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
                   2377:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
                   2378:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2379:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2380:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
                   2381:       fu=(*func)(u); 
                   2382: #ifdef DEBUG
                   2383:       /* f(x)=A(x-u)**2+f(u) */
                   2384:       double A, fparabu; 
                   2385:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2386:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2387:       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);
                   2388:       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);
                   2389:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2390:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2391:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2392:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
                   2393: #endif 
                   2394: #ifdef MNBRAKORIGINAL
                   2395: #else
                   2396: /*       if (fu > *fc) { */
                   2397: /* #ifdef DEBUG */
                   2398: /*       printf("mnbrak4  fu > fc \n"); */
                   2399: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2400: /* #endif */
                   2401: /*     /\* 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 *\\/  *\/ */
                   2402: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2403: /*     dum=u; /\* Shifting c and u *\/ */
                   2404: /*     u = *cx; */
                   2405: /*     *cx = dum; */
                   2406: /*     dum = fu; */
                   2407: /*     fu = *fc; */
                   2408: /*     *fc =dum; */
                   2409: /*       } else { /\* end *\/ */
                   2410: /* #ifdef DEBUG */
                   2411: /*       printf("mnbrak3  fu < fc \n"); */
                   2412: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2413: /* #endif */
                   2414: /*     dum=u; /\* Shifting c and u *\/ */
                   2415: /*     u = *cx; */
                   2416: /*     *cx = dum; */
                   2417: /*     dum = fu; */
                   2418: /*     fu = *fc; */
                   2419: /*     *fc =dum; */
                   2420: /*       } */
                   2421: #ifdef DEBUGMNBRAK
                   2422:                 double A, fparabu; 
                   2423:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2424:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2425:      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);
                   2426:      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);
                   2427: #endif
                   2428:       dum=u; /* Shifting c and u */
                   2429:       u = *cx;
                   2430:       *cx = dum;
                   2431:       dum = fu;
                   2432:       fu = *fc;
                   2433:       *fc =dum;
                   2434: #endif
                   2435:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
                   2436: #ifdef DEBUG
                   2437:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2438:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2439: #endif
                   2440:       fu=(*func)(u); 
                   2441:       if (fu < *fc) { 
                   2442: #ifdef DEBUG
                   2443:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2444:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2445: #endif
                   2446:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2447:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2448: #ifdef DEBUG
                   2449:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
                   2450: #endif
                   2451:       } 
                   2452:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
                   2453: #ifdef DEBUG
                   2454:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2455:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2456: #endif
                   2457:       u=ulim; 
                   2458:       fu=(*func)(u); 
                   2459:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2460: #ifdef DEBUG
                   2461:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2462:       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);
                   2463: #endif
                   2464:       u=(*cx)+GOLD*(*cx-*bx); 
                   2465:       fu=(*func)(u); 
                   2466: #ifdef DEBUG
                   2467:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2468:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2469: #endif
                   2470:     } /* end tests */
                   2471:     SHFT(*ax,*bx,*cx,u) 
                   2472:     SHFT(*fa,*fb,*fc,fu) 
                   2473: #ifdef DEBUG
                   2474:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2475:       fprintf(ficlog, "\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2476: #endif
                   2477:   } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
                   2478: } 
                   2479: 
                   2480: /*************** linmin ************************/
                   2481: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2482: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2483: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2484: the value of func at the returned location p . This is actually all accomplished by calling the
                   2485: routines mnbrak and brent .*/
                   2486: int ncom; 
                   2487: double *pcom,*xicom;
                   2488: double (*nrfunc)(double []); 
                   2489:  
                   2490: #ifdef LINMINORIGINAL
                   2491: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   2492: #else
                   2493: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2494: #endif
                   2495: { 
                   2496:   double brent(double ax, double bx, double cx, 
                   2497:               double (*f)(double), double tol, double *xmin); 
                   2498:   double f1dim(double x); 
                   2499:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2500:              double *fc, double (*func)(double)); 
                   2501:   int j; 
                   2502:   double xx,xmin,bx,ax; 
                   2503:   double fx,fb,fa;
                   2504: 
                   2505: #ifdef LINMINORIGINAL
                   2506: #else
                   2507:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2508: #endif
                   2509:   
                   2510:   ncom=n; 
                   2511:   pcom=vector(1,n); 
                   2512:   xicom=vector(1,n); 
                   2513:   nrfunc=func; 
                   2514:   for (j=1;j<=n;j++) { 
                   2515:     pcom[j]=p[j]; 
                   2516:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
                   2517:   } 
                   2518: 
                   2519: #ifdef LINMINORIGINAL
                   2520:   xx=1.;
                   2521: #else
                   2522:   axs=0.0;
                   2523:   xxs=1.;
                   2524:   do{
                   2525:     xx= xxs;
                   2526: #endif
                   2527:     ax=0.;
                   2528:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2529:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2530:     /* 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))   */
                   2531:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2532:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2533:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2534:     /* 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]]*/
                   2535: #ifdef LINMINORIGINAL
                   2536: #else
                   2537:     if (fx != fx){
                   2538:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2539:                        printf("|");
                   2540:                        fprintf(ficlog,"|");
                   2541: #ifdef DEBUGLINMIN
                   2542:                        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);
                   2543: #endif
                   2544:     }
                   2545:   }while(fx != fx && xxs > 1.e-5);
                   2546: #endif
                   2547:   
                   2548: #ifdef DEBUGLINMIN
                   2549:   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);
                   2550:   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);
                   2551: #endif
                   2552: #ifdef LINMINORIGINAL
                   2553: #else
                   2554:   if(fb == fx){ /* Flat function in the direction */
                   2555:     xmin=xx;
                   2556:     *flat=1;
                   2557:   }else{
                   2558:     *flat=0;
                   2559: #endif
                   2560:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
                   2561:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2562:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2563:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2564:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2565:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
                   2566: #ifdef DEBUG
                   2567:   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);
                   2568:   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);
                   2569: #endif
                   2570: #ifdef LINMINORIGINAL
                   2571: #else
                   2572:                        }
                   2573: #endif
                   2574: #ifdef DEBUGLINMIN
                   2575:   printf("linmin end ");
                   2576:   fprintf(ficlog,"linmin end ");
                   2577: #endif
                   2578:   for (j=1;j<=n;j++) { 
                   2579: #ifdef LINMINORIGINAL
                   2580:     xi[j] *= xmin; 
                   2581: #else
                   2582: #ifdef DEBUGLINMIN
                   2583:     if(xxs <1.0)
                   2584:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2585: #endif
                   2586:     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) */
                   2587: #ifdef DEBUGLINMIN
                   2588:     if(xxs <1.0)
                   2589:       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 );
                   2590: #endif
                   2591: #endif
                   2592:     p[j] += xi[j]; /* Parameters values are updated accordingly */
                   2593:   } 
                   2594: #ifdef DEBUGLINMIN
                   2595:   printf("\n");
                   2596:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
                   2597:   fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
                   2598:   for (j=1;j<=n;j++) { 
                   2599:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2600:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2601:     if(j % ncovmodel == 0){
                   2602:       printf("\n");
                   2603:       fprintf(ficlog,"\n");
                   2604:     }
                   2605:   }
                   2606: #else
                   2607: #endif
                   2608:   free_vector(xicom,1,n); 
                   2609:   free_vector(pcom,1,n); 
                   2610: } 
                   2611: 
                   2612: /**** praxis ****/
1.2     ! brouard  2613: double pythag( double x, double y )
1.1       brouard  2614: 
                   2615: /******************************************************************************/
                   2616: /*
                   2617:   Purpose:
1.2     ! brouard  2618:     R8_HYPOT returns the value of sqrt ( X^2 + Y^2 ).
1.1       brouard  2619:   Licensing:
                   2620:     This code is distributed under the GNU LGPL license.
                   2621:   Modified:
1.2     ! brouard  2622:     26 March 2012
1.1       brouard  2623:   Author:
1.2     ! brouard  2624:     John Burkardt
1.1       brouard  2625:   Parameters:
1.2     ! brouard  2626:     Input, double X, Y, the arguments.
        !          2627:     Output, double R8_HYPOT, the value of sqrt ( X^2 + Y^2 ).
1.1       brouard  2628: */
                   2629: {
1.2     ! brouard  2630:   double a;
        !          2631:   double b;
1.1       brouard  2632:   double value;
                   2633: 
1.2     ! brouard  2634:   if ( fabs ( x ) < fabs ( y ) )  {
        !          2635:     a = fabs ( y );
        !          2636:     b = fabs ( x );
        !          2637:   }  else  {
        !          2638:     a = fabs ( x );
        !          2639:     b = fabs ( y );
1.1       brouard  2640:   }
                   2641: /*
1.2     ! brouard  2642:   A contains the larger value.
1.1       brouard  2643: */
1.2     ! brouard  2644:   if ( a == 0.0 )  {
        !          2645:     value = 0.0;
        !          2646:   }  else  {
        !          2647:     value = a * sqrt ( 1.0 + ( b / a ) * ( b / a ) );
1.1       brouard  2648:   }
                   2649:   return value;
                   2650: }
                   2651: 
1.2     ! brouard  2652: /* void svdcmp(double **a, int m, int n, double w[], double **v)  */
        !          2653: void svdcmp(double **a, int m, int n, double w[]) 
1.1       brouard  2654: {
1.2     ! brouard  2655:   /* Golub 1970 Algol60 */
        !          2656: /*   Computation of the singular values and complete orthogonal decom- */
        !          2657: /* position of a real rectangular matrix A, */
        !          2658: /* A = U diag (q) V^T, U^T U = V^T V =I , */
        !          2659: /*     where the arrays a[1:m, 1:n], u[1:m, 1 :n], v[1:n, 1:n], q[1:n] re- */
        !          2660: /* present A, U, V, q respectively. The actual parameters corresponding */
        !          2661: /* to a, u, v may all be identical unless withu=withv = true . In this */
        !          2662: /* case, the actual parameters corresponding to u and v must differ. */
        !          2663: /* m >= n is assumed; */
        !          2664:   
        !          2665:   /* Simplified (as in praxis) in order to output only V (replacing A), w is the diagonal matrix q  */
        !          2666: 
        !          2667:   
        !          2668:   double pythag(double a, double b); 
        !          2669:   int flag,i,its,j,jj,k,l,nm; 
        !          2670:   double anorm,c,f,g,h,s,scale,x,y,z,*rv1; 
        !          2671:   
        !          2672:   rv1=vector(1,n);
        !          2673:   /* Householder's reduction to bidiagonal form; */
        !          2674:   g=scale=anorm=0.0; 
        !          2675:   for (i=1;i<=n;i++) { 
        !          2676:     l=i+1; 
        !          2677:     rv1[i]=scale*g; 
        !          2678:     g=s=scale=0.0; 
        !          2679:     if (i <= m) { 
        !          2680:       for (k=i;k<=m;k++) scale += fabs(a[k][i]); 
        !          2681:       if (scale) { 
        !          2682:         for (k=i;k<=m;k++) { 
        !          2683:           a[k][i] /= scale; 
        !          2684:           s += a[k][i]*a[k][i]; 
        !          2685:         } 
        !          2686:         f=a[i][i]; 
        !          2687:         g = -SIGN(sqrt(s),f); 
        !          2688:         h=f*g-s; 
        !          2689:         a[i][i]=f-g; 
        !          2690:         for (j=l;j<=n;j++) { 
        !          2691:           for (s=0.0,k=i;k<=m;k++) s += a[k][i]*a[k][j]; 
        !          2692:           f=s/h; 
        !          2693:           for (k=i;k<=m;k++) a[k][j] += f*a[k][i]; 
        !          2694:         } 
        !          2695:         for (k=i;k<=m;k++) a[k][i] *= scale; 
        !          2696:       } 
        !          2697:     } 
        !          2698:     w[i]=scale *g; /* p 411*/
        !          2699:     g=s=scale=0.0; 
        !          2700:     if (i <= m && i != n) { 
        !          2701:       for (k=l;k<=n;k++) scale += fabs(a[i][k]); 
        !          2702:       if (scale) { 
        !          2703:         for (k=l;k<=n;k++) { 
        !          2704:           a[i][k] /= scale; 
        !          2705:           s += a[i][k]*a[i][k]; 
        !          2706:         } 
        !          2707:         f=a[i][l]; 
        !          2708:         g = -SIGN(sqrt(s),f); 
        !          2709:         h=f*g-s; 
        !          2710:         a[i][l]=f-g; 
        !          2711:         for (k=l;k<=n;k++) rv1[k]=a[i][k]/h; 
        !          2712:         for (j=l;j<=m;j++) { 
        !          2713:           for (s=0.0,k=l;k<=n;k++) s += a[j][k]*a[i][k]; 
        !          2714:           for (k=l;k<=n;k++) a[j][k] += s*rv1[k]; 
        !          2715:         } 
        !          2716:         for (k=l;k<=n;k++) a[i][k] *= scale; 
1.1       brouard  2717:       } 
                   2718:     }
1.2     ! brouard  2719:     /* y : = abs(q[i]) +abs(e[i]); if y > x then x : = y */
        !          2720:     /* anorm=DMAX(anorm,(fabs(w[i])+fabs(rv1[i])));  */
        !          2721:     anorm=FMAX(anorm,(fabs(w[i])+fabs(rv1[i]))); 
1.1       brouard  2722:   }
1.2     ! brouard  2723:   /* Comment accumulation of right-hand transformations */
        !          2724:   for (i=n;i>=1;i--) { 
        !          2725:     if (i < n) { 
        !          2726:       if (g) { 
        !          2727:         for (j=l;j<=n;j++) a[j][i]=(a[i][j]/a[i][l])/g; /* Double division to avoid possible underflow. */
        !          2728:         /* for (j=l;j<=n;j++) v[j][i]=(a[i][j]/a[i][l])/g;  */
        !          2729:         for (j=l;j<=n;j++) { 
        !          2730:           /* for (s=0.0,k=l;k<=n;k++) s += a[i][k]*v[k][j];  */
        !          2731:            for (s=0.0,k=l;k<=n;k++) s += a[i][k]*a[k][j];
        !          2732:           /* for (k=l;k<=n;k++) v[k][j] += s*v[k][i];  */
        !          2733:           for (k=l;k<=n;k++) a[k][j] += s*a[k][i]; 
        !          2734:         } 
        !          2735:       } 
        !          2736:       /* for (j=l;j<=n;j++) v[i][j]=v[j][i]=0.0;  */
        !          2737:       for (j=l;j<=n;j++) a[i][j]=a[j][i]=0.0; 
        !          2738:     } 
        !          2739:     /* v[i][i]=1.0;  */
        !          2740:     a[i][i]=1.0; 
        !          2741:     g=rv1[i]; 
        !          2742:     l=i; 
        !          2743:   } 
        !          2744:  /* Comment accumulation of left-hand transformations; */
        !          2745:  /* for (i=IMIN(m,n);i>=1;i--) {  */
        !          2746:  for (i=FMIN(m,n);i>=1;i--) { 
        !          2747:     l=i+1; 
        !          2748:     g=w[i]; 
        !          2749:     for (j=l;j<=n;j++) a[i][j]=0.0; 
        !          2750:     if (g) { 
        !          2751:       g=1.0/g; 
        !          2752:       for (j=l;j<=n;j++) { 
        !          2753:         for (s=0.0,k=l;k<=m;k++) s += a[k][i]*a[k][j]; 
        !          2754:         f=(s/a[i][i])*g; 
        !          2755:         for (k=i;k<=m;k++) a[k][j] += f*a[k][i]; 
        !          2756:       } 
        !          2757:       for (j=i;j<=m;j++) a[j][i] *= g; 
        !          2758:     } else for (j=i;j<=m;j++) a[j][i]=0.0; 
        !          2759:     ++a[i][i]; 
        !          2760:   } 
        !          2761: /* comment diagonalization of the bidiagonal form; */
        !          2762:  for (k=n;k>=1;k--) { 
        !          2763:     for (its=1;its<=30;its++) { /* Loop over singular values, and over allowed iterations. */
        !          2764:       flag=1; 
        !          2765:       for (l=k;l>=1;l--) { /* Test for splitting. */
        !          2766:         nm=l-1;            /* Note that rv1[1] is always zero. */
        !          2767:         if ((double)(fabs(rv1[l])+anorm) == anorm) { 
        !          2768:           flag=0; 
        !          2769:           break; 
        !          2770:         } 
        !          2771:         if ((double)(fabs(w[nm])+anorm) == anorm) break; 
        !          2772:       } 
        !          2773:       if (flag) { 
        !          2774:         c=0.0;    /* Cancellation of rv1[l], if l > 1. */
        !          2775:         s=1.0; 
        !          2776:         for (i=l;i<=k;i++) { 
        !          2777:           f=s*rv1[i]; 
        !          2778:           rv1[i]=c*rv1[i]; 
        !          2779:           if ((double)(fabs(f)+anorm) == anorm) break; 
        !          2780:           g=w[i]; 
        !          2781:           h=pythag(f,g); 
        !          2782:           w[i]=h; 
        !          2783:           h=1.0/h; 
        !          2784:           c=g*h; 
        !          2785:           s = -f*h; 
        !          2786:           for (j=1;j<=m;j++) { 
        !          2787:             y=a[j][nm]; 
        !          2788:             z=a[j][i]; 
        !          2789:             a[j][nm]=y*c+z*s; 
        !          2790:             a[j][i]=z*c-y*s; 
        !          2791:           } 
        !          2792:         } 
        !          2793:       } 
        !          2794:       z=w[k]; 
        !          2795:       if (l == k) { /* Convergence */
        !          2796:         if (z < 0.0) { /* Singular value is made nonnegative. */   
        !          2797:           w[k] = -z;   
        !          2798:           /* for (j=1;j<=n;j++) v[j][k] = -v[j][k];  */
        !          2799:           for (j=1;j<=n;j++) a[j][k] = -a[j][k]; 
        !          2800:         } 
        !          2801:         break; 
        !          2802:       } 
        !          2803:       if (its == 30) nrerror("no convergence in 30 dsvdcmp iterations"); 
        !          2804:       x=w[l];  /* shift from bottom 2 x 2 minor; */
        !          2805:       nm=k-1; 
        !          2806:       y=w[nm]; 
        !          2807:       g=rv1[nm]; 
        !          2808:       h=rv1[k]; 
        !          2809:       f=((y-z)*(y+z)+(g-h)*(g+h))/(2.0*h*y); 
        !          2810:       g=pythag(f,1.0); 
        !          2811:       /* g=dpythag(f,1.0);  */
        !          2812:       f=((x-z)*(x+z)+h*((y/(f+SIGN(g,f)))-h))/x; 
        !          2813:       c=s=1.0;  /* next QR transformation  */
        !          2814:       for (j=l;j<=nm;j++) { 
        !          2815:         i=j+1; 
        !          2816:         g=rv1[i]; 
        !          2817:         y=w[i]; 
        !          2818:         h=s*g; 
        !          2819:         g=c*g; 
        !          2820:         /* z=dpythag(f,h);  */
        !          2821:         z=pythag(f,h); 
        !          2822:         rv1[j]=z; 
        !          2823:         c=f/z; 
        !          2824:         s=h/z; 
        !          2825:         f=x*c+g*s; 
        !          2826:         g = g*c-x*s; 
        !          2827:         h=y*s; 
        !          2828:         y *= c; 
        !          2829: /* if withv then for j:= 1 step 1 until n do */
        !          2830:         for (jj=1;jj<=n;jj++) { 
        !          2831:           /* x=v[jj][j];  */
        !          2832:           /* z=v[jj][i];  */
        !          2833:           x=a[jj][j]; 
        !          2834:           z=a[jj][i]; 
        !          2835:           /* v[jj][j]=x*c+z*s;  */
        !          2836:           /* v[jj][i]=z*c-x*s;  */
        !          2837:           a[jj][j]=x*c+z*s; 
        !          2838:           a[jj][i]=z*c-x*s; 
        !          2839:         } 
        !          2840:         /* z=dpythag(f,h);  */
        !          2841:         z=pythag(f,h); 
        !          2842:         w[j]=z; 
        !          2843:         if (z) { 
        !          2844:           z=1.0/z; 
        !          2845:           c=f*z; 
        !          2846:           s=h*z; 
        !          2847:         } 
        !          2848:         f=c*g+s*y; 
        !          2849:         x=c*y-s*g;
        !          2850:         /* if withu then for j:=1 step 1 until m do */
        !          2851:         /* for (jj=1;jj<=m;jj++) {  */
        !          2852:         /*   y=a[jj][j];  */
        !          2853:         /*   z=a[jj][i];  */
        !          2854:         /*   a[jj][j]=y*c+z*s;  */
        !          2855:         /*   a[jj][i]=z*c-y*s;  */
        !          2856:         /* }  */
        !          2857:       } 
        !          2858:       rv1[l]=0.0; 
        !          2859:       rv1[k]=f; 
        !          2860:       w[k]=x; 
        !          2861:     } 
        !          2862:   } 
        !          2863:   free_vector(rv1,1,n); 
        !          2864: } 
1.1       brouard  2865: 
                   2866: /* end praxis */
                   2867: 
                   2868: /*************** powell ************************/
                   2869: /*
                   2870: Minimization of a function func of n variables. Input consists in an initial starting point
                   2871: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2872: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2873: such that failure to decrease by more than this amount in one iteration signals doneness. On
                   2874: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2875: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2876:  */
                   2877: #ifdef LINMINORIGINAL
                   2878: #else
                   2879:        int *flatdir; /* Function is vanishing in that direction */
                   2880:        int flat=0, flatd=0; /* Function is vanishing in that direction */
                   2881: #endif
                   2882: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2883:            double (*func)(double [])) 
                   2884: { 
                   2885: #ifdef LINMINORIGINAL
                   2886:  void linmin(double p[], double xi[], int n, double *fret, 
                   2887:              double (*func)(double [])); 
                   2888: #else 
                   2889:  void linmin(double p[], double xi[], int n, double *fret,
                   2890:             double (*func)(double []),int *flat); 
                   2891: #endif
                   2892:  int i,ibig,j,jk,k; 
                   2893:   double del,t,*pt,*ptt,*xit;
                   2894:   double directest;
                   2895:   double fp,fptt;
                   2896:   double *xits;
                   2897:   int niterf, itmp;
1.2     ! brouard  2898:   int Bigter=0, nBigterf=1;
        !          2899:   
1.1       brouard  2900:   pt=vector(1,n); 
                   2901:   ptt=vector(1,n); 
                   2902:   xit=vector(1,n); 
                   2903:   xits=vector(1,n); 
                   2904:   *fret=(*func)(p); 
                   2905:   for (j=1;j<=n;j++) pt[j]=p[j]; 
                   2906:   rcurr_time = time(NULL);
                   2907:   fp=(*fret); /* Initialisation */
                   2908:   for (*iter=1;;++(*iter)) { 
                   2909:     ibig=0; 
                   2910:     del=0.0; 
                   2911:     rlast_time=rcurr_time;
1.2     ! brouard  2912:     rlast_btime=rcurr_time;
1.1       brouard  2913:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2914:     rcurr_time = time(NULL);  
                   2915:     curr_time = *localtime(&rcurr_time);
                   2916:     /* 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); */
                   2917:     /* 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); */
1.2     ! brouard  2918:     Bigter=(*iter - *iter % ncovmodel)/ncovmodel +1; /* Big iteration, i.e on ncovmodel cycle */
        !          2919:     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);
        !          2920:     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);
        !          2921:     fprintf(ficrespow,"%d %d %.12f %d",*iter,Bigter, *fret,curr_time.tm_sec-start_time.tm_sec);
1.1       brouard  2922:     fp=(*fret); /* From former iteration or initial value */
                   2923:     for (i=1;i<=n;i++) {
                   2924:       fprintf(ficrespow," %.12lf", p[i]);
                   2925:     }
                   2926:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2927:     printf("\n#model=  1      +     age ");
                   2928:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2929:     if(nagesqr==1){
                   2930:        printf("  + age*age  ");
                   2931:        fprintf(ficlog,"  + age*age  ");
                   2932:     }
                   2933:     for(j=1;j <=ncovmodel-2;j++){
                   2934:       if(Typevar[j]==0) {
                   2935:        printf("  +      V%d  ",Tvar[j]);
                   2936:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2937:       }else if(Typevar[j]==1) {
                   2938:        printf("  +    V%d*age ",Tvar[j]);
                   2939:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2940:       }else if(Typevar[j]==2) {
                   2941:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2942:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2943:       }else if(Typevar[j]==3) {
                   2944:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2945:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2946:       }
                   2947:     }
                   2948:     printf("\n");
                   2949: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2950: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
                   2951:     fprintf(ficlog,"\n");
                   2952:     for(i=1,jk=1; i <=nlstate; i++){
                   2953:       for(k=1; k <=(nlstate+ndeath); k++){
                   2954:        if (k != i) {
                   2955:          printf("%d%d ",i,k);
                   2956:          fprintf(ficlog,"%d%d ",i,k);
                   2957:          for(j=1; j <=ncovmodel; j++){
                   2958:            printf("%12.7f ",p[jk]);
                   2959:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2960:            jk++; 
                   2961:          }
                   2962:          printf("\n");
                   2963:          fprintf(ficlog,"\n");
                   2964:        }
                   2965:       }
                   2966:     }
                   2967:     if(*iter <=3 && *iter >1){
                   2968:       tml = *localtime(&rcurr_time);
                   2969:       strcpy(strcurr,asctime(&tml));
                   2970:       rforecast_time=rcurr_time; 
                   2971:       itmp = strlen(strcurr);
                   2972:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   2973:        strcurr[itmp-1]='\0';
                   2974:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
                   2975:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.2     ! brouard  2976:       for(nBigterf=1;nBigterf<=31;nBigterf+=10){
        !          2977:        niterf=nBigterf*ncovmodel;
        !          2978:        /* rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time); */
1.1       brouard  2979:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2980:        forecast_time = *localtime(&rforecast_time);
                   2981:        strcpy(strfor,asctime(&forecast_time));
                   2982:        itmp = strlen(strfor);
                   2983:        if(strfor[itmp-1]=='\n')
                   2984:          strfor[itmp-1]='\0';
1.2     ! brouard  2985:        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);
        !          2986:        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);
1.1       brouard  2987:       }
                   2988:     }
                   2989:     for (i=1;i<=n;i++) { /* For each direction i */
                   2990:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
                   2991:       fptt=(*fret); 
                   2992: #ifdef DEBUG
                   2993:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2994:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2995: #endif
                   2996:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
                   2997:       fprintf(ficlog,"%d",i);fflush(ficlog);
                   2998: #ifdef LINMINORIGINAL
                   2999:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   3000: #else
                   3001:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   3002:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   3003: #endif
                   3004:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
                   3005:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
                   3006:                                /* because that direction will be replaced unless the gain del is small */
                   3007:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   3008:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   3009:                                /* with the new direction. */
                   3010:                                del=fabs(fptt-(*fret)); 
                   3011:                                ibig=i; 
                   3012:       } 
                   3013: #ifdef DEBUG
                   3014:       printf("%d %.12e",i,(*fret));
                   3015:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   3016:       for (j=1;j<=n;j++) {
                   3017:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   3018:                                printf(" x(%d)=%.12e",j,xit[j]);
                   3019:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   3020:       }
                   3021:       for(j=1;j<=n;j++) {
                   3022:                                printf(" p(%d)=%.12e",j,p[j]);
                   3023:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
                   3024:       }
                   3025:       printf("\n");
                   3026:       fprintf(ficlog,"\n");
                   3027: #endif
                   3028:     } /* end loop on each direction i */
                   3029:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
                   3030:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
                   3031:     /* New value of last point Pn is not computed, P(n-1) */
                   3032:     for(j=1;j<=n;j++) {
                   3033:       if(flatdir[j] >0){
                   3034:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   3035:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   3036:       }
                   3037:       /* printf("\n"); */
                   3038:       /* fprintf(ficlog,"\n"); */
                   3039:     }
                   3040:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   3041:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
                   3042:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   3043:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   3044:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   3045:       /* decreased of more than 3.84  */
                   3046:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   3047:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   3048:       /* By adding 10 parameters more the gain should be 18.31 */
                   3049:                        
                   3050:       /* Starting the program with initial values given by a former maximization will simply change */
                   3051:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   3052:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   3053:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
                   3054: #ifdef DEBUG
                   3055:       int k[2],l;
                   3056:       k[0]=1;
                   3057:       k[1]=-1;
                   3058:       printf("Max: %.12e",(*func)(p));
                   3059:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   3060:       for (j=1;j<=n;j++) {
                   3061:        printf(" %.12e",p[j]);
                   3062:        fprintf(ficlog," %.12e",p[j]);
                   3063:       }
                   3064:       printf("\n");
                   3065:       fprintf(ficlog,"\n");
                   3066:       for(l=0;l<=1;l++) {
                   3067:        for (j=1;j<=n;j++) {
                   3068:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   3069:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   3070:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   3071:        }
                   3072:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   3073:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   3074:       }
                   3075: #endif
                   3076: 
                   3077:       free_vector(xit,1,n); 
                   3078:       free_vector(xits,1,n); 
                   3079:       free_vector(ptt,1,n); 
                   3080:       free_vector(pt,1,n); 
                   3081:       return; 
                   3082:     } /* enough precision */ 
                   3083:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
                   3084:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
                   3085:       ptt[j]=2.0*p[j]-pt[j]; 
                   3086:       xit[j]=p[j]-pt[j]; 
                   3087:       pt[j]=p[j]; 
                   3088:     } 
                   3089:     fptt=(*func)(ptt); /* f_3 */
                   3090: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   3091:                if (*iter <=4) {
                   3092: #else
                   3093: #endif
                   3094: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
                   3095: #else
                   3096:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
                   3097: #endif
                   3098:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
                   3099:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
                   3100:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   3101:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   3102:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
                   3103:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   3104:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   3105:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
                   3106:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
                   3107:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   3108:       /* mu² and del² are equal when f3=f1 */
                   3109:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   3110:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   3111:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   3112:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
                   3113: #ifdef NRCORIGINAL
                   3114:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   3115: #else
                   3116:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
                   3117:       t= t- del*SQR(fp-fptt);
                   3118: #endif
                   3119:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
                   3120: #ifdef DEBUG
                   3121:       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);
                   3122:       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);
                   3123:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   3124:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   3125:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   3126:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   3127:       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);
                   3128:       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);
                   3129: #endif
                   3130: #ifdef POWELLORIGINAL
                   3131:       if (t < 0.0) { /* Then we use it for new direction */
                   3132: #else
                   3133:       if (directest*t < 0.0) { /* Contradiction between both tests */
                   3134:                                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);
                   3135:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   3136:         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);
                   3137:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   3138:       } 
                   3139:       if (directest < 0.0) { /* Then we use it for new direction */
                   3140: #endif
                   3141: #ifdef DEBUGLINMIN
                   3142:        printf("Before linmin in direction P%d-P0\n",n);
                   3143:        for (j=1;j<=n;j++) {
                   3144:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   3145:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   3146:          if(j % ncovmodel == 0){
                   3147:            printf("\n");
                   3148:            fprintf(ficlog,"\n");
                   3149:          }
                   3150:        }
                   3151: #endif
                   3152: #ifdef LINMINORIGINAL
                   3153:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   3154: #else
                   3155:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   3156:        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   3157: #endif
                   3158:        
                   3159: #ifdef DEBUGLINMIN
                   3160:        for (j=1;j<=n;j++) { 
                   3161:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   3162:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   3163:          if(j % ncovmodel == 0){
                   3164:            printf("\n");
                   3165:            fprintf(ficlog,"\n");
                   3166:          }
                   3167:        }
                   3168: #endif
                   3169:        for (j=1;j<=n;j++) { 
                   3170:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   3171:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   3172:        }
                   3173: #ifdef LINMINORIGINAL
                   3174: #else
                   3175:        for (j=1, flatd=0;j<=n;j++) {
                   3176:          if(flatdir[j]>0)
                   3177:            flatd++;
                   3178:        }
                   3179:        if(flatd >0){
                   3180:          printf("%d flat directions: ",flatd);
                   3181:          fprintf(ficlog,"%d flat directions :",flatd);
                   3182:          for (j=1;j<=n;j++) { 
                   3183:            if(flatdir[j]>0){
                   3184:              printf("%d ",j);
                   3185:              fprintf(ficlog,"%d ",j);
                   3186:            }
                   3187:          }
                   3188:          printf("\n");
                   3189:          fprintf(ficlog,"\n");
                   3190: #ifdef FLATSUP
                   3191:           free_vector(xit,1,n); 
                   3192:           free_vector(xits,1,n); 
                   3193:           free_vector(ptt,1,n); 
                   3194:           free_vector(pt,1,n); 
                   3195:           return;
                   3196: #endif
                   3197:        }
                   3198: #endif
                   3199:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   3200:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   3201:        
                   3202: #ifdef DEBUG
                   3203:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   3204:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   3205:        for(j=1;j<=n;j++){
                   3206:          printf(" %lf",xit[j]);
                   3207:          fprintf(ficlog," %lf",xit[j]);
                   3208:        }
                   3209:        printf("\n");
                   3210:        fprintf(ficlog,"\n");
                   3211: #endif
                   3212:       } /* end of t or directest negative */
                   3213: #ifdef POWELLNOF3INFF1TEST
                   3214: #else
                   3215:       } /* end if (fptt < fp)  */
                   3216: #endif
                   3217: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   3218:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
                   3219: #else
                   3220: #endif
                   3221:                } /* loop iteration */ 
                   3222: } 
                   3223:   
                   3224: /**** Prevalence limit (stable or period prevalence)  ****************/
                   3225:   
                   3226:   double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij, int nres)
                   3227:   {
                   3228:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
                   3229:      *   (and selected quantitative values in nres)
                   3230:      *  by left multiplying the unit
                   3231:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   3232:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   3233:      * Wx is row vector: population in state 1, population in state 2, population dead
                   3234:      * or prevalence in state 1, prevalence in state 2, 0
                   3235:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   3236:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   3237:      * Output is prlim.
                   3238:      * Initial matrix pimij 
                   3239:      */
                   3240:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3241:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3242:   /*  0,                   0                  , 1} */
                   3243:   /*
                   3244:    * and after some iteration: */
                   3245:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3246:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3247:   /*  0,                   0                  , 1} */
                   3248:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3249:   /* {0.51571254859325999, 0.4842874514067399, */
                   3250:   /*  0.51326036147820708, 0.48673963852179264} */
                   3251:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3252:     
                   3253:     int i, ii,j,k, k1;
                   3254:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3255:   /* double **matprod2(); */ /* test */
                   3256:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
                   3257:   double **newm;
                   3258:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3259:   int ncvloop=0;
                   3260:   int first=0;
                   3261:   
                   3262:   min=vector(1,nlstate);
                   3263:   max=vector(1,nlstate);
                   3264:   meandiff=vector(1,nlstate);
                   3265: 
                   3266:        /* Starting with matrix unity */
                   3267:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3268:     for (j=1;j<=nlstate+ndeath;j++){
                   3269:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3270:     }
                   3271:   
                   3272:   cov[1]=1.;
                   3273:   
                   3274:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3275:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
                   3276:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
                   3277:     ncvloop++;
                   3278:     newm=savm;
                   3279:     /* Covariates have to be included here again */
                   3280:     cov[2]=agefin;
                   3281:      if(nagesqr==1){
                   3282:       cov[3]= agefin*agefin;
                   3283:      }
                   3284:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3285:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3286:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3287:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
                   3288:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3289:        }else{
                   3290:         cov[2+nagesqr+k1]=precov[nres][k1];
                   3291:        }
                   3292:      }/* End of loop on model equation */
                   3293:      
                   3294: /* Start of old code (replaced by a loop on position in the model equation */
                   3295:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   3296:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3297:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   3298:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   3299:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   3300:     /*    * k                  1        2      3    4      5      6     7        8 */
                   3301:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   3302:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   3303:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   3304:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   3305:     /*    *nsd=3                              (1)  (2)           (3) */
                   3306:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   3307:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   3308:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   3309:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   3310:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   3311:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   3312:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   3313:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   3314:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   3315:     /*    *TvarsDpType */
                   3316:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   3317:     /*    * nsd=1              (1)           (2) */
                   3318:     /*    *TvarsD[nsd]          3             2 */
                   3319:     /*    *TnsdVar           (3)=1          (2)=2 */
                   3320:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   3321:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   3322:     /*    *\/ */
                   3323:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   3324:     /*   /\* 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)); *\/ */
                   3325:     /* } */
                   3326:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   3327:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3328:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   3329:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3330:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   3331:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3332:     /*   /\* 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]); *\/ */
                   3333:     /* } */
                   3334:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3335:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   3336:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3337:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   3338:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   3339:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3340:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3341:     /*   } */
                   3342:     /*   /\* 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]); *\/ */
                   3343:     /* } */
                   3344:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3345:     /*   /\* 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]); *\/ */
                   3346:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3347:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3348:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3349:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3350:     /*         }else{ */
                   3351:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3352:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   3353:     /*         } */
                   3354:     /*   }else{ */
                   3355:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3356:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3357:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   3358:     /*         }else{ */
                   3359:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3360:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   3361:     /*         } */
                   3362:     /*   } */
                   3363:     /* } /\* End product without age *\/ */
                   3364: /* ENd of old code */
                   3365:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3366:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3367:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3368:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3369:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
                   3370:     /* age and covariate values of ij are in 'cov' */
                   3371:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
                   3372:     
                   3373:     savm=oldm;
                   3374:     oldm=newm;
                   3375: 
                   3376:     for(j=1; j<=nlstate; j++){
                   3377:       max[j]=0.;
                   3378:       min[j]=1.;
                   3379:     }
                   3380:     for(i=1;i<=nlstate;i++){
                   3381:       sumnew=0;
                   3382:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   3383:       for(j=1; j<=nlstate; j++){ 
                   3384:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   3385:        max[j]=FMAX(max[j],prlim[i][j]);
                   3386:        min[j]=FMIN(min[j],prlim[i][j]);
                   3387:       }
                   3388:     }
                   3389: 
                   3390:     maxmax=0.;
                   3391:     for(j=1; j<=nlstate; j++){
                   3392:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   3393:       maxmax=FMAX(maxmax,meandiff[j]);
                   3394:       /* 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); */
                   3395:     } /* j loop */
                   3396:     *ncvyear= (int)age- (int)agefin;
                   3397:     /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3398:     if(maxmax < ftolpl){
                   3399:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3400:       free_vector(min,1,nlstate);
                   3401:       free_vector(max,1,nlstate);
                   3402:       free_vector(meandiff,1,nlstate);
                   3403:       return prlim;
                   3404:     }
                   3405:   } /* agefin loop */
                   3406:     /* After some age loop it doesn't converge */
                   3407:   if(!first){
                   3408:     first=1;
                   3409:     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);
                   3410:     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);
                   3411:   }else if (first >=1 && first <10){
                   3412:     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);
                   3413:     first++;
                   3414:   }else if (first ==10){
                   3415:     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);
                   3416:     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");
                   3417:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   3418:     first++;
                   3419:   }
                   3420: 
                   3421:   /* 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); */
                   3422:   free_vector(min,1,nlstate);
                   3423:   free_vector(max,1,nlstate);
                   3424:   free_vector(meandiff,1,nlstate);
                   3425:   
                   3426:   return prlim; /* should not reach here */
                   3427: }
                   3428: 
                   3429: 
                   3430:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3431: 
                   3432:  /* 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) */
                   3433:  /* 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) */
                   3434:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
                   3435: {
                   3436:   /* Computes the prevalence limit in each live state at age x and for covariate combination ij (<=2**cptcoveff) by left multiplying the unit
                   3437:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3438:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3439:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3440:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3441:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3442:   /* Initial matrix pimij */
                   3443:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3444:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3445:   /*  0,                   0                  , 1} */
                   3446:   /*
                   3447:    * and after some iteration: */
                   3448:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3449:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3450:   /*  0,                   0                  , 1} */
                   3451:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3452:   /* {0.51571254859325999, 0.4842874514067399, */
                   3453:   /*  0.51326036147820708, 0.48673963852179264} */
                   3454:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3455: 
                   3456:   int i, ii,j,k, k1;
                   3457:   int first=0;
                   3458:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3459:   /* double **matprod2(); */ /* test */
                   3460:   double **out, cov[NCOVMAX+1], **bmij();
                   3461:   double **newm;
                   3462:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3463:   double        **oldm, **savm;  /* for use */
                   3464: 
                   3465:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3466:   int ncvloop=0;
                   3467:   
                   3468:   min=vector(1,nlstate);
                   3469:   max=vector(1,nlstate);
                   3470:   meandiff=vector(1,nlstate);
                   3471: 
                   3472:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3473:   oldm=oldms; savm=savms;
                   3474:   
                   3475:   /* Starting with matrix unity */
                   3476:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3477:     for (j=1;j<=nlstate+ndeath;j++){
                   3478:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3479:     }
                   3480:   
                   3481:   cov[1]=1.;
                   3482:   
                   3483:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3484:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
                   3485:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3486:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3487:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
                   3488:     ncvloop++;
                   3489:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3490:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
                   3491:     /* Covariates have to be included here again */
                   3492:     cov[2]=agefin;
                   3493:     if(nagesqr==1){
                   3494:       cov[3]= agefin*agefin;;
                   3495:     }
                   3496:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3497:       if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
                   3498:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3499:       }else{
                   3500:        cov[2+nagesqr+k1]=precov[nres][k1];
                   3501:       }
                   3502:     }/* End of loop on model equation */
                   3503: 
                   3504: /* Old code */ 
                   3505: 
                   3506:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3507:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3508:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3509:     /*   /\* 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)); *\/ */
                   3510:     /* } */
                   3511:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3512:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3513:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3514:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3515:     /* /\* } *\/ */
                   3516:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3517:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3518:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3519:     /*   /\* 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]); *\/ */
                   3520:     /* } */
                   3521:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3522:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3523:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3524:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3525:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3526:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3527:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3528:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3529:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3530:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3531:     /*   } */
                   3532:     /*   /\* 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]); *\/ */
                   3533:     /* } */
                   3534:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3535:     /*   /\* 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]); *\/ */
                   3536:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3537:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3538:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3539:     /*         }else{ */
                   3540:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3541:     /*         } */
                   3542:     /*   }else{ */
                   3543:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3544:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3545:     /*         }else{ */
                   3546:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3547:     /*         } */
                   3548:     /*   } */
                   3549:     /* } */
                   3550:     
                   3551:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3552:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3553:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3554:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3555:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
                   3556:                /* ij should be linked to the correct index of cov */
                   3557:                /* age and covariate values ij are in 'cov', but we need to pass
                   3558:                 * ij for the observed prevalence at age and status and covariate
                   3559:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3560:                 */
                   3561:     /* 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 *\/ */
                   3562:     /* 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 *\/ */
                   3563:     out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij)); /* Bug Valgrind */
                   3564:     /* if((int)age == 86 || (int)age == 87){ */
                   3565:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3566:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3567:     /*         printf("%d newm= ",i); */
                   3568:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3569:     /*           printf("%f ",newm[i][j]); */
                   3570:     /*         } */
                   3571:     /*         printf("oldm * "); */
                   3572:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3573:     /*           printf("%f ",oldm[i][j]); */
                   3574:     /*         } */
                   3575:     /*         printf(" bmmij "); */
                   3576:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3577:     /*           printf("%f ",pmmij[i][j]); */
                   3578:     /*         } */
                   3579:     /*         printf("\n"); */
                   3580:     /*   } */
                   3581:     /* } */
                   3582:     savm=oldm;
                   3583:     oldm=newm;
                   3584: 
                   3585:     for(j=1; j<=nlstate; j++){
                   3586:       max[j]=0.;
                   3587:       min[j]=1.;
                   3588:     }
                   3589:     for(j=1; j<=nlstate; j++){ 
                   3590:       for(i=1;i<=nlstate;i++){
                   3591:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3592:        bprlim[i][j]= newm[i][j];
                   3593:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3594:        min[i]=FMIN(min[i],bprlim[i][j]);
                   3595:       }
                   3596:     }
                   3597:                
                   3598:     maxmax=0.;
                   3599:     for(i=1; i<=nlstate; i++){
                   3600:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
                   3601:       maxmax=FMAX(maxmax,meandiff[i]);
                   3602:       /* 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); */
                   3603:     } /* i loop */
                   3604:     *ncvyear= -( (int)age- (int)agefin);
                   3605:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3606:     if(maxmax < ftolpl){
                   3607:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3608:       free_vector(min,1,nlstate);
                   3609:       free_vector(max,1,nlstate);
                   3610:       free_vector(meandiff,1,nlstate);
                   3611:       return bprlim;
                   3612:     }
                   3613:   } /* agefin loop */
                   3614:     /* After some age loop it doesn't converge */
                   3615:   if(!first){
                   3616:     first=1;
                   3617:     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\
                   3618: 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);
                   3619:   }
                   3620:   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\
                   3621: 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);
                   3622:   /* 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); */
                   3623:   free_vector(min,1,nlstate);
                   3624:   free_vector(max,1,nlstate);
                   3625:   free_vector(meandiff,1,nlstate);
                   3626:   
                   3627:   return bprlim; /* should not reach here */
                   3628: }
                   3629: 
                   3630: /*************** transition probabilities ***************/ 
                   3631: 
                   3632: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3633: {
                   3634:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3635:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
                   3636:      model to the ncovmodel covariates (including constant and age).
                   3637:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3638:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3639:      ncth covariate in the global vector x is given by the formula:
                   3640:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3641:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3642:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3643:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3644:      Outputs ps[i][j] or probability to be observed in j being in i according to
                   3645:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3646:      Sum on j ps[i][j] should equal to 1.
                   3647:   */
                   3648:   double s1, lnpijopii;
                   3649:   /*double t34;*/
                   3650:   int i,j, nc, ii, jj;
                   3651: 
                   3652:   for(i=1; i<= nlstate; i++){
                   3653:     for(j=1; j<i;j++){
                   3654:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3655:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3656:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3657:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3658:       }
                   3659:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3660:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
                   3661:     }
                   3662:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3663:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3664:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3665:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3666:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3667:       }
                   3668:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3669:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
                   3670:     }
                   3671:   }
                   3672:   
                   3673:   for(i=1; i<= nlstate; i++){
                   3674:     s1=0;
                   3675:     for(j=1; j<i; j++){
                   3676:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
                   3677:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3678:     }
                   3679:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3680:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
                   3681:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3682:     }
                   3683:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3684:     ps[i][i]=1./(s1+1.);
                   3685:     /* Computing other pijs */
                   3686:     for(j=1; j<i; j++)
                   3687:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
                   3688:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3689:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3690:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3691:   } /* end i */
                   3692:   
                   3693:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3694:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3695:       ps[ii][jj]=0;
                   3696:       ps[ii][ii]=1;
                   3697:     }
                   3698:   }
                   3699: 
                   3700: 
                   3701:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3702:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3703:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3704:   /*   } */
                   3705:   /*   printf("\n "); */
                   3706:   /* } */
                   3707:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3708:   /*
                   3709:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3710:                goto end;*/
                   3711:   return ps; /* Pointer is unchanged since its call */
                   3712: }
                   3713: 
                   3714: /*************** backward transition probabilities ***************/ 
                   3715: 
                   3716:  /* 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 ) */
                   3717: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3718:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3719: {
                   3720:   /* Computes the backward probability at age agefin, cov[2], and covariate combination 'ij'. In fact cov is already filled and x too.
                   3721:    * Call to pmij(cov and x), call to cross prevalence, sums and inverses, left multiply, and returns in **ps as well as **bmij.
                   3722:    */
                   3723:   int i, ii, j,k;
                   3724:   
                   3725:   double **out, **pmij();
                   3726:   double sumnew=0.;
                   3727:   double agefin;
                   3728:   double k3=0.; /* constant of the w_x diagonal matrix (in order for B to sum to 1 even for death state) */
                   3729:   double **dnewm, **dsavm, **doldm;
                   3730:   double **bbmij;
                   3731:   
                   3732:   doldm=ddoldms; /* global pointers */
                   3733:   dnewm=ddnewms;
                   3734:   dsavm=ddsavms;
                   3735: 
                   3736:   /* Debug */
                   3737:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
                   3738:   agefin=cov[2];
                   3739:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
                   3740:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
                   3741:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3742:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3743: 
                   3744:   /* P_x */
                   3745:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
                   3746:   /* outputs pmmij which is a stochastic matrix in row */
                   3747: 
                   3748:   /* Diag(w_x) */
                   3749:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
                   3750:   sumnew=0.;
                   3751:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
                   3752:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
                   3753:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
                   3754:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3755:   }
                   3756:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3757:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3758:       for (j=1;j<=nlstate+ndeath;j++)
                   3759:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
                   3760:     }
                   3761:   }else{
                   3762:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3763:       for (j=1;j<=nlstate+ndeath;j++)
                   3764:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3765:     }
                   3766:     /* if(sumnew <0.9){ */
                   3767:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3768:     /* } */
                   3769:   }
                   3770:   k3=0.0;  /* We put the last diagonal to 0 */
                   3771:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3772:       doldm[ii][ii]= k3;
                   3773:   }
                   3774:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3775:   
                   3776:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3777:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
                   3778: 
                   3779:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
                   3780:   /* w1 p11 + w2 p21 only on live states N1./N..*N11/N1. + N2./N..*N21/N2.=(N11+N21)/N..=N.1/N.. */
                   3781:   for (j=1;j<=nlstate+ndeath;j++){
                   3782:     sumnew=0.;
                   3783:     for (ii=1;ii<=nlstate;ii++){
                   3784:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
                   3785:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
                   3786:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
                   3787:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3788:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
                   3789:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   3790:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
                   3791:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   3792:        /* }else */
                   3793:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3794:     } /*End ii */
                   3795:   } /* 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 */
                   3796: 
                   3797:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
                   3798:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
                   3799:   /* end bmij */
                   3800:   return ps; /*pointer is unchanged */
                   3801: }
                   3802: /*************** transition probabilities ***************/ 
                   3803: 
                   3804: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3805: {
                   3806:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3807:      computes the probability to be observed in state j being in state i by appying the
                   3808:      model to the ncovmodel covariates (including constant and age).
                   3809:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3810:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3811:      ncth covariate in the global vector x is given by the formula:
                   3812:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3813:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3814:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3815:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3816:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3817:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3818:   */
                   3819:   double s1, lnpijopii;
                   3820:   /*double t34;*/
                   3821:   int i,j, nc, ii, jj;
                   3822: 
                   3823:   for(i=1; i<= nlstate; i++){
                   3824:     for(j=1; j<i;j++){
                   3825:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3826:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3827:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3828:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3829:       }
                   3830:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3831:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3832:     }
                   3833:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3834:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3835:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3836:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3837:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3838:       }
                   3839:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3840:     }
                   3841:   }
                   3842:   
                   3843:   for(i=1; i<= nlstate; i++){
                   3844:     s1=0;
                   3845:     for(j=1; j<i; j++){
                   3846:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3847:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3848:     }
                   3849:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3850:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3851:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3852:     }
                   3853:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3854:     ps[i][i]=1./(s1+1.);
                   3855:     /* Computing other pijs */
                   3856:     for(j=1; j<i; j++)
                   3857:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3858:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3859:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3860:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3861:   } /* end i */
                   3862:   
                   3863:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3864:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3865:       ps[ii][jj]=0;
                   3866:       ps[ii][ii]=1;
                   3867:     }
                   3868:   }
                   3869:   /* Added for prevbcast */ /* Transposed matrix too */
                   3870:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3871:     s1=0.;
                   3872:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3873:       s1+=ps[ii][jj];
                   3874:     }
                   3875:     for(ii=1; ii<= nlstate; ii++){
                   3876:       ps[ii][jj]=ps[ii][jj]/s1;
                   3877:     }
                   3878:   }
                   3879:   /* Transposition */
                   3880:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3881:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3882:       s1=ps[ii][jj];
                   3883:       ps[ii][jj]=ps[jj][ii];
                   3884:       ps[jj][ii]=s1;
                   3885:     }
                   3886:   }
                   3887:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3888:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3889:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3890:   /*   } */
                   3891:   /*   printf("\n "); */
                   3892:   /* } */
                   3893:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3894:   /*
                   3895:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3896:     goto end;*/
                   3897:   return ps;
                   3898: }
                   3899: 
                   3900: 
                   3901: /**************** Product of 2 matrices ******************/
                   3902: 
                   3903: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
                   3904: {
                   3905:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3906:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3907:   /* in, b, out are matrice of pointers which should have been initialized 
                   3908:      before: only the contents of out is modified. The function returns
                   3909:      a pointer to pointers identical to out */
                   3910:   int i, j, k;
                   3911:   for(i=nrl; i<= nrh; i++)
                   3912:     for(k=ncolol; k<=ncoloh; k++){
                   3913:       out[i][k]=0.;
                   3914:       for(j=ncl; j<=nch; j++)
                   3915:        out[i][k] +=in[i][j]*b[j][k];
                   3916:     }
                   3917:   return out;
                   3918: }
                   3919: 
                   3920: 
                   3921: /************* Higher Matrix Product ***************/
                   3922: 
                   3923: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij, int nres )
                   3924: {
                   3925:   /* Already optimized with precov.
                   3926:      Computes the transition matrix starting at age 'age' and dummies values in each resultline (loop on ij to find the corresponding combination) to over 
                   3927:      'nhstepm*hstepm*stepm' months (i.e. until
                   3928:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3929:      nhstepm*hstepm matrices. 
                   3930:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3931:      (typically every 2 years instead of every month which is too big 
                   3932:      for the memory).
                   3933:      Model is determined by parameters x and covariates have to be 
                   3934:      included manually here. 
                   3935: 
                   3936:      */
                   3937: 
                   3938:   int i, j, d, h, k, k1;
                   3939:   double **out, cov[NCOVMAX+1];
                   3940:   double **newm;
                   3941:   double agexact;
                   3942:   double agebegin, ageend;
                   3943: 
                   3944:   /* Hstepm could be zero and should return the unit matrix */
                   3945:   for (i=1;i<=nlstate+ndeath;i++)
                   3946:     for (j=1;j<=nlstate+ndeath;j++){
                   3947:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3948:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3949:     }
                   3950:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3951:   for(h=1; h <=nhstepm; h++){
                   3952:     for(d=1; d <=hstepm; d++){
                   3953:       newm=savm;
                   3954:       /* Covariates have to be included here again */
                   3955:       cov[1]=1.;
                   3956:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
                   3957:       cov[2]=agexact;
                   3958:       if(nagesqr==1){
                   3959:        cov[3]= agexact*agexact;
                   3960:       }
                   3961:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3962:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3963:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3964:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
                   3965:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3966:        }else{
                   3967:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3968:        }
                   3969:       }/* End of loop on model equation */
                   3970:        /* Old code */ 
                   3971: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3972: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3973: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3974: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3975: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3976: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3977: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3978: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3979: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3980: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3981: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3982: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3983: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3984: /*       /\* 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]])); *\/ */
                   3985: /*       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); */
                   3986: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3987: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3988: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3989: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3990: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3991: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3992: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3993: /*       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]]); */
                   3994: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3995: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3996: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3997: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3998: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3999: /*       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]); */
                   4000: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   4001: 
                   4002: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   4003: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   4004: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   4005: /*       /\* *\/ */
                   4006: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   4007: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   4008: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   4009: /* /\*cptcovage=2                   1               2      *\/ */
                   4010: /* /\*Tage[k]=                      5               8      *\/  */
                   4011: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   4012: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   4013: /*       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]]); */
                   4014: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   4015: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   4016: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   4017: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   4018: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   4019: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   4020: /*       /\*   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); *\/ */
                   4021: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   4022: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   4023: /*       /\* } *\/ */
                   4024: /*       /\* 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]); *\/ */
                   4025: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   4026: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   4027: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   4028: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   4029: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   4030: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   4031: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   4032: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   4033: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
                   4034:          
                   4035: /*       /\* 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])]); *\/ */
                   4036: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   4037: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   4038: /*       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]]); */
                   4039: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   4040: 
                   4041: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   4042: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   4043: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   4044: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   4045: /*           /\* 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]])]; *\/ */
                   4046: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   4047: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   4048: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   4049: /*       /\*   } *\/ */
                   4050: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   4051: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   4052: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   4053: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   4054: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   4055: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   4056: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   4057: /*       /\*   } *\/ */
                   4058: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   4059: /*     }/\*end of products *\/ */
                   4060:       /* } /\* End of loop on model equation *\/ */
                   4061:       /* for (k=1; k<=cptcovn;k++)  */
                   4062:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   4063:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   4064:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   4065:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   4066:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   4067:       
                   4068:       
                   4069:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   4070:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   4071:       /* right multiplication of oldm by the current matrix */
                   4072:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   4073:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4074:       /* if((int)age == 70){ */
                   4075:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   4076:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   4077:       /*         printf("%d pmmij ",i); */
                   4078:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4079:       /*           printf("%f ",pmmij[i][j]); */
                   4080:       /*         } */
                   4081:       /*         printf(" oldm "); */
                   4082:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4083:       /*           printf("%f ",oldm[i][j]); */
                   4084:       /*         } */
                   4085:       /*         printf("\n"); */
                   4086:       /*       } */
                   4087:       /* } */
                   4088:       savm=oldm;
                   4089:       oldm=newm;
                   4090:     }
                   4091:     for(i=1; i<=nlstate+ndeath; i++)
                   4092:       for(j=1;j<=nlstate+ndeath;j++) {
                   4093:        po[i][j][h]=newm[i][j];
                   4094:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
                   4095:       }
                   4096:     /*printf("h=%d ",h);*/
                   4097:   } /* end h */
                   4098:   /*     printf("\n H=%d \n",h); */
                   4099:   return po;
                   4100: }
                   4101: 
                   4102: /************* Higher Back Matrix Product ***************/
                   4103: /* 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 ) */
                   4104: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij, int nres )
                   4105: {
                   4106:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   4107:      computes the transition matrix starting at age 'age' over
                   4108:      'nhstepm*hstepm*stepm' months (i.e. until
                   4109:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   4110:      nhstepm*hstepm matrices.
                   4111:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   4112:      (typically every 2 years instead of every month which is too big
                   4113:      for the memory).
                   4114:      Model is determined by parameters x and covariates have to be
                   4115:      included manually here. Then we use a call to bmij(x and cov)
                   4116:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
                   4117:   */
                   4118: 
                   4119:   int i, j, d, h, k, k1;
                   4120:   double **out, cov[NCOVMAX+1], **bmij();
                   4121:   double **newm, ***newmm;
                   4122:   double agexact;
                   4123:   double agebegin, ageend;
                   4124:   double **oldm, **savm;
                   4125: 
                   4126:   newmm=po; /* To be saved */
                   4127:   oldm=oldms;savm=savms; /* Global pointers */
                   4128:   /* Hstepm could be zero and should return the unit matrix */
                   4129:   for (i=1;i<=nlstate+ndeath;i++)
                   4130:     for (j=1;j<=nlstate+ndeath;j++){
                   4131:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   4132:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   4133:     }
                   4134:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   4135:   for(h=1; h <=nhstepm; h++){
                   4136:     for(d=1; d <=hstepm; d++){
                   4137:       newm=savm;
                   4138:       /* Covariates have to be included here again */
                   4139:       cov[1]=1.;
                   4140:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
                   4141:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   4142:         /* Debug */
                   4143:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
                   4144:       cov[2]=agexact;
                   4145:       if(nagesqr==1){
                   4146:        cov[3]= agexact*agexact;
                   4147:       }
                   4148:       /** New code */
                   4149:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   4150:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
                   4151:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   4152:        }else{
                   4153:          cov[2+nagesqr+k1]=precov[nres][k1];
                   4154:        }
                   4155:       }/* End of loop on model equation */
                   4156:       /** End of new code */
                   4157:   /** This was old code */
                   4158:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   4159:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   4160:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   4161:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   4162:       /*   /\* 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)); *\/ */
                   4163:       /* } */
                   4164:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   4165:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   4166:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   4167:       /*       /\* 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]); *\/ */
                   4168:       /* } */
                   4169:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   4170:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   4171:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   4172:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   4173:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   4174:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   4175:       /*       } */
                   4176:       /*       /\* 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]); *\/ */
                   4177:       /* } */
                   4178:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   4179:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   4180:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   4181:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   4182:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   4183:       /*         }else{ */
                   4184:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   4185:       /*         } */
                   4186:       /*       }else{ */
                   4187:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   4188:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   4189:       /*         }else{ */
                   4190:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   4191:       /*         } */
                   4192:       /*       } */
                   4193:       /* }                      */
                   4194:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   4195:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   4196: /** End of old code */
                   4197:       
                   4198:       /* Careful transposed matrix */
                   4199:       /* age is in cov[2], prevacurrent at beginning of transition. */
                   4200:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
                   4201:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
                   4202:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
                   4203:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
                   4204:       /* if((int)age == 70){ */
                   4205:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   4206:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   4207:       /*         printf("%d pmmij ",i); */
                   4208:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4209:       /*           printf("%f ",pmmij[i][j]); */
                   4210:       /*         } */
                   4211:       /*         printf(" oldm "); */
                   4212:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4213:       /*           printf("%f ",oldm[i][j]); */
                   4214:       /*         } */
                   4215:       /*         printf("\n"); */
                   4216:       /*       } */
                   4217:       /* } */
                   4218:       savm=oldm;
                   4219:       oldm=newm;
                   4220:     }
                   4221:     for(i=1; i<=nlstate+ndeath; i++)
                   4222:       for(j=1;j<=nlstate+ndeath;j++) {
                   4223:        po[i][j][h]=newm[i][j];
                   4224:        /* if(h==nhstepm) */
                   4225:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
                   4226:       }
                   4227:     /* printf("h=%d %.1f ",h, agexact); */
                   4228:   } /* end h */
                   4229:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
                   4230:   return po;
                   4231: }
                   4232: 
                   4233: 
                   4234: #ifdef NLOPT
                   4235:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   4236:   double fret;
                   4237:   double *xt;
                   4238:   int j;
                   4239:   myfunc_data *d2 = (myfunc_data *) pd;
                   4240: /* xt = (p1-1); */
                   4241:   xt=vector(1,n); 
                   4242:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   4243: 
                   4244:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   4245:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   4246:   printf("Function = %.12lf ",fret);
                   4247:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   4248:   printf("\n");
                   4249:  free_vector(xt,1,n);
                   4250:   return fret;
                   4251: }
                   4252: #endif
                   4253: 
                   4254: /*************** log-likelihood *************/
                   4255: double func( double *x)
                   4256: {
                   4257:   int i, ii, j, k, mi, d, kk, kf=0;
                   4258:   int ioffset=0;
                   4259:   int ipos=0,iposold=0,ncovv=0;
                   4260: 
                   4261:   double cotvarv, cotvarvold;
                   4262:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   4263:   double **out;
                   4264:   double lli; /* Individual log likelihood */
                   4265:   int s1, s2;
                   4266:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4267: 
                   4268:   double bbh, survp;
                   4269:   double agexact;
                   4270:   double agebegin, ageend;
                   4271:   /*extern weight */
                   4272:   /* We are differentiating ll according to initial status */
                   4273:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4274:   /*for(i=1;i<imx;i++) 
                   4275:     printf(" %d\n",s[4][i]);
                   4276:   */
                   4277: 
                   4278:   ++countcallfunc;
                   4279: 
                   4280:   cov[1]=1.;
                   4281: 
                   4282:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   4283:   ioffset=0;
1.2     ! brouard  4284:   if(mle==1){
        !          4285:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
        !          4286:       /* Computes the values of the ncovmodel covariates of the model
        !          4287:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
        !          4288:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
        !          4289:         to be observed in j being in i according to the model.
        !          4290:       */
        !          4291:       ioffset=2+nagesqr ;
        !          4292:    /* Fixed */
        !          4293:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummy or quant or prod */
        !          4294:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
        !          4295:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
        !          4296:        /*  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 */
        !          4297:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
        !          4298:        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)*/
        !          4299:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
        !          4300:       }
        !          4301:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
        !          4302:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
        !          4303:         has been calculated etc */
        !          4304:       /* For an individual i, wav[i] gives the number of effective waves */
        !          4305:       /* We compute the contribution to Likelihood of each effective transition
        !          4306:         mw[mi][i] is real wave of the mi th effectve wave */
        !          4307:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
        !          4308:         s2=s[mw[mi+1][i]][i];
        !          4309:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i] because now is moved after nvocol+nqv 
        !          4310:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
        !          4311:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
        !          4312:       */
        !          4313:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.1       brouard  4314:       /* Wave varying (but not age varying) */
1.2     ! brouard  4315:        /* 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*\/ */
        !          4316:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
        !          4317:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
        !          4318:        /* } */
        !          4319:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
        !          4320:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
        !          4321:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
        !          4322:          if(FixedV[itv]!=0){ /* Not a fixed covariate */
        !          4323:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.1       brouard  4324:          }else{ /* fixed covariate */
                   4325:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4326:          }
                   4327:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4328:            cotvarvold=cotvarv;
                   4329:          }else{ /* A second product */
                   4330:            cotvarv=cotvarv*cotvarvold;
                   4331:          }
                   4332:          iposold=ipos;
1.2     ! brouard  4333:          cov[ioffset+ipos]=cotvarv;
1.1       brouard  4334:        }
1.2     ! brouard  4335:        /* for products of time varying to be done */
        !          4336:        for (ii=1;ii<=nlstate+ndeath;ii++)
        !          4337:          for (j=1;j<=nlstate+ndeath;j++){
        !          4338:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          4339:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          4340:          }
        !          4341: 
        !          4342:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
        !          4343:        ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
        !          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;  /* Should be changed here */
        !          4350:          /* for (kk=1; kk<=cptcovage;kk++) { */
        !          4351:          /*   if(!FixedV[Tvar[Tage[kk]]]) */
        !          4352:          /*     cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /\* Tage[kk] gives the data-covariate associated with age *\/ */
        !          4353:          /*   else */
        !          4354:          /*     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) *\/  */
        !          4355:          /* } */
        !          4356:          for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
        !          4357:            itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
        !          4358:            ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
        !          4359:            if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
        !          4360:              cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
        !          4361:            }else{ /* fixed covariate */
        !          4362:              cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
        !          4363:            }
        !          4364:            if(ipos!=iposold){ /* Not a product or first of a product */
        !          4365:              cotvarvold=cotvarv;
        !          4366:            }else{ /* A second product */
        !          4367:              cotvarv=cotvarv*cotvarvold;
        !          4368:            }
        !          4369:            iposold=ipos;
        !          4370:            cov[ioffset+ipos]=cotvarv*agexact;
        !          4371:            /* For products */
        !          4372:          }
        !          4373:          
        !          4374:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
        !          4375:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
        !          4376:          savm=oldm;
        !          4377:          oldm=newm;
        !          4378:        } /* end mult */
1.1       brouard  4379:        
                   4380:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1.2     ! brouard  4381:        /* But now since version 0.9 we anticipate for bias at large stepm.
        !          4382:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
        !          4383:         * (in months) between two waves is not a multiple of stepm, we rounded to 
        !          4384:         * the nearest (and in case of equal distance, to the lowest) interval but now
        !          4385:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
        !          4386:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
        !          4387:         * probability in order to take into account the bias as a fraction of the way
        !          4388:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
        !          4389:                                 * -stepm/2 to stepm/2 .
        !          4390:                                 * For stepm=1 the results are the same as for previous versions of Imach.
        !          4391:                                 * For stepm > 1 the results are less biased than in previous versions. 
        !          4392:                                 */
        !          4393:        s1=s[mw[mi][i]][i];
        !          4394:        s2=s[mw[mi+1][i]][i];
        !          4395:        bbh=(double)bh[mi][i]/(double)stepm; 
        !          4396:        /* bias bh is positive if real duration
        !          4397:         * is higher than the multiple of stepm and negative otherwise.
        !          4398:         */
        !          4399:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
        !          4400:        if( s2 > nlstate){ 
        !          4401:          /* i.e. if s2 is a death state and if the date of death is known 
        !          4402:             then the contribution to the likelihood is the probability to 
        !          4403:             die between last step unit time and current  step unit time, 
        !          4404:             which is also equal to probability to die before dh 
        !          4405:             minus probability to die before dh-stepm . 
        !          4406:             In version up to 0.92 likelihood was computed
        !          4407:             as if date of death was unknown. Death was treated as any other
        !          4408:             health state: the date of the interview describes the actual state
        !          4409:             and not the date of a change in health state. The former idea was
        !          4410:             to consider that at each interview the state was recorded
        !          4411:             (healthy, disable or death) and IMaCh was corrected; but when we
        !          4412:             introduced the exact date of death then we should have modified
        !          4413:             the contribution of an exact death to the likelihood. This new
        !          4414:             contribution is smaller and very dependent of the step unit
        !          4415:             stepm. It is no more the probability to die between last interview
        !          4416:             and month of death but the probability to survive from last
        !          4417:             interview up to one month before death multiplied by the
        !          4418:             probability to die within a month. Thanks to Chris
        !          4419:             Jackson for correcting this bug.  Former versions increased
        !          4420:             mortality artificially. The bad side is that we add another loop
        !          4421:             which slows down the processing. The difference can be up to 10%
        !          4422:             lower mortality.
        !          4423:          */
        !          4424:          /* If, at the beginning of the maximization mostly, the
        !          4425:             cumulative probability or probability to be dead is
        !          4426:             constant (ie = 1) over time d, the difference is equal to
        !          4427:             0.  out[s1][3] = savm[s1][3]: probability, being at state
        !          4428:             s1 at precedent wave, to be dead a month before current
        !          4429:             wave is equal to probability, being at state s1 at
        !          4430:             precedent wave, to be dead at mont of the current
        !          4431:             wave. Then the observed probability (that this person died)
        !          4432:             is null according to current estimated parameter. In fact,
        !          4433:             it should be very low but not zero otherwise the log go to
        !          4434:             infinity.
        !          4435:          */
1.1       brouard  4436: /* #ifdef INFINITYORIGINAL */
                   4437: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4438: /* #else */
                   4439: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   4440: /*         lli=log(mytinydouble); */
                   4441: /*       else */
                   4442: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4443: /* #endif */
1.2     ! brouard  4444:          lli=log(out[s1][s2] - savm[s1][s2]);
        !          4445:          
        !          4446:        } else if  ( s2==-1 ) { /* alive */
        !          4447:          for (j=1,survp=0. ; j<=nlstate; j++) 
        !          4448:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
        !          4449:          /*survp += out[s1][j]; */
        !          4450:          lli= log(survp);
        !          4451:        }
        !          4452:        /* else if  (s2==-4) {  */
        !          4453:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
        !          4454:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
        !          4455:        /*   lli= log(survp);  */
        !          4456:        /* }  */
        !          4457:        /* else if  (s2==-5) {  */
        !          4458:        /*   for (j=1,survp=0. ; j<=2; j++)   */
        !          4459:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
        !          4460:        /*   lli= log(survp);  */
        !          4461:        /* }  */
        !          4462:        else{
        !          4463:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
        !          4464:          /*  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 */
        !          4465:        } 
        !          4466:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
        !          4467:        /*if(lli ==000.0)*/
        !          4468:        /* 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); */
        !          4469:        ipmx +=1;
        !          4470:        sw += weight[i];
        !          4471:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
        !          4472:        /* if (lli < log(mytinydouble)){ */
        !          4473:        /*   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); */
        !          4474:        /*   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]); */
        !          4475:        /* } */
        !          4476:       } /* end of wave */
        !          4477:     } /* end of individual */
        !          4478:   }  else if(mle==2){
        !          4479:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
        !          4480:       ioffset=2+nagesqr ;
        !          4481:       for (k=1; k<=ncovf;k++)
        !          4482:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
        !          4483:       for(mi=1; mi<= wav[i]-1; mi++){
        !          4484:        for(k=1; k <= ncovv ; k++){
        !          4485:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; /* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
        !          4486:        }
        !          4487:        for (ii=1;ii<=nlstate+ndeath;ii++)
        !          4488:          for (j=1;j<=nlstate+ndeath;j++){
        !          4489:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          4490:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          4491:          }
        !          4492:        for(d=0; d<=dh[mi][i]; d++){
        !          4493:          newm=savm;
        !          4494:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          4495:          cov[2]=agexact;
        !          4496:          if(nagesqr==1)
        !          4497:            cov[3]= agexact*agexact;
        !          4498:          for (kk=1; kk<=cptcovage;kk++) {
        !          4499:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
        !          4500:          }
        !          4501:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
        !          4502:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
        !          4503:          savm=oldm;
        !          4504:          oldm=newm;
        !          4505:        } /* end mult */
        !          4506:       
        !          4507:        s1=s[mw[mi][i]][i];
        !          4508:        s2=s[mw[mi+1][i]][i];
        !          4509:        bbh=(double)bh[mi][i]/(double)stepm; 
        !          4510:        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 */
        !          4511:        ipmx +=1;
        !          4512:        sw += weight[i];
        !          4513:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
        !          4514:       } /* end of wave */
        !          4515:     } /* end of individual */
        !          4516:   }  else if(mle==3){  /* exponential inter-extrapolation */
        !          4517:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
        !          4518:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
        !          4519:       for(mi=1; mi<= wav[i]-1; mi++){
        !          4520:        for (ii=1;ii<=nlstate+ndeath;ii++)
        !          4521:          for (j=1;j<=nlstate+ndeath;j++){
        !          4522:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          4523:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          4524:          }
        !          4525:        for(d=0; d<dh[mi][i]; d++){
        !          4526:          newm=savm;
        !          4527:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          4528:          cov[2]=agexact;
        !          4529:          if(nagesqr==1)
        !          4530:            cov[3]= agexact*agexact;
        !          4531:          for (kk=1; kk<=cptcovage;kk++) {
        !          4532:            if(!FixedV[Tvar[Tage[kk]]])
        !          4533:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
        !          4534:            else
        !          4535:              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) */ 
        !          4536:          }
        !          4537:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
        !          4538:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
        !          4539:          savm=oldm;
        !          4540:          oldm=newm;
        !          4541:        } /* end mult */
        !          4542:       
        !          4543:        s1=s[mw[mi][i]][i];
        !          4544:        s2=s[mw[mi+1][i]][i];
        !          4545:        bbh=(double)bh[mi][i]/(double)stepm; 
        !          4546:        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 */
        !          4547:        ipmx +=1;
        !          4548:        sw += weight[i];
        !          4549:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
        !          4550:       } /* end of wave */
        !          4551:     } /* end of individual */
        !          4552:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
        !          4553:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
        !          4554:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
        !          4555:       for(mi=1; mi<= wav[i]-1; mi++){
        !          4556:        for (ii=1;ii<=nlstate+ndeath;ii++)
        !          4557:          for (j=1;j<=nlstate+ndeath;j++){
        !          4558:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          4559:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          4560:          }
        !          4561:        for(d=0; d<dh[mi][i]; d++){
        !          4562:          newm=savm;
        !          4563:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          4564:          cov[2]=agexact;
        !          4565:          if(nagesqr==1)
        !          4566:            cov[3]= agexact*agexact;
        !          4567:          for (kk=1; kk<=cptcovage;kk++) {
        !          4568:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
        !          4569:          }
        !          4570:        
        !          4571:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
        !          4572:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
        !          4573:          savm=oldm;
        !          4574:          oldm=newm;
        !          4575:        } /* end mult */
        !          4576:       
        !          4577:        s1=s[mw[mi][i]][i];
        !          4578:        s2=s[mw[mi+1][i]][i];
        !          4579:        if( s2 > nlstate){ 
        !          4580:          lli=log(out[s1][s2] - savm[s1][s2]);
        !          4581:        } else if  ( s2==-1 ) { /* alive */
        !          4582:          for (j=1,survp=0. ; j<=nlstate; j++) 
        !          4583:            survp += out[s1][j];
        !          4584:          lli= log(survp);
        !          4585:        }else{
        !          4586:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
        !          4587:        }
        !          4588:        ipmx +=1;
        !          4589:        sw += weight[i];
        !          4590:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
        !          4591:        /* 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])); */
        !          4592:       } /* end of wave */
        !          4593:     } /* end of individual */
        !          4594:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
        !          4595:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
        !          4596:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
        !          4597:       for(mi=1; mi<= wav[i]-1; mi++){
        !          4598:        for (ii=1;ii<=nlstate+ndeath;ii++)
        !          4599:          for (j=1;j<=nlstate+ndeath;j++){
        !          4600:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          4601:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          4602:          }
        !          4603:        for(d=0; d<dh[mi][i]; d++){
        !          4604:          newm=savm;
        !          4605:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          4606:          cov[2]=agexact;
        !          4607:          if(nagesqr==1)
        !          4608:            cov[3]= agexact*agexact;
        !          4609:          for (kk=1; kk<=cptcovage;kk++) {
        !          4610:            if(!FixedV[Tvar[Tage[kk]]])
        !          4611:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
        !          4612:            else
        !          4613:              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) */ 
        !          4614:          }
1.1       brouard  4615:        
1.2     ! brouard  4616:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
        !          4617:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
        !          4618:          savm=oldm;
        !          4619:          oldm=newm;
        !          4620:        } /* end mult */
        !          4621:       
        !          4622:        s1=s[mw[mi][i]][i];
        !          4623:        s2=s[mw[mi+1][i]][i];
        !          4624:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
        !          4625:        ipmx +=1;
        !          4626:        sw += weight[i];
        !          4627:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
        !          4628:        /*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]);*/
        !          4629:       } /* end of wave */
        !          4630:     } /* end of individual */
        !          4631:   } /* End of if */
1.1       brouard  4632:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4633:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4634:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4635:   return -l;
                   4636: }
                   4637: 
                   4638: /*************** log-likelihood *************/
                   4639: double funcone( double *x)
                   4640: {
                   4641:   /* Same as func but slower because of a lot of printf and if */
                   4642:   int i, ii, j, k, mi, d, kk, kv=0, kf=0;
                   4643:   int ioffset=0;
                   4644:   int ipos=0,iposold=0,ncovv=0;
                   4645: 
                   4646:   double cotvarv, cotvarvold;
                   4647:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   4648:   double **out;
                   4649:   double lli; /* Individual log likelihood */
                   4650:   double llt;
                   4651:   int s1, s2;
                   4652:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4653: 
                   4654:   double bbh, survp;
                   4655:   double agexact;
                   4656:   double agebegin, ageend;
                   4657:   /*extern weight */
                   4658:   /* We are differentiating ll according to initial status */
                   4659:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4660:   /*for(i=1;i<imx;i++) 
                   4661:     printf(" %d\n",s[4][i]);
                   4662:   */
                   4663:   cov[1]=1.;
                   4664: 
                   4665:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   4666:   ioffset=0;
                   4667:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4668:     /* Computes the values of the ncovmodel covariates of the model
                   4669:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4670:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4671:        to be observed in j being in i according to the model.
                   4672:     */
                   4673:     /* ioffset=2+nagesqr+cptcovage; */
                   4674:     ioffset=2+nagesqr;
                   4675:     /* Fixed */
                   4676:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
                   4677:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
                   4678:     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 */
                   4679:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   4680:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   4681:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
                   4682:       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)*/
                   4683: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4684: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4685: /*    cov[2+6]=covar[2][i]; V2  */
                   4686: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4687: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4688: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4689: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4690: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4691: /*    cov[2+9]=covar[1][i]; V1  */
                   4692:     }
1.2     ! brouard  4693:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
        !          4694:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
        !          4695:         has been calculated etc */
        !          4696:       /* For an individual i, wav[i] gives the number of effective waves */
        !          4697:       /* We compute the contribution to Likelihood of each effective transition
        !          4698:         mw[mi][i] is real wave of the mi th effectve wave */
        !          4699:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
        !          4700:         s2=s[mw[mi+1][i]][i];
        !          4701:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
        !          4702:       */
1.1       brouard  4703:     /* This part may be useless now because everythin should be in covar */
                   4704:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4705:     /*   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?)*\/ */
                   4706:     /* } */
                   4707:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4708:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4709:     /* } */
                   4710:     
                   4711: 
                   4712:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   4713:       /* 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 */
                   4714:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   4715:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   4716:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4717:       /* } */
                   4718:       
                   4719:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   4720:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   4721:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   4722:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   4723:       /* We need the position of the time varying or product in the model */
                   4724:       /* 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 */            
                   4725:       /* TvarVV gives the variable name */
                   4726:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   4727:       *      k=         1   2     3     4         5        6        7       8        9
                   4728:       *  varying            1     2                                 3       4        5
                   4729:       *  ncovv              1     2                                3 4     5 6      7 8
                   4730:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
                   4731:       * TvarVVind           2     3                                7 7     8 8      9 9
                   4732:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   4733:       */
                   4734:       /* Other model ncovcol=5 nqv=0 ntv=3 nqtv=0 nlstate=3
                   4735:        * 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
                   4736:        * FixedV[ncovcol+qv+ntv+nqtv]       V5
                   4737:        * 3           V1  V2     V3    V4   V5 V6     V7  V8 V3*V2 V7*V2  V6*V3 V7*V3 V6*V4 V7*V4
                   4738:        *             0   0      0      0    0  1      1   1  0, 0, 1,1,   1, 0, 1, 0, 1, 0, 1, 0}
                   4739:        * 3           0   0      0      0    0  1      1   1  0,     1      1    1      1    1}
                   4740:        * model=          V2  +  V3  +  V4  +  V6  +  V7  +  V6*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4741:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4742:         *                +age*V6*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4743:        * model2=          V2  +  V3  +  V4  +  V6  +  V7  +  V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4744:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4745:         *                +age*V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4746:        * model3=          V2  +  V3  +  V4  +  V6  +  V7  + age*V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4747:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4748:         *                +V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4749:        * kmodel           1     2      3      4      5        6         7         8         9        10        11    
                   4750:        *                  12       13      14      15       16
                   4751:        *                    17        18         19        20         21
                   4752:        * Tvar[kmodel]     2     3      4      6      7        9        10        11        12        13        14
                   4753:        *                   2       3        4       6        7
                   4754:        *                     9         11          12        13         14            
                   4755:        * cptcovage=5+5 total of covariates with age 
                   4756:        * Tage[cptcovage] age*V2=12      13      14      15       16
                   4757:        *1                   17            18         19        20         21 gives the position in model of covariates associated with age
                   4758:        *3 Tage[cptcovage] age*V3*V2=6  
                   4759:        *3                age*V2=12         13      14      15       16
                   4760:        *3                age*V6*V3=18      19    20   21
                   4761:        * Tvar[Tage[cptcovage]]    Tvar[12]=2      3      4       6         Tvar[16]=7(age*V7)
                   4762:        *     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
                   4763:        * 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
                   4764:        * 3 Tvar[Tage[cptcovage]]    Tvar[6]=9      Tvar[12]=2      3     4       6         Tvar[16]=7(age*V7)
                   4765:        * 3     Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   4766:        * 3 Tage[cptcovage] age*V3*V2=6   age*V2=12 age*V3 13    14      15       16
                   4767:        *                    age*V6*V3=18         19        20         21 gives the position in model of covariates associated with age
                   4768:        * 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
                   4769:        * Tvar=                {2, 3, 4, 6, 7,
                   4770:        *                       9, 10, 11, 12, 13, 14,
                   4771:        *              Tvar[12]=2, 3, 4, 6, 7,
                   4772:        *              Tvar[17]=9, 11, 12, 13, 14}
                   4773:        * Typevar[1]@21 = {0, 0, 0, 0, 0,
                   4774:        *                  2, 2, 2, 2, 2, 2,
                   4775:        * 3                3, 2, 2, 2, 2, 2,
                   4776:        *                  1, 1, 1, 1, 1, 
                   4777:        *                  3, 3, 3, 3, 3}
                   4778:        * 3                 2, 3, 3, 3, 3}
                   4779:        * 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
                   4780:        * p Tprod[1]@21 {6, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   4781:        * 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}
                   4782:        * 3 Tprod[1]@21 {17, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   4783:        * cptcovprod=11 (6+5)
                   4784:        * FixedV[Tvar[Tage[cptcovage]]]]  FixedV[2]=0      FixedV[3]=0      0      1          (age*V7)Tvar[16]=1 FixedV[absolute] not [kmodel]
                   4785:        *   FixedV[Tvar[17]=FixedV[age*V6*V2]=FixedV[9]=1        1         1          1         1  
                   4786:        * 3 FixedV[Tvar[17]=FixedV[age*V3*V2]=FixedV[9]=0        [11]=1         1          1         1  
                   4787:        * FixedV[]          V1=0     V2=0   V3=0  v4=0    V5=0  V6=1    V7=1 v8=1  OK then model dependent
                   4788:        *                   9=1  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   4789:        * 3                 9=0  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   4790:        * cptcovdageprod=5  for gnuplot printing
                   4791:        * cptcovprodvage=6 
                   4792:        * ncova=15           1        2       3       4       5
                   4793:        *                      6 7        8 9      10 11        12 13     14 15
                   4794:        * TvarA              2        3       4       6       7
                   4795:        *                      6 2        6 7       7 3          6 4       7 4
                   4796:        * TvaAind             12 12      13 13     14 14      15 15       16 16        
                   4797:        * ncovf            1     2      3
                   4798:        *                                    V6       V7      V6*V2     V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   4799:        * ncovvt=14                            1      2        3 4       5 6       7 8       9 10     11 12     13 14     
                   4800:        * TvarVV[1]@14 = itv               {V6=6,     7, V6*V2=6, 2,     7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4801:        * TvarVVind[1]@14=                    {4,     5,       6, 6,     7, 7,     8, 8,      9, 9,   10, 10,   11, 11}
                   4802:        * 3 ncovvt=12                        V6       V7      V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   4803:        * 3 TvarVV[1]@12 = itv                {6,     7, V7*V2=7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4804:        * 3                                    1      2        3  4      5  6      7  8      9 10     11 12
                   4805:        * TvarVVind[1]@12=         {V6 is in k=4,     5,  7,(4isV2)=7,   8, 8,      9, 9,   10,10,    11,11}TvarVVind[12]=k=11
                   4806:        * TvarV              6, 7, 9, 10, 11, 12, 13, 14
                   4807:        * 3 cptcovprodvage=6
                   4808:        * 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
                   4809:        * 3 TvarAVVA[1]@15= itva 3 2    2      3    4        6       7        6 3         7 3         6 4         7 4 
                   4810:        * 3 ncovta             1 2      3      4    5        6       7        8 9       10 11       12 13        14 15
                   4811:        * 
                   4812:        * TvarAVVAind[1]@15= V3 is in k=6 6 12  13   14      15      16       18 18       19,19,     20,20        21,21}TvarVVAind[]
                   4813:        * 3 ncovvta=10     +age*V6 + age*V7 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4814:        * 3 we want to compute =cotvar[mw[mi][i]][TvarVVA[ncovva]][i] at position TvarVVAind[ncovva]
                   4815:        * 3 TvarVVA[1]@10= itva   6       7        6 3         7 3         6 4         7 4 
                   4816:        * 3 ncovva                1       2        3 4         5 6         7 8         9 10
                   4817:        * TvarVVAind[1]@10= V6 is in k=4  5        8,8         9, 9,      10,10        11 11}TvarVVAind[]
                   4818:        * TvarVVAind[1]@10=       15       16     18,18        19,19,      20,20        21 21}TvarVVAind[]
                   4819:        * TvarVA              V3*V2=6 6 , 1, 2, 11, 12, 13, 14
                   4820:        * TvarFind[1]@14= {1,    2,     3,     0 <repeats 12 times>}
                   4821:        * Tvar[1]@21=     {2,    3,     4,    6,      7,      9,      10,        11,       12,      13,       14,
                   4822:        *                   2, 3, 4, 6, 7,
                   4823:        *                     6, 8, 9, 10, 11}
                   4824:        * TvarFind[itv]                        0      0       0
                   4825:        * FixedV[itv]                          1      1       1  0      1 0       1 0       1 0      1 0     1 0
                   4826:        * Tvar[TvarFind[ncovf]]=[1]=2 [2]=3 [4]=4
                   4827:        * Tvar[TvarFind[itv]]                [0]=?      ?ncovv 1 à ncovvt]
                   4828:        *   Not a fixed cotvar[mw][itv][i]     6       7      6  2      7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   4829:        *   fixed covar[itv]                  [6]     [7]    [6][2] 
                   4830:        */
1.2     ! brouard  4831: 
1.1       brouard  4832:       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 */
                   4833:        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  */
                   4834:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4835:        /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4836:        if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4837:          /* printf("DEBUG ncovv=%d, Varying TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
                   4838:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4839:          /* printf("DEBUG Varying cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
                   4840:        }else{ /* fixed covariate */
                   4841:          /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   4842:          /* printf("DEBUG ncovv=%d, Fixed TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
                   4843:          cotvarv=covar[itv][i];  /* Good: In V6*V3, 3 is fixed at position of the data */
                   4844:          /* printf("DEBUG Fixed cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
                   4845:        }
                   4846:        if(ipos!=iposold){ /* Not a product or first of a product */
                   4847:          cotvarvold=cotvarv;
                   4848:        }else{ /* A second product */
                   4849:          cotvarv=cotvarv*cotvarvold;
                   4850:        }
                   4851:        iposold=ipos;
                   4852:        cov[ioffset+ipos]=cotvarv;
                   4853:        /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   4854:        /* For products */
                   4855:       }
                   4856:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   4857:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   4858:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   4859:       /*       /\*           1  2   3      4      5                         *\/ */
                   4860:       /*       /\*itv           1                                           *\/ */
                   4861:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   4862:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   4863:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   4864:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   4865:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   4866:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   4867:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   4868:       /*       /\* 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]); *\/ */
                   4869:       /* } */
                   4870:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
                   4871:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4872:       /*       /\* 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]); *\/ */
                   4873:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
                   4874:       /* } */
                   4875:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   4876:        for (j=1;j<=nlstate+ndeath;j++){
                   4877:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4878:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4879:        }
                   4880:       
                   4881:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4882:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4883:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
                   4884:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
                   4885:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4886:          and mw[mi+1][i]. dh depends on stepm.*/
                   4887:        newm=savm;
                   4888:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
                   4889:        cov[2]=agexact;
                   4890:        if(nagesqr==1)
                   4891:          cov[3]= agexact*agexact;
1.2     ! brouard  4892:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
        !          4893:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
        !          4894:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.1       brouard  4895:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   4896:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
1.2     ! brouard  4897:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
        !          4898:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
1.1       brouard  4899:          }else{ /* fixed covariate */
                   4900:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
1.2     ! brouard  4901:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
1.1       brouard  4902:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4903:          }
                   4904:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4905:            cotvarvold=cotvarv;
                   4906:          }else{ /* A second product */
                   4907:            /* printf("DEBUG * \n"); */
                   4908:            cotvarv=cotvarv*cotvarvold;
                   4909:          }
                   4910:          iposold=ipos;
1.2     ! brouard  4911:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
1.1       brouard  4912:          cov[ioffset+ipos]=cotvarv*agexact;
                   4913:          /* For products */
                   4914:        }
                   4915: 
                   4916:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4917:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4918:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4919:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4920:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4921:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4922:        savm=oldm;
                   4923:        oldm=newm;
                   4924:       } /* end mult */
                   4925:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4926:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4927:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4928:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4929:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4930:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4931:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4932:         * probability in order to take into account the bias as a fraction of the way
                   4933:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4934:                                 * -stepm/2 to stepm/2 .
                   4935:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4936:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4937:                                 */
                   4938:       s1=s[mw[mi][i]][i];
                   4939:       s2=s[mw[mi+1][i]][i];
                   4940:       /* if(s2==-1){ */
                   4941:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
                   4942:       /*       /\* exit(1); *\/ */
                   4943:       /* } */
                   4944:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4945:       /* bias is positive if real duration
                   4946:        * is higher than the multiple of stepm and negative otherwise.
                   4947:        */
                   4948:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   4949:        lli=log(out[s1][s2] - savm[s1][s2]);
                   4950:       } else if  ( s2==-1 ) { /* alive */
                   4951:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4952:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4953:        lli= log(survp);
                   4954:       }else if (mle==1){
                   4955:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4956:       } else if(mle==2){
                   4957:        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 */
                   4958:       } else if(mle==3){  /* exponential inter-extrapolation */
                   4959:        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 */
                   4960:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   4961:        lli=log(out[s1][s2]); /* Original formula */
                   4962:       } else{  /* mle=0 back to 1 */
                   4963:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4964:        /*lli=log(out[s1][s2]); */ /* Original formula */
                   4965:       } /* End of if */
                   4966:       ipmx +=1;
                   4967:       sw += weight[i];
                   4968:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4969:       /* Printing covariates values for each contribution for checking */
                   4970:       /* 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])); */
                   4971:       if(globpr){
                   4972:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
                   4973:  %11.6f %11.6f %11.6f ", \
                   4974:                num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
                   4975:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.2     ! brouard  4976:        /*      printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
1.1       brouard  4977:        /* %11.6f %11.6f %11.6f ", \ */
                   4978:        /*              num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   4979:        /*              2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
                   4980:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4981:          llt +=ll[k]*gipmx/gsw;
                   4982:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   4983:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
                   4984:        }
                   4985:        fprintf(ficresilk," %10.6f ", -llt);
                   4986:        /* printf(" %10.6f\n", -llt); */
                   4987:        /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
                   4988:        /* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
                   4989:        for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   4990:          fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
                   4991:        }
                   4992:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   4993:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4994:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4995:            fprintf(ficresilk," %g",cov[ioffset+ipos]);
                   4996:            /* printf(" %g",cov[ioffset+ipos]); */
                   4997:          }else{
                   4998:            fprintf(ficresilk,"*");
                   4999:            /* printf("*"); */
                   5000:          }
                   5001:          iposold=ipos;
                   5002:        }
                   5003:        /* for (kk=1; kk<=cptcovage;kk++) { */
                   5004:        /*   if(!FixedV[Tvar[Tage[kk]]]){ */
                   5005:        /*     fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]); */
                   5006:        /*     /\* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); *\/ */
                   5007:        /*   }else{ */
                   5008:        /*     fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   5009:        /*     /\* printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\\/  *\/ */
                   5010:        /*   } */
                   5011:        /* } */
1.2     ! brouard  5012:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
        !          5013:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
        !          5014:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
        !          5015:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
        !          5016:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
        !          5017:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
        !          5018:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
        !          5019:          }else{ /* fixed covariate */
        !          5020:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
        !          5021:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
        !          5022:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
        !          5023:          }
        !          5024:          if(ipos!=iposold){ /* Not a product or first of a product */
        !          5025:            cotvarvold=cotvarv;
        !          5026:          }else{ /* A second product */
        !          5027:            /* printf("DEBUG * \n"); */
        !          5028:            cotvarv=cotvarv*cotvarvold;
        !          5029:          }
        !          5030:          cotvarv=cotvarv*agexact;
        !          5031:          fprintf(ficresilk," %g*age",cotvarv);
        !          5032:          iposold=ipos;
        !          5033:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
        !          5034:          cov[ioffset+ipos]=cotvarv;
        !          5035:          /* For products */
        !          5036:        }
1.1       brouard  5037:        /* printf("\n"); */
                   5038:        /* } /\*  End debugILK *\/ */
                   5039:        fprintf(ficresilk,"\n");
                   5040:       } /* End if globpr */
                   5041:     } /* end of wave */
                   5042:   } /* end of individual */
                   5043:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   5044: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   5045:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   5046:   if(globpr==0){ /* First time we count the contributions and weights */
                   5047:     gipmx=ipmx;
                   5048:     gsw=sw;
                   5049:   }
                   5050:   return -l;
                   5051: }
                   5052: 
                   5053: 
                   5054: /*************** function likelione ***********/
                   5055: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
                   5056: {
                   5057:   /* This routine should help understanding what is done with 
                   5058:      the selection of individuals/waves and
                   5059:      to check the exact contribution to the likelihood.
                   5060:      Plotting could be done.
                   5061:   */
                   5062:   void pstamp(FILE *ficres);
1.2     ! brouard  5063:   int k, kf, kk, kvar, ncovv, iposold, ipos;
1.1       brouard  5064: 
                   5065:   if(*globpri !=0){ /* Just counts and sums, no printings */
                   5066:     strcpy(fileresilk,"ILK_"); 
                   5067:     strcat(fileresilk,fileresu);
                   5068:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   5069:       printf("Problem with resultfile: %s\n", fileresilk);
                   5070:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   5071:     }
                   5072:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
                   5073:     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");
                   5074:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
                   5075:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   5076:     for(k=1; k<=nlstate; k++) 
                   5077:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   5078:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
                   5079: 
                   5080:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
1.2     ! brouard  5081:       for(kf=1;kf <= ncovf; kf++){
        !          5082:        fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
        !          5083:        /* printf("V%d",Tvar[TvarFind[kf]]); */
        !          5084:       }
        !          5085:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
        !          5086:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
        !          5087:        if(ipos!=iposold){ /* Not a product or first of a product */
        !          5088:          /* printf(" %d",ipos); */
        !          5089:          fprintf(ficresilk," V%d",TvarVV[ncovv]);
        !          5090:        }else{
        !          5091:          /* printf("*"); */
        !          5092:          fprintf(ficresilk,"*");
        !          5093:        }
        !          5094:        iposold=ipos;
1.1       brouard  5095:       }
1.2     ! brouard  5096:       for (kk=1; kk<=cptcovage;kk++) {
        !          5097:        if(!FixedV[Tvar[Tage[kk]]]){
        !          5098:          /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
        !          5099:          fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
        !          5100:        }else{
        !          5101:          fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
        !          5102:          /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
        !          5103:        }
1.1       brouard  5104:       }
                   5105:     /* } /\* End if debugILK *\/ */
                   5106:     /* printf("\n"); */
                   5107:     fprintf(ficresilk,"\n");
                   5108:   } /* End glogpri */
                   5109: 
                   5110:   *fretone=(*func)(p);
                   5111:   if(*globpri !=0){
                   5112:     fclose(ficresilk);
                   5113:     if (mle ==0)
                   5114:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   5115:     else if(mle >=1)
                   5116:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   5117:     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));
                   5118:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
                   5119:       
                   5120:     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> \
                   5121: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   5122:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
                   5123: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   5124:     
                   5125:     for (k=1; k<= nlstate ; k++) {
                   5126:       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 \
                   5127: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   5128:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.2     ! brouard  5129:         kvar=Tvar[TvarFind[kf]];  /* variable */
        !          5130:         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]]);
        !          5131:         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);
        !          5132:         fprintf(fichtm,"<img src=\"%s-p%dj-%d.png\">",subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]);
1.1       brouard  5133:       }
                   5134:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
                   5135:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   5136:        kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   5137:        /* 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]); */
                   5138:        if(ipos!=iposold){ /* Not a product or first of a product */
                   5139:          /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   5140:          /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
                   5141:          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)  */
                   5142:            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> \
                   5143: <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);
                   5144:          } /* End only for dummies time varying (single?) */
                   5145:        }else{ /* Useless product */
                   5146:          /* printf("*"); */
                   5147:          /* fprintf(ficresilk,"*"); */ 
                   5148:        }
                   5149:        iposold=ipos;
                   5150:       } /* For each time varying covariate */
                   5151:     } /* End loop on states */
                   5152: 
                   5153: /*     if(debugILK){ */
                   5154: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
                   5155: /*     /\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
                   5156: /*     for (k=1; k<= nlstate ; k++) { */
                   5157: /*       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> \ */
                   5158: /* <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]]); */
                   5159: /*     } */
                   5160: /*       } */
                   5161: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
                   5162: /*     ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
                   5163: /*     kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
                   5164: /*     /\* 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]); *\/ */
                   5165: /*     if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
                   5166: /*       /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
                   5167: /*       /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
                   5168: /*       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)  *\/ */
                   5169: /*         for (k=1; k<= nlstate ; k++) { */
                   5170: /*           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> \ */
                   5171: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
                   5172: /*         } /\* End state *\/ */
                   5173: /*       } /\* End only for dummies time varying (single?) *\/ */
                   5174: /*     }else{ /\* Useless product *\/ */
                   5175: /*       /\* printf("*"); *\/ */
                   5176: /*       /\* fprintf(ficresilk,"*"); *\/  */
                   5177: /*     } */
                   5178: /*     iposold=ipos; */
                   5179: /*       } /\* For each time varying covariate *\/ */
                   5180: /*     }/\* End debugILK *\/ */
                   5181:     fflush(fichtm);
                   5182:   }/* End globpri */
                   5183:   return;
                   5184: }
                   5185: 
                   5186: 
                   5187: /*********** Maximum Likelihood Estimation ***************/
                   5188: 
                   5189: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   5190: {
                   5191:   int i,j,k, jk, jkk=0, iter=0;
                   5192:   double **xi;
                   5193:   double fret;
                   5194:   double fretone; /* Only one call to likelihood */
                   5195:   /*  char filerespow[FILENAMELENGTH];*/
                   5196:   
                   5197:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   5198: #ifdef NLOPT
                   5199:   int creturn;
                   5200:   nlopt_opt opt;
                   5201:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   5202:   double *lb;
                   5203:   double minf; /* the minimum objective value, upon return */
                   5204: 
                   5205:   myfunc_data dinst, *d = &dinst;
                   5206: #endif
                   5207: 
                   5208: 
                   5209:   xi=matrix(1,npar,1,npar);
                   5210:   for (i=1;i<=npar;i++)
                   5211:     for (j=1;j<=npar;j++)
                   5212:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   5213:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
                   5214:   strcpy(filerespow,"POW_"); 
                   5215:   strcat(filerespow,fileres);
                   5216:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   5217:     printf("Problem with resultfile: %s\n", filerespow);
                   5218:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   5219:   }
                   5220:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   5221:   for (i=1;i<=nlstate;i++)
                   5222:     for(j=1;j<=nlstate+ndeath;j++)
                   5223:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   5224:   fprintf(ficrespow,"\n");
                   5225: #ifdef POWELL
                   5226: #ifdef LINMINORIGINAL
                   5227: #else /* LINMINORIGINAL */
                   5228:   
                   5229:   flatdir=ivector(1,npar); 
                   5230:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   5231: #endif /*LINMINORIGINAL */
                   5232: 
                   5233: #ifdef FLATSUP
                   5234:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   5235:   /* reorganizing p by suppressing flat directions */
                   5236:   for(i=1, jk=1; i <=nlstate; i++){
                   5237:     for(k=1; k <=(nlstate+ndeath); k++){
                   5238:       if (k != i) {
                   5239:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   5240:         if(flatdir[jk]==1){
                   5241:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   5242:         }
                   5243:         for(j=1; j <=ncovmodel; j++){
                   5244:           printf("%12.7f ",p[jk]);
                   5245:           jk++; 
                   5246:         }
                   5247:         printf("\n");
                   5248:       }
                   5249:     }
                   5250:   }
                   5251: /* skipping */
                   5252:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   5253:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   5254:     for(k=1; k <=(nlstate+ndeath); k++){
                   5255:       if (k != i) {
                   5256:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   5257:         if(flatdir[jk]==1){
                   5258:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   5259:           for(j=1; j <=ncovmodel;  jk++,j++){
                   5260:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   5261:             /*q[jjk]=p[jk];*/
                   5262:           }
                   5263:         }else{
                   5264:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   5265:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   5266:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   5267:             /*q[jjk]=p[jk];*/
                   5268:           }
                   5269:         }
                   5270:         printf("\n");
                   5271:       }
                   5272:       fflush(stdout);
                   5273:     }
                   5274:   }
                   5275:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   5276: #else  /* FLATSUP */
                   5277: /*  powell(p,xi,npar,ftol,&iter,&fret,func);*/
                   5278: /*   praxis ( t0, h0, n, prin, x, beale_f ); */
                   5279:   int prin=4;
                   5280:   double h0=0.25;
                   5281: #include "praxis.h"
                   5282:   /* Be careful that praxis start at x[0] and powell start at p[1] */
                   5283:    /* praxis ( ftol, h0, npar, prin, p, func ); */
                   5284: p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   5285: printf("Praxis \n");
                   5286: fprintf(ficlog, "Praxis \n");fflush(ficlog);
                   5287: praxis ( ftol, h0, npar, prin, p1, func );
                   5288: printf("End Praxis\n");
                   5289: #endif  /* FLATSUP */
                   5290: 
                   5291: #ifdef LINMINORIGINAL
                   5292: #else
                   5293:       free_ivector(flatdir,1,npar); 
                   5294: #endif  /* LINMINORIGINAL*/
                   5295: #endif /* POWELL */
                   5296: 
                   5297: #ifdef NLOPT
                   5298: #ifdef NEWUOA
                   5299:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   5300: #else
                   5301:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   5302: #endif
                   5303:   lb=vector(0,npar-1);
                   5304:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   5305:   nlopt_set_lower_bounds(opt, lb);
                   5306:   nlopt_set_initial_step1(opt, 0.1);
                   5307:   
                   5308:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   5309:   d->function = func;
                   5310:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   5311:   nlopt_set_min_objective(opt, myfunc, d);
                   5312:   nlopt_set_xtol_rel(opt, ftol);
                   5313:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   5314:     printf("nlopt failed! %d\n",creturn); 
                   5315:   }
                   5316:   else {
                   5317:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   5318:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   5319:     iter=1; /* not equal */
                   5320:   }
                   5321:   nlopt_destroy(opt);
                   5322: #endif
                   5323: #ifdef FLATSUP
                   5324:   /* npared = npar -flatd/ncovmodel; */
                   5325:   /* xired= matrix(1,npared,1,npared); */
                   5326:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   5327:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   5328:   /* free_matrix(xire,1,npared,1,npared); */
                   5329: #else  /* FLATSUP */
                   5330: #endif /* FLATSUP */
                   5331:   free_matrix(xi,1,npar,1,npar);
                   5332:   fclose(ficrespow);
                   5333:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   5334:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   5335:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   5336: 
                   5337: }
                   5338: 
                   5339: /**** Computes Hessian and covariance matrix ***/
                   5340: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
                   5341: {
                   5342:   double  **a,**y,*x,pd;
                   5343:   /* double **hess; */
                   5344:   int i, j;
                   5345:   int *indx;
                   5346: 
                   5347:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
                   5348:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
                   5349:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   5350:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   5351:   double gompertz(double p[]);
                   5352:   /* hess=matrix(1,npar,1,npar); */
                   5353: 
                   5354:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   5355:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   5356:   for (i=1;i<=npar;i++){
                   5357:     printf("%d-",i);fflush(stdout);
                   5358:     fprintf(ficlog,"%d-",i);fflush(ficlog);
                   5359:    
                   5360:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   5361:     
                   5362:     /*  printf(" %f ",p[i]);
                   5363:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   5364:   }
                   5365:   
                   5366:   for (i=1;i<=npar;i++) {
                   5367:     for (j=1;j<=npar;j++)  {
                   5368:       if (j>i) { 
                   5369:        printf(".%d-%d",i,j);fflush(stdout);
                   5370:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   5371:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
                   5372:        
                   5373:        hess[j][i]=hess[i][j];    
                   5374:        /*printf(" %lf ",hess[i][j]);*/
                   5375:       }
                   5376:     }
                   5377:   }
                   5378:   printf("\n");
                   5379:   fprintf(ficlog,"\n");
                   5380: 
                   5381:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   5382:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   5383:   
                   5384:   a=matrix(1,npar,1,npar);
                   5385:   y=matrix(1,npar,1,npar);
                   5386:   x=vector(1,npar);
                   5387:   indx=ivector(1,npar);
                   5388:   for (i=1;i<=npar;i++)
                   5389:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   5390:   ludcmp(a,npar,indx,&pd);
                   5391: 
                   5392:   for (j=1;j<=npar;j++) {
                   5393:     for (i=1;i<=npar;i++) x[i]=0;
                   5394:     x[j]=1;
                   5395:     lubksb(a,npar,indx,x);
                   5396:     for (i=1;i<=npar;i++){ 
                   5397:       matcov[i][j]=x[i];
                   5398:     }
                   5399:   }
                   5400: 
                   5401:   printf("\n#Hessian matrix#\n");
                   5402:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   5403:   for (i=1;i<=npar;i++) { 
                   5404:     for (j=1;j<=npar;j++) { 
                   5405:       printf("%.6e ",hess[i][j]);
                   5406:       fprintf(ficlog,"%.6e ",hess[i][j]);
                   5407:     }
                   5408:     printf("\n");
                   5409:     fprintf(ficlog,"\n");
                   5410:   }
                   5411: 
                   5412:   /* printf("\n#Covariance matrix#\n"); */
                   5413:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   5414:   /* for (i=1;i<=npar;i++) {  */
                   5415:   /*   for (j=1;j<=npar;j++) {  */
                   5416:   /*     printf("%.6e ",matcov[i][j]); */
                   5417:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   5418:   /*   } */
                   5419:   /*   printf("\n"); */
                   5420:   /*   fprintf(ficlog,"\n"); */
                   5421:   /* } */
                   5422: 
                   5423:   /* Recompute Inverse */
                   5424:   /* for (i=1;i<=npar;i++) */
                   5425:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   5426:   /* ludcmp(a,npar,indx,&pd); */
                   5427: 
                   5428:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   5429: 
                   5430:   /* for (j=1;j<=npar;j++) { */
                   5431:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   5432:   /*   x[j]=1; */
                   5433:   /*   lubksb(a,npar,indx,x); */
                   5434:   /*   for (i=1;i<=npar;i++){  */
                   5435:   /*     y[i][j]=x[i]; */
                   5436:   /*     printf("%.3e ",y[i][j]); */
                   5437:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   5438:   /*   } */
                   5439:   /*   printf("\n"); */
                   5440:   /*   fprintf(ficlog,"\n"); */
                   5441:   /* } */
                   5442: 
                   5443:   /* Verifying the inverse matrix */
                   5444: #ifdef DEBUGHESS
                   5445:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
                   5446: 
                   5447:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   5448:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
                   5449: 
                   5450:   for (j=1;j<=npar;j++) {
                   5451:     for (i=1;i<=npar;i++){ 
                   5452:       printf("%.2f ",y[i][j]);
                   5453:       fprintf(ficlog,"%.2f ",y[i][j]);
                   5454:     }
                   5455:     printf("\n");
                   5456:     fprintf(ficlog,"\n");
                   5457:   }
                   5458: #endif
                   5459: 
                   5460:   free_matrix(a,1,npar,1,npar);
                   5461:   free_matrix(y,1,npar,1,npar);
                   5462:   free_vector(x,1,npar);
                   5463:   free_ivector(indx,1,npar);
                   5464:   /* free_matrix(hess,1,npar,1,npar); */
                   5465: 
                   5466: 
                   5467: }
                   5468: 
                   5469: /*************** hessian matrix ****************/
                   5470: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
                   5471: { /* Around values of x, computes the function func and returns the scales delti and hessian */
                   5472:   int i;
                   5473:   int l=1, lmax=20;
                   5474:   double k1,k2, res, fx;
                   5475:   double p2[MAXPARM+1]; /* identical to x */
                   5476:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   5477:   int k=0,kmax=10;
                   5478:   double l1;
                   5479: 
                   5480:   fx=func(x);
                   5481:   for (i=1;i<=npar;i++) p2[i]=x[i];
                   5482:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
                   5483:     l1=pow(10,l);
                   5484:     delts=delt;
                   5485:     for(k=1 ; k <kmax; k=k+1){
                   5486:       delt = delta*(l1*k);
                   5487:       p2[theta]=x[theta] +delt;
                   5488:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
                   5489:       p2[theta]=x[theta]-delt;
                   5490:       k2=func(p2)-fx;
                   5491:       /*res= (k1-2.0*fx+k2)/delt/delt; */
                   5492:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
                   5493:       
                   5494: #ifdef DEBUGHESSII
                   5495:       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);
                   5496:       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);
                   5497: #endif
                   5498:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   5499:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   5500:        k=kmax;
                   5501:       }
                   5502:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
                   5503:        k=kmax; l=lmax*10;
                   5504:       }
                   5505:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   5506:        delts=delt;
                   5507:       }
                   5508:     } /* End loop k */
                   5509:   }
                   5510:   delti[theta]=delts;
                   5511:   return res; 
                   5512:   
                   5513: }
                   5514: 
                   5515: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
                   5516: {
                   5517:   int i;
                   5518:   int l=1, lmax=20;
                   5519:   double k1,k2,k3,k4,res,fx;
                   5520:   double p2[MAXPARM+1];
                   5521:   int k, kmax=1;
                   5522:   double v1, v2, cv12, lc1, lc2;
                   5523: 
                   5524:   int firstime=0;
                   5525:   
                   5526:   fx=func(x);
                   5527:   for (k=1; k<=kmax; k=k+10) {
                   5528:     for (i=1;i<=npar;i++) p2[i]=x[i];
                   5529:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5530:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
                   5531:     k1=func(p2)-fx;
                   5532:   
                   5533:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5534:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
                   5535:     k2=func(p2)-fx;
                   5536:   
                   5537:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5538:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
                   5539:     k3=func(p2)-fx;
                   5540:   
                   5541:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5542:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
                   5543:     k4=func(p2)-fx;
                   5544:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   5545:     if(k1*k2*k3*k4 <0.){
                   5546:       firstime=1;
                   5547:       kmax=kmax+10;
                   5548:     }
                   5549:     if(kmax >=10 || firstime ==1){
                   5550:       /* What are the thetai and thetaj? thetai/ncovmodel thetai=(thetai-thetai%ncovmodel)/ncovmodel +thetai%ncovmodel=(line,pos)  */
                   5551:       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);
                   5552:       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);
                   5553:       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);
                   5554:       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);
                   5555:     }
                   5556: #ifdef DEBUGHESSIJ
                   5557:     v1=hess[thetai][thetai];
                   5558:     v2=hess[thetaj][thetaj];
                   5559:     cv12=res;
                   5560:     /* Computing eigen value of Hessian matrix */
                   5561:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5562:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5563:     if ((lc2 <0) || (lc1 <0) ){
                   5564:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5565:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5566:       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);
                   5567:       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);
                   5568:     }
                   5569: #endif
                   5570:   }
                   5571:   return res;
                   5572: }
                   5573: 
                   5574:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   5575: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   5576: /* { */
                   5577: /*   int i; */
                   5578: /*   int l=1, lmax=20; */
                   5579: /*   double k1,k2,k3,k4,res,fx; */
                   5580: /*   double p2[MAXPARM+1]; */
                   5581: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   5582: /*   int k=0,kmax=10; */
                   5583: /*   double l1; */
                   5584:   
                   5585: /*   fx=func(x); */
                   5586: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   5587: /*     l1=pow(10,l); */
                   5588: /*     delts=delt; */
                   5589: /*     for(k=1 ; k <kmax; k=k+1){ */
                   5590: /*       delt = delti*(l1*k); */
                   5591: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   5592: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5593: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5594: /*       k1=func(p2)-fx; */
                   5595:       
                   5596: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5597: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5598: /*       k2=func(p2)-fx; */
                   5599:       
                   5600: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5601: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5602: /*       k3=func(p2)-fx; */
                   5603:       
                   5604: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5605: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5606: /*       k4=func(p2)-fx; */
                   5607: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   5608: /* #ifdef DEBUGHESSIJ */
                   5609: /*       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); */
                   5610: /*       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); */
                   5611: /* #endif */
                   5612: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   5613: /*     k=kmax; */
                   5614: /*       } */
                   5615: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   5616: /*     k=kmax; l=lmax*10; */
                   5617: /*       } */
                   5618: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   5619: /*     delts=delt; */
                   5620: /*       } */
                   5621: /*     } /\* End loop k *\/ */
                   5622: /*   } */
                   5623: /*   delti[theta]=delts; */
                   5624: /*   return res;  */
                   5625: /* } */
                   5626: 
                   5627: 
                   5628: /************** Inverse of matrix **************/
                   5629: void ludcmp(double **a, int n, int *indx, double *d) 
                   5630: { 
                   5631:   int i,imax,j,k; 
                   5632:   double big,dum,sum,temp; 
                   5633:   double *vv; 
                   5634:  
                   5635:   vv=vector(1,n); 
                   5636:   *d=1.0; 
                   5637:   for (i=1;i<=n;i++) { 
                   5638:     big=0.0; 
                   5639:     for (j=1;j<=n;j++) 
                   5640:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   5641:     if (big == 0.0){
                   5642:       printf(" Singular Hessian matrix at row %d:\n",i);
                   5643:       for (j=1;j<=n;j++) {
                   5644:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   5645:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   5646:       }
                   5647:       fflush(ficlog);
                   5648:       fclose(ficlog);
                   5649:       nrerror("Singular matrix in routine ludcmp"); 
                   5650:     }
                   5651:     vv[i]=1.0/big; 
                   5652:   } 
                   5653:   for (j=1;j<=n;j++) { 
                   5654:     for (i=1;i<j;i++) { 
                   5655:       sum=a[i][j]; 
                   5656:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   5657:       a[i][j]=sum; 
                   5658:     } 
                   5659:     big=0.0; 
                   5660:     for (i=j;i<=n;i++) { 
                   5661:       sum=a[i][j]; 
                   5662:       for (k=1;k<j;k++) 
                   5663:        sum -= a[i][k]*a[k][j]; 
                   5664:       a[i][j]=sum; 
                   5665:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   5666:        big=dum; 
                   5667:        imax=i; 
                   5668:       } 
                   5669:     } 
                   5670:     if (j != imax) { 
                   5671:       for (k=1;k<=n;k++) { 
                   5672:        dum=a[imax][k]; 
                   5673:        a[imax][k]=a[j][k]; 
                   5674:        a[j][k]=dum; 
                   5675:       } 
                   5676:       *d = -(*d); 
                   5677:       vv[imax]=vv[j]; 
                   5678:     } 
                   5679:     indx[j]=imax; 
                   5680:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   5681:     if (j != n) { 
                   5682:       dum=1.0/(a[j][j]); 
                   5683:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   5684:     } 
                   5685:   } 
                   5686:   free_vector(vv,1,n);  /* Doesn't work */
                   5687: ;
                   5688: } 
                   5689: 
                   5690: void lubksb(double **a, int n, int *indx, double b[]) 
                   5691: { 
                   5692:   int i,ii=0,ip,j; 
                   5693:   double sum; 
                   5694:  
                   5695:   for (i=1;i<=n;i++) { 
                   5696:     ip=indx[i]; 
                   5697:     sum=b[ip]; 
                   5698:     b[ip]=b[i]; 
                   5699:     if (ii) 
                   5700:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   5701:     else if (sum) ii=i; 
                   5702:     b[i]=sum; 
                   5703:   } 
                   5704:   for (i=n;i>=1;i--) { 
                   5705:     sum=b[i]; 
                   5706:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   5707:     b[i]=sum/a[i][i]; 
                   5708:   } 
                   5709: } 
                   5710: 
                   5711: void pstamp(FILE *fichier)
                   5712: {
                   5713:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
                   5714: }
                   5715: 
                   5716: void date2dmy(double date,double *day, double *month, double *year){
                   5717:   double yp=0., yp1=0., yp2=0.;
                   5718:   
                   5719:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   5720:                        fractional in yp1 */
                   5721:   *year=yp;
                   5722:   yp2=modf((yp1*12),&yp);
                   5723:   *month=yp;
                   5724:   yp1=modf((yp2*30.5),&yp);
                   5725:   *day=yp;
                   5726:   if(*day==0) *day=1;
                   5727:   if(*month==0) *month=1;
                   5728: }
                   5729: 
                   5730: 
                   5731: 
                   5732: /************ Frequencies ********************/
                   5733: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
                   5734:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   5735:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
                   5736: {  /* Some frequencies as well as proposing some starting values */
                   5737:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
                   5738:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
                   5739:   int iind=0, iage=0;
                   5740:   int mi; /* Effective wave */
                   5741:   int first;
                   5742:   double ***freq; /* Frequencies */
                   5743:   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 */
                   5744:   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);
                   5745:   double *meanq, *stdq, *idq;
                   5746:   double **meanqt;
                   5747:   double *pp, **prop, *posprop, *pospropt;
                   5748:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   5749:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   5750:   double agebegin, ageend;
                   5751:     
                   5752:   pp=vector(1,nlstate);
                   5753:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
                   5754:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   5755:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   5756:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   5757:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
                   5758:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
                   5759:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
                   5760:   meanqt=matrix(1,lastpass,1,nqtveff);
                   5761:   strcpy(fileresp,"P_");
                   5762:   strcat(fileresp,fileresu);
                   5763:   /*strcat(fileresphtm,fileresu);*/
                   5764:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   5765:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   5766:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   5767:     exit(0);
                   5768:   }
                   5769:   
                   5770:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   5771:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   5772:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5773:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5774:     fflush(ficlog);
                   5775:     exit(70); 
                   5776:   }
                   5777:   else{
                   5778:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   5779: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
                   5780: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
                   5781:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5782:   }
                   5783:   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);
                   5784:   
                   5785:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   5786:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   5787:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5788:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5789:     fflush(ficlog);
                   5790:     exit(70); 
                   5791:   } else{
                   5792:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   5793: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
                   5794: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
                   5795:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5796:   }
                   5797:   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);
                   5798:   
                   5799:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   5800:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   5801:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   5802:   j1=0;
                   5803:   
                   5804:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   5805:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
                   5806:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
                   5807:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   5808:   
                   5809:   
                   5810:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   5811:      reference=low_education V1=0,V2=0
                   5812:      med_educ                V1=1 V2=0, 
                   5813:      high_educ               V1=0 V2=1
                   5814:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
                   5815:   */
                   5816:   dateintsum=0;
                   5817:   k2cpt=0;
                   5818: 
                   5819:   if(cptcoveff == 0 )
                   5820:     nl=1;  /* Constant and age model only */
                   5821:   else
                   5822:     nl=2;
                   5823: 
                   5824:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   5825:   /* Loop on nj=1 or 2 if dummy covariates j!=0
                   5826:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
                   5827:    *     freq[s1][s2][iage] =0.
                   5828:    *     Loop on iind
                   5829:    *       ++freq[s1][s2][iage] weighted
                   5830:    *     end iind
                   5831:    *     if covariate and j!0
                   5832:    *       headers Variable on one line
                   5833:    *     endif cov j!=0
                   5834:    *     header of frequency table by age
                   5835:    *     Loop on age
                   5836:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   5837:    *       pos+=freq[s1][s2][iage] weighted
                   5838:    *       Loop on s1 initial state
                   5839:    *         fprintf(ficresp
                   5840:    *       end s1
                   5841:    *     end age
                   5842:    *     if j!=0 computes starting values
                   5843:    *     end compute starting values
                   5844:    *   end j1
                   5845:    * end nl 
                   5846:    */
                   5847:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5848:     if(nj==1)
                   5849:       j=0;  /* First pass for the constant */
                   5850:     else{
                   5851:       j=cptcoveff; /* Other passes for the covariate values number of simple covariates in the model V2+V1 =2 (simple dummy fixed or time varying) */
                   5852:     }
                   5853:     first=1;
                   5854:     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 */
                   5855:       posproptt=0.;
                   5856:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
                   5857:        scanf("%d", i);*/
                   5858:       for (i=-5; i<=nlstate+ndeath; i++)  
                   5859:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
                   5860:          for(m=iagemin; m <= iagemax+3; m++)
                   5861:            freq[i][s2][m]=0;
                   5862:       
                   5863:       for (i=1; i<=nlstate; i++)  {
                   5864:        for(m=iagemin; m <= iagemax+3; m++)
                   5865:          prop[i][m]=0;
                   5866:        posprop[i]=0;
                   5867:        pospropt[i]=0;
                   5868:       }
                   5869:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
                   5870:         idq[z1]=0.;
                   5871:         meanq[z1]=0.;
                   5872:         stdq[z1]=0.;
                   5873:       }
                   5874:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5875:       /*   for(m=1;m<=lastpass;m++){ */
                   5876:       /*         meanqt[m][z1]=0.; */
                   5877:       /*       } */
                   5878:       /* }       */
                   5879:       /* dateintsum=0; */
                   5880:       /* k2cpt=0; */
                   5881:       
                   5882:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
                   5883:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5884:        bool=1;
                   5885:        if(j !=0){
                   5886:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
                   5887:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5888:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
                   5889:                /* if(Tvaraff[z1] ==-20){ */
                   5890:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5891:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5892:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
                   5893:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
                   5894:                /* 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); */
                   5895:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
                   5896:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
                   5897:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
                   5898:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
                   5899:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
                   5900:                  /* 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", */
                   5901:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5902:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   5903:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5904:                } /* Onlyf fixed */
                   5905:              } /* end z1 */
                   5906:            } /* cptcoveff > 0 */
                   5907:          } /* end any */
                   5908:        }/* end j==0 */
                   5909:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
                   5910:          /* for(m=firstpass; m<=lastpass; m++){ */
                   5911:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
                   5912:            m=mw[mi][iind];
                   5913:            if(j!=0){
                   5914:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   5915:                for (z1=1; z1<=cptcoveff; z1++) {
                   5916:                  if( Fixed[Tmodelind[z1]]==1){
                   5917:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
                   5918:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
                   5919:                    if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality. If covariate's 
                   5920:                                                                                      value is -1, we don't select. It differs from the 
                   5921:                                                                                      constant and age model which counts them. */
                   5922:                      bool=0; /* not selected */
                   5923:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   5924:                    /* i1=Tvaraff[z1]; */
                   5925:                    /* i2=TnsdVar[i1]; */
                   5926:                    /* i3=nbcode[i1][i2]; */
                   5927:                    /* i4=covar[i1][iind]; */
                   5928:                    /* if(i4 != i3){ */
                   5929:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
                   5930:                      bool=0;
                   5931:                    }
                   5932:                  }
                   5933:                }
                   5934:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5935:            } /* end j==0 */
                   5936:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
                   5937:            if(bool==1){ /*Selected */
                   5938:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5939:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5940:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5941:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5942:              if(m >=firstpass && m <=lastpass){
                   5943:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5944:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5945:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5946:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5947:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5948:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5949:                if (m<lastpass) {
                   5950:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5951:                  /*   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]); */
                   5952:                  if(s[m][iind]==-1)
                   5953:                    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.));
                   5954:                  freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
                   5955:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5956:                    if(!isnan(covar[ncovcol+z1][iind])){
                   5957:                      idq[z1]=idq[z1]+weight[iind];
                   5958:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5959:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5960:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
                   5961:                    }
                   5962:                  }
                   5963:                  /* if((int)agev[m][iind] == 55) */
                   5964:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5965:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5966:                  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 */
                   5967:                }
                   5968:              } /* end if between passes */  
                   5969:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5970:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5971:                k2cpt++;
                   5972:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
                   5973:              }
                   5974:            }else{
                   5975:              bool=1;
                   5976:            }/* end bool 2 */
                   5977:          } /* end m */
                   5978:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5979:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5980:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5981:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5982:          /* } */
                   5983:        } /* end bool */
                   5984:       } /* end iind = 1 to imx */
                   5985:       /* prop[s][age] is fed for any initial and valid live state as well as
                   5986:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5987:       
                   5988:       
                   5989:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   5990:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
                   5991:         pstamp(ficresp);
                   5992:       if  (cptcoveff>0 && j!=0){
                   5993:         pstamp(ficresp);
                   5994:        printf( "\n#********** Variable "); 
                   5995:        fprintf(ficresp, "\n#********** Variable "); 
                   5996:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5997:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5998:        fprintf(ficlog, "\n#********** Variable "); 
                   5999:        for (z1=1; z1<=cptcoveff; z1++){
                   6000:          if(!FixedV[Tvaraff[z1]]){
                   6001:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   6002:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   6003:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   6004:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   6005:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   6006:          }else{
                   6007:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   6008:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   6009:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   6010:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   6011:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   6012:          }
                   6013:        }
                   6014:        printf( "**********\n#");
                   6015:        fprintf(ficresp, "**********\n#");
                   6016:        fprintf(ficresphtm, "**********</h3>\n");
                   6017:        fprintf(ficresphtmfr, "**********</h3>\n");
                   6018:        fprintf(ficlog, "**********\n");
                   6019:       }
                   6020:       /*
                   6021:        Printing means of quantitative variables if any
                   6022:       */
                   6023:       for (z1=1; z1<= nqfveff; z1++) {
                   6024:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
                   6025:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
                   6026:        if(weightopt==1){
                   6027:          printf(" Weighted mean and standard deviation of");
                   6028:          fprintf(ficlog," Weighted mean and standard deviation of");
                   6029:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   6030:        }
                   6031:        /* mu = \frac{w x}{\sum w}
                   6032:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   6033:        */
                   6034:        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]));
                   6035:        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]));
                   6036:        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]));
                   6037:       }
                   6038:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   6039:       /*       for(m=1;m<=lastpass;m++){ */
                   6040:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   6041:       /*   } */
                   6042:       /* } */
                   6043: 
                   6044:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
                   6045:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
                   6046:         fprintf(ficresp, " Age");
                   6047:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   6048:          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]]);
                   6049:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   6050:        }
                   6051:       for(i=1; i<=nlstate;i++) {
                   6052:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
                   6053:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   6054:       }
                   6055:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
                   6056:       fprintf(ficresphtm, "\n");
                   6057:       
                   6058:       /* Header of frequency table by age */
                   6059:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   6060:       fprintf(ficresphtmfr,"<th>Age</th> ");
                   6061:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   6062:        for(m=-1; m <=nlstate+ndeath; m++){
                   6063:          if(s2!=0 && m!=0)
                   6064:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
                   6065:        }
                   6066:       }
                   6067:       fprintf(ficresphtmfr, "\n");
                   6068:     
                   6069:       /* For each age */
                   6070:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   6071:        fprintf(ficresphtm,"<tr>");
                   6072:        if(iage==iagemax+1){
                   6073:          fprintf(ficlog,"1");
                   6074:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   6075:        }else if(iage==iagemax+2){
                   6076:          fprintf(ficlog,"0");
                   6077:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   6078:        }else if(iage==iagemax+3){
                   6079:          fprintf(ficlog,"Total");
                   6080:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   6081:        }else{
                   6082:          if(first==1){
                   6083:            first=0;
                   6084:            printf("See log file for details...\n");
                   6085:          }
                   6086:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   6087:          fprintf(ficlog,"Age %d", iage);
                   6088:        }
                   6089:        for(s1=1; s1 <=nlstate ; s1++){
                   6090:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   6091:            pp[s1] += freq[s1][m][iage]; 
                   6092:        }
                   6093:        for(s1=1; s1 <=nlstate ; s1++){
                   6094:          for(m=-1, pos=0; m <=0 ; m++)
                   6095:            pos += freq[s1][m][iage];
                   6096:          if(pp[s1]>=1.e-10){
                   6097:            if(first==1){
                   6098:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
                   6099:            }
                   6100:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
                   6101:          }else{
                   6102:            if(first==1)
                   6103:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   6104:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   6105:          }
                   6106:        }
                   6107:       
                   6108:        for(s1=1; s1 <=nlstate ; s1++){ 
                   6109:          /* posprop[s1]=0; */
                   6110:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   6111:            pp[s1] += freq[s1][m][iage];
                   6112:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   6113:       
                   6114:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   6115:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   6116:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   6117:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   6118:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   6119:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   6120:        }
                   6121:        
                   6122:        /* Writing ficresp */
                   6123:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   6124:           if( iage <= iagemax){
                   6125:            fprintf(ficresp," %d",iage);
                   6126:           }
                   6127:         }else if( nj==2){
                   6128:           if( iage <= iagemax){
                   6129:            fprintf(ficresp," %d",iage);
                   6130:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   6131:           }
                   6132:        }
                   6133:        for(s1=1; s1 <=nlstate ; s1++){
                   6134:          if(pos>=1.e-5){
                   6135:            if(first==1)
                   6136:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   6137:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   6138:          }else{
                   6139:            if(first==1)
                   6140:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   6141:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   6142:          }
                   6143:          if( iage <= iagemax){
                   6144:            if(pos>=1.e-5){
                   6145:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   6146:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   6147:               }else if( nj==2){
                   6148:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   6149:               }
                   6150:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   6151:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   6152:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   6153:            } else{
                   6154:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
                   6155:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
                   6156:            }
                   6157:          }
                   6158:          pospropt[s1] +=posprop[s1];
                   6159:        } /* end loop s1 */
                   6160:        /* pospropt=0.; */
                   6161:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   6162:          for(m=-1; m <=nlstate+ndeath; m++){
                   6163:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
                   6164:              if(first==1){
                   6165:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
                   6166:              }
                   6167:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   6168:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
                   6169:            }
                   6170:            if(s1!=0 && m!=0)
                   6171:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
                   6172:          }
                   6173:        } /* end loop s1 */
                   6174:        posproptt=0.; 
                   6175:        for(s1=1; s1 <=nlstate; s1++){
                   6176:          posproptt += pospropt[s1];
                   6177:        }
                   6178:        fprintf(ficresphtmfr,"</tr>\n ");
                   6179:        fprintf(ficresphtm,"</tr>\n");
                   6180:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
                   6181:          if(iage <= iagemax)
                   6182:            fprintf(ficresp,"\n");
                   6183:        }
                   6184:        if(first==1)
                   6185:          printf("Others in log...\n");
                   6186:        fprintf(ficlog,"\n");
                   6187:       } /* end loop age iage */
                   6188:       
                   6189:       fprintf(ficresphtm,"<tr><th>Tot</th>");
                   6190:       for(s1=1; s1 <=nlstate ; s1++){
                   6191:        if(posproptt < 1.e-5){
                   6192:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
                   6193:        }else{
                   6194:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
                   6195:        }
                   6196:       }
                   6197:       fprintf(ficresphtm,"</tr>\n");
                   6198:       fprintf(ficresphtm,"</table>\n");
                   6199:       fprintf(ficresphtmfr,"</table>\n");
                   6200:       if(posproptt < 1.e-5){
                   6201:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   6202:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   6203:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   6204:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
                   6205:        invalidvarcomb[j1]=1;
                   6206:       }else{
                   6207:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
                   6208:        invalidvarcomb[j1]=0;
                   6209:       }
                   6210:       fprintf(ficresphtmfr,"</table>\n");
                   6211:       fprintf(ficlog,"\n");
                   6212:       if(j!=0){
                   6213:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
                   6214:        for(i=1,s1=1; i <=nlstate; i++){
                   6215:          for(k=1; k <=(nlstate+ndeath); k++){
                   6216:            if (k != i) {
                   6217:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
                   6218:                if(jj==1){  /* Constant case (in fact cste + age) */
                   6219:                  if(j1==1){ /* All dummy covariates to zero */
                   6220:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   6221:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
                   6222:                    printf("%d%d ",i,k);
                   6223:                    fprintf(ficlog,"%d%d ",i,k);
                   6224:                    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]));
                   6225:                    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]));
                   6226:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   6227:                  }
                   6228:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   6229:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   6230:                    x[iage]= (double)iage;
                   6231:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
                   6232:                    /* printf("i=%d, k=%d, s1=%d, j1=%d, jj=%d, y[%d]=%f\n",i,k,s1,j1,jj, iage, y[iage]); */
                   6233:                  }
                   6234:                  /* Some are not finite, but linreg will ignore these ages */
                   6235:                  no=0;
                   6236:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
                   6237:                  pstart[s1]=b;
                   6238:                  pstart[s1-1]=a;
                   6239:                }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 */ 
                   6240:                  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]);
                   6241:                  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]);
                   6242:                  pstart[s1]= log((freq[i][k][iagemax+3]/freq[i][i][iagemax+3])/(freq[i][k][iagemax+4]/freq[i][i][iagemax+4]));
                   6243:                  printf("%d%d ",i,k);
                   6244:                  fprintf(ficlog,"%d%d ",i,k);
                   6245:                  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]));
                   6246:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   6247:                  ;
                   6248:                }
                   6249:                /* printf("%12.7f )", param[i][jj][k]); */
                   6250:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
                   6251:                s1++; 
                   6252:              } /* end jj */
                   6253:            } /* end k!= i */
                   6254:          } /* end k */
                   6255:        } /* end i, s1 */
                   6256:       } /* end j !=0 */
                   6257:     } /* end selected combination of covariate j1 */
                   6258:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   6259:       printf("#Freqsummary: Starting values for the constants:\n");
                   6260:       fprintf(ficlog,"\n");
                   6261:       for(i=1,s1=1; i <=nlstate; i++){
                   6262:        for(k=1; k <=(nlstate+ndeath); k++){
                   6263:          if (k != i) {
                   6264:            printf("%d%d ",i,k);
                   6265:            fprintf(ficlog,"%d%d ",i,k);
                   6266:            for(jj=1; jj <=ncovmodel; jj++){
                   6267:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
                   6268:              if(jj==1){ /* Age has to be done */
                   6269:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   6270:                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]));
                   6271:                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]));
                   6272:              }
                   6273:              /* printf("%12.7f )", param[i][jj][k]); */
                   6274:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
                   6275:              s1++; 
                   6276:            }
                   6277:            printf("\n");
                   6278:            fprintf(ficlog,"\n");
                   6279:          }
                   6280:        }
                   6281:       } /* end of state i */
                   6282:       printf("#Freqsummary\n");
                   6283:       fprintf(ficlog,"\n");
                   6284:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   6285:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   6286:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   6287:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   6288:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   6289:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   6290:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   6291:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   6292:          /* } */
                   6293:        }
                   6294:       } /* end loop s1 */
                   6295:       
                   6296:       printf("\n");
                   6297:       fprintf(ficlog,"\n");
                   6298:     } /* end j=0 */
                   6299:   } /* end j */
                   6300: 
                   6301:   if(mle == -2){  /* We want to use these values as starting values */
                   6302:     for(i=1, jk=1; i <=nlstate; i++){
                   6303:       for(j=1; j <=nlstate+ndeath; j++){
                   6304:        if(j!=i){
                   6305:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   6306:          printf("%1d%1d",i,j);
                   6307:          fprintf(ficparo,"%1d%1d",i,j);
                   6308:          for(k=1; k<=ncovmodel;k++){
                   6309:            /*    printf(" %lf",param[i][j][k]); */
                   6310:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   6311:            p[jk]=pstart[jk];
                   6312:            printf(" %f ",pstart[jk]);
                   6313:            fprintf(ficparo," %f ",pstart[jk]);
                   6314:            jk++;
                   6315:          }
                   6316:          printf("\n");
                   6317:          fprintf(ficparo,"\n");
                   6318:        }
                   6319:       }
                   6320:     }
                   6321:   } /* end mle=-2 */
                   6322:   dateintmean=dateintsum/k2cpt; 
                   6323:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
                   6324:   
                   6325:   fclose(ficresp);
                   6326:   fclose(ficresphtm);
                   6327:   fclose(ficresphtmfr);
                   6328:   free_vector(idq,1,nqfveff);
                   6329:   free_vector(meanq,1,nqfveff);
                   6330:   free_vector(stdq,1,nqfveff);
                   6331:   free_matrix(meanqt,1,lastpass,1,nqtveff);
                   6332:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   6333:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   6334:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   6335:   free_vector(pospropt,1,nlstate);
                   6336:   free_vector(posprop,1,nlstate);
                   6337:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   6338:   free_vector(pp,1,nlstate);
                   6339:   /* End of freqsummary */
                   6340: }
                   6341: 
                   6342: /* Simple linear regression */
                   6343: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   6344: 
                   6345:   /* y=a+bx regression */
                   6346:   double   sumx = 0.0;                        /* sum of x                      */
                   6347:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   6348:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   6349:   double   sumy = 0.0;                        /* sum of y                      */
                   6350:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   6351:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   6352:   double yhat;
                   6353:   
                   6354:   double denom=0;
                   6355:   int i;
                   6356:   int ne=*no;
                   6357:   
                   6358:   for ( i=ifi, ne=0;i<=ila;i++) {
                   6359:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   6360:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   6361:       continue;
                   6362:     }
                   6363:     ne=ne+1;
                   6364:     sumx  += x[i];       
                   6365:     sumx2 += x[i]*x[i];  
                   6366:     sumxy += x[i] * y[i];
                   6367:     sumy  += y[i];      
                   6368:     sumy2 += y[i]*y[i]; 
                   6369:     denom = (ne * sumx2 - sumx*sumx);
                   6370:     /* 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); */
                   6371:   } 
                   6372:   
                   6373:   denom = (ne * sumx2 - sumx*sumx);
                   6374:   if (denom == 0) {
                   6375:     // vertical, slope m is infinity
                   6376:     *b = INFINITY;
                   6377:     *a = 0;
                   6378:     if (r) *r = 0;
                   6379:     return 1;
                   6380:   }
                   6381:   
                   6382:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   6383:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   6384:   if (r!=NULL) {
                   6385:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   6386:       sqrt((sumx2 - sumx*sumx/ne) *
                   6387:           (sumy2 - sumy*sumy/ne));
                   6388:   }
                   6389:   *no=ne;
                   6390:   for ( i=ifi, ne=0;i<=ila;i++) {
                   6391:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   6392:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   6393:       continue;
                   6394:     }
                   6395:     ne=ne+1;
                   6396:     yhat = y[i] - *a -*b* x[i];
                   6397:     sume2  += yhat * yhat ;       
                   6398:     
                   6399:     denom = (ne * sumx2 - sumx*sumx);
                   6400:     /* 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); */
                   6401:   } 
                   6402:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   6403:   *sa= *sb * sqrt(sumx2/ne);
                   6404:   
                   6405:   return 0; 
                   6406: }
                   6407: 
                   6408: /************ Prevalence ********************/
                   6409: 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)
                   6410: {  
                   6411:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   6412:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   6413:      We still use firstpass and lastpass as another selection.
                   6414:   */
                   6415:  
                   6416:   int i, m, jk, j1, bool, z1,j, iv;
                   6417:   int mi; /* Effective wave */
                   6418:   int iage;
                   6419:   double agebegin, ageend;
                   6420: 
                   6421:   double **prop;
                   6422:   double posprop; 
                   6423:   double  y2; /* in fractional years */
                   6424:   int iagemin, iagemax;
                   6425:   int first; /** to stop verbosity which is redirected to log file */
                   6426: 
                   6427:   iagemin= (int) agemin;
                   6428:   iagemax= (int) agemax;
                   6429:   /*pp=vector(1,nlstate);*/
                   6430:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
                   6431:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   6432:   j1=0;
                   6433:   
                   6434:   /*j=cptcoveff;*/
                   6435:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   6436:   
                   6437:   first=0;
                   6438:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
                   6439:     for (i=1; i<=nlstate; i++)  
                   6440:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
                   6441:        prop[i][iage]=0.0;
                   6442:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   6443:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   6444:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   6445:     
                   6446:     for (i=1; i<=imx; i++) { /* Each individual */
                   6447:       bool=1;
                   6448:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   6449:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   6450:        m=mw[mi][i];
                   6451:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   6452:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   6453:        for (z1=1; z1<=cptcoveff; z1++){
                   6454:          if( Fixed[Tmodelind[z1]]==1){
                   6455:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   6456:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
                   6457:              bool=0;
                   6458:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   6459:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
                   6460:              bool=0;
                   6461:            }
                   6462:        }
                   6463:        if(bool==1){ /* Otherwise we skip that wave/person */
                   6464:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   6465:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   6466:          if(m >=firstpass && m <=lastpass){
                   6467:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   6468:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   6469:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   6470:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   6471:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
                   6472:                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); 
                   6473:                exit(1);
                   6474:              }
                   6475:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   6476:                /*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]]);*/
                   6477:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   6478:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   6479:              } /* end valid statuses */ 
                   6480:            } /* end selection of dates */
                   6481:          } /* end selection of waves */
                   6482:        } /* end bool */
                   6483:       } /* end wave */
                   6484:     } /* end individual */
                   6485:     for(i=iagemin; i <= iagemax+3; i++){  
                   6486:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   6487:        posprop += prop[jk][i]; 
                   6488:       } 
                   6489:       
                   6490:       for(jk=1; jk <=nlstate ; jk++){      
                   6491:        if( i <=  iagemax){ 
                   6492:          if(posprop>=1.e-5){ 
                   6493:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   6494:          } else{
                   6495:            if(!first){
                   6496:              first=1;
                   6497:              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]);
                   6498:            }else{
                   6499:              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]);
                   6500:            }
                   6501:          }
                   6502:        } 
                   6503:       }/* end jk */ 
                   6504:     }/* end i */ 
                   6505:      /*} *//* end i1 */
                   6506:   } /* end j1 */
                   6507:   
                   6508:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   6509:   /*free_vector(pp,1,nlstate);*/
                   6510:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   6511: }  /* End of prevalence */
                   6512: 
                   6513: /************* Waves Concatenation ***************/
                   6514: 
                   6515: 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)
                   6516: {
                   6517:   /* Concatenates waves: wav[i] is the number of effective (useful waves in the sense that a non interview is useless) of individual i.
                   6518:      Death is a valid wave (if date is known).
                   6519:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   6520:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   6521:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
                   6522:   */
                   6523: 
                   6524:   int i=0, mi=0, m=0, mli=0;
                   6525:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   6526:      double sum=0., jmean=0.;*/
                   6527:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
                   6528:   int j, k=0,jk, ju, jl;
                   6529:   double sum=0.;
                   6530:   first=0;
                   6531:   firstwo=0;
                   6532:   firsthree=0;
                   6533:   firstfour=0;
                   6534:   jmin=100000;
                   6535:   jmax=-1;
                   6536:   jmean=0.;
                   6537: 
                   6538: /* Treating live states */
                   6539:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
                   6540:     mi=0;  /* First valid wave */
                   6541:     mli=0; /* Last valid wave */
                   6542:     m=firstpass;  /* Loop on waves */
                   6543:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
                   6544:       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 */
                   6545:        mli=m-1;/* mw[++mi][i]=m-1; */
                   6546:       }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 */
                   6547:        mw[++mi][i]=m; /* Valid wave: incrementing mi and updating mi; mw[mi] is the wave number of mi_th valid transition   */
                   6548:        mli=m;
                   6549:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   6550:       if(m < lastpass){ /* m < lastpass, standard case */
                   6551:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
                   6552:       }
                   6553:       else{ /* m = lastpass, eventual special issue with warning */
                   6554: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
                   6555:        break;
                   6556: #else
                   6557:        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 */
                   6558:          if(firsthree == 0){
                   6559:            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);
                   6560:            firsthree=1;
                   6561:          }else if(firsthree >=1 && firsthree < 10){
                   6562:            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);
                   6563:            firsthree++;
                   6564:          }else if(firsthree == 10){
                   6565:            printf("Information, too many Information flags: no more reported to log either\n");
                   6566:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   6567:            firsthree++;
                   6568:          }else{
                   6569:            firsthree++;
                   6570:          }
                   6571:          mw[++mi][i]=m; /* Valid transition with unknown status */
                   6572:          mli=m;
                   6573:        }
                   6574:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   6575:          nbwarn++;
                   6576:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
                   6577:            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);
                   6578:            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);
                   6579:          }
                   6580:          break;
                   6581:        }
                   6582:        break;
                   6583: #endif
                   6584:       }/* End m >= lastpass */
                   6585:     }/* end while */
                   6586: 
                   6587:     /* mi is the last effective wave, m is lastpass, mw[j][i] gives the # of j-th effective wave for individual i */
                   6588:     /* After last pass */
                   6589: /* Treating death states */
                   6590:     if (s[m][i] > nlstate){  /* In a death state */
                   6591:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   6592:       /* } */
                   6593:       mi++;    /* Death is another wave */
                   6594:       /* if(mi==0)  never been interviewed correctly before death */
                   6595:       /* Only death is a correct wave */
                   6596:       mw[mi][i]=m;
                   6597:     } /* else not in a death state */
                   6598: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
                   6599:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
                   6600:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
                   6601:        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 */
                   6602:          nbwarn++;
                   6603:          if(firstfiv==0){
                   6604:            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 );
                   6605:            firstfiv=1;
                   6606:          }else{
                   6607:            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 );
                   6608:          }
                   6609:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   6610:        }else{ /* Month of Death occured afer last wave month, potential bias */
                   6611:          nberr++;
                   6612:          if(firstwo==0){
                   6613:            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 );
                   6614:            firstwo=1;
                   6615:          }
                   6616:          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 );
                   6617:        }
                   6618:       }else{ /* if date of interview is unknown */
                   6619:        /* death is known but not confirmed by death status at any wave */
                   6620:        if(firstfour==0){
                   6621:          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 );
                   6622:          firstfour=1;
                   6623:        }
                   6624:        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 );
                   6625:       }
                   6626:     } /* end if date of death is known */
                   6627: #endif
                   6628:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   6629:     /* wav[i]=mw[mi][i];   */
                   6630:     if(mi==0){
                   6631:       nbwarn++;
                   6632:       if(first==0){
                   6633:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   6634:        first=1;
                   6635:       }
                   6636:       if(first==1){
                   6637:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   6638:       }
                   6639:     } /* end mi==0 */
                   6640:   } /* End individuals */
                   6641:   /* wav and mw are no more changed */
                   6642:        
                   6643:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6644:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6645: 
                   6646: 
                   6647:   for(i=1; i<=imx; i++){
                   6648:     for(mi=1; mi<wav[i];mi++){
                   6649:       if (stepm <=0)
                   6650:        dh[mi][i]=1;
                   6651:       else{
                   6652:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
                   6653:          if (agedc[i] < 2*AGESUP) {
                   6654:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   6655:            if(j==0) j=1;  /* Survives at least one month after exam */
                   6656:            else if(j<0){
                   6657:              nberr++;
                   6658:              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]);
                   6659:              j=1; /* Temporary Dangerous patch */
                   6660:              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);
                   6661:              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]);
                   6662:              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);
                   6663:            }
                   6664:            k=k+1;
                   6665:            if (j >= jmax){
                   6666:              jmax=j;
                   6667:              ijmax=i;
                   6668:            }
                   6669:            if (j <= jmin){
                   6670:              jmin=j;
                   6671:              ijmin=i;
                   6672:            }
                   6673:            sum=sum+j;
                   6674:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   6675:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   6676:          }
                   6677:        }
                   6678:        else{
                   6679:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   6680: /*       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]); */
                   6681:                                        
                   6682:          k=k+1;
                   6683:          if (j >= jmax) {
                   6684:            jmax=j;
                   6685:            ijmax=i;
                   6686:          }
                   6687:          else if (j <= jmin){
                   6688:            jmin=j;
                   6689:            ijmin=i;
                   6690:          }
                   6691:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   6692:          /*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]);*/
                   6693:          if(j<0){
                   6694:            nberr++;
                   6695:            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]);
                   6696:            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]);
                   6697:          }
                   6698:          sum=sum+j;
                   6699:        }
                   6700:        jk= j/stepm;
                   6701:        jl= j -jk*stepm;
                   6702:        ju= j -(jk+1)*stepm;
                   6703:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   6704:          if(jl==0){
                   6705:            dh[mi][i]=jk;
                   6706:            bh[mi][i]=0;
                   6707:          }else{ /* We want a negative bias in order to only have interpolation ie
                   6708:                  * to avoid the price of an extra matrix product in likelihood */
                   6709:            dh[mi][i]=jk+1;
                   6710:            bh[mi][i]=ju;
                   6711:          }
                   6712:        }else{
                   6713:          if(jl <= -ju){
                   6714:            dh[mi][i]=jk;
                   6715:            bh[mi][i]=jl;       /* bias is positive if real duration
                   6716:                                 * is higher than the multiple of stepm and negative otherwise.
                   6717:                                 */
                   6718:          }
                   6719:          else{
                   6720:            dh[mi][i]=jk+1;
                   6721:            bh[mi][i]=ju;
                   6722:          }
                   6723:          if(dh[mi][i]==0){
                   6724:            dh[mi][i]=1; /* At least one step */
                   6725:            bh[mi][i]=ju; /* At least one step */
                   6726:            /*  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);*/
                   6727:          }
                   6728:        } /* end if mle */
                   6729:       }
                   6730:     } /* end wave */
                   6731:   }
                   6732:   jmean=sum/k;
                   6733:   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);
                   6734:   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);
                   6735: }
                   6736: 
                   6737: /*********** Tricode ****************************/
                   6738:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
                   6739:  {
                   6740:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   6741:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   6742:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   6743:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   6744:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   6745:     */
                   6746: 
                   6747:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   6748:    int modmaxcovj=0; /* Modality max of covariates j */
                   6749:    int cptcode=0; /* Modality max of covariates j */
                   6750:    int modmincovj=0; /* Modality min of covariates j */
                   6751: 
                   6752: 
                   6753:    /* cptcoveff=0;  */
                   6754:    /* *cptcov=0; */
                   6755:  
                   6756:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
                   6757:    for (k=1; k <= maxncov; k++)
                   6758:      for(j=1; j<=2; j++)
                   6759:        nbcode[k][j]=0; /* Valgrind */
                   6760: 
                   6761:    /* Loop on covariates without age and products and no quantitative variable */
                   6762:    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 */
                   6763:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   6764:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
                   6765:      if(Dummy[k]==0 && Typevar[k] !=1 && Typevar[k] != 3  && Typevar[k] != 2){ /* Dummy covariate and not age product nor fixed product */ 
                   6766:        switch(Fixed[k]) {
                   6767:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
                   6768:         modmaxcovj=0;
                   6769:         modmincovj=0;
                   6770:         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*/
                   6771:           /* 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])); */
                   6772:           ij=(int)(covar[Tvar[k]][i]);
                   6773:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   6774:            * If product of Vn*Vm, still boolean *:
                   6775:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   6776:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   6777:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   6778:              modality of the nth covariate of individual i. */
                   6779:           if (ij > modmaxcovj)
                   6780:             modmaxcovj=ij; 
                   6781:           else if (ij < modmincovj) 
                   6782:             modmincovj=ij; 
                   6783:           if (ij <0 || ij >1 ){
                   6784:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6785:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6786:             fflush(ficlog);
                   6787:             exit(1);
                   6788:           }
                   6789:           if ((ij < -1) || (ij > NCOVMAX)){
                   6790:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   6791:             exit(1);
                   6792:           }else
                   6793:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   6794:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   6795:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   6796:           /* getting the maximum value of the modality of the covariate
                   6797:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   6798:              female ies 1, then modmaxcovj=1.
                   6799:           */
                   6800:         } /* end for loop on individuals i */
                   6801:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6802:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6803:         cptcode=modmaxcovj;
                   6804:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   6805:         /*for (i=0; i<=cptcode; i++) {*/
                   6806:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   6807:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6808:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6809:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   6810:             if( j != -1){
                   6811:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   6812:                                  covariate for which somebody answered excluding 
                   6813:                                  undefined. Usually 2: 0 and 1. */
                   6814:             }
                   6815:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   6816:                                     covariate for which somebody answered including 
                   6817:                                     undefined. Usually 3: -1, 0 and 1. */
                   6818:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   6819:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   6820:         } /* Ndum[-1] number of undefined modalities */
                   6821:                        
                   6822:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   6823:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   6824:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   6825:         /* modmincovj=3; modmaxcovj = 7; */
                   6826:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   6827:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   6828:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   6829:         /* nbcode[Tvar[j]][ij]=k; */
                   6830:         /* nbcode[Tvar[j]][1]=0; */
                   6831:         /* nbcode[Tvar[j]][2]=1; */
                   6832:         /* nbcode[Tvar[j]][3]=2; */
                   6833:         /* To be continued (not working yet). */
                   6834:         ij=0; /* ij is similar to i but can jump over null modalities */
                   6835: 
                   6836:         /* 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*/
                   6837:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   6838:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   6839:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   6840:         /*, could be restored in the future */
                   6841:         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*/
                   6842:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   6843:             break;
                   6844:           }
                   6845:           ij++;
                   6846:           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*/
                   6847:           cptcode = ij; /* New max modality for covar j */
                   6848:         } /* end of loop on modality i=-1 to 1 or more */
                   6849:         break;
                   6850:        case 1: /* Testing on varying covariate, could be simple and
                   6851:                * should look at waves or product of fixed *
                   6852:                * varying. No time to test -1, assuming 0 and 1 only */
                   6853:         ij=0;
                   6854:         for(i=0; i<=1;i++){
                   6855:           nbcode[Tvar[k]][++ij]=i;
                   6856:         }
                   6857:         break;
                   6858:        default:
                   6859:         break;
                   6860:        } /* end switch */
                   6861:      } /* end dummy test */
                   6862:      if(Dummy[k]==1 && Typevar[k] !=1 && Typevar[k] !=3 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
                   6863:        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*/
                   6864:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   6865:           printf("Error k=%d \n",k);
                   6866:           exit(1);
                   6867:         }
                   6868:         if(isnan(covar[Tvar[k]][i])){
                   6869:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6870:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6871:           fflush(ficlog);
                   6872:           exit(1);
                   6873:          }
                   6874:        }
                   6875:      } /* end Quanti */
                   6876:    } /* 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*/  
                   6877:   
                   6878:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6879:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6880:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6881:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6882:      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 */ 
                   6883:      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 */
                   6884:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6885:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6886:   
                   6887:    ij=0;
                   6888:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   6889:    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 */
                   6890:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   6891:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6892:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   6893:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   6894:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   6895:        /* Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product*/
                   6896:        /* If product not in single variable we don't print results */
                   6897:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6898:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   6899:        /* k=       1    2   3     4       5       6      7       8        9  */
                   6900:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   6901:        /* ij            1    2                                            3  */  
                   6902:        /* Tvaraff[ij]=  4    3                                            1  */
                   6903:        /* Tmodelind[ij]=2    3                                            9  */
                   6904:        /* TmodelInvind[ij]=2 1                                            1  */
                   6905:        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*/
                   6906:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6907:        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 */
                   6908:        if(Fixed[k]!=0)
                   6909:         anyvaryingduminmodel=1;
                   6910:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6911:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6912:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6913:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6914:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6915:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6916:      } 
                   6917:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6918:    /* ij--; */
                   6919:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   6920:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
                   6921:                * because they can be excluded from the model and real
                   6922:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6923:    for(j=ij+1; j<= cptcovt; j++){
                   6924:      Tvaraff[j]=0;
                   6925:      Tmodelind[j]=0;
                   6926:    }
                   6927:    for(j=ntveff+1; j<= cptcovt; j++){
                   6928:      TmodelInvind[j]=0;
                   6929:    }
                   6930:    /* To be sorted */
                   6931:    ;
                   6932:  }
                   6933: 
                   6934: 
                   6935: /*********** Health Expectancies ****************/
                   6936: 
                   6937:  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 )
                   6938: 
                   6939: {
                   6940:   /* Health expectancies, no variances */
                   6941:   /* cij is the combination in the list of combination of dummy covariates */
                   6942:   /* strstart is a string of time at start of computing */
                   6943:   int i, j, nhstepm, hstepm, h, nstepm;
                   6944:   int nhstepma, nstepma; /* Decreasing with age */
                   6945:   double age, agelim, hf;
                   6946:   double ***p3mat;
                   6947:   double eip;
                   6948: 
                   6949:   /* pstamp(ficreseij); */
                   6950:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6951:   fprintf(ficreseij,"# Age");
                   6952:   for(i=1; i<=nlstate;i++){
                   6953:     for(j=1; j<=nlstate;j++){
                   6954:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6955:     }
                   6956:     fprintf(ficreseij," e%1d. ",i);
                   6957:   }
                   6958:   fprintf(ficreseij,"\n");
                   6959: 
                   6960:   
                   6961:   if(estepm < stepm){
                   6962:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6963:   }
                   6964:   else  hstepm=estepm;   
                   6965:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6966:    * This is mainly to measure the difference between two models: for example
                   6967:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6968:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6969:    * progression in between and thus overestimating or underestimating according
                   6970:    * to the curvature of the survival function. If, for the same date, we 
                   6971:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6972:    * to compare the new estimate of Life expectancy with the same linear 
                   6973:    * hypothesis. A more precise result, taking into account a more precise
                   6974:    * curvature will be obtained if estepm is as small as stepm. */
                   6975: 
                   6976:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6977:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6978:      nhstepm is the number of hstepm from age to agelim 
                   6979:      nstepm is the number of stepm from age to agelin. 
                   6980:      Look at hpijx to understand the reason which relies in memory size consideration
                   6981:      and note for a fixed period like estepm months */
                   6982:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6983:      survival function given by stepm (the optimization length). Unfortunately it
                   6984:      means that if the survival funtion is printed only each two years of age and if
                   6985:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6986:      results. So we changed our mind and took the option of the best precision.
                   6987:   */
                   6988:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6989: 
                   6990:   agelim=AGESUP;
                   6991:   /* If stepm=6 months */
                   6992:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6993:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6994:     
                   6995: /* nhstepm age range expressed in number of stepm */
                   6996:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6997:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6998:   /* if (stepm >= YEARM) hstepm=1;*/
                   6999:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   7000:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7001: 
                   7002:   for (age=bage; age<=fage; age ++){ 
                   7003:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   7004:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   7005:     /* if (stepm >= YEARM) hstepm=1;*/
                   7006:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   7007: 
                   7008:     /* If stepm=6 months */
                   7009:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   7010:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   7011:     /* printf("HELLO evsij Entering hpxij age=%d cij=%d hstepm=%d x[1]=%f nres=%d\n",(int) age, cij, hstepm, x[1], nres); */
                   7012:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
                   7013:     
                   7014:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   7015:     
                   7016:     printf("%d|",(int)age);fflush(stdout);
                   7017:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   7018:     
                   7019:     /* Computing expectancies */
                   7020:     for(i=1; i<=nlstate;i++)
                   7021:       for(j=1; j<=nlstate;j++)
                   7022:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   7023:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   7024:          
                   7025:          /* 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]);*/
                   7026: 
                   7027:        }
                   7028: 
                   7029:     fprintf(ficreseij,"%3.0f",age );
                   7030:     for(i=1; i<=nlstate;i++){
                   7031:       eip=0;
                   7032:       for(j=1; j<=nlstate;j++){
                   7033:        eip +=eij[i][j][(int)age];
                   7034:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   7035:       }
                   7036:       fprintf(ficreseij,"%9.4f", eip );
                   7037:     }
                   7038:     fprintf(ficreseij,"\n");
                   7039:     
                   7040:   }
                   7041:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7042:   printf("\n");
                   7043:   fprintf(ficlog,"\n");
                   7044:   
                   7045: }
                   7046: 
                   7047:  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 )
                   7048: 
                   7049: {
                   7050:   /* Covariances of health expectancies eij and of total life expectancies according
                   7051:      to initial status i, ei. .
                   7052:   */
                   7053:   /* Very time consuming function, but already optimized with precov */
                   7054:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   7055:   int nhstepma, nstepma; /* Decreasing with age */
                   7056:   double age, agelim, hf;
                   7057:   double ***p3matp, ***p3matm, ***varhe;
                   7058:   double **dnewm,**doldm;
                   7059:   double *xp, *xm;
                   7060:   double **gp, **gm;
                   7061:   double ***gradg, ***trgradg;
                   7062:   int theta;
                   7063: 
                   7064:   double eip, vip;
                   7065: 
                   7066:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   7067:   xp=vector(1,npar);
                   7068:   xm=vector(1,npar);
                   7069:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   7070:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   7071:   
                   7072:   pstamp(ficresstdeij);
                   7073:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   7074:   fprintf(ficresstdeij,"# Age");
                   7075:   for(i=1; i<=nlstate;i++){
                   7076:     for(j=1; j<=nlstate;j++)
                   7077:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   7078:     fprintf(ficresstdeij," e%1d. ",i);
                   7079:   }
                   7080:   fprintf(ficresstdeij,"\n");
                   7081: 
                   7082:   pstamp(ficrescveij);
                   7083:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   7084:   fprintf(ficrescveij,"# Age");
                   7085:   for(i=1; i<=nlstate;i++)
                   7086:     for(j=1; j<=nlstate;j++){
                   7087:       cptj= (j-1)*nlstate+i;
                   7088:       for(i2=1; i2<=nlstate;i2++)
                   7089:        for(j2=1; j2<=nlstate;j2++){
                   7090:          cptj2= (j2-1)*nlstate+i2;
                   7091:          if(cptj2 <= cptj)
                   7092:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   7093:        }
                   7094:     }
                   7095:   fprintf(ficrescveij,"\n");
                   7096:   
                   7097:   if(estepm < stepm){
                   7098:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   7099:   }
                   7100:   else  hstepm=estepm;   
                   7101:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   7102:    * This is mainly to measure the difference between two models: for example
                   7103:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   7104:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   7105:    * progression in between and thus overestimating or underestimating according
                   7106:    * to the curvature of the survival function. If, for the same date, we 
                   7107:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   7108:    * to compare the new estimate of Life expectancy with the same linear 
                   7109:    * hypothesis. A more precise result, taking into account a more precise
                   7110:    * curvature will be obtained if estepm is as small as stepm. */
                   7111: 
                   7112:   /* For example we decided to compute the life expectancy with the smallest unit */
                   7113:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   7114:      nhstepm is the number of hstepm from age to agelim 
                   7115:      nstepm is the number of stepm from age to agelin. 
                   7116:      Look at hpijx to understand the reason of that which relies in memory size
                   7117:      and note for a fixed period like estepm months */
                   7118:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   7119:      survival function given by stepm (the optimization length). Unfortunately it
                   7120:      means that if the survival funtion is printed only each two years of age and if
                   7121:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   7122:      results. So we changed our mind and took the option of the best precision.
                   7123:   */
                   7124:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   7125: 
                   7126:   /* If stepm=6 months */
                   7127:   /* nhstepm age range expressed in number of stepm */
                   7128:   agelim=AGESUP;
                   7129:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   7130:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   7131:   /* if (stepm >= YEARM) hstepm=1;*/
                   7132:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   7133:   
                   7134:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7135:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7136:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   7137:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   7138:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   7139:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   7140: 
                   7141:   for (age=bage; age<=fage; age ++){ 
                   7142:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   7143:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   7144:     /* if (stepm >= YEARM) hstepm=1;*/
                   7145:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   7146:                
                   7147:     /* If stepm=6 months */
                   7148:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   7149:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   7150:     
                   7151:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   7152:                
                   7153:     /* Computing  Variances of health expectancies */
                   7154:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   7155:        decrease memory allocation */
                   7156:     for(theta=1; theta <=npar; theta++){
                   7157:       for(i=1; i<=npar; i++){ 
                   7158:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7159:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   7160:       }
                   7161:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   7162:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
                   7163:                        
                   7164:       for(j=1; j<= nlstate; j++){
                   7165:        for(i=1; i<=nlstate; i++){
                   7166:          for(h=0; h<=nhstepm-1; h++){
                   7167:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   7168:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   7169:          }
                   7170:        }
                   7171:       }
                   7172:                        
                   7173:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   7174:        for(h=0; h<=nhstepm-1; h++){
                   7175:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   7176:        }
                   7177:     }/* End theta */
                   7178:     
                   7179:     
                   7180:     for(h=0; h<=nhstepm-1; h++)
                   7181:       for(j=1; j<=nlstate*nlstate;j++)
                   7182:        for(theta=1; theta <=npar; theta++)
                   7183:          trgradg[h][j][theta]=gradg[h][theta][j];
                   7184:     
                   7185:                
                   7186:     for(ij=1;ij<=nlstate*nlstate;ij++)
                   7187:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   7188:        varhe[ij][ji][(int)age] =0.;
                   7189:                
                   7190:     printf("%d|",(int)age);fflush(stdout);
                   7191:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   7192:     for(h=0;h<=nhstepm-1;h++){
                   7193:       for(k=0;k<=nhstepm-1;k++){
                   7194:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   7195:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   7196:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   7197:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   7198:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   7199:       }
                   7200:     }
                   7201:     /* if((int)age ==50){ */
                   7202:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   7203:     /* } */
                   7204:     /* Computing expectancies */
                   7205:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
                   7206:     for(i=1; i<=nlstate;i++)
                   7207:       for(j=1; j<=nlstate;j++)
                   7208:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   7209:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   7210:                                        
                   7211:          /* 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]);*/
                   7212:                                        
                   7213:        }
                   7214: 
                   7215:     /* Standard deviation of expectancies ij */                
                   7216:     fprintf(ficresstdeij,"%3.0f",age );
                   7217:     for(i=1; i<=nlstate;i++){
                   7218:       eip=0.;
                   7219:       vip=0.;
                   7220:       for(j=1; j<=nlstate;j++){
                   7221:        eip += eij[i][j][(int)age];
                   7222:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   7223:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   7224:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   7225:       }
                   7226:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   7227:     }
                   7228:     fprintf(ficresstdeij,"\n");
                   7229:                
                   7230:     /* Variance of expectancies ij */          
                   7231:     fprintf(ficrescveij,"%3.0f",age );
                   7232:     for(i=1; i<=nlstate;i++)
                   7233:       for(j=1; j<=nlstate;j++){
                   7234:        cptj= (j-1)*nlstate+i;
                   7235:        for(i2=1; i2<=nlstate;i2++)
                   7236:          for(j2=1; j2<=nlstate;j2++){
                   7237:            cptj2= (j2-1)*nlstate+i2;
                   7238:            if(cptj2 <= cptj)
                   7239:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   7240:          }
                   7241:       }
                   7242:     fprintf(ficrescveij,"\n");
                   7243:                
                   7244:   }
                   7245:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   7246:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   7247:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   7248:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   7249:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7250:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7251:   printf("\n");
                   7252:   fprintf(ficlog,"\n");
                   7253:        
                   7254:   free_vector(xm,1,npar);
                   7255:   free_vector(xp,1,npar);
                   7256:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   7257:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   7258:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   7259: }
                   7260:  
                   7261: /************ Variance ******************/
                   7262:  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)
                   7263:  {
                   7264:    /** Variance of health expectancies 
                   7265:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   7266:     * double **newm;
                   7267:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   7268:     */
                   7269:   
                   7270:    /* int movingaverage(); */
                   7271:    double **dnewm,**doldm;
                   7272:    double **dnewmp,**doldmp;
                   7273:    int i, j, nhstepm, hstepm, h, nstepm ;
                   7274:    int first=0;
                   7275:    int k;
                   7276:    double *xp;
                   7277:    double **gp, **gm;  /**< for var eij */
                   7278:    double ***gradg, ***trgradg; /**< for var eij */
                   7279:    double **gradgp, **trgradgp; /**< for var p point j */
                   7280:    double *gpp, *gmp; /**< for var p point j */
                   7281:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
                   7282:    double ***p3mat;
                   7283:    double age,agelim, hf;
                   7284:    /* double ***mobaverage; */
                   7285:    int theta;
                   7286:    char digit[4];
                   7287:    char digitp[25];
                   7288: 
                   7289:    char fileresprobmorprev[FILENAMELENGTH];
                   7290: 
                   7291:    if(popbased==1){
                   7292:      if(mobilav!=0)
                   7293:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   7294:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   7295:    }
                   7296:    else 
                   7297:      strcpy(digitp,"-STABLBASED_");
                   7298: 
                   7299:    /* if (mobilav!=0) { */
                   7300:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7301:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   7302:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   7303:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   7304:    /*   } */
                   7305:    /* } */
                   7306: 
                   7307:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   7308:    sprintf(digit,"%-d",ij);
                   7309:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   7310:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   7311:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   7312:    strcat(fileresprobmorprev,fileresu);
                   7313:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   7314:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   7315:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   7316:    }
                   7317:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   7318:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   7319:    pstamp(ficresprobmorprev);
                   7320:    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);
                   7321:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   7322: 
                   7323:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   7324:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   7325:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   7326:    /* } */
                   7327:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
                   7328:      /* fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); */
                   7329:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   7330:    }
                   7331:    /* for(j=1;j<=cptcoveff;j++)  */
                   7332:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
                   7333:    fprintf(ficresprobmorprev,"\n");
                   7334: 
                   7335:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   7336:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7337:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   7338:      for(i=1; i<=nlstate;i++)
                   7339:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   7340:    }  
                   7341:    fprintf(ficresprobmorprev,"\n");
                   7342:   
                   7343:    fprintf(ficgp,"\n# Routine varevsij");
                   7344:    fprintf(ficgp,"\nunset title \n");
                   7345:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   7346:    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");
                   7347:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   7348: 
                   7349:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7350:    pstamp(ficresvij);
                   7351:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   7352:    if(popbased==1)
                   7353:      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);
                   7354:    else
                   7355:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   7356:    fprintf(ficresvij,"# Age");
                   7357:    for(i=1; i<=nlstate;i++)
                   7358:      for(j=1; j<=nlstate;j++)
                   7359:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   7360:    fprintf(ficresvij,"\n");
                   7361: 
                   7362:    xp=vector(1,npar);
                   7363:    dnewm=matrix(1,nlstate,1,npar);
                   7364:    doldm=matrix(1,nlstate,1,nlstate);
                   7365:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   7366:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7367: 
                   7368:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   7369:    gpp=vector(nlstate+1,nlstate+ndeath);
                   7370:    gmp=vector(nlstate+1,nlstate+ndeath);
                   7371:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   7372:   
                   7373:    if(estepm < stepm){
                   7374:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   7375:    }
                   7376:    else  hstepm=estepm;   
                   7377:    /* For example we decided to compute the life expectancy with the smallest unit */
                   7378:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   7379:       nhstepm is the number of hstepm from age to agelim 
                   7380:       nstepm is the number of stepm from age to agelim. 
                   7381:       Look at function hpijx to understand why because of memory size limitations, 
                   7382:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   7383:       survival function given by stepm (the optimization length). Unfortunately it
                   7384:       means that if the survival funtion is printed every two years of age and if
                   7385:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   7386:       results. So we changed our mind and took the option of the best precision.
                   7387:    */
                   7388:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   7389:    agelim = AGESUP;
                   7390:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7391:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7392:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   7393:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7394:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   7395:      gp=matrix(0,nhstepm,1,nlstate);
                   7396:      gm=matrix(0,nhstepm,1,nlstate);
                   7397:                
                   7398:                
                   7399:      for(theta=1; theta <=npar; theta++){
                   7400:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   7401:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7402:        }
                   7403:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   7404:        * returns into prlim .
                   7405:        */
                   7406:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
                   7407: 
                   7408:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
                   7409:        if (popbased==1) {
                   7410:         if(mobilav ==0){
                   7411:           for(i=1; i<=nlstate;i++)
                   7412:             prlim[i][i]=probs[(int)age][i][ij];
                   7413:         }else{ /* mobilav */ 
                   7414:           for(i=1; i<=nlstate;i++)
                   7415:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   7416:         }
                   7417:        }
                   7418:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
                   7419:        */                      
                   7420:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  /* Returns p3mat[i][j][h] for h=0 to nhstepm */
                   7421:        /**< And for each alive state j, sums over i \f$ w^i_x {}{h}_p^{ij}x\f$, which are the probability
                   7422:        * at horizon h in state j including mortality.
                   7423:        */
                   7424:        for(j=1; j<= nlstate; j++){
                   7425:         for(h=0; h<=nhstepm; h++){
                   7426:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   7427:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   7428:         }
                   7429:        }
                   7430:        /* Next for computing shifted+ probability of death (h=1 means
                   7431:          computed over hstepm matrices product = hstepm*stepm months) 
                   7432:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
                   7433:        */
                   7434:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7435:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   7436:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   7437:        }
                   7438:        
                   7439:        /* Again with minus shift */
                   7440:                        
                   7441:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   7442:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7443: 
                   7444:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
                   7445:                        
                   7446:        if (popbased==1) {
                   7447:         if(mobilav ==0){
                   7448:           for(i=1; i<=nlstate;i++)
                   7449:             prlim[i][i]=probs[(int)age][i][ij];
                   7450:         }else{ /* mobilav */ 
                   7451:           for(i=1; i<=nlstate;i++)
                   7452:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   7453:         }
                   7454:        }
                   7455:                        
                   7456:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
                   7457:                        
                   7458:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   7459:         for(h=0; h<=nhstepm; h++){
                   7460:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   7461:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   7462:         }
                   7463:        }
                   7464:        /* This for computing probability of death (h=1 means
                   7465:          computed over hstepm matrices product = hstepm*stepm months) 
                   7466:          as a weighted average of prlim.
                   7467:        */
                   7468:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7469:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   7470:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   7471:        }    
                   7472:        /* end shifting computations */
                   7473: 
                   7474:        /**< Computing gradient matrix at horizon h 
                   7475:        */
                   7476:        for(j=1; j<= nlstate; j++) /* vareij */
                   7477:         for(h=0; h<=nhstepm; h++){
                   7478:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   7479:         }
                   7480:        /**< Gradient of overall mortality p.3 (or p.j) 
                   7481:        */
                   7482:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
                   7483:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   7484:        }
                   7485:                        
                   7486:      } /* End theta */
                   7487:      
                   7488:      /* We got the gradient matrix for each theta and state j */               
                   7489:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   7490:                
                   7491:      for(h=0; h<=nhstepm; h++) /* veij */
                   7492:        for(j=1; j<=nlstate;j++)
                   7493:         for(theta=1; theta <=npar; theta++)
                   7494:           trgradg[h][j][theta]=gradg[h][theta][j];
                   7495:                
                   7496:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   7497:        for(theta=1; theta <=npar; theta++)
                   7498:         trgradgp[j][theta]=gradgp[theta][j];
                   7499:      /**< as well as its transposed matrix 
                   7500:       */               
                   7501:                
                   7502:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   7503:      for(i=1;i<=nlstate;i++)
                   7504:        for(j=1;j<=nlstate;j++)
                   7505:         vareij[i][j][(int)age] =0.;
                   7506: 
                   7507:      /* Computing trgradg by matcov by gradg at age and summing over h
                   7508:       * and k (nhstepm) formula 15 of article
                   7509:       * Lievre-Brouard-Heathcote
                   7510:       */
                   7511:      
                   7512:      for(h=0;h<=nhstepm;h++){
                   7513:        for(k=0;k<=nhstepm;k++){
                   7514:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   7515:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   7516:         for(i=1;i<=nlstate;i++)
                   7517:           for(j=1;j<=nlstate;j++)
                   7518:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   7519:        }
                   7520:      }
                   7521:                
                   7522:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   7523:       * p.j overall mortality formula 49 but computed directly because
                   7524:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   7525:       * wix is independent of theta.
                   7526:       */
                   7527:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   7528:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   7529:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   7530:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   7531:         varppt[j][i]=doldmp[j][i];
                   7532:      /* end ppptj */
                   7533:      /*  x centered again */
                   7534:                
                   7535:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
                   7536:                
                   7537:      if (popbased==1) {
                   7538:        if(mobilav ==0){
                   7539:         for(i=1; i<=nlstate;i++)
                   7540:           prlim[i][i]=probs[(int)age][i][ij];
                   7541:        }else{ /* mobilav */ 
                   7542:         for(i=1; i<=nlstate;i++)
                   7543:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   7544:        }
                   7545:      }
                   7546:                
                   7547:      /* This for computing probability of death (h=1 means
                   7548:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   7549:        as a weighted average of prlim.
                   7550:      */
                   7551:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
                   7552:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7553:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   7554:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   7555:      }    
                   7556:      /* end probability of death */
                   7557:                
                   7558:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   7559:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7560:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   7561:        for(i=1; i<=nlstate;i++){
                   7562:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   7563:        }
                   7564:      } 
                   7565:      fprintf(ficresprobmorprev,"\n");
                   7566:                
                   7567:      fprintf(ficresvij,"%.0f ",age );
                   7568:      for(i=1; i<=nlstate;i++)
                   7569:        for(j=1; j<=nlstate;j++){
                   7570:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   7571:        }
                   7572:      fprintf(ficresvij,"\n");
                   7573:      free_matrix(gp,0,nhstepm,1,nlstate);
                   7574:      free_matrix(gm,0,nhstepm,1,nlstate);
                   7575:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   7576:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   7577:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7578:    } /* End age */
                   7579:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   7580:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   7581:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   7582:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   7583:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   7584:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   7585:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   7586:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   7587:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   7588:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   7589:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7590:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7591:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   7592:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   7593:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   7594:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   7595:    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);
                   7596:    /*  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);
                   7597:     */
                   7598:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   7599:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   7600: 
                   7601:    free_vector(xp,1,npar);
                   7602:    free_matrix(doldm,1,nlstate,1,nlstate);
                   7603:    free_matrix(dnewm,1,nlstate,1,npar);
                   7604:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7605:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   7606:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7607:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7608:    fclose(ficresprobmorprev);
                   7609:    fflush(ficgp);
                   7610:    fflush(fichtm); 
                   7611:  }  /* end varevsij */
                   7612: 
                   7613: /************ Variance of prevlim ******************/
                   7614:  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)
                   7615: {
                   7616:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   7617:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   7618: 
                   7619:   double **dnewmpar,**doldm;
                   7620:   int i, j, nhstepm, hstepm;
                   7621:   double *xp;
                   7622:   double *gp, *gm;
                   7623:   double **gradg, **trgradg;
                   7624:   double **mgm, **mgp;
                   7625:   double age,agelim;
                   7626:   int theta;
                   7627:   
                   7628:   pstamp(ficresvpl);
                   7629:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
                   7630:   fprintf(ficresvpl,"# Age ");
                   7631:   if(nresult >=1)
                   7632:     fprintf(ficresvpl," Result# ");
                   7633:   for(i=1; i<=nlstate;i++)
                   7634:       fprintf(ficresvpl," %1d-%1d",i,i);
                   7635:   fprintf(ficresvpl,"\n");
                   7636: 
                   7637:   xp=vector(1,npar);
                   7638:   dnewmpar=matrix(1,nlstate,1,npar);
                   7639:   doldm=matrix(1,nlstate,1,nlstate);
                   7640:   
                   7641:   hstepm=1*YEARM; /* Every year of age */
                   7642:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7643:   agelim = AGESUP;
                   7644:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7645:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7646:     if (stepm >= YEARM) hstepm=1;
                   7647:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7648:     gradg=matrix(1,npar,1,nlstate);
                   7649:     mgp=matrix(1,npar,1,nlstate);
                   7650:     mgm=matrix(1,npar,1,nlstate);
                   7651:     gp=vector(1,nlstate);
                   7652:     gm=vector(1,nlstate);
                   7653: 
                   7654:     for(theta=1; theta <=npar; theta++){
                   7655:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7656:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7657:       }
                   7658:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7659:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7660:       /* else */
                   7661:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
                   7662:       for(i=1;i<=nlstate;i++){
                   7663:        gp[i] = prlim[i][i];
                   7664:        mgp[theta][i] = prlim[i][i];
                   7665:       }
                   7666:       for(i=1; i<=npar; i++) /* Computes gradient */
                   7667:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7668:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7669:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7670:       /* else */
                   7671:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
                   7672:       for(i=1;i<=nlstate;i++){
                   7673:        gm[i] = prlim[i][i];
                   7674:        mgm[theta][i] = prlim[i][i];
                   7675:       }
                   7676:       for(i=1;i<=nlstate;i++)
                   7677:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   7678:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   7679:     } /* End theta */
                   7680: 
                   7681:     trgradg =matrix(1,nlstate,1,npar);
                   7682: 
                   7683:     for(j=1; j<=nlstate;j++)
                   7684:       for(theta=1; theta <=npar; theta++)
                   7685:        trgradg[j][theta]=gradg[theta][j];
                   7686:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7687:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7688:     /*   for(j=1; j<=nlstate;j++){ */
                   7689:     /*         printf(" %d ",j); */
                   7690:     /*         for(theta=1; theta <=npar; theta++) */
                   7691:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7692:     /*         printf("\n "); */
                   7693:     /*   } */
                   7694:     /* } */
                   7695:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7696:     /*   printf("\n gradg %d ",(int)age); */
                   7697:     /*   for(j=1; j<=nlstate;j++){ */
                   7698:     /*         printf("%d ",j); */
                   7699:     /*         for(theta=1; theta <=npar; theta++) */
                   7700:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7701:     /*         printf("\n "); */
                   7702:     /*   } */
                   7703:     /* } */
                   7704: 
                   7705:     for(i=1;i<=nlstate;i++)
                   7706:       varpl[i][(int)age] =0.;
                   7707:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7708:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7709:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7710:     }else{
                   7711:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7712:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7713:     }
                   7714:     for(i=1;i<=nlstate;i++)
                   7715:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7716: 
                   7717:     fprintf(ficresvpl,"%.0f ",age );
                   7718:     if(nresult >=1)
                   7719:       fprintf(ficresvpl,"%d ",nres );
                   7720:     for(i=1; i<=nlstate;i++){
                   7721:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   7722:       /* for(j=1;j<=nlstate;j++) */
                   7723:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   7724:     }
                   7725:     fprintf(ficresvpl,"\n");
                   7726:     free_vector(gp,1,nlstate);
                   7727:     free_vector(gm,1,nlstate);
                   7728:     free_matrix(mgm,1,npar,1,nlstate);
                   7729:     free_matrix(mgp,1,npar,1,nlstate);
                   7730:     free_matrix(gradg,1,npar,1,nlstate);
                   7731:     free_matrix(trgradg,1,nlstate,1,npar);
                   7732:   } /* End age */
                   7733: 
                   7734:   free_vector(xp,1,npar);
                   7735:   free_matrix(doldm,1,nlstate,1,npar);
                   7736:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   7737: 
                   7738: }
                   7739: 
                   7740: 
                   7741: /************ Variance of backprevalence limit ******************/
                   7742:  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)
                   7743: {
                   7744:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   7745:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   7746: 
                   7747:   double **dnewmpar,**doldm;
                   7748:   int i, j, nhstepm, hstepm;
                   7749:   double *xp;
                   7750:   double *gp, *gm;
                   7751:   double **gradg, **trgradg;
                   7752:   double **mgm, **mgp;
                   7753:   double age,agelim;
                   7754:   int theta;
                   7755:   
                   7756:   pstamp(ficresvbl);
                   7757:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   7758:   fprintf(ficresvbl,"# Age ");
                   7759:   if(nresult >=1)
                   7760:     fprintf(ficresvbl," Result# ");
                   7761:   for(i=1; i<=nlstate;i++)
                   7762:       fprintf(ficresvbl," %1d-%1d",i,i);
                   7763:   fprintf(ficresvbl,"\n");
                   7764: 
                   7765:   xp=vector(1,npar);
                   7766:   dnewmpar=matrix(1,nlstate,1,npar);
                   7767:   doldm=matrix(1,nlstate,1,nlstate);
                   7768:   
                   7769:   hstepm=1*YEARM; /* Every year of age */
                   7770:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7771:   agelim = AGEINF;
                   7772:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   7773:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7774:     if (stepm >= YEARM) hstepm=1;
                   7775:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7776:     gradg=matrix(1,npar,1,nlstate);
                   7777:     mgp=matrix(1,npar,1,nlstate);
                   7778:     mgm=matrix(1,npar,1,nlstate);
                   7779:     gp=vector(1,nlstate);
                   7780:     gm=vector(1,nlstate);
                   7781: 
                   7782:     for(theta=1; theta <=npar; theta++){
                   7783:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7784:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7785:       }
                   7786:       if(mobilavproj > 0 )
                   7787:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7788:       else
                   7789:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7790:       for(i=1;i<=nlstate;i++){
                   7791:        gp[i] = bprlim[i][i];
                   7792:        mgp[theta][i] = bprlim[i][i];
                   7793:       }
                   7794:      for(i=1; i<=npar; i++) /* Computes gradient */
                   7795:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7796:        if(mobilavproj > 0 )
                   7797:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7798:        else
                   7799:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7800:       for(i=1;i<=nlstate;i++){
                   7801:        gm[i] = bprlim[i][i];
                   7802:        mgm[theta][i] = bprlim[i][i];
                   7803:       }
                   7804:       for(i=1;i<=nlstate;i++)
                   7805:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   7806:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   7807:     } /* End theta */
                   7808: 
                   7809:     trgradg =matrix(1,nlstate,1,npar);
                   7810: 
                   7811:     for(j=1; j<=nlstate;j++)
                   7812:       for(theta=1; theta <=npar; theta++)
                   7813:        trgradg[j][theta]=gradg[theta][j];
                   7814:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7815:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7816:     /*   for(j=1; j<=nlstate;j++){ */
                   7817:     /*         printf(" %d ",j); */
                   7818:     /*         for(theta=1; theta <=npar; theta++) */
                   7819:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7820:     /*         printf("\n "); */
                   7821:     /*   } */
                   7822:     /* } */
                   7823:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7824:     /*   printf("\n gradg %d ",(int)age); */
                   7825:     /*   for(j=1; j<=nlstate;j++){ */
                   7826:     /*         printf("%d ",j); */
                   7827:     /*         for(theta=1; theta <=npar; theta++) */
                   7828:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7829:     /*         printf("\n "); */
                   7830:     /*   } */
                   7831:     /* } */
                   7832: 
                   7833:     for(i=1;i<=nlstate;i++)
                   7834:       varbpl[i][(int)age] =0.;
                   7835:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7836:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7837:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7838:     }else{
                   7839:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7840:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7841:     }
                   7842:     for(i=1;i<=nlstate;i++)
                   7843:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7844: 
                   7845:     fprintf(ficresvbl,"%.0f ",age );
                   7846:     if(nresult >=1)
                   7847:       fprintf(ficresvbl,"%d ",nres );
                   7848:     for(i=1; i<=nlstate;i++)
                   7849:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   7850:     fprintf(ficresvbl,"\n");
                   7851:     free_vector(gp,1,nlstate);
                   7852:     free_vector(gm,1,nlstate);
                   7853:     free_matrix(mgm,1,npar,1,nlstate);
                   7854:     free_matrix(mgp,1,npar,1,nlstate);
                   7855:     free_matrix(gradg,1,npar,1,nlstate);
                   7856:     free_matrix(trgradg,1,nlstate,1,npar);
                   7857:   } /* End age */
                   7858: 
                   7859:   free_vector(xp,1,npar);
                   7860:   free_matrix(doldm,1,nlstate,1,npar);
                   7861:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   7862: 
                   7863: }
                   7864: 
                   7865: /************ Variance of one-step probabilities  ******************/
                   7866: 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[])
                   7867:  {
                   7868:    int i, j=0,  k1, l1, tj;
                   7869:    int k2, l2, j1,  z1;
                   7870:    int k=0, l;
                   7871:    int first=1, first1, first2;
                   7872:    int nres=0; /* New */
                   7873:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   7874:    double **dnewm,**doldm;
                   7875:    double *xp;
                   7876:    double *gp, *gm;
                   7877:    double **gradg, **trgradg;
                   7878:    double **mu;
                   7879:    double age, cov[NCOVMAX+1];
                   7880:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7881:    int theta;
                   7882:    char fileresprob[FILENAMELENGTH];
                   7883:    char fileresprobcov[FILENAMELENGTH];
                   7884:    char fileresprobcor[FILENAMELENGTH];
                   7885:    double ***varpij;
                   7886: 
                   7887:    strcpy(fileresprob,"PROB_"); 
1.2     ! brouard  7888:    strcat(fileresprob,fileresu);
1.1       brouard  7889:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7890:      printf("Problem with resultfile: %s\n", fileresprob);
                   7891:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7892:    }
                   7893:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7894:    strcat(fileresprobcov,fileresu);
                   7895:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7896:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7897:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7898:    }
                   7899:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7900:    strcat(fileresprobcor,fileresu);
                   7901:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7902:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7903:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7904:    }
                   7905:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7906:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7907:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7908:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7909:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7910:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7911:    pstamp(ficresprob);
                   7912:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7913:    fprintf(ficresprob,"# Age");
                   7914:    pstamp(ficresprobcov);
                   7915:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7916:    fprintf(ficresprobcov,"# Age");
                   7917:    pstamp(ficresprobcor);
                   7918:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7919:    fprintf(ficresprobcor,"# Age");
                   7920: 
                   7921: 
                   7922:    for(i=1; i<=nlstate;i++)
                   7923:      for(j=1; j<=(nlstate+ndeath);j++){
                   7924:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7925:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7926:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7927:      }  
                   7928:    /* fprintf(ficresprob,"\n");
                   7929:       fprintf(ficresprobcov,"\n");
                   7930:       fprintf(ficresprobcor,"\n");
                   7931:    */
                   7932:    xp=vector(1,npar);
                   7933:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7934:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7935:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7936:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7937:    first=1;
                   7938:    fprintf(ficgp,"\n# Routine varprob");
                   7939:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7940:    fprintf(fichtm,"\n");
                   7941: 
                   7942:    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);
                   7943:    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);
                   7944:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
                   7945: and drawn. It helps understanding how is the covariance between two incidences.\
                   7946:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   7947:    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. \
                   7948: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7949: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7950: standard deviations wide on each axis. <br>\
                   7951:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7952:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7953: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7954: 
                   7955:    cov[1]=1;
                   7956:    /* tj=cptcoveff; */
                   7957:    tj = (int) pow(2,cptcoveff);
                   7958:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7959:    j1=0;
                   7960: 
                   7961:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7962:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
                   7963:      /* 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); */
                   7964:      if(tj != 1 && TKresult[nres]!= j1)
                   7965:        continue;
                   7966: 
                   7967:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7968:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7969:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
                   7970:      if  (cptcovn>0) {
                   7971:        fprintf(ficresprob, "\n#********** Variable ");
                   7972:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   7973:        fprintf(ficgp, "\n#********** Variable ");
                   7974:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   7975:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   7976: 
                   7977:        /* Including quantitative variables of the resultline to be done */
                   7978:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
                   7979:         /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
                   7980:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   7981:         /* fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s resultline[%d]=%s \n",nres, z1, modelresult[nres][z1], model, nres, resultline[nres]); */
                   7982:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   7983:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   7984:             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  */
                   7985:             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  */
                   7986:             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  */
                   7987:             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  */
                   7988:             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  */
                   7989:             fprintf(ficresprob,"fixed ");
                   7990:             fprintf(ficresprobcov,"fixed ");
                   7991:             fprintf(ficgp,"fixed ");
                   7992:             fprintf(fichtmcov,"fixed ");
                   7993:             fprintf(ficresprobcor,"fixed ");
                   7994:           }else{
                   7995:             fprintf(ficresprob,"varyi ");
                   7996:             fprintf(ficresprobcov,"varyi ");
                   7997:             fprintf(ficgp,"varyi ");
                   7998:             fprintf(fichtmcov,"varyi ");
                   7999:             fprintf(ficresprobcor,"varyi ");
                   8000:           }
                   8001:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   8002:           /* For each selected (single) quantitative value */
                   8003:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
                   8004:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   8005:             fprintf(ficresprob,"fixed ");
                   8006:             fprintf(ficresprobcov,"fixed ");
                   8007:             fprintf(ficgp,"fixed ");
                   8008:             fprintf(fichtmcov,"fixed ");
                   8009:             fprintf(ficresprobcor,"fixed ");
                   8010:           }else{
                   8011:             fprintf(ficresprob,"varyi ");
                   8012:             fprintf(ficresprobcov,"varyi ");
                   8013:             fprintf(ficgp,"varyi ");
                   8014:             fprintf(fichtmcov,"varyi ");
                   8015:             fprintf(ficresprobcor,"varyi ");
                   8016:           }
                   8017:         }else{
                   8018:           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 */
                   8019:           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 */
                   8020:           exit(1);
                   8021:         }
                   8022:        } /* End loop on variable of this resultline */
                   8023:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
                   8024:        fprintf(ficresprob, "**********\n#\n");
                   8025:        fprintf(ficresprobcov, "**********\n#\n");
                   8026:        fprintf(ficgp, "**********\n#\n");
                   8027:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   8028:        fprintf(ficresprobcor, "**********\n#");    
                   8029:        if(invalidvarcomb[j1]){
                   8030:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   8031:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   8032:         continue;
                   8033:        }
                   8034:      }
                   8035:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   8036:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   8037:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   8038:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   8039:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
                   8040:        cov[2]=age;
                   8041:        if(nagesqr==1)
                   8042:         cov[3]= age*age;
                   8043:        /* New code end of combination but for each resultline */
                   8044:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   8045:         if(Typevar[k1]==1 || Typevar[k1] ==3){ /* A product with age */
                   8046:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   8047:         }else{
                   8048:           cov[2+nagesqr+k1]=precov[nres][k1];
                   8049:         }
                   8050:        }/* End of loop on model equation */
                   8051: /* Old code */
                   8052:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   8053:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   8054:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   8055:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   8056:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   8057:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   8058:        /*                                                                  * 1  1 1 1 1 */
                   8059:        /*                                                                  * 2  2 1 1 1 */
                   8060:        /*                                                                  * 3  1 2 1 1 */
                   8061:        /*                                                                  *\/ */
                   8062:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   8063:        /* } */
                   8064:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   8065:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   8066:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   8067:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   8068:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   8069:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   8070:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   8071:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   8072:        /*         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]); */
                   8073:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   8074:        /*         /\* exit(1); *\/ */
                   8075:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   8076:        /*       } */
                   8077:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   8078:        /* } */
                   8079:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   8080:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   8081:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   8082:        /*           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]])]; */
                   8083:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   8084:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   8085:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   8086:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   8087:        /*         } */
                   8088:        /*       }else{ */
                   8089:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   8090:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   8091:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   8092:        /*         }else{ */
                   8093:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   8094:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   8095:        /*         } */
                   8096:        /*       } */
                   8097:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   8098:        /* } */                 
                   8099: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
                   8100:        for(theta=1; theta <=npar; theta++){
                   8101:         for(i=1; i<=npar; i++)
                   8102:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   8103:                                
                   8104:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   8105:                                
                   8106:         k=0;
                   8107:         for(i=1; i<= (nlstate); i++){
                   8108:           for(j=1; j<=(nlstate+ndeath);j++){
                   8109:             k=k+1;
                   8110:             gp[k]=pmmij[i][j];
                   8111:           }
                   8112:         }
                   8113:                                
                   8114:         for(i=1; i<=npar; i++)
                   8115:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   8116:                                
                   8117:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   8118:         k=0;
                   8119:         for(i=1; i<=(nlstate); i++){
                   8120:           for(j=1; j<=(nlstate+ndeath);j++){
                   8121:             k=k+1;
                   8122:             gm[k]=pmmij[i][j];
                   8123:           }
                   8124:         }
                   8125:                                
                   8126:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   8127:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   8128:        }
                   8129: 
                   8130:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   8131:         for(theta=1; theta <=npar; theta++)
                   8132:           trgradg[j][theta]=gradg[theta][j];
                   8133:                        
                   8134:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   8135:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   8136:                        
                   8137:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   8138:                        
                   8139:        k=0;
                   8140:        for(i=1; i<=(nlstate); i++){
                   8141:         for(j=1; j<=(nlstate+ndeath);j++){
                   8142:           k=k+1;
                   8143:           mu[k][(int) age]=pmmij[i][j];
                   8144:         }
                   8145:        }
                   8146:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   8147:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   8148:           varpij[i][j][(int)age] = doldm[i][j];
                   8149:                        
                   8150:        /*printf("\n%d ",(int)age);
                   8151:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   8152:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   8153:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   8154:         }*/
                   8155:                        
                   8156:        fprintf(ficresprob,"\n%d ",(int)age);
                   8157:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   8158:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   8159:                        
                   8160:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   8161:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   8162:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   8163:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   8164:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   8165:        }
                   8166:        i=0;
                   8167:        for (k=1; k<=(nlstate);k++){
                   8168:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   8169:           i++;
                   8170:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   8171:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   8172:           for (j=1; j<=i;j++){
                   8173:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   8174:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   8175:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   8176:           }
                   8177:         }
                   8178:        }/* end of loop for state */
                   8179:      } /* end of loop for age */
                   8180:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   8181:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   8182:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   8183:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   8184:     
                   8185:      /* Confidence intervalle of pij  */
                   8186:      /*
                   8187:        fprintf(ficgp,"\nunset parametric;unset label");
                   8188:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   8189:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   8190:        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);
                   8191:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   8192:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   8193:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   8194:      */
                   8195:                
                   8196:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   8197:      first1=1;first2=2;
                   8198:      for (k2=1; k2<=(nlstate);k2++){
                   8199:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   8200:         if(l2==k2) continue;
                   8201:         j=(k2-1)*(nlstate+ndeath)+l2;
                   8202:         for (k1=1; k1<=(nlstate);k1++){
                   8203:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   8204:             if(l1==k1) continue;
                   8205:             i=(k1-1)*(nlstate+ndeath)+l1;
                   8206:             if(i<=j) continue;
                   8207:             for (age=bage; age<=fage; age ++){ 
                   8208:               if ((int)age %5==0){
                   8209:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   8210:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   8211:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   8212:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   8213:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   8214:                 c12=cv12/sqrt(v1*v2);
                   8215:                 /* Computing eigen value of matrix of covariance */
                   8216:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   8217:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   8218:                 if ((lc2 <0) || (lc1 <0) ){
                   8219:                   if(first2==1){
                   8220:                     first1=0;
                   8221:                     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);
                   8222:                   }
                   8223:                   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);
                   8224:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   8225:                   /* lc2=fabs(lc2); */
                   8226:                 }
                   8227:                                                                
                   8228:                 /* Eigen vectors */
                   8229:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   8230:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   8231:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   8232:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   8233:                 }else
                   8234:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   8235:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   8236:                 v21=(lc1-v1)/cv12*v11;
                   8237:                 v12=-v21;
                   8238:                 v22=v11;
                   8239:                 tnalp=v21/v11;
                   8240:                 if(first1==1){
                   8241:                   first1=0;
                   8242:                   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);
                   8243:                 }
                   8244:                 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);
                   8245:                 /*printf(fignu*/
                   8246:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   8247:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   8248:                 if(first==1){
                   8249:                   first=0;
                   8250:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   8251:                   fprintf(ficgp,"\nset parametric;unset label");
                   8252:                   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);
                   8253:                   fprintf(ficgp,"\nset ter svg size 640, 480");
                   8254:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
                   8255:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
                   8256: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
                   8257:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   8258:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   8259:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   8260:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   8261:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   8262:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   8263:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   8264:                   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",      \
                   8265:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   8266:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
                   8267:                 }else{
                   8268:                   first=0;
                   8269:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   8270:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   8271:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   8272:                   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", \
                   8273:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   8274:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
                   8275:                 }/* if first */
                   8276:               } /* age mod 5 */
                   8277:             } /* end loop age */
                   8278:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   8279:             first=1;
                   8280:           } /*l12 */
                   8281:         } /* k12 */
                   8282:        } /*l1 */
                   8283:      }/* k1 */
                   8284:    }  /* loop on combination of covariates j1 */
                   8285:    } /* loop on nres */
                   8286:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   8287:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   8288:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   8289:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   8290:    free_vector(xp,1,npar);
                   8291:    fclose(ficresprob);
                   8292:    fclose(ficresprobcov);
                   8293:    fclose(ficresprobcor);
                   8294:    fflush(ficgp);
                   8295:    fflush(fichtmcov);
                   8296:  }
                   8297: 
                   8298: 
                   8299: /******************* Printing html file ***********/
                   8300: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
                   8301:                  int lastpass, int stepm, int weightopt, char model[],\
                   8302:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   8303:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   8304:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   8305:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
                   8306:   int jj1, k1, i1, cpt, k4, nres;
                   8307:   /* In fact some results are already printed in fichtm which is open */
                   8308:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   8309:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   8310: </ul>");
                   8311: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   8312: /* </ul>", model); */
                   8313:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   8314:    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",
                   8315:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   8316:    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) ",
                   8317:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   8318:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
                   8319:    fprintf(fichtm,"\
                   8320:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   8321:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
                   8322:    fprintf(fichtm,"\
                   8323:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   8324:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   8325:    fprintf(fichtm,"\
                   8326:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   8327:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
                   8328:    fprintf(fichtm,"\
                   8329:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   8330:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   8331:    fprintf(fichtm,"\
                   8332:  - (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): \
                   8333:    <a href=\"%s\">%s</a> <br>\n",
                   8334:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
                   8335:    if(prevfcast==1){
                   8336:      fprintf(fichtm,"\
                   8337:  - Prevalence projections by age and states:                           \
                   8338:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
                   8339:    }
                   8340: 
                   8341: 
                   8342:    m=pow(2,cptcoveff);
                   8343:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   8344: 
                   8345:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
                   8346: 
                   8347:    jj1=0;
                   8348: 
                   8349:    fprintf(fichtm," \n<ul>");
                   8350:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8351:      /* k1=nres; */
                   8352:      k1=TKresult[nres];
                   8353:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
                   8354:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8355:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   8356:    /*     continue; */
                   8357:      jj1++;
                   8358:      if (cptcovn > 0) {
                   8359:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
                   8360:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   8361:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8362:        }
                   8363:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   8364:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   8365:        /* } */
                   8366:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8367:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8368:        /* } */
                   8369:        fprintf(fichtm,"\">");
                   8370:        
                   8371:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8372:        fprintf(fichtm,"************ Results for covariates");
                   8373:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8374:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8375:        }
                   8376:        /* fprintf(fichtm,"************ Results for covariates"); */
                   8377:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   8378:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   8379:        /* } */
                   8380:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8381:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8382:        /* } */
                   8383:        if(invalidvarcomb[k1]){
                   8384:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8385:         continue;
                   8386:        }
                   8387:        fprintf(fichtm,"</a></li>");
                   8388:      } /* cptcovn >0 */
                   8389:    }
                   8390:    fprintf(fichtm," \n</ul>");
                   8391: 
                   8392:    jj1=0;
                   8393: 
                   8394:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8395:      /* k1=nres; */
                   8396:      k1=TKresult[nres];
                   8397:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
                   8398:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8399:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   8400:    /*     continue; */
                   8401: 
                   8402:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8403:      jj1++;
                   8404:      if (cptcovn > 0) {
                   8405:        fprintf(fichtm,"\n<p><a name=\"rescov");
                   8406:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8407:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8408:        }
                   8409:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8410:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8411:        /* } */
                   8412:        fprintf(fichtm,"\"</a>");
                   8413:  
                   8414:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   8415:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8416:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8417:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8418:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   8419:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
                   8420:        }
                   8421:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8422:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
                   8423:        if(invalidvarcomb[k1]){
                   8424:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   8425:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   8426:         continue;
                   8427:        }
                   8428:      }
                   8429:      /* aij, bij */
                   8430:      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> \
                   8431: <img src=\"%s_%d-1-%d.svg\">",model,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres);
                   8432:      /* Pij */
                   8433:      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> \
                   8434: <img src=\"%s_%d-2-%d.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres);     
                   8435:      /* Quasi-incidences */
                   8436:      fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
                   8437:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
                   8438:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
                   8439: 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> \
                   8440: <img src=\"%s_%d-3-%d.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres); 
                   8441:      /* Survival functions (period) in state j */
                   8442:      for(cpt=1; cpt<=nlstate;cpt++){
                   8443:        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);
                   8444:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   8445:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
                   8446:      }
                   8447:      /* State specific survival functions (period) */
                   8448:      for(cpt=1; cpt<=nlstate;cpt++){
                   8449:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   8450:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
                   8451:  <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);
                   8452:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   8453:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
                   8454:      }
                   8455:      /* Period (forward stable) prevalence in each health state */
                   8456:      for(cpt=1; cpt<=nlstate;cpt++){
                   8457:        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);
                   8458:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   8459:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
                   8460:      }
                   8461:      if(prevbcast==1){
                   8462:        /* Backward prevalence in each health state */
                   8463:        for(cpt=1; cpt<=nlstate;cpt++){
                   8464:         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);
                   8465:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   8466:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
                   8467:        }
                   8468:      }
                   8469:      if(prevfcast==1){
                   8470:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
                   8471:        for(cpt=1; cpt<=nlstate;cpt++){
                   8472:         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);
                   8473:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   8474:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   8475:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
                   8476:        }
                   8477:      }
                   8478:      if(prevbcast==1){
                   8479:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   8480:        for(cpt=1; cpt<=nlstate;cpt++){
                   8481:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   8482:  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 \
                   8483:  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) \
                   8484: 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);
                   8485:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   8486:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   8487:        }
                   8488:      }
                   8489:         
                   8490:      for(cpt=1; cpt<=nlstate;cpt++) {
                   8491:        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);
                   8492:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   8493:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
                   8494:      }
                   8495:      /* } /\* end i1 *\/ */
                   8496:    }/* End k1=nres */
                   8497:    fprintf(fichtm,"</ul>");
                   8498: 
                   8499:    fprintf(fichtm,"\
                   8500: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
                   8501:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
                   8502:  - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
                   8503: But because parameters are usually highly correlated (a higher incidence of disability \
                   8504: and a higher incidence of recovery can give very close observed transition) it might \
                   8505: be very useful to look not only at linear confidence intervals estimated from the \
                   8506: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   8507: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   8508: covariance matrix of the one-step probabilities. \
                   8509: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
                   8510: 
                   8511:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   8512:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   8513:    fprintf(fichtm,"\
                   8514:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   8515:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
                   8516: 
                   8517:    fprintf(fichtm,"\
                   8518:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   8519:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   8520:    fprintf(fichtm,"\
                   8521:  - 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): \
                   8522:    <a href=\"%s\">%s</a> <br>\n</li>",
                   8523:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
                   8524:    fprintf(fichtm,"\
                   8525:  - (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): \
                   8526:    <a href=\"%s\">%s</a> <br>\n</li>",
                   8527:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
                   8528:    fprintf(fichtm,"\
                   8529:  - 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",
                   8530:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   8531:    fprintf(fichtm,"\
                   8532:  - 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",
                   8533:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   8534:    fprintf(fichtm,"\
                   8535:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
                   8536:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   8537: 
                   8538: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   8539: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   8540: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   8541: /*     <br>",fileres,fileres,fileres,fileres); */
                   8542: /*  else  */
                   8543: /*    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); */
                   8544:    fflush(fichtm);
                   8545: 
                   8546:    m=pow(2,cptcoveff);
                   8547:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   8548: 
                   8549:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   8550: 
                   8551:   jj1=0;
                   8552: 
                   8553:    fprintf(fichtm," \n<ul>");
                   8554:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8555:      /* k1=nres; */
                   8556:      k1=TKresult[nres];
                   8557:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8558:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8559:      /*   continue; */
                   8560:      jj1++;
                   8561:      if (cptcovn > 0) {
                   8562:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
                   8563:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8564:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8565:        }
                   8566:        fprintf(fichtm,"\">");
                   8567:        
                   8568:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8569:        fprintf(fichtm,"************ Results for covariates");
                   8570:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8571:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8572:        }
                   8573:        if(invalidvarcomb[k1]){
                   8574:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8575:         continue;
                   8576:        }
                   8577:        fprintf(fichtm,"</a></li>");
                   8578:      } /* cptcovn >0 */
                   8579:    } /* End nres */
                   8580:    fprintf(fichtm," \n</ul>");
                   8581: 
                   8582:    jj1=0;
                   8583: 
                   8584:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8585:      /* k1=nres; */
                   8586:      k1=TKresult[nres];
                   8587:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
                   8588:      /* for(k1=1; k1<=m;k1++){ */
                   8589:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8590:      /*   continue; */
                   8591:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8592:      jj1++;
                   8593:      if (cptcovn > 0) {
                   8594:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
                   8595:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8596:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8597:        }
                   8598:        fprintf(fichtm,"\"</a>");
                   8599:        
                   8600:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   8601:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   8602:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8603:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8604:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   8605:        }
                   8606: 
                   8607:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
                   8608: 
                   8609:        if(invalidvarcomb[k1]){
                   8610:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   8611:         continue;
                   8612:        }
                   8613:      } /* If cptcovn >0 */
                   8614:      for(cpt=1; cpt<=nlstate;cpt++) {
                   8615:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
                   8616: 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);
                   8617:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   8618:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
                   8619:      }
                   8620:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
                   8621: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
                   8622: true period expectancies (those weighted with period prevalences are also\
                   8623:  drawn in addition to the population based expectancies computed using\
                   8624:  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);
                   8625:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   8626:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
                   8627:      /* } /\* end i1 *\/ */
                   8628:   }/* End nres */
                   8629:    fprintf(fichtm,"</ul>");
                   8630:    fflush(fichtm);
                   8631: }
                   8632: 
                   8633: /******************* Gnuplot file **************/
                   8634: 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){
                   8635: 
                   8636:   char dirfileres[256],optfileres[256];
                   8637:   char gplotcondition[256], gplotlabel[256];
                   8638:   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;
                   8639:   int lv=0, vlv=0, kl=0;
                   8640:   int ng=0;
                   8641:   int vpopbased;
                   8642:   int ioffset; /* variable offset for columns */
                   8643:   int iyearc=1; /* variable column for year of projection  */
                   8644:   int iagec=1; /* variable column for age of projection  */
                   8645:   int nres=0; /* Index of resultline */
                   8646:   int istart=1; /* For starting graphs in projections */
                   8647: 
                   8648: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   8649: /*     printf("Problem with file %s",optionfilegnuplot); */
                   8650: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   8651: /*   } */
                   8652: 
                   8653:   /*#ifdef windows */
                   8654:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   8655:   /*#endif */
                   8656:   m=pow(2,cptcoveff);
                   8657: 
                   8658:   /* diagram of the model */
                   8659:   fprintf(ficgp,"\n#Diagram of the model \n");
                   8660:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   8661:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   8662:   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);
                   8663: 
                   8664:   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);
                   8665:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   8666:   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);
                   8667:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   8668:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   8669:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   8670:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   8671: 
                   8672:   /* Contribution to likelihood */
                   8673:   /* Plot the probability implied in the likelihood */
                   8674:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   8675:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   8676:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   8677:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   8678: /* nice for mle=4 plot by number of matrix products.
                   8679:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   8680: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
                   8681:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   8682:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8683:   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));
                   8684:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8685:   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));
                   8686:   for (i=1; i<= nlstate ; i ++) {
                   8687:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   8688:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   8689:     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);
                   8690:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   8691:       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);
                   8692:     }
                   8693:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8694:   }
                   8695:   /* 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 */               
                   8696:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8697:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8698:   fprintf(ficgp,"\nset out;unset log\n");
                   8699:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   8700: 
                   8701:   /* Plot the probability implied in the likelihood by covariate value */
                   8702:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   8703:   /* if(debugILK==1){ */
                   8704:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
                   8705:     kvar=Tvar[TvarFind[kf]]; /* variable name */
                   8706:     /* k=18+Tvar[TvarFind[kf]];/\*offset because there are 18 columns in the ILK_ file but could be placed else where *\/ */
1.2     ! brouard  8707:     /* k=18+kf;/\*offset because there are 18 columns in the ILK_ file *\/ */
        !          8708:     /* k=19+kf;/\*offset because there are 19 columns in the ILK_ file *\/ */
        !          8709:     k=16+nlstate+kf;/*offset because there are 19 columns in the ILK_ file, first cov Vn on col 21 with 4 living states */
1.1       brouard  8710:     for (i=1; i<= nlstate ; i ++) {
                   8711:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8712:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   8713:       if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8714:        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);
                   8715:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   8716:          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);
                   8717:        }
                   8718:       }else{
                   8719:        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);
                   8720:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   8721:          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);
                   8722:        }
                   8723:       }
                   8724:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8725:     }
                   8726:   } /* End of each covariate dummy */
                   8727:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
                   8728:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   8729:      *     kmodel       =     1   2     3     4         5        6        7       8        9
                   8730:      *  varying                   1     2                                 3       4        5
                   8731:      *  ncovv                     1     2                                3 4     5 6      7 8
                   8732:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
                   8733:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
                   8734:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
                   8735:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
                   8736:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
                   8737:      */
                   8738:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   8739:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   8740:     /* 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]); */
                   8741:     if(ipos!=iposold){ /* Not a product or first of a product */
                   8742:       /* printf(" %d",ipos); */
                   8743:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   8744:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
                   8745:       kk++; /* Position of the ncovv column in ILK_ */
                   8746:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
                   8747:       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)  */
                   8748:        for (i=1; i<= nlstate ; i ++) {
                   8749:          fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8750:          fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   8751: 
                   8752:            /* printf("Before DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
                   8753:          if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8754:            /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
                   8755:            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);
                   8756:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8757:              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);
                   8758:            }
                   8759:          }else{
                   8760:            /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
                   8761:            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);
                   8762:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8763:              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);
                   8764:            }
                   8765:          }
                   8766:          fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8767:        }
                   8768:       }/* End if dummy varying */
                   8769:     }else{ /*Product */
                   8770:       /* printf("*"); */
                   8771:       /* fprintf(ficresilk,"*"); */
                   8772:     }
                   8773:     iposold=ipos;
                   8774:   } /* For each time varying covariate */
                   8775:   /* } /\* debugILK==1 *\/ */
                   8776:   /* 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 */               
                   8777:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8778:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8779:   fprintf(ficgp,"\nset out;unset log\n");
                   8780:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   8781: 
                   8782: 
                   8783:   
                   8784:   strcpy(dirfileres,optionfilefiname);
                   8785:   strcpy(optfileres,"vpl");
                   8786:   /* 1eme*/
                   8787:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   8788:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
                   8789:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8790:        k1=TKresult[nres];
                   8791:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
                   8792:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   8793:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8794:        /*   continue; */
                   8795:        /* We are interested in selected combination by the resultline */
                   8796:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
                   8797:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
                   8798:        strcpy(gplotlabel,"(");
                   8799:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8800:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8801:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8802: 
                   8803:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   8804:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   8805:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8806:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8807:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8808:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8809:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   8810:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   8811:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   8812:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8813:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8814:        /* } */
                   8815:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8816:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   8817:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8818:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8819:        }
                   8820:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   8821:        /* printf("\n#\n"); */
                   8822:        fprintf(ficgp,"\n#\n");
                   8823:        if(invalidvarcomb[k1]){
                   8824:           /*k1=k1-1;*/ /* To be checked */
                   8825:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8826:          continue;
                   8827:        }
                   8828:       
                   8829:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   8830:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
                   8831:        /* fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel); */
                   8832:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
                   8833:        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);
                   8834:        /* 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); */
                   8835:       /* k1-1 error should be nres-1*/
                   8836:        for (i=1; i<= nlstate ; i ++) {
                   8837:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8838:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   8839:        }
                   8840:        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);
                   8841:        for (i=1; i<= nlstate ; i ++) {
                   8842:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8843:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8844:        } 
                   8845:        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); 
                   8846:        for (i=1; i<= nlstate ; i ++) {
                   8847:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8848:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8849:        }  
                   8850:        /* 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)); */
                   8851:        
                   8852:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   8853:         if(cptcoveff ==0){
                   8854:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
                   8855:        }else{
                   8856:          kl=0;
                   8857:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   8858:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8859:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
                   8860:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8861:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8862:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8863:            vlv= nbcode[Tvaraff[k]][lv];
                   8864:            kl++;
                   8865:            /* 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 *\/ */
                   8866:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8867:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8868:            /* ''  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*/
                   8869:            if(k==cptcoveff){
                   8870:              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], \
                   8871:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   8872:            }else{
                   8873:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   8874:              kl++;
                   8875:            }
                   8876:          } /* end covariate */
                   8877:        } /* end if no covariate */
                   8878: 
                   8879:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
                   8880:          /* 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); */
                   8881:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
                   8882:          if(cptcoveff ==0){
                   8883:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
                   8884:          }else{
                   8885:            kl=0;
                   8886:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   8887:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8888:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
                   8889:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8890:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8891:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8892:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8893:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
                   8894:              kl++;
                   8895:              /* 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 *\/ */
                   8896:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8897:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8898:              /* ''  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*/
                   8899:              if(k==cptcoveff){
                   8900:                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], \
                   8901:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
                   8902:              }else{
                   8903:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
                   8904:                kl++;
                   8905:              }
                   8906:            } /* end covariate */
                   8907:          } /* end if no covariate */
                   8908:          if(prevbcast == 1){
                   8909:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   8910:            /* k1-1 error should be nres-1*/
                   8911:            for (i=1; i<= nlstate ; i ++) {
                   8912:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8913:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   8914:            }
                   8915:            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);
                   8916:            for (i=1; i<= nlstate ; i ++) {
                   8917:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8918:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8919:            } 
                   8920:            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); 
                   8921:            for (i=1; i<= nlstate ; i ++) {
                   8922:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8923:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8924:            } 
                   8925:            fprintf(ficgp,"\" t\"\" w l lt 4");
                   8926:          } /* end if backprojcast */
                   8927:        } /* end if prevbcast */
                   8928:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   8929:        fprintf(ficgp,"\nset out ;unset title;\n");
                   8930:       } /* nres */
                   8931:     /* } /\* k1 *\/ */
                   8932:   } /* cpt */
                   8933: 
                   8934:   
                   8935:   /*2 eme*/
                   8936:   /* for (k1=1; k1<= m ; k1 ++){   */
                   8937:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8938:       k1=TKresult[nres];
                   8939:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
                   8940:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8941:       /*       continue; */
                   8942:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
                   8943:       strcpy(gplotlabel,"(");
                   8944:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8945:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8946:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8947:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8948:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8949:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8950:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8951:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8952:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8953:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8954:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8955:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8956:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8957:       /* } */
                   8958:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   8959:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8960:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8961:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8962:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8963:       }
                   8964:       strcpy(gplotlabel+strlen(gplotlabel),")");
                   8965:       fprintf(ficgp,"\n#\n");
                   8966:       if(invalidvarcomb[k1]){
                   8967:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8968:        continue;
                   8969:       }
                   8970:                        
                   8971:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
                   8972:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   8973:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   8974:        if(vpopbased==0){
                   8975:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   8976:        }else
                   8977:          fprintf(ficgp,"\nreplot ");
                   8978:        for (i=1; i<= nlstate+1 ; i ++) {
                   8979:          k=2*i;
                   8980:          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);
                   8981:          for (j=1; j<= nlstate+1 ; j ++) {
                   8982:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8983:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8984:          }   
                   8985:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   8986:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   8987:          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);
                   8988:          for (j=1; j<= nlstate+1 ; j ++) {
                   8989:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8990:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8991:          }   
                   8992:          fprintf(ficgp,"\" t\"\" w l lt 0,");
                   8993:          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);
                   8994:          for (j=1; j<= nlstate+1 ; j ++) {
                   8995:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8996:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8997:          }   
                   8998:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   8999:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   9000:        } /* state */
                   9001:       } /* vpopbased */
                   9002:       fprintf(ficgp,"\nset out;set out \"%s_%d-%d.svg\"; replot; set out; unset label;\n",subdirf2(optionfilefiname,"E_"),k1,nres); /* Buggy gnuplot */
                   9003:     } /* end nres */
                   9004:   /* } /\* k1 end 2 eme*\/ */
                   9005:        
                   9006:        
                   9007:   /*3eme*/
                   9008:   /* for (k1=1; k1<= m ; k1 ++){ */
                   9009:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9010:       k1=TKresult[nres];
                   9011:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
                   9012:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9013:       /*       continue; */
                   9014: 
                   9015:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
                   9016:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
                   9017:        strcpy(gplotlabel,"(");
                   9018:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9019:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9020:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9021:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   9022:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   9023:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9024:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9025:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9026:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9027:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9028:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9029:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9030:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9031:        /* } */
                   9032:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9033:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   9034:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   9035:        }
                   9036:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   9037:        fprintf(ficgp,"\n#\n");
                   9038:        if(invalidvarcomb[k1]){
                   9039:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9040:          continue;
                   9041:        }
                   9042:                        
                   9043:        /*       k=2+nlstate*(2*cpt-2); */
                   9044:        k=2+(nlstate+1)*(cpt-1);
                   9045:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
                   9046:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
                   9047:        fprintf(ficgp,"set ter svg size 640, 480\n\
                   9048: 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);
                   9049:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   9050:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   9051:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   9052:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   9053:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   9054:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   9055:                                
                   9056:        */
                   9057:        for (i=1; i< nlstate ; i ++) {
                   9058:          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);
                   9059:          /*    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);*/
                   9060:                                
                   9061:        } 
                   9062:        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),nres-1,nres-1,k+nlstate,cpt);
                   9063:       }
                   9064:       fprintf(ficgp,"\nunset label;\n");
                   9065:     } /* end nres */
                   9066:   /* } /\* end kl 3eme *\/ */
                   9067:   
                   9068:   /* 4eme */
                   9069:   /* Survival functions (period) from state i in state j by initial state i */
                   9070:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
                   9071:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9072:       k1=TKresult[nres];
                   9073:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
                   9074:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9075:       /*       continue; */
                   9076:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
                   9077:        strcpy(gplotlabel,"(");
                   9078:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   9079:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9080:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9081:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9082:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   9083:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9084:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   9085:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9086:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9087:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9088:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9089:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9090:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9091:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9092:        /* } */
                   9093:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9094:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9095:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9096:        }       
                   9097:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   9098:        fprintf(ficgp,"\n#\n");
                   9099:        if(invalidvarcomb[k1]){
                   9100:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9101:          continue;
                   9102:        }
                   9103:       
                   9104:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
                   9105:        fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   9106:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   9107: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   9108:        k=3;
                   9109:        for (i=1; i<= nlstate ; i ++){
                   9110:          if(i==1){
                   9111:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   9112:          }else{
                   9113:            fprintf(ficgp,", '' ");
                   9114:          }
                   9115:          l=(nlstate+ndeath)*(i-1)+1;
                   9116:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   9117:          for (j=2; j<= nlstate+ndeath ; j ++)
                   9118:            fprintf(ficgp,"+$%d",k+l+j-1);
                   9119:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   9120:        } /* nlstate */
                   9121:        fprintf(ficgp,"\nset out; unset label;\n");
                   9122:       } /* end cpt state*/ 
                   9123:     } /* end nres */
                   9124:   /* } /\* end covariate k1 *\/   */
                   9125: 
                   9126: /* 5eme */
                   9127:   /* Survival functions (period) from state i in state j by final state j */
                   9128:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
                   9129:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9130:       k1=TKresult[nres];
                   9131:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
                   9132:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9133:       /*       continue; */
                   9134:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
                   9135:        strcpy(gplotlabel,"(");
                   9136:        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);
                   9137:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9138:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9139:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9140:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   9141:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9142:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   9143:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9144:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9145:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9146:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9147:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9148:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9149:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9150:        /* } */
                   9151:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9152:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9153:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9154:        }       
                   9155:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   9156:        fprintf(ficgp,"\n#\n");
                   9157:        if(invalidvarcomb[k1]){
                   9158:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9159:          continue;
                   9160:        }
                   9161:       
                   9162:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
                   9163:        fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   9164:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   9165: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   9166:        k=3;
                   9167:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   9168:          if(j==1)
                   9169:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   9170:          else
                   9171:            fprintf(ficgp,", '' ");
                   9172:          l=(nlstate+ndeath)*(cpt-1) +j;
                   9173:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   9174:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   9175:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   9176:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   9177:        } /* nlstate */
                   9178:        fprintf(ficgp,", '' ");
                   9179:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   9180:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   9181:          l=(nlstate+ndeath)*(cpt-1) +j;
                   9182:          if(j < nlstate)
                   9183:            fprintf(ficgp,"$%d +",k+l);
                   9184:          else
                   9185:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   9186:        }
                   9187:        fprintf(ficgp,"\nset out; unset label;\n");
                   9188:       } /* end cpt state*/ 
                   9189:     /* } /\* end covariate *\/   */
                   9190:   } /* end nres */
                   9191:   
                   9192: /* 6eme */
                   9193:   /* CV preval stable (period) for each covariate */
                   9194:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
                   9195:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9196:      k1=TKresult[nres];
                   9197:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
                   9198:      /* if(m != 1 && TKresult[nres]!= k1) */
                   9199:      /*  continue; */
                   9200:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
                   9201:       strcpy(gplotlabel,"(");      
                   9202:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   9203:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9204:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9205:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9206:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   9207:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   9208:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9209:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9210:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9211:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9212:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9213:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9214:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9215:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9216:       /* } */
                   9217:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9218:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9219:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9220:       }        
                   9221:       strcpy(gplotlabel+strlen(gplotlabel),")");
                   9222:       fprintf(ficgp,"\n#\n");
                   9223:       if(invalidvarcomb[k1]){
                   9224:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9225:        continue;
                   9226:       }
                   9227:       
                   9228:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
                   9229:       fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   9230:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
                   9231: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   9232:       k=3; /* Offset */
                   9233:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
                   9234:        if(i==1)
                   9235:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   9236:        else
                   9237:          fprintf(ficgp,", '' ");
                   9238:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
                   9239:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   9240:        for (j=2; j<= nlstate ; j ++)
                   9241:          fprintf(ficgp,"+$%d",k+l+j-1);
                   9242:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   9243:       } /* nlstate */
                   9244:       fprintf(ficgp,"\nset out; unset label;\n");
                   9245:     } /* end cpt state*/ 
                   9246:   } /* end covariate */  
                   9247:   
                   9248:   
                   9249: /* 7eme */
                   9250:   if(prevbcast == 1){
                   9251:     /* CV backward prevalence  for each covariate */
                   9252:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
                   9253:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9254:       k1=TKresult[nres];
                   9255:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
                   9256:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9257:       /*       continue; */
                   9258:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
                   9259:        strcpy(gplotlabel,"(");      
                   9260:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
                   9261:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9262:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9263:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9264:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   9265:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   9266:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9267:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9268:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9269:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9270:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9271:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9272:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9273:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9274:        /* } */
                   9275:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9276:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9277:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9278:        }       
                   9279:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   9280:        fprintf(ficgp,"\n#\n");
                   9281:        if(invalidvarcomb[k1]){
                   9282:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9283:          continue;
                   9284:        }
                   9285:        
                   9286:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
                   9287:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   9288:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
                   9289: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   9290:        k=3; /* Offset */
                   9291:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
                   9292:          if(i==1)
                   9293:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   9294:          else
                   9295:            fprintf(ficgp,", '' ");
                   9296:          /* l=(nlstate+ndeath)*(i-1)+1; */
                   9297:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
                   9298:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   9299:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
                   9300:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
                   9301:          /* for (j=2; j<= nlstate ; j ++) */
                   9302:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   9303:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
                   9304:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
                   9305:        } /* nlstate */
                   9306:        fprintf(ficgp,"\nset out; unset label;\n");
                   9307:       } /* end cpt state*/ 
                   9308:     } /* end covariate */  
                   9309:   } /* End if prevbcast */
                   9310:   
                   9311:   /* 8eme */
                   9312:   if(prevfcast==1){
                   9313:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
                   9314:     
                   9315:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
                   9316:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9317:       k1=TKresult[nres];
                   9318:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
                   9319:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9320:       /*       continue; */
                   9321:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   9322:        strcpy(gplotlabel,"(");      
                   9323:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
                   9324:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9325:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9326:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9327:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9328:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9329:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9330:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9331:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9332:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9333:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9334:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9335:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9336:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9337:        /* } */
                   9338:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9339:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9340:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9341:        }       
                   9342:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   9343:        fprintf(ficgp,"\n#\n");
                   9344:        if(invalidvarcomb[k1]){
                   9345:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9346:          continue;
                   9347:        }
                   9348:        
                   9349:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
                   9350:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
                   9351:        fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   9352:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   9353: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   9354: 
                   9355:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   9356:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9357:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9358:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   9359:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9360:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9361:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9362:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9363:          if(i==istart){
                   9364:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   9365:          }else{
                   9366:            fprintf(ficgp,",\\\n '' ");
                   9367:          }
                   9368:          if(cptcoveff ==0){ /* No covariate */
                   9369:            ioffset=2; /* Age is in 2 */
                   9370:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9371:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9372:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9373:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9374:            fprintf(ficgp," u %d:(", ioffset); 
                   9375:            if(i==nlstate+1){
                   9376:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
                   9377:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9378:              fprintf(ficgp,",\\\n '' ");
                   9379:              fprintf(ficgp," u %d:(",ioffset); 
                   9380:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
                   9381:                     offyear,                           \
                   9382:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
                   9383:            }else
                   9384:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   9385:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   9386:          }else{ /* more than 2 covariates */
                   9387:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9388:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9389:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9390:            iyearc=ioffset-1;
                   9391:            iagec=ioffset;
                   9392:            fprintf(ficgp," u %d:(",ioffset); 
                   9393:            kl=0;
                   9394:            strcpy(gplotcondition,"(");
1.2     ! brouard  9395:            /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
1.1       brouard  9396:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
1.2     ! brouard  9397:            for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
        !          9398:              /* lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
        !          9399:              lv=Tvresult[nres][k];
        !          9400:              vlv=TinvDoQresult[nres][Tvresult[nres][k]];
1.1       brouard  9401:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9402:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9403:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   9404:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
1.2     ! brouard  9405:              /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
1.1       brouard  9406:              kl++;
1.2     ! brouard  9407:              /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
        !          9408:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,lv, kl+1, vlv );
1.1       brouard  9409:              kl++;
1.2     ! brouard  9410:              if(k <cptcovs && cptcovs>1)
1.1       brouard  9411:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9412:            }
                   9413:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9414:            /* 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 *\/ */
                   9415:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9416:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9417:            /* ''  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*/
                   9418:            if(i==nlstate+1){
                   9419:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   9420:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
                   9421:              fprintf(ficgp,",\\\n '' ");
                   9422:              fprintf(ficgp," u %d:(",iagec); 
                   9423:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   9424:                      iyearc, iagec, offyear,                           \
                   9425:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
                   9426: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   9427:            }else{
                   9428:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   9429:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   9430:            }
                   9431:          } /* end if covariate */
                   9432:        } /* nlstate */
                   9433:        fprintf(ficgp,"\nset out; unset label;\n");
                   9434:       } /* end cpt state*/
                   9435:     } /* end covariate */
                   9436:   } /* End if prevfcast */
                   9437:   
                   9438:   if(prevbcast==1){
                   9439:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   9440:     
                   9441:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
                   9442:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9443:      k1=TKresult[nres];
                   9444:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
                   9445:        /* if(m != 1 && TKresult[nres]!= k1) */
                   9446:        /*      continue; */
                   9447:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   9448:        strcpy(gplotlabel,"(");      
                   9449:        fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
                   9450:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9451:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9452:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9453:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9454:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9455:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9456:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9457:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9458:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9459:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9460:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9461:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9462:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9463:        /* } */
                   9464:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9465:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9466:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9467:        }       
                   9468:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   9469:        fprintf(ficgp,"\n#\n");
                   9470:        if(invalidvarcomb[k1]){
                   9471:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9472:          continue;
                   9473:        }
                   9474:        
                   9475:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   9476:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   9477:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   9478:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   9479: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   9480: 
                   9481:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   9482:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9483:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9484:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   9485:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9486:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9487:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9488:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9489:          if(i==istart){
                   9490:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   9491:          }else{
                   9492:            fprintf(ficgp,",\\\n '' ");
                   9493:          }
1.2     ! brouard  9494:          /* if(cptcoveff ==0){ /\* No covariate *\/ */
        !          9495:          if(cptcovs ==0){ /* No covariate */
1.1       brouard  9496:            ioffset=2; /* Age is in 2 */
                   9497:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9498:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9499:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9500:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9501:            fprintf(ficgp," u %d:(", ioffset); 
                   9502:            if(i==nlstate+1){
                   9503:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
                   9504:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9505:              fprintf(ficgp,",\\\n '' ");
                   9506:              fprintf(ficgp," u %d:(",ioffset); 
                   9507:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
                   9508:                     offbyear,                          \
                   9509:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   9510:            }else
                   9511:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   9512:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   9513:          }else{ /* more than 2 covariates */
                   9514:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9515:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9516:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9517:            iyearc=ioffset-1;
                   9518:            iagec=ioffset;
1.2     ! brouard  9519:            fprintf(ficgp," u %d:(",ioffset); 
1.1       brouard  9520:            kl=0;
                   9521:            strcpy(gplotcondition,"(");
                   9522:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
                   9523:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
                   9524:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   9525:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9526:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9527:                lv=Tvresult[nres][k];
                   9528:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   9529:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9530:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9531:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   9532:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   9533:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9534:                kl++;
                   9535:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   9536:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   9537:                kl++;
                   9538:                if(k <cptcovs && cptcovs>1)
                   9539:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9540:              }
                   9541:            }
                   9542:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9543:            /* 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 *\/ */
                   9544:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9545:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9546:            /* ''  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*/
                   9547:            if(i==nlstate+1){
                   9548:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   9549:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
                   9550:              fprintf(ficgp,",\\\n '' ");
                   9551:              fprintf(ficgp," u %d:(",iagec); 
                   9552:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
                   9553:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   9554:                      iyearc,iagec,offbyear,                            \
                   9555:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
                   9556: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   9557:            }else{
                   9558:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   9559:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   9560:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   9561:            }
                   9562:          } /* end if covariate */
                   9563:        } /* nlstate */
                   9564:        fprintf(ficgp,"\nset out; unset label;\n");
                   9565:       } /* end cpt state*/
                   9566:     } /* end covariate */
                   9567:   } /* End if prevbcast */
                   9568:   
                   9569:   
                   9570:   /* 9eme writing MLE parameters */
                   9571:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
                   9572:   for(i=1,jk=1; i <=nlstate; i++){
                   9573:     fprintf(ficgp,"# initial state %d\n",i);
                   9574:     for(k=1; k <=(nlstate+ndeath); k++){
                   9575:       if (k != i) {
                   9576:        fprintf(ficgp,"#   current state %d\n",k);
                   9577:        for(j=1; j <=ncovmodel; j++){
                   9578:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   9579:          jk++; 
                   9580:        }
                   9581:        fprintf(ficgp,"\n");
                   9582:       }
                   9583:     }
                   9584:   }
                   9585:   fprintf(ficgp,"##############\n#\n");
                   9586:   
                   9587:   /*goto avoid;*/
                   9588:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   9589:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
                   9590:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   9591:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   9592:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   9593:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   9594:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9595:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9596:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9597:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9598:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   9599:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9600:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   9601:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   9602:   fprintf(ficgp,"#\n");
                   9603:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
                   9604:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
                   9605:     fprintf(ficgp,"#model=1+age+%s \n",model);
                   9606:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.2     ! brouard  9607:     /* fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/\* to be checked *\/ */
        !          9608:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcovs,m);/* to be checked */
1.1       brouard  9609:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
                   9610:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9611:      /* k1=nres; */
                   9612:       k1=TKresult[nres];
                   9613:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
                   9614:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
                   9615:       strcpy(gplotlabel,"(");
                   9616:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
                   9617:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   9618:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   9619:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   9620:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9621:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9622:       }
                   9623:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9624:       /*       continue; */
                   9625:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   9626:       /* strcpy(gplotlabel,"("); */
                   9627:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   9628:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9629:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9630:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9631:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9632:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9633:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9634:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9635:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9636:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9637:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9638:       /* } */
                   9639:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9640:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9641:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9642:       /* }      */
                   9643:       strcpy(gplotlabel+strlen(gplotlabel),")");
                   9644:       fprintf(ficgp,"\n#\n");
                   9645:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
                   9646:       fprintf(ficgp,"\nset key outside ");
                   9647:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   9648:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
                   9649:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   9650:       if (ng==1){
                   9651:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   9652:        fprintf(ficgp,"\nunset log y");
                   9653:       }else if (ng==2){
                   9654:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   9655:        fprintf(ficgp,"\nset log y");
                   9656:       }else if (ng==3){
                   9657:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   9658:        fprintf(ficgp,"\nset log y");
                   9659:       }else
                   9660:        fprintf(ficgp,"\nunset title ");
                   9661:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   9662:       i=1;
                   9663:       for(k2=1; k2<=nlstate; k2++) {
                   9664:        k3=i;
                   9665:        for(k=1; k<=(nlstate+ndeath); k++) {
                   9666:          if (k != k2){
                   9667:            switch( ng) {
                   9668:            case 1:
                   9669:              if(nagesqr==0)
                   9670:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   9671:              else /* nagesqr =1 */
                   9672:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9673:              break;
                   9674:            case 2: /* ng=2 */
                   9675:              if(nagesqr==0)
                   9676:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   9677:              else /* nagesqr =1 */
                   9678:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9679:              break;
                   9680:            case 3:
                   9681:              if(nagesqr==0)
                   9682:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   9683:              else /* nagesqr =1 */
                   9684:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   9685:              break;
                   9686:            }
                   9687:            ij=1;/* To be checked else nbcode[0][0] wrong */
                   9688:            ijp=1; /* product no age */
                   9689:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   9690:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   9691:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
                   9692:              switch(Typevar[j]){
                   9693:              case 1:
                   9694:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9695:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   9696:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9697:                      if(DummyV[j]==0){/* Bug valgrind */
                   9698:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   9699:                      }else{ /* quantitative */
                   9700:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9701:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9702:                      }
                   9703:                      ij++;
                   9704:                    }
                   9705:                  }
                   9706:                }
                   9707:                break;
                   9708:              case 2:
                   9709:                if(cptcovprod >0){
                   9710:                  if(j==Tprod[ijp]) { /* */ 
                   9711:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9712:                    if(ijp <=cptcovprod) { /* Product */
                   9713:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9714:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9715:                          /* 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)]); */
                   9716:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9717:                        }else{ /* Vn is dummy and Vm is quanti */
                   9718:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9719:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9720:                        }
                   9721:                      }else{ /* Vn*Vm Vn is quanti */
                   9722:                        if(DummyV[Tvard[ijp][2]]==0){
                   9723:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9724:                        }else{ /* Both quanti */
                   9725:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9726:                        }
                   9727:                      }
                   9728:                      ijp++;
                   9729:                    }
                   9730:                  } /* end Tprod */
                   9731:                }
                   9732:                break;
                   9733:              case 3:
                   9734:                if(cptcovdageprod >0){
                   9735:                  /* if(j==Tprod[ijp]) { */ /* not necessary */ 
                   9736:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
1.2     ! brouard  9737:                    if(ijp <=cptcovprod) { /* Product Vn*Vm and age*VN*Vm*/
        !          9738:                      if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
        !          9739:                        if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.1       brouard  9740:                          /* 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)]); */
                   9741:                          fprintf(ficgp,"+p%d*%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9742:                        }else{ /* Vn is dummy and Vm is quanti */
                   9743:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
1.2     ! brouard  9744:                          fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
1.1       brouard  9745:                        }
1.2     ! brouard  9746:                      }else{ /* age* Vn*Vm Vn is quanti HERE */
1.1       brouard  9747:                        if(DummyV[Tvard[ijp][2]]==0){
1.2     ! brouard  9748:                          fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvardk[ijp][2]],Tqinvresult[nres][Tvardk[ijp][1]]);
1.1       brouard  9749:                        }else{ /* Both quanti */
1.2     ! brouard  9750:                          fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
1.1       brouard  9751:                        }
                   9752:                      }
                   9753:                      ijp++;
                   9754:                    }
                   9755:                    /* } */ /* end Tprod */
                   9756:                }
                   9757:                break;
                   9758:              case 0:
                   9759:                /* simple covariate */
                   9760:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   9761:                if(Dummy[j]==0){
                   9762:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   9763:                }else{ /* quantitative */
                   9764:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
                   9765:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9766:                }
                   9767:               /* end simple */
                   9768:                break;
                   9769:              default:
                   9770:                break;
                   9771:              } /* end switch */
                   9772:            } /* end j */
                   9773:          }else{ /* k=k2 */
                   9774:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   9775:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   9776:            }else
                   9777:              i=i-ncovmodel;
                   9778:          }
                   9779:          
                   9780:          if(ng != 1){
                   9781:            fprintf(ficgp,")/(1");
                   9782:            
                   9783:            for(cpt=1; cpt <=nlstate; cpt++){ 
                   9784:              if(nagesqr==0)
                   9785:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
                   9786:              else /* nagesqr =1 */
                   9787:                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);
                   9788:               
                   9789:              ij=1;
                   9790:              ijp=1;
                   9791:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   9792:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   9793:                switch(Typevar[j]){
                   9794:                case 1:
                   9795:                  if(cptcovage >0){ 
                   9796:                    if(j==Tage[ij]) { /* Bug valgrind */
                   9797:                      if(ij <=cptcovage) { /* Bug valgrind */
                   9798:                        if(DummyV[j]==0){/* Bug valgrind */
                   9799:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   9800:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   9801:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   9802:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   9803:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9804:                        }else{ /* quantitative */
                   9805:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9806:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9807:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9808:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9809:                        }
                   9810:                        ij++;
                   9811:                      }
                   9812:                    }
                   9813:                  }
                   9814:                  break;
                   9815:                case 2:
                   9816:                  if(cptcovprod >0){
                   9817:                    if(j==Tprod[ijp]) { /* */ 
                   9818:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9819:                      if(ijp <=cptcovprod) { /* Product */
                   9820:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9821:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9822:                            /* 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)]); */
                   9823:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9824:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9825:                          }else{ /* Vn is dummy and Vm is quanti */
                   9826:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9827:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9828:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9829:                          }
                   9830:                        }else{ /* Vn*Vm Vn is quanti */
                   9831:                          if(DummyV[Tvard[ijp][2]]==0){
                   9832:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9833:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9834:                          }else{ /* Both quanti */
                   9835:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9836:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9837:                          } 
                   9838:                        }
                   9839:                        ijp++;
                   9840:                      }
                   9841:                    } /* end Tprod */
                   9842:                  } /* end if */
                   9843:                  break;
                   9844:                case 3:
                   9845:                  if(cptcovdageprod >0){
                   9846:                    /* if(j==Tprod[ijp]) { /\* *\/  */
                   9847:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9848:                      if(ijp <=cptcovprod) { /* Product */
1.2     ! brouard  9849:                        if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
        !          9850:                          if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.1       brouard  9851:                            /* 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)]); */
1.2     ! brouard  9852:                            fprintf(ficgp,"+p%d*%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvardk[ijp][1]],Tinvresult[nres][Tvardk[ijp][2]]);
1.1       brouard  9853:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9854:                          }else{ /* Vn is dummy and Vm is quanti */
                   9855:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
1.2     ! brouard  9856:                            fprintf(ficgp,"+p%d*%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
1.1       brouard  9857:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9858:                          }
                   9859:                        }else{ /* Vn*Vm Vn is quanti */
1.2     ! brouard  9860:                          if(DummyV[Tvardk[ijp][2]]==0){
        !          9861:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvardk[ijp][2]],Tqinvresult[nres][Tvardk[ijp][1]]);
1.1       brouard  9862:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9863:                          }else{ /* Both quanti */
1.2     ! brouard  9864:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
1.1       brouard  9865:                            /* fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9866:                          } 
                   9867:                        }
                   9868:                        ijp++;
                   9869:                      }
                   9870:                    /* } /\* end Tprod *\/ */
                   9871:                  } /* end if */
                   9872:                  break;
                   9873:                case 0: 
                   9874:                  /* simple covariate */
                   9875:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   9876:                  if(Dummy[j]==0){
                   9877:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9878:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   9879:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9880:                  }else{ /* quantitative */
                   9881:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   9882:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   9883:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9884:                  }
                   9885:                  /* end simple */
                   9886:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   9887:                  break;
                   9888:                default:
                   9889:                  break;
                   9890:                } /* end switch */
                   9891:              }
                   9892:              fprintf(ficgp,")");
                   9893:            }
                   9894:            fprintf(ficgp,")");
                   9895:            if(ng ==2)
                   9896:              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);
                   9897:            else /* ng= 3 */
                   9898:              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);
                   9899:           }else{ /* end ng <> 1 */
                   9900:            if( k !=k2) /* logit p11 is hard to draw */
                   9901:              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);
                   9902:          }
                   9903:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   9904:            fprintf(ficgp,",");
                   9905:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   9906:            fprintf(ficgp,",");
                   9907:          i=i+ncovmodel;
                   9908:        } /* end k */
                   9909:       } /* end k2 */
                   9910:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   9911:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
                   9912:     } /* end resultline */
                   9913:   } /* end ng */
                   9914:   /* avoid: */
                   9915:   fflush(ficgp); 
                   9916: }  /* end gnuplot */
                   9917: 
                   9918: 
                   9919: /*************** Moving average **************/
                   9920: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
                   9921:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
                   9922:    
                   9923:    int i, cpt, cptcod;
                   9924:    int modcovmax =1;
                   9925:    int mobilavrange, mob;
                   9926:    int iage=0;
                   9927:    int firstA1=0, firstA2=0;
                   9928: 
                   9929:    double sum=0., sumr=0.;
                   9930:    double age;
                   9931:    double *sumnewp, *sumnewm, *sumnewmr;
                   9932:    double *agemingood, *agemaxgood; 
                   9933:    double *agemingoodr, *agemaxgoodr; 
                   9934:   
                   9935:   
                   9936:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   9937:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
                   9938: 
                   9939:    sumnewp = vector(1,ncovcombmax);
                   9940:    sumnewm = vector(1,ncovcombmax);
                   9941:    sumnewmr = vector(1,ncovcombmax);
                   9942:    agemingood = vector(1,ncovcombmax); 
                   9943:    agemingoodr = vector(1,ncovcombmax);        
                   9944:    agemaxgood = vector(1,ncovcombmax);
                   9945:    agemaxgoodr = vector(1,ncovcombmax);
                   9946: 
                   9947:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   9948:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
                   9949:      sumnewp[cptcod]=0.;
                   9950:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   9951:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
                   9952:    }
                   9953:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   9954:   
                   9955:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   9956:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
                   9957:      else mobilavrange=mobilav;
                   9958:      for (age=bage; age<=fage; age++)
                   9959:        for (i=1; i<=nlstate;i++)
                   9960:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   9961:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9962:      /* We keep the original values on the extreme ages bage, fage and for 
                   9963:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   9964:        we use a 5 terms etc. until the borders are no more concerned. 
                   9965:      */ 
                   9966:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   9967:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   9968:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   9969:           sumnewm[cptcod]=0.;
                   9970:           for (i=1; i<=nlstate;i++){
                   9971:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   9972:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   9973:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   9974:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   9975:             }
                   9976:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   9977:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9978:           } /* end i */
                   9979:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   9980:         } /* end cptcod */
                   9981:        }/* end age */
                   9982:      }/* end mob */
                   9983:    }else{
                   9984:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
                   9985:      return -1;
                   9986:    }
                   9987: 
                   9988:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
                   9989:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   9990:      if(invalidvarcomb[cptcod]){
                   9991:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   9992:        continue;
                   9993:      }
                   9994: 
                   9995:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   9996:        sumnewm[cptcod]=0.;
                   9997:        sumnewmr[cptcod]=0.;
                   9998:        for (i=1; i<=nlstate;i++){
                   9999:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   10000:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   10001:        }
                   10002:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   10003:         agemingoodr[cptcod]=age;
                   10004:        }
                   10005:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   10006:           agemingood[cptcod]=age;
                   10007:        }
                   10008:      } /* age */
                   10009:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
                   10010:        sumnewm[cptcod]=0.;
                   10011:        sumnewmr[cptcod]=0.;
                   10012:        for (i=1; i<=nlstate;i++){
                   10013:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   10014:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   10015:        }
                   10016:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   10017:         agemaxgoodr[cptcod]=age;
                   10018:        }
                   10019:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   10020:         agemaxgood[cptcod]=age;
                   10021:        }
                   10022:      } /* age */
                   10023:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   10024:      /* but they will change */
                   10025:      firstA1=0;firstA2=0;
                   10026:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   10027:        sumnewm[cptcod]=0.;
                   10028:        sumnewmr[cptcod]=0.;
                   10029:        for (i=1; i<=nlstate;i++){
                   10030:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   10031:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   10032:        }
                   10033:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   10034:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   10035:           agemaxgoodr[cptcod]=age;  /* age min */
                   10036:           for (i=1; i<=nlstate;i++)
                   10037:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   10038:         }else{ /* bad we change the value with the values of good ages */
                   10039:           for (i=1; i<=nlstate;i++){
                   10040:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   10041:           } /* i */
                   10042:         } /* end bad */
                   10043:        }else{
                   10044:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   10045:           agemaxgood[cptcod]=age;
                   10046:         }else{ /* bad we change the value with the values of good ages */
                   10047:           for (i=1; i<=nlstate;i++){
                   10048:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   10049:           } /* i */
                   10050:         } /* end bad */
                   10051:        }/* end else */
                   10052:        sum=0.;sumr=0.;
                   10053:        for (i=1; i<=nlstate;i++){
                   10054:         sum+=mobaverage[(int)age][i][cptcod];
                   10055:         sumr+=probs[(int)age][i][cptcod];
                   10056:        }
                   10057:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   10058:         if(!firstA1){
                   10059:           firstA1=1;
                   10060:           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);
                   10061:         }
                   10062:         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);
                   10063:        } /* end bad */
                   10064:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   10065:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
                   10066:         if(!firstA2){
                   10067:           firstA2=1;
                   10068:           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);
                   10069:         }
                   10070:         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);
                   10071:        } /* end bad */
                   10072:      }/* age */
                   10073: 
                   10074:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
                   10075:        sumnewm[cptcod]=0.;
                   10076:        sumnewmr[cptcod]=0.;
                   10077:        for (i=1; i<=nlstate;i++){
                   10078:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   10079:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   10080:        } 
                   10081:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   10082:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   10083:           agemingoodr[cptcod]=age;
                   10084:           for (i=1; i<=nlstate;i++)
                   10085:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   10086:         }else{ /* bad we change the value with the values of good ages */
                   10087:           for (i=1; i<=nlstate;i++){
                   10088:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   10089:           } /* i */
                   10090:         } /* end bad */
                   10091:        }else{
                   10092:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   10093:           agemingood[cptcod]=age;
                   10094:         }else{ /* bad */
                   10095:           for (i=1; i<=nlstate;i++){
                   10096:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   10097:           } /* i */
                   10098:         } /* end bad */
                   10099:        }/* end else */
                   10100:        sum=0.;sumr=0.;
                   10101:        for (i=1; i<=nlstate;i++){
                   10102:         sum+=mobaverage[(int)age][i][cptcod];
                   10103:         sumr+=mobaverage[(int)age][i][cptcod];
                   10104:        }
                   10105:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   10106:         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);
                   10107:        } /* end bad */
                   10108:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   10109:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
                   10110:         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);
                   10111:        } /* end bad */
                   10112:      }/* age */
                   10113: 
                   10114:                
                   10115:      for (age=bage; age<=fage; age++){
                   10116:        /* printf("%d %d ", cptcod, (int)age); */
                   10117:        sumnewp[cptcod]=0.;
                   10118:        sumnewm[cptcod]=0.;
                   10119:        for (i=1; i<=nlstate;i++){
                   10120:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   10121:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   10122:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   10123:        }
                   10124:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   10125:      }
                   10126:      /* printf("\n"); */
                   10127:      /* } */
                   10128: 
                   10129:      /* brutal averaging */
                   10130:      /* for (i=1; i<=nlstate;i++){ */
                   10131:      /*   for (age=1; age<=bage; age++){ */
                   10132:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   10133:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   10134:      /*   }     */
                   10135:      /*   for (age=fage; age<=AGESUP; age++){ */
                   10136:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   10137:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   10138:      /*   } */
                   10139:      /* } /\* end i status *\/ */
                   10140:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   10141:      /*   for (age=1; age<=AGESUP; age++){ */
                   10142:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   10143:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   10144:      /*   } */
                   10145:      /* } */
                   10146:    }/* end cptcod */
                   10147:    free_vector(agemaxgoodr,1, ncovcombmax);
                   10148:    free_vector(agemaxgood,1, ncovcombmax);
                   10149:    free_vector(agemingood,1, ncovcombmax);
                   10150:    free_vector(agemingoodr,1, ncovcombmax);
                   10151:    free_vector(sumnewmr,1, ncovcombmax);
                   10152:    free_vector(sumnewm,1, ncovcombmax);
                   10153:    free_vector(sumnewp,1, ncovcombmax);
                   10154:    return 0;
                   10155:  }/* End movingaverage */
                   10156:  
                   10157: 
                   10158:  
                   10159: /************** Forecasting ******************/
                   10160: /* 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)*/
                   10161: 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){
                   10162:   /* dateintemean, mean date of interviews
                   10163:      dateprojd, year, month, day of starting projection 
                   10164:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
                   10165:      agemin, agemax range of age
                   10166:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   10167:   */
                   10168:   /* double anprojd, mprojd, jprojd; */
                   10169:   /* double anprojf, mprojf, jprojf; */
                   10170:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   10171:   double agec; /* generic age */
                   10172:   double agelim, ppij, yp,yp1,yp2;
                   10173:   double *popeffectif,*popcount;
                   10174:   double ***p3mat;
                   10175:   /* double ***mobaverage; */
                   10176:   char fileresf[FILENAMELENGTH];
                   10177: 
                   10178:   agelim=AGESUP;
                   10179:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   10180:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   10181:      We still use firstpass and lastpass as another selection.
                   10182:   */
                   10183:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   10184:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   10185:  
                   10186:   strcpy(fileresf,"F_"); 
                   10187:   strcat(fileresf,fileresu);
                   10188:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   10189:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   10190:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   10191:   }
                   10192:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   10193:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   10194: 
                   10195:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   10196: 
                   10197: 
                   10198:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10199:   if (stepm<=12) stepsize=1;
                   10200:   if(estepm < stepm){
                   10201:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   10202:   }
                   10203:   else{
                   10204:     hstepm=estepm;   
                   10205:   }
                   10206:   if(estepm > stepm){ /* Yes every two year */
                   10207:     stepsize=2;
                   10208:   }
                   10209:   hstepm=hstepm/stepm;
                   10210: 
                   10211:   
                   10212:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   10213:   /*                              fractional in yp1 *\/ */
                   10214:   /* aintmean=yp; */
                   10215:   /* yp2=modf((yp1*12),&yp); */
                   10216:   /* mintmean=yp; */
                   10217:   /* yp1=modf((yp2*30.5),&yp); */
                   10218:   /* jintmean=yp; */
                   10219:   /* if(jintmean==0) jintmean=1; */
                   10220:   /* if(mintmean==0) mintmean=1; */
                   10221: 
                   10222: 
                   10223:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   10224:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   10225:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.2     ! brouard  10226:   /* i1=pow(2,cptcoveff); */
        !          10227:   /* if (cptcovn < 1){i1=1;} */
1.1       brouard  10228:   
                   10229:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
                   10230:   
                   10231:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   10232:   
                   10233: /*           if (h==(int)(YEARM*yearp)){ */
1.2     ! brouard  10234:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
        !          10235:     k=TKresult[nres];
        !          10236:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
        !          10237:     /*  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) *\/ */
        !          10238:     /* if(i1 != 1 && TKresult[nres]!= k) */
        !          10239:     /*   continue; */
        !          10240:     /* if(invalidvarcomb[k]){ */
        !          10241:     /*   printf("\nCombination (%d) projection ignored because no cases \n",k);  */
        !          10242:     /*   continue; */
        !          10243:     /* } */
1.1       brouard  10244:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.2     ! brouard  10245:     for(j=1;j<=cptcovs;j++){
        !          10246:       /* for(j=1;j<=cptcoveff;j++) { */
        !          10247:     /*   /\* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); *\/ */
        !          10248:     /*   fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
        !          10249:     /* } */
        !          10250:     /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
        !          10251:     /*   fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
        !          10252:     /* } */
        !          10253:       fprintf(ficresf," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.1       brouard  10254:     }
1.2     ! brouard  10255:  
1.1       brouard  10256:     fprintf(ficresf," yearproj age");
                   10257:     for(j=1; j<=nlstate+ndeath;j++){ 
                   10258:       for(i=1; i<=nlstate;i++)               
                   10259:        fprintf(ficresf," p%d%d",i,j);
                   10260:       fprintf(ficresf," wp.%d",j);
                   10261:     }
                   10262:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
                   10263:       fprintf(ficresf,"\n");
                   10264:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
                   10265:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   10266:       for (agec=fage; agec>=(bage); agec--){ 
                   10267:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   10268:        nhstepm = nhstepm/hstepm; 
                   10269:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10270:        oldm=oldms;savm=savms;
                   10271:        /* We compute pii at age agec over nhstepm);*/
                   10272:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
                   10273:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   10274:        for (h=0; h<=nhstepm; h++){
                   10275:          if (h*hstepm/YEARM*stepm ==yearp) {
                   10276:            break;
                   10277:          }
                   10278:        }
                   10279:        fprintf(ficresf,"\n");
1.2     ! brouard  10280:        /* for(j=1;j<=cptcoveff;j++)  */
        !          10281:        for(j=1;j<=cptcovs;j++) 
        !          10282:          fprintf(ficresf,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.1       brouard  10283:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
1.2     ! brouard  10284:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* TnsdVar[Tvaraff]  correct *\/ */
1.1       brouard  10285:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
                   10286:        
                   10287:        for(j=1; j<=nlstate+ndeath;j++) {
                   10288:          ppij=0.;
                   10289:          for(i=1; i<=nlstate;i++) {
                   10290:            if (mobilav>=1)
                   10291:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   10292:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   10293:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   10294:            }
                   10295:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   10296:          } /* end i */
                   10297:          fprintf(ficresf," %.3f", ppij);
                   10298:        }/* end j */
                   10299:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10300:       } /* end agec */
                   10301:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   10302:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
                   10303:     } /* end yearp */
                   10304:   } /* end  k */
                   10305:        
                   10306:   fclose(ficresf);
                   10307:   printf("End of Computing forecasting \n");
                   10308:   fprintf(ficlog,"End of Computing forecasting\n");
                   10309: 
                   10310: }
                   10311: 
                   10312: /************** Back Forecasting ******************/
                   10313:  /* 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){ */
                   10314:  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){
                   10315:   /* back1, year, month, day of starting backprojection
                   10316:      agemin, agemax range of age
                   10317:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   10318:      anback2 year of end of backprojection (same day and month as back1).
                   10319:      prevacurrent and prev are prevalences.
                   10320:   */
                   10321:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   10322:   double agec; /* generic age */
                   10323:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
                   10324:   double *popeffectif,*popcount;
                   10325:   double ***p3mat;
                   10326:   /* double ***mobaverage; */
                   10327:   char fileresfb[FILENAMELENGTH];
                   10328:  
                   10329:   agelim=AGEINF;
                   10330:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   10331:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   10332:      We still use firstpass and lastpass as another selection.
                   10333:   */
                   10334:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   10335:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   10336: 
                   10337:   /*Do we need to compute prevalence again?*/
                   10338: 
                   10339:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   10340:   
                   10341:   strcpy(fileresfb,"FB_");
                   10342:   strcat(fileresfb,fileresu);
                   10343:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   10344:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   10345:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   10346:   }
                   10347:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   10348:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   10349:   
                   10350:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   10351:   
                   10352:    
                   10353:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10354:   if (stepm<=12) stepsize=1;
                   10355:   if(estepm < stepm){
                   10356:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   10357:   }
                   10358:   else{
                   10359:     hstepm=estepm;   
                   10360:   }
                   10361:   if(estepm >= stepm){ /* Yes every two year */
                   10362:     stepsize=2;
                   10363:   }
                   10364:   
                   10365:   hstepm=hstepm/stepm;
                   10366:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   10367:   /*                              fractional in yp1 *\/ */
                   10368:   /* aintmean=yp; */
                   10369:   /* yp2=modf((yp1*12),&yp); */
                   10370:   /* mintmean=yp; */
                   10371:   /* yp1=modf((yp2*30.5),&yp); */
                   10372:   /* jintmean=yp; */
                   10373:   /* if(jintmean==0) jintmean=1; */
                   10374:   /* if(mintmean==0) jintmean=1; */
                   10375:   
1.2     ! brouard  10376:   /* i1=pow(2,cptcoveff); */
        !          10377:   /* if (cptcovn < 1){i1=1;} */
1.1       brouard  10378:   
                   10379:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   10380:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   10381:   
                   10382:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   10383:   
1.2     ! brouard  10384:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
        !          10385:     k=TKresult[nres];
        !          10386:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
        !          10387:   /* for(k=1; k<=i1;k++){ */
        !          10388:   /*   if(i1 != 1 && TKresult[nres]!= k) */
        !          10389:   /*     continue; */
        !          10390:   /*   if(invalidvarcomb[k]){ */
        !          10391:   /*     printf("\nCombination (%d) projection ignored because no cases \n",k);  */
        !          10392:   /*     continue; */
        !          10393:   /*   } */
1.1       brouard  10394:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.2     ! brouard  10395:     for(j=1;j<=cptcovs;j++){
        !          10396:     /* for(j=1;j<=cptcoveff;j++) { */
        !          10397:     /*   fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
        !          10398:     /* } */
        !          10399:       fprintf(ficresfb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.1       brouard  10400:     }
1.2     ! brouard  10401:    /*  fprintf(ficrespij,"******\n"); */
        !          10402:    /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
        !          10403:    /*    fprintf(ficresfb," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
        !          10404:    /*  } */
1.1       brouard  10405:     fprintf(ficresfb," yearbproj age");
                   10406:     for(j=1; j<=nlstate+ndeath;j++){
                   10407:       for(i=1; i<=nlstate;i++)
                   10408:        fprintf(ficresfb," b%d%d",i,j);
                   10409:       fprintf(ficresfb," b.%d",j);
                   10410:     }
                   10411:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
                   10412:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   10413:       fprintf(ficresfb,"\n");
                   10414:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
                   10415:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
                   10416:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   10417:       for (agec=bage; agec<=fage; agec++){  /* testing */
                   10418:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
                   10419:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
                   10420:        nhstepm = nhstepm/hstepm;
                   10421:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10422:        oldm=oldms;savm=savms;
                   10423:        /* computes hbxij at age agec over 1 to nhstepm */
                   10424:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
                   10425:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
                   10426:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   10427:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   10428:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
                   10429:        for (h=0; h<=nhstepm; h++){
                   10430:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   10431:            break;
                   10432:          }
                   10433:        }
                   10434:        fprintf(ficresfb,"\n");
1.2     ! brouard  10435:        /* for(j=1;j<=cptcoveff;j++) */
        !          10436:        for(j=1;j<=cptcovs;j++)
        !          10437:          fprintf(ficresfb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
        !          10438:          /* fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.1       brouard  10439:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
                   10440:        for(i=1; i<=nlstate+ndeath;i++) {
                   10441:          ppij=0.;ppi=0.;
                   10442:          for(j=1; j<=nlstate;j++) {
                   10443:            /* if (mobilav==1) */
                   10444:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   10445:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   10446:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   10447:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
                   10448:              /* else { */
                   10449:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   10450:              /* } */
                   10451:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   10452:          } /* end j */
                   10453:          if(ppi <0.99){
                   10454:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   10455:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   10456:          }
                   10457:          fprintf(ficresfb," %.3f", ppij);
                   10458:        }/* end j */
                   10459:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10460:       } /* end agec */
                   10461:     } /* end yearp */
                   10462:   } /* end k */
                   10463:   
                   10464:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10465:   
                   10466:   fclose(ficresfb);
                   10467:   printf("End of Computing Back forecasting \n");
                   10468:   fprintf(ficlog,"End of Computing Back forecasting\n");
                   10469:        
                   10470: }
                   10471: 
                   10472: /* Variance of prevalence limit: varprlim */
                   10473:  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){
                   10474:     /*------- Variance of forward period (stable) prevalence------*/   
                   10475:  
                   10476:    char fileresvpl[FILENAMELENGTH];  
                   10477:    FILE *ficresvpl;
                   10478:    double **oldm, **savm;
                   10479:    double **varpl; /* Variances of prevalence limits by age */   
                   10480:    int i1, k, nres, j ;
                   10481:    
                   10482:     strcpy(fileresvpl,"VPL_");
                   10483:     strcat(fileresvpl,fileresu);
                   10484:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   10485:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   10486:       exit(0);
                   10487:     }
                   10488:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   10489:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
                   10490:     
                   10491:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   10492:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   10493:     
                   10494:     i1=pow(2,cptcoveff);
                   10495:     if (cptcovn < 1){i1=1;}
                   10496: 
                   10497:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10498:        k=TKresult[nres];
                   10499:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   10500:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
                   10501:       if(i1 != 1 && TKresult[nres]!= k)
                   10502:        continue;
                   10503:       fprintf(ficresvpl,"\n#****** ");
                   10504:       printf("\n#****** ");
                   10505:       fprintf(ficlog,"\n#****** ");
                   10506:       for(j=1;j<=cptcovs;j++) {
                   10507:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10508:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10509:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10510:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10511:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10512:       }
                   10513:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10514:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10515:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10516:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10517:       /* }      */
                   10518:       fprintf(ficresvpl,"******\n");
                   10519:       printf("******\n");
                   10520:       fprintf(ficlog,"******\n");
                   10521:       
                   10522:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10523:       oldm=oldms;savm=savms;
                   10524:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   10525:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   10526:       /*}*/
                   10527:     }
                   10528:     
                   10529:     fclose(ficresvpl);
                   10530:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   10531:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
                   10532: 
                   10533:  }
                   10534: /* Variance of back prevalence: varbprlim */
                   10535:  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){
                   10536:       /*------- Variance of back (stable) prevalence------*/
                   10537: 
                   10538:    char fileresvbl[FILENAMELENGTH];  
                   10539:    FILE  *ficresvbl;
                   10540: 
                   10541:    double **oldm, **savm;
                   10542:    double **varbpl; /* Variances of back prevalence limits by age */   
                   10543:    int i1, k, nres, j ;
                   10544: 
                   10545:    strcpy(fileresvbl,"VBL_");
                   10546:    strcat(fileresvbl,fileresu);
                   10547:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   10548:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   10549:      exit(0);
                   10550:    }
                   10551:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   10552:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   10553:    
                   10554:    
                   10555:    i1=pow(2,cptcoveff);
                   10556:    if (cptcovn < 1){i1=1;}
                   10557:    
                   10558:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10559:      k=TKresult[nres];
                   10560:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   10561:     /* for(k=1; k<=i1;k++){ */
                   10562:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   10563:     /*          continue; */
                   10564:        fprintf(ficresvbl,"\n#****** ");
                   10565:        printf("\n#****** ");
                   10566:        fprintf(ficlog,"\n#****** ");
                   10567:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
                   10568:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10569:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10570:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10571:        /* for(j=1;j<=cptcoveff;j++) { */
                   10572:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10573:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10574:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10575:        /* } */
                   10576:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10577:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10578:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10579:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10580:        }
                   10581:        fprintf(ficresvbl,"******\n");
                   10582:        printf("******\n");
                   10583:        fprintf(ficlog,"******\n");
                   10584:        
                   10585:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10586:        oldm=oldms;savm=savms;
                   10587:        
                   10588:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   10589:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   10590:        /*}*/
                   10591:      }
                   10592:    
                   10593:    fclose(ficresvbl);
                   10594:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   10595:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   10596: 
                   10597:  } /* End of varbprlim */
                   10598: 
                   10599: /************** Forecasting *****not tested NB*************/
                   10600: /* 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){ */
                   10601:   
                   10602: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   10603: /*   int *popage; */
                   10604: /*   double calagedatem, agelim, kk1, kk2; */
                   10605: /*   double *popeffectif,*popcount; */
                   10606: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   10607: /*   /\* double ***mobaverage; *\/ */
                   10608: /*   char filerespop[FILENAMELENGTH]; */
                   10609: 
                   10610: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10611: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10612: /*   agelim=AGESUP; */
                   10613: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
                   10614:   
                   10615: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   10616:   
                   10617:   
                   10618: /*   strcpy(filerespop,"POP_");  */
                   10619: /*   strcat(filerespop,fileresu); */
                   10620: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   10621: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   10622: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   10623: /*   } */
                   10624: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   10625: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
                   10626: 
                   10627: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
                   10628: 
                   10629: /*   /\* if (mobilav!=0) { *\/ */
                   10630: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   10631: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   10632: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10633: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10634: /*   /\*   } *\/ */
                   10635: /*   /\* } *\/ */
                   10636: 
                   10637: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   10638: /*   if (stepm<=12) stepsize=1; */
                   10639:   
                   10640: /*   agelim=AGESUP; */
                   10641:   
                   10642: /*   hstepm=1; */
                   10643: /*   hstepm=hstepm/stepm;  */
                   10644:        
                   10645: /*   if (popforecast==1) { */
                   10646: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   10647: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   10648: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   10649: /*     }  */
                   10650: /*     popage=ivector(0,AGESUP); */
                   10651: /*     popeffectif=vector(0,AGESUP); */
                   10652: /*     popcount=vector(0,AGESUP); */
                   10653:     
                   10654: /*     i=1;    */
                   10655: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
                   10656:     
                   10657: /*     imx=i; */
                   10658: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   10659: /*   } */
                   10660:   
                   10661: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   10662: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   10663: /*       k=k+1; */
                   10664: /*       fprintf(ficrespop,"\n#******"); */
                   10665: /*       for(j=1;j<=cptcoveff;j++) { */
                   10666: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   10667: /*       } */
                   10668: /*       fprintf(ficrespop,"******\n"); */
                   10669: /*       fprintf(ficrespop,"# Age"); */
                   10670: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   10671: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
                   10672:       
                   10673: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   10674: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   10675:        
                   10676: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10677: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10678: /*       nhstepm = nhstepm/hstepm;  */
                   10679:          
                   10680: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10681: /*       oldm=oldms;savm=savms; */
                   10682: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   10683:          
                   10684: /*       for (h=0; h<=nhstepm; h++){ */
                   10685: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10686: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10687: /*         }  */
                   10688: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10689: /*           kk1=0.;kk2=0; */
                   10690: /*           for(i=1; i<=nlstate;i++) {               */
                   10691: /*             if (mobilav==1)  */
                   10692: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   10693: /*             else { */
                   10694: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   10695: /*             } */
                   10696: /*           } */
                   10697: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   10698: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   10699: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   10700: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   10701: /*           } */
                   10702: /*         } */
                   10703: /*         for(i=1; i<=nlstate;i++){ */
                   10704: /*           kk1=0.; */
                   10705: /*           for(j=1; j<=nlstate;j++){ */
                   10706: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   10707: /*           } */
                   10708: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   10709: /*         } */
                   10710:            
                   10711: /*         if (h==(int)(calagedatem+12*cpt)) */
                   10712: /*           for(j=1; j<=nlstate;j++)  */
                   10713: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   10714: /*       } */
                   10715: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10716: /*     } */
                   10717: /*       } */
                   10718:       
                   10719: /*       /\******\/ */
                   10720:       
                   10721: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   10722: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   10723: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10724: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10725: /*       nhstepm = nhstepm/hstepm;  */
                   10726:          
                   10727: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10728: /*       oldm=oldms;savm=savms; */
                   10729: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   10730: /*       for (h=0; h<=nhstepm; h++){ */
                   10731: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10732: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10733: /*         }  */
                   10734: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10735: /*           kk1=0.;kk2=0; */
                   10736: /*           for(i=1; i<=nlstate;i++) {               */
                   10737: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   10738: /*           } */
                   10739: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   10740: /*         } */
                   10741: /*       } */
                   10742: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10743: /*     } */
                   10744: /*       } */
                   10745: /*     }  */
                   10746: /*   } */
                   10747:   
                   10748: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   10749:   
                   10750: /*   if (popforecast==1) { */
                   10751: /*     free_ivector(popage,0,AGESUP); */
                   10752: /*     free_vector(popeffectif,0,AGESUP); */
                   10753: /*     free_vector(popcount,0,AGESUP); */
                   10754: /*   } */
                   10755: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10756: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10757: /*   fclose(ficrespop); */
                   10758: /* } /\* End of popforecast *\/ */
                   10759:  
                   10760: int fileappend(FILE *fichier, char *optionfich)
                   10761: {
                   10762:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   10763:     printf("Problem with file: %s\n", optionfich);
                   10764:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   10765:     return (0);
                   10766:   }
                   10767:   fflush(fichier);
                   10768:   return (1);
                   10769: }
                   10770: 
                   10771: 
                   10772: /**************** function prwizard **********************/
                   10773: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   10774: {
                   10775: 
                   10776:   /* Wizard to print covariance matrix template */
                   10777: 
                   10778:   char ca[32], cb[32];
                   10779:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
                   10780:   int numlinepar;
                   10781: 
                   10782:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10783:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10784:   for(i=1; i <=nlstate; i++){
                   10785:     jj=0;
                   10786:     for(j=1; j <=nlstate+ndeath; j++){
                   10787:       if(j==i) continue;
                   10788:       jj++;
                   10789:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   10790:       printf("%1d%1d",i,j);
                   10791:       fprintf(ficparo,"%1d%1d",i,j);
                   10792:       for(k=1; k<=ncovmodel;k++){
                   10793:        /*        printf(" %lf",param[i][j][k]); */
                   10794:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   10795:        printf(" 0.");
                   10796:        fprintf(ficparo," 0.");
                   10797:       }
                   10798:       printf("\n");
                   10799:       fprintf(ficparo,"\n");
                   10800:     }
                   10801:   }
                   10802:   printf("# Scales (for hessian or gradient estimation)\n");
                   10803:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   10804:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   10805:   for(i=1; i <=nlstate; i++){
                   10806:     jj=0;
                   10807:     for(j=1; j <=nlstate+ndeath; j++){
                   10808:       if(j==i) continue;
                   10809:       jj++;
                   10810:       fprintf(ficparo,"%1d%1d",i,j);
                   10811:       printf("%1d%1d",i,j);
                   10812:       fflush(stdout);
                   10813:       for(k=1; k<=ncovmodel;k++){
                   10814:        /*      printf(" %le",delti3[i][j][k]); */
                   10815:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   10816:        printf(" 0.");
                   10817:        fprintf(ficparo," 0.");
                   10818:       }
                   10819:       numlinepar++;
                   10820:       printf("\n");
                   10821:       fprintf(ficparo,"\n");
                   10822:     }
                   10823:   }
                   10824:   printf("# Covariance matrix\n");
                   10825: /* # 121 Var(a12)\n\ */
                   10826: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10827: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10828: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10829: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10830: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10831: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10832: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10833:   fflush(stdout);
                   10834:   fprintf(ficparo,"# Covariance matrix\n");
                   10835:   /* # 121 Var(a12)\n\ */
                   10836:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10837:   /* #   ...\n\ */
                   10838:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   10839:   
                   10840:   for(itimes=1;itimes<=2;itimes++){
                   10841:     jj=0;
                   10842:     for(i=1; i <=nlstate; i++){
                   10843:       for(j=1; j <=nlstate+ndeath; j++){
                   10844:        if(j==i) continue;
                   10845:        for(k=1; k<=ncovmodel;k++){
                   10846:          jj++;
                   10847:          ca[0]= k+'a'-1;ca[1]='\0';
                   10848:          if(itimes==1){
                   10849:            printf("#%1d%1d%d",i,j,k);
                   10850:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   10851:          }else{
                   10852:            printf("%1d%1d%d",i,j,k);
                   10853:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   10854:            /*  printf(" %.5le",matcov[i][j]); */
                   10855:          }
                   10856:          ll=0;
                   10857:          for(li=1;li <=nlstate; li++){
                   10858:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   10859:              if(lj==li) continue;
                   10860:              for(lk=1;lk<=ncovmodel;lk++){
                   10861:                ll++;
                   10862:                if(ll<=jj){
                   10863:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   10864:                  if(ll<jj){
                   10865:                    if(itimes==1){
                   10866:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10867:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10868:                    }else{
                   10869:                      printf(" 0.");
                   10870:                      fprintf(ficparo," 0.");
                   10871:                    }
                   10872:                  }else{
                   10873:                    if(itimes==1){
                   10874:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   10875:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   10876:                    }else{
                   10877:                      printf(" 0.");
                   10878:                      fprintf(ficparo," 0.");
                   10879:                    }
                   10880:                  }
                   10881:                }
                   10882:              } /* end lk */
                   10883:            } /* end lj */
                   10884:          } /* end li */
                   10885:          printf("\n");
                   10886:          fprintf(ficparo,"\n");
                   10887:          numlinepar++;
                   10888:        } /* end k*/
                   10889:       } /*end j */
                   10890:     } /* end i */
                   10891:   } /* end itimes */
                   10892: 
                   10893: } /* end of prwizard */
                   10894: /******************* Gompertz Likelihood ******************************/
                   10895: double gompertz(double x[])
                   10896: { 
                   10897:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
                   10898:   int i,n=0; /* n is the size of the sample */
                   10899: 
                   10900:   for (i=1;i<=imx ; i++) {
                   10901:     sump=sump+weight[i];
                   10902:     /*    sump=sump+1;*/
                   10903:     num=num+1;
                   10904:   }
                   10905:   L=0.0;
                   10906:   /* agegomp=AGEGOMP; */
                   10907:   /* for (i=0; i<=imx; i++) 
                   10908:      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]);*/
                   10909: 
                   10910:   for (i=1;i<=imx ; i++) {
                   10911:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   10912:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   10913:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   10914:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   10915:      * +
                   10916:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   10917:      */
                   10918:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   10919:        if (cens[i] == 1){
                   10920:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   10921:        } else if (cens[i] == 0){
                   10922:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   10923:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   10924:       } else
                   10925:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
                   10926:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   10927:        L=L+A*weight[i];
                   10928:        /*      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]);*/
                   10929:      }
                   10930:   }
                   10931: 
                   10932:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   10933:  
                   10934:   return -2*L*num/sump;
                   10935: }
                   10936: 
                   10937: #ifdef GSL
                   10938: /******************* Gompertz_f Likelihood ******************************/
                   10939: double gompertz_f(const gsl_vector *v, void *params)
                   10940: { 
                   10941:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
                   10942:   double *x= (double *) v->data;
                   10943:   int i,n=0; /* n is the size of the sample */
                   10944: 
                   10945:   for (i=0;i<=imx-1 ; i++) {
                   10946:     sump=sump+weight[i];
                   10947:     /*    sump=sump+1;*/
                   10948:     num=num+1;
                   10949:   }
                   10950:  
                   10951:  
                   10952:   /* for (i=0; i<=imx; i++) 
                   10953:      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]);*/
                   10954:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   10955:   for (i=1;i<=imx ; i++)
                   10956:     {
                   10957:       if (cens[i] == 1 && wav[i]>1)
                   10958:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   10959:       
                   10960:       if (cens[i] == 0 && wav[i]>1)
                   10961:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   10962:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   10963:       
                   10964:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   10965:       if (wav[i] > 1 ) { /* ??? */
                   10966:        LL=LL+A*weight[i];
                   10967:        /*      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]);*/
                   10968:       }
                   10969:     }
                   10970: 
                   10971:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   10972:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   10973:  
                   10974:   return -2*LL*num/sump;
                   10975: }
                   10976: #endif
                   10977: 
                   10978: /******************* Printing html file ***********/
                   10979: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
                   10980:                  int lastpass, int stepm, int weightopt, char model[],\
                   10981:                  int imx,  double p[],double **matcov,double agemortsup){
                   10982:   int i,k;
                   10983: 
                   10984:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   10985:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   10986:   for (i=1;i<=2;i++) 
                   10987:     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]));
                   10988:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
                   10989:   fprintf(fichtm,"</ul>");
                   10990: 
                   10991: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   10992: 
                   10993:  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>");
                   10994: 
                   10995:  for (k=agegomp;k<(agemortsup-2);k++) 
                   10996:    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]);
                   10997: 
                   10998:  
                   10999:   fflush(fichtm);
                   11000: }
                   11001: 
                   11002: /******************* Gnuplot file **************/
                   11003: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   11004: 
                   11005:   char dirfileres[132],optfileres[132];
                   11006: 
                   11007:   int ng;
                   11008: 
                   11009: 
                   11010:   /*#ifdef windows */
                   11011:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   11012:     /*#endif */
                   11013: 
                   11014: 
                   11015:   strcpy(dirfileres,optionfilefiname);
                   11016:   strcpy(optfileres,"vpl");
                   11017:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
                   11018:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
                   11019:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
                   11020:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
                   11021:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   11022: 
                   11023: } 
                   11024: 
                   11025: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   11026: {
                   11027: 
                   11028:   /*-------- data file ----------*/
                   11029:   FILE *fic;
                   11030:   char dummy[]="                         ";
                   11031:   int i=0, j=0, n=0, iv=0, v;
                   11032:   int lstra;
                   11033:   int linei, month, year,iout;
                   11034:   int noffset=0; /* This is the offset if BOM data file */
                   11035:   char line[MAXLINE], linetmp[MAXLINE];
                   11036:   char stra[MAXLINE], strb[MAXLINE];
                   11037:   char *stratrunc;
                   11038: 
                   11039:   /* DummyV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
                   11040:   /* FixedV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
                   11041:   
                   11042:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   11043:   
                   11044:   if((fic=fopen(datafile,"r"))==NULL)    {
                   11045:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   11046:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   11047:   }
                   11048: 
                   11049:     /* Is it a BOM UTF-8 Windows file? */
                   11050:   /* First data line */
                   11051:   linei=0;
                   11052:   while(fgets(line, MAXLINE, fic)) {
                   11053:     noffset=0;
                   11054:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   11055:     {
                   11056:       noffset=noffset+3;
                   11057:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   11058:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   11059:       fflush(ficlog); return 1;
                   11060:     }
                   11061:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   11062:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   11063:     {
                   11064:       noffset=noffset+2;
                   11065:       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);
                   11066:       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);
                   11067:       fflush(ficlog); return 1;
                   11068:     }
                   11069:     else if( line[0] == 0 && line[1] == 0)
                   11070:     {
                   11071:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   11072:        noffset=noffset+4;
                   11073:        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);
                   11074:        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);
                   11075:        fflush(ficlog); return 1;
                   11076:       }
                   11077:     } else{
                   11078:       ;/*printf(" Not a BOM file\n");*/
                   11079:     }
                   11080:         /* If line starts with a # it is a comment */
                   11081:     if (line[noffset] == '#') {
                   11082:       linei=linei+1;
                   11083:       break;
                   11084:     }else{
                   11085:       break;
                   11086:     }
                   11087:   }
                   11088:   fclose(fic);
                   11089:   if((fic=fopen(datafile,"r"))==NULL)    {
                   11090:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   11091:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   11092:   }
                   11093:   /* Not a Bom file */
                   11094:   
                   11095:   i=1;
                   11096:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   11097:     linei=linei+1;
                   11098:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   11099:       if(line[j] == '\t')
                   11100:        line[j] = ' ';
                   11101:     }
                   11102:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   11103:       ;
                   11104:     };
                   11105:     line[j+1]=0;  /* Trims blanks at end of line */
                   11106:     if(line[0]=='#'){
                   11107:       fprintf(ficlog,"Comment line\n%s\n",line);
                   11108:       printf("Comment line\n%s\n",line);
                   11109:       continue;
                   11110:     }
                   11111:     trimbb(linetmp,line); /* Trims multiple blanks in line */
                   11112:     strcpy(line, linetmp);
                   11113:     
                   11114:     /* Loops on waves */
                   11115:     for (j=maxwav;j>=1;j--){
                   11116:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
                   11117:        cutv(stra, strb, line, ' '); 
                   11118:        if(strb[0]=='.') { /* Missing value */
                   11119:          lval=-1;
                   11120:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   11121:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
                   11122:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   11123:            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);
                   11124:            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);
                   11125:            return 1;
                   11126:          }
                   11127:        }else{
                   11128:          errno=0;
                   11129:          /* what_kind_of_number(strb); */
                   11130:          dval=strtod(strb,&endptr); 
                   11131:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   11132:          /* if(strb != endptr && *endptr == '\0') */
                   11133:          /*    dval=dlval; */
                   11134:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   11135:          if( strb[0]=='\0' || (*endptr != '\0')){
                   11136:            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);
                   11137:            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);
                   11138:            return 1;
                   11139:          }
                   11140:          cotqvar[j][iv][i]=dval; 
                   11141:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
                   11142:        }
                   11143:        strcpy(line,stra);
                   11144:       }/* end loop ntqv */
                   11145:       
                   11146:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
                   11147:        cutv(stra, strb, line, ' '); 
                   11148:        if(strb[0]=='.') { /* Missing value */
                   11149:          lval=-1;
                   11150:        }else{
                   11151:          errno=0;
                   11152:          lval=strtol(strb,&endptr,10); 
                   11153:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   11154:          if( strb[0]=='\0' || (*endptr != '\0')){
                   11155:            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);
                   11156:            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);
                   11157:            return 1;
                   11158:          }
                   11159:        }
                   11160:        if(lval <-1 || lval >1){
                   11161:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
                   11162:  Should be a value of %d(nth) covariate of wave %d (0 should be the value for the reference and 1\n \
                   11163:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   11164:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11165:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11166:         V1=1 V2=0 for (2) \n                                           \
                   11167:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   11168:  output of IMaCh is often meaningless.\n                               \
                   11169:  Exiting.\n",lval,linei, i,line,iv,j);
                   11170:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
                   11171:  Should be a value of %d(nth) covariate of wave %d (0 should be the value for the reference and 1\n \
                   11172:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   11173:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11174:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11175:         V1=1 V2=0 for (2) \n                                           \
                   11176:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   11177:  output of IMaCh is often meaningless.\n                               \
                   11178:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
                   11179:          return 1;
                   11180:        }
                   11181:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
                   11182:        strcpy(line,stra);
                   11183:       }/* end loop ntv */
                   11184:       
                   11185:       /* Statuses  at wave */
                   11186:       cutv(stra, strb, line, ' '); 
                   11187:       if(strb[0]=='.') { /* Missing value */
                   11188:        lval=-1;
                   11189:       }else{
                   11190:        errno=0;
                   11191:        lval=strtol(strb,&endptr,10); 
                   11192:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   11193:        if( strb[0]=='\0' || (*endptr != '\0' )){
                   11194:          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);
                   11195:          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);
                   11196:          return 1;
                   11197:        }else if( lval==0 || lval > nlstate+ndeath){
                   11198:          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);
                   11199:          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);
                   11200:          return 1;
                   11201:        }
                   11202:       }
                   11203:       
                   11204:       s[j][i]=lval;
                   11205:       
                   11206:       /* Date of Interview */
                   11207:       strcpy(line,stra);
                   11208:       cutv(stra, strb,line,' ');
                   11209:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
                   11210:       }
                   11211:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
                   11212:        month=99;
                   11213:        year=9999;
                   11214:       }else{
                   11215:        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);
                   11216:        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);
                   11217:        return 1;
                   11218:       }
                   11219:       anint[j][i]= (double) year; 
                   11220:       mint[j][i]= (double)month;
                   11221:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   11222:       /*       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]); */
                   11223:       /*       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]); */
                   11224:       /* } */
                   11225:       strcpy(line,stra);
                   11226:     } /* End loop on waves */
                   11227:     
                   11228:     /* Date of death */
                   11229:     cutv(stra, strb,line,' '); 
                   11230:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
                   11231:     }
                   11232:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
                   11233:       month=99;
                   11234:       year=9999;
                   11235:     }else{
                   11236:       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);
                   11237:       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);
                   11238:       return 1;
                   11239:     }
                   11240:     andc[i]=(double) year; 
                   11241:     moisdc[i]=(double) month; 
                   11242:     strcpy(line,stra);
                   11243:     
                   11244:     /* Date of birth */
                   11245:     cutv(stra, strb,line,' '); 
                   11246:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
                   11247:     }
                   11248:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
                   11249:       month=99;
                   11250:       year=9999;
                   11251:     }else{
                   11252:       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);
                   11253:       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);
                   11254:       return 1;
                   11255:     }
                   11256:     if (year==9999) {
                   11257:       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);
                   11258:       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);
                   11259:       return 1;
                   11260:       
                   11261:     }
                   11262:     annais[i]=(double)(year);
                   11263:     moisnais[i]=(double)(month);
                   11264:     for (j=1;j<=maxwav;j++){
                   11265:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   11266:        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]);
                   11267:        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]);
                   11268:       }
                   11269:     }
                   11270: 
                   11271:     strcpy(line,stra);
                   11272:     
                   11273:     /* Sample weight */
                   11274:     cutv(stra, strb,line,' '); 
                   11275:     errno=0;
                   11276:     dval=strtod(strb,&endptr); 
                   11277:     if( strb[0]=='\0' || (*endptr != '\0')){
                   11278:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   11279:       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);
                   11280:       fflush(ficlog);
                   11281:       return 1;
                   11282:     }
                   11283:     weight[i]=dval; 
                   11284:     strcpy(line,stra);
                   11285:     
                   11286:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   11287:       cutv(stra, strb, line, ' '); 
                   11288:       if(strb[0]=='.') { /* Missing value */
                   11289:        lval=-1;
                   11290:        coqvar[iv][i]=NAN; 
                   11291:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
                   11292:       }else{
                   11293:        errno=0;
                   11294:        /* what_kind_of_number(strb); */
                   11295:        dval=strtod(strb,&endptr);
                   11296:        /* if(strb != endptr && *endptr == '\0') */
                   11297:        /*   dval=dlval; */
                   11298:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   11299:        if( strb[0]=='\0' || (*endptr != '\0')){
                   11300:          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);
                   11301:          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);
                   11302:          return 1;
                   11303:        }
                   11304:        coqvar[iv][i]=dval; 
                   11305:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
                   11306:       }
                   11307:       strcpy(line,stra);
                   11308:     }/* end loop nqv */
                   11309:     
                   11310:     /* Covariate values */
                   11311:     for (j=ncovcol;j>=1;j--){
                   11312:       cutv(stra, strb,line,' '); 
                   11313:       if(strb[0]=='.') { /* Missing covariate value */
                   11314:        lval=-1;
                   11315:       }else{
                   11316:        errno=0;
                   11317:        lval=strtol(strb,&endptr,10); 
                   11318:        if( strb[0]=='\0' || (*endptr != '\0')){
                   11319:          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);
                   11320:          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);
                   11321:          return 1;
                   11322:        }
                   11323:       }
                   11324:       if(lval <-1 || lval >1){
                   11325:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
                   11326:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   11327:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   11328:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11329:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11330:         V1=1 V2=0 for (2) \n                                           \
                   11331:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   11332:  output of IMaCh is often meaningless.\n                               \
                   11333:  Exiting.\n",lval,linei, i,line,j);
                   11334:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
                   11335:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   11336:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   11337:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11338:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11339:         V1=1 V2=0 for (2) \n                                           \
                   11340:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   11341:  output of IMaCh is often meaningless.\n                               \
                   11342:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   11343:        return 1;
                   11344:       }
                   11345:       covar[j][i]=(double)(lval);
                   11346:       strcpy(line,stra);
                   11347:     }  
                   11348:     lstra=strlen(stra);
                   11349:     
                   11350:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   11351:       stratrunc = &(stra[lstra-9]);
                   11352:       num[i]=atol(stratrunc);
                   11353:     }
                   11354:     else
                   11355:       num[i]=atol(stra);
                   11356:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   11357:       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;}*/
                   11358:     
                   11359:     i=i+1;
                   11360:   } /* End loop reading  data */
                   11361:   
                   11362:   *imax=i-1; /* Number of individuals */
                   11363:   fclose(fic);
                   11364:   
                   11365:   return (0);
                   11366:   /* endread: */
                   11367:   printf("Exiting readdata: ");
                   11368:   fclose(fic);
                   11369:   return (1);
                   11370: }
                   11371: 
                   11372: void removefirstspace(char **stri){/*, char stro[]) {*/
                   11373:   char *p1 = *stri, *p2 = *stri;
                   11374:   while (*p2 == ' ')
                   11375:     p2++; 
                   11376:   /* while ((*p1++ = *p2++) !=0) */
                   11377:   /*   ; */
                   11378:   /* do */
                   11379:   /*   while (*p2 == ' ') */
                   11380:   /*     p2++; */
                   11381:   /* while (*p1++ == *p2++); */
                   11382:   *stri=p2; 
                   11383: }
                   11384: 
                   11385: int decoderesult( char resultline[], int nres)
                   11386: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   11387: {
                   11388:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
                   11389:   char resultsav[MAXLINE];
                   11390:   /* int resultmodel[MAXLINE]; */
                   11391:   /* int modelresult[MAXLINE]; */
                   11392:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   11393: 
                   11394:   removefirstspace(&resultline);
                   11395:   printf("decoderesult:%s\n",resultline);
                   11396: 
                   11397:   strcpy(resultsav,resultline);
                   11398:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
                   11399:   if (strlen(resultsav) >1){
                   11400:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
                   11401:   }
1.2     ! brouard  11402:   if(j == 0 && cptcovs== 0){ /* Resultline but no =  and no covariate in the model */
1.1       brouard  11403:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   11404:     return (0);
                   11405:   }
                   11406:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.2     ! brouard  11407:     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);
        !          11408:     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);
        !          11409:     if(j==0)
        !          11410:       return 1;
1.1       brouard  11411:   }
                   11412:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
                   11413:     if(nbocc(resultsav,'=') >1){
                   11414:       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" */
                   11415:       /* If resultsav= "V4= 1 V5=25.1 V3=0" with a blank then strb="V4=" and stra="1 V5=25.1 V3=0" */
                   11416:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
                   11417:       /* If a blank, then strc="V4=" and strd='\0' */
                   11418:       if(strc[0]=='\0'){
                   11419:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   11420:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   11421:        return 1;
                   11422:       }
                   11423:     }else
                   11424:       cutl(strc,strd,resultsav,'=');
                   11425:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
                   11426:     
                   11427:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
                   11428:     Tvarsel[k]=atoi(strc);  /* 4 */ /* Tvarsel is the id of the kth covariate in the result line Tvarsel[1] in "V4=1.." is 4.*/
                   11429:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   11430:     /* cptcovsel++;     */
                   11431:     if (nbocc(stra,'=') >0)
                   11432:       strcpy(resultsav,stra); /* and analyzes it */
                   11433:   }
                   11434:   /* Checking for missing or useless values in comparison of current model needs */
                   11435:   /* Feeds resultmodel[nres][k1]=k2 for k1th product covariate with age in the model equation fed by the index k2 of the resutline*/
                   11436:   for(k1=1; k1<= cptcovt ;k1++){ /* Loop on MODEL LINE V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11437:     if(Typevar[k1]==0){ /* Single covariate in model */
                   11438:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
                   11439:       match=0;
                   11440:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11441:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11442:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
                   11443:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11444:          break;
                   11445:        }
                   11446:       }
                   11447:       if(match == 0){
                   11448:        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]);
                   11449:        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);
                   11450:        return 1;
                   11451:       }
                   11452:     }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*/
                   11453:       /* We feed resultmodel[k1]=k2; */
                   11454:       match=0;
                   11455:       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 */
                   11456:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11457:          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 */
                   11458:          resultmodel[nres][k1]=k2; /* Added here */
                   11459:          /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
                   11460:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11461:          break;
                   11462:        }
                   11463:       }
                   11464:       if(match == 0){
                   11465:        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]);
                   11466:        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]);
                   11467:       return 1;
                   11468:       }
                   11469:     }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*/
                   11470:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   11471:       match=0;
                   11472:       /* 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]); */
                   11473:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11474:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11475:          /* modelresult[k2]=k1; */
                   11476:          /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
                   11477:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11478:        }
                   11479:       }
                   11480:       if(match == 0){
                   11481:        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);
                   11482:        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);
                   11483:        return 1;
                   11484:       }
                   11485:       match=0;
                   11486:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11487:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11488:          /* modelresult[k2]=k1;*/
                   11489:          /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
                   11490:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11491:          break;
                   11492:        }
                   11493:       }
                   11494:       if(match == 0){
                   11495:        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);
                   11496:        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);
                   11497:        return 1;
                   11498:       }
                   11499:     }/* End of testing */
                   11500:   }/* End loop cptcovt */
                   11501:   /* Checking for missing or useless values in comparison of current model needs */
                   11502:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
                   11503:   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)
                   11504:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11505:     match=0;
                   11506:     for(k1=1; k1<= cptcovt ;k1++){ /* loop on model: model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11507:       if(Typevar[k1]==0){ /* Single only */
                   11508:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4  What if a product?  */
                   11509:          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 */
                   11510:          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 */
                   11511:          ++match;
                   11512:        }
                   11513:       }
                   11514:     }
                   11515:     if(match == 0){
                   11516:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   11517:       fprintf(ficlog,"Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   11518:       return 1;
                   11519:     }else if(match > 1){
                   11520:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   11521:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   11522:       return 1;
                   11523:     }
                   11524:   }
                   11525:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
                   11526:   /* We need to deduce which combination number is chosen and save quantitative values */
                   11527:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11528:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   11529:   /* 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*/
                   11530:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11531:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   11532:   /*    1 0 0 0 */
                   11533:   /*    2 1 0 0 */
                   11534:   /*    3 0 1 0 */ 
                   11535:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
                   11536:   /*    5 0 0 1 */
                   11537:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
                   11538:   /*    7 0 1 1 */
                   11539:   /*    8 1 1 1 */
                   11540:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   11541:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   11542:   /* V5*age V5 known which value for nres?  */
                   11543:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
                   11544:   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.
                   11545:                                                   * loop on position k1 in the MODEL LINE */
                   11546:     /* k counting number of combination of single dummies in the equation model */
                   11547:     /* k4 counting single dummies in the equation model */
                   11548:     /* k4q counting single quantitatives in the equation model */
                   11549:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Dummy and Single, fixed or timevarying, k1 is sorting according to MODEL, but k3 to resultline */
                   11550:        /* 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) */
                   11551:       /* modelresult[k3]=k1: k3th position in the result line corresponds to the k1 position in the model line (doesn't work with products)*/
                   11552:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
                   11553:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   11554:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   11555:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   11556:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   11557:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
                   11558:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
                   11559:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
                   11560:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
                   11561:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   11562:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   11563:       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)*/
                   11564:       k+=Tvalsel[k3]*pow(2,k4);  /* nres=1 k1=2 Tvalsel[1]=1 (V4=1); k1=3 k3=2 Tvalsel[2]=0 (V3=0) */
                   11565:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
                   11566:       /* Tinvresult[nres][4]=1 */
                   11567:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   11568:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   11569:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11570:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   11571:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
                   11572:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
                   11573:       /* 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); */
                   11574:       k4++;;
                   11575:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
                   11576:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
                   11577:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
                   11578:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
                   11579:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   11580:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   11581:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
                   11582:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   11583:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11584:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   11585:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   11586:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   11587:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   11588:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
                   11589:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
                   11590:       precov[nres][k1]=Tvalsel[k3q];
                   11591:       /* 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]); */
                   11592:       k4q++;;
1.2     ! brouard  11593:     }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"*/
        !          11594:       /* Tvar[k1]; */ /* Age variable */ /* 17 age*V6*V2 ?*/
1.1       brouard  11595:       /* Wrong we want the value of variable name Tvar[k1] */
1.2     ! brouard  11596:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
        !          11597:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
        !          11598:       /* 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]]); */
        !          11599:       }else{
        !          11600:        k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
        !          11601:        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)*/
        !          11602:        TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
        !          11603:        precov[nres][k1]=Tvalsel[k3];
        !          11604:       }
1.1       brouard  11605:       /* 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]); */
                   11606:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.2     ! brouard  11607:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
        !          11608:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
        !          11609:       /* 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]]); */
        !          11610:       }else{
        !          11611:        k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
        !          11612:        k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
        !          11613:        TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
        !          11614:        precov[nres][k1]=Tvalsel[k3q];
        !          11615:       }
1.1       brouard  11616:       /* 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]); */
                   11617:     }else if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   11618:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   11619:       /* 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]]); */
                   11620:     }else{
                   11621:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   11622:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   11623:     }
                   11624:   }
                   11625:   
                   11626:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
                   11627:   return (0);
                   11628: }
                   11629: 
                   11630: int decodemodel( char model[], int lastobs)
                   11631:  /**< This routine decodes the model and returns:
                   11632:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   11633:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   11634:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   11635:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   11636:        * - cptcovage number of covariates with age*products =2
                   11637:        * - cptcovs number of simple covariates
                   11638:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
                   11639:        * - 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
                   11640:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
                   11641:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
                   11642:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   11643:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   11644:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   11645:        */
                   11646: /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   11647: {
                   11648:   int i, j, k, ks, v;
                   11649:   int n,m;
                   11650:   int  j1, k1, k11, k12, k2, k3, k4;
                   11651:   char modelsav[300];
                   11652:   char stra[300], strb[300], strc[300], strd[300],stre[300],strf[300];
                   11653:   char *strpt;
                   11654:   int  **existcomb;
                   11655:   
                   11656:   existcomb=imatrix(1,NCOVMAX,1,NCOVMAX);
                   11657:   for(i=1;i<=NCOVMAX;i++)
                   11658:     for(j=1;j<=NCOVMAX;j++)
                   11659:       existcomb[i][j]=0;
                   11660:     
                   11661:   /*removespace(model);*/
                   11662:   if (strlen(model) >1){ /* If there is at least 1 covariate */
                   11663:     j=0, j1=0, k1=0, k12=0, k2=-1, ks=0, cptcovn=0;
                   11664:     if (strstr(model,"AGE") !=0){
                   11665:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   11666:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
                   11667:       return 1;
                   11668:     }
                   11669:     if (strstr(model,"v") !=0){
                   11670:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   11671:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
                   11672:       return 1;
                   11673:     }
                   11674:     strcpy(modelsav,model); 
                   11675:     if ((strpt=strstr(model,"age*age")) !=0){
                   11676:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
                   11677:       if(strpt != model){
                   11678:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
                   11679:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
                   11680:  corresponding column of parameters.\n",model);
                   11681:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
                   11682:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
                   11683:  corresponding column of parameters.\n",model); fflush(ficlog);
                   11684:        return 1;
                   11685:       }
                   11686:       nagesqr=1;
                   11687:       if (strstr(model,"+age*age") !=0)
                   11688:        substrchaine(modelsav, model, "+age*age");
                   11689:       else if (strstr(model,"age*age+") !=0)
                   11690:        substrchaine(modelsav, model, "age*age+");
                   11691:       else 
                   11692:        substrchaine(modelsav, model, "age*age");
                   11693:     }else
                   11694:       nagesqr=0;
                   11695:     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 */
                   11696:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   11697:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.2     ! brouard  11698:       cptcovs=0; /**<  Number of simple covariates V1 +V1*age +V3 +V3*V4 +age*age => V1 + V3 =4+1-3=2  Wrong */
1.1       brouard  11699:       cptcovt= j+1; /* Number of total covariates in the model, not including
                   11700:                     * cst, age and age*age 
                   11701:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   11702:       /* including age products which are counted in cptcovage.
                   11703:        * but the covariates which are products must be treated 
                   11704:        * separately: ncovn=4- 2=2 (V1+V3). */
1.2     ! brouard  11705:       cptcovprod=0; /**< Number of products  V1*V2 +v3*age = 2 */
        !          11706:       cptcovdageprod=0; /* Number of doouble products with age age*Vn*VM or Vn*age*Vm or Vn*Vm*age */
1.1       brouard  11707:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.2     ! brouard  11708:       cptcovprodage=0;
1.1       brouard  11709:       /* cptcovprodage=nboccstr(modelsav,"age");*/
                   11710:       
                   11711:       /*   Design
                   11712:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   11713:        *  <          ncovcol=8                >
                   11714:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   11715:        *   k=  1    2      3       4     5       6      7        8
                   11716:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   11717:        *  covar[k,i], are for fixed covariates, value of kth covariate if not including age for individual i:
                   11718:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   11719:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
                   11720:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   11721:        *  Tage[++cptcovage]=k
                   11722:        *       if products, new covar are created after ncovcol + nqv (quanti fixed) with k1
                   11723:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   11724:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   11725:        *  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
                   11726:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   11727:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   11728:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   11729:        *  <          ncovcol=8  8 fixed covariate. Additional starts at 9 (V5*V6) and 10(V7*V8)              >
                   11730:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   11731:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   11732:        *     Tvard[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   11733:        * p Tvar[1]@12={2,   1,     3,      3,   9,     10,     8,       8}
                   11734:        * p Tprod[1]@2={                         6, 5}
                   11735:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   11736:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   11737:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   11738:        *How to reorganize? Tvars(orted)
                   11739:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   11740:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   11741:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   11742:        * Struct []
                   11743:        */
                   11744:       
                   11745:       /* This loop fills the array Tvar from the string 'model'.*/
                   11746:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   11747:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   11748:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   11749:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   11750:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   11751:       /*       k=1 Tvar[1]=2 (from V2) */
                   11752:       /*       k=5 Tvar[5] */
                   11753:       /* for (k=1; k<=cptcovn;k++) { */
                   11754:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   11755:       /*       } */
                   11756:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
                   11757:       /*
                   11758:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   11759:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   11760:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   11761:       }
                   11762:       cptcovage=0;
1.2     ! brouard  11763: 
        !          11764:       /* First loop in order to calculate */
        !          11765:       /* for age*VN*Vm
        !          11766:        * Provides, Typevar[k], Tage[cptcovage], existcomb[n][m], FixedV[ncovcolt+k12]
        !          11767:        * Tprod[k1]=k  Tposprod[k]=k1;    Tvard[k1][1] =m;
        !          11768:       */
        !          11769:       /* Needs  FixedV[Tvardk[k][1]] */
        !          11770:       /* For others:
        !          11771:        * Sets  Typevar[k];
        !          11772:        * Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
        !          11773:        *       Tposprod[k]=k11;
        !          11774:        *       Tprod[k11]=k;
        !          11775:        *       Tvardk[k][1] =m;
        !          11776:        * Needs FixedV[Tvardk[k][1]] == 0
        !          11777:       */
        !          11778:       
1.1       brouard  11779:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   11780:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   11781:                                         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" */
                   11782:        if (nbocc(modelsav,'+')==0)
                   11783:          strcpy(strb,modelsav); /* and analyzes it */
                   11784:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   11785:        /*scanf("%d",i);*/
                   11786:        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 */
1.2     ! brouard  11787:          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  */
        !          11788:          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   */
1.1       brouard  11789:            Typevar[k]=3;  /* 3 for age and double product age*Vn*Vm varying of fixed */
1.2     ! brouard  11790:             if(strstr(strc,"age")!=0) { /* It means that strc=V2*age or age*V2 and thus that strd=Vn */
        !          11791:               cutl(stre,strf,strc,'*') ; /* strf=age or Vm, stre=Vm or age. If strc=V6*V2 then strf=V6 and stre=V2 */
        !          11792:              strcpy(strc,strb); /* save strb(=age*Vn*Vm) into strc */
1.1       brouard  11793:              /* We want strb=Vn*Vm */
1.2     ! brouard  11794:               if(strcmp(strf,"age")==0){ /* strf is "age" so that stre=Vm =V2 . */
        !          11795:                 strcpy(strb,strd);
        !          11796:                 strcat(strb,"*");
        !          11797:                 strcat(strb,stre);
        !          11798:               }else{  /* strf=Vm  If strf=V6 then stre=V2 */
1.1       brouard  11799:                 strcpy(strb,strf);
                   11800:                 strcat(strb,"*");
1.2     ! brouard  11801:                 strcat(strb,stre);
        !          11802:                 strcpy(strd,strb); /* in order for strd to not be "age"  for next test (will be Vn*Vm */
1.1       brouard  11803:               }
1.2     ! brouard  11804:              /* 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]]]); */
        !          11805:              /* FixedV[Tvar[Tage[k]]]=0; /\* HERY not sure if V7*V4*age Fixed might not exist  yet*\/ */
        !          11806:             }else{  /* strc=Vn*Vm (and strd=age) and should be strb=Vn*Vm but want to keep original strb double product  */
1.1       brouard  11807:              strcpy(stre,strb); /* save full b in stre */
                   11808:              strcpy(strb,strc); /* save short c in new short b for next block strb=Vn*Vm*/
                   11809:              strcpy(strf,strc); /* save short c in new short f */
                   11810:               cutl(strc,strd,strf,'*'); /* We get strd=Vn and strc=Vm for next block (strb=Vn*Vm)*/
                   11811:              /* strcpy(strc,stre);*/ /* save full e in c for future */
                   11812:             }
                   11813:             cptcovdageprod++; /* double product with age  Which product is it? */
                   11814:             /* 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 *\/ */
                   11815:             /* cutl(strc,strd,strb,'*'); /\* strd=  V6    or   V2     or    age and  strc=  V2 or    age or    V2 *\/ */
                   11816:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   11817:            n=atoi(stre);
                   11818:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   11819:            m=atoi(strc);
                   11820:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   11821:            Tage[cptcovage]=k; /* For age*V3*V2 gives the position in model of covariates associated with age Tage[1]=6 HERY too*/
                   11822:            if(existcomb[n][m] == 0){
                   11823:              /*  r /home/brouard/Documents/Recherches/REVES/Zachary/Zach-2022/Feinuo_Sun/Feinuo-threeway/femV12V15_3wayintNBe.imach */
                   11824:              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);
                   11825:              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);
                   11826:              fflush(ficlog);
                   11827:              k1++;  /* The combination Vn*Vm will be in the model so we create it at k1 */
                   11828:              k12++;
                   11829:              existcomb[n][m]=k1;
                   11830:              existcomb[m][n]=k1;
                   11831:              Tvar[k]=ncovcol+nqv+ntv+nqtv+k1;
                   11832:              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*/
                   11833:              Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 Gives the k1 double product  Vn*Vm or age*Vn*Vm at the k position */
                   11834:              Tvard[k1][1] =m; /* m 1 for V1*/
                   11835:              Tvardk[k][1] =m; /* m 1 for V1*/
                   11836:              Tvard[k1][2] =n; /* n 4 for V4*/
                   11837:              Tvardk[k][2] =n; /* n 4 for V4*/
1.2     ! brouard  11838: /*           Tvar[Tage[cptcovage]]=k1;*/ /* Tvar[6=age*V3*V2]=9 (new fixed covariate) */ /* We don't know about Fixed yet HERE */
1.1       brouard  11839:              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 */
                   11840:                for (i=1; i<=lastobs;i++){/* For fixed product */
                   11841:                  /* Computes the new covariate which is a product of
                   11842:                     covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   11843:                  covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11844:                }
                   11845:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11846:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   11847:                k12++;
                   11848:                FixedV[ncovcolt+k12]=0;
                   11849:              }else{ /*End of FixedV */
                   11850:                cptcovprodvage++; /* Counting the number of varying covariate with age */
                   11851:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   11852:                k12++;
                   11853:                FixedV[ncovcolt+k12]=1;
                   11854:              }
                   11855:            }else{  /* k1 Vn*Vm already exists */
                   11856:              k11=existcomb[n][m];
                   11857:              Tposprod[k]=k11; /* OK */
                   11858:              Tvar[k]=Tvar[Tprod[k11]]; /* HERY */
                   11859:              Tvardk[k][1]=m;
                   11860:              Tvardk[k][2]=n;
                   11861:              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 */
                   11862:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   11863:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11864:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   11865:                Tvar[Tage[cptcovage]]=k1;
                   11866:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   11867:                k12++;
                   11868:                FixedV[ncovcolt+k12]=0;
                   11869:              }else{ /* Already exists but time varying (and age) */
                   11870:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   11871:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   11872:                /* Tvar[Tage[cptcovage]]=k1; */
                   11873:                cptcovprodvage++;
                   11874:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
1.2     ! brouard  11875:                k12++;
        !          11876:                FixedV[ncovcolt+k12]=1;
1.1       brouard  11877:              }
                   11878:            }
                   11879:            /* Tage[cptcovage]=k;  /\*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   11880:            /* Tvar[k]=k11; /\* HERY *\/ */
                   11881:          } 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 */
                   11882:             cptcovprod++;
                   11883:             if (strcmp(strc,"age")==0) { /**< Model includes age: strb= Vn*age c=age d=Vn*/
                   11884:               /* covar is not filled and then is empty */
                   11885:               cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   11886:               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 */
                   11887:               Typevar[k]=1;  /* 1 for age product */
                   11888:               cptcovage++; /* Counts the number of covariates which include age as a product */
                   11889:               Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   11890:              if( FixedV[Tvar[k]] == 0){
                   11891:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11892:              }else{
                   11893:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
                   11894:              }
                   11895:               /*printf("stre=%s ", stre);*/
                   11896:             } else if (strcmp(strd,"age")==0) { /* strb= age*Vn c=Vn */
                   11897:               cutl(stre,strb,strc,'V');
                   11898:               Tvar[k]=atoi(stre);
                   11899:               Typevar[k]=1;  /* 1 for age product */
                   11900:               cptcovage++;
                   11901:               Tage[cptcovage]=k;
                   11902:              if( FixedV[Tvar[k]] == 0){
                   11903:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   11904:              }else{
                   11905:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
                   11906:              }
                   11907:             }else{ /*  for product Vn*Vm */
                   11908:              Typevar[k]=2;  /* 2 for product Vn*Vm */
                   11909:              cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   11910:              n=atoi(stre);
                   11911:              cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   11912:              m=atoi(strc);
                   11913:              k1++;
                   11914:              cptcovprodnoage++;
                   11915:              if(existcomb[n][m] != 0 || existcomb[m][n] != 0){
                   11916:                printf("Warning in model combination V%d*V%d already exists in the model in position k1=%d!\n",n,m,existcomb[n][m]);
                   11917:                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]);
                   11918:                fflush(ficlog);
                   11919:                k11=existcomb[n][m];
                   11920:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   11921:                Tposprod[k]=k11;
                   11922:                Tprod[k11]=k;
                   11923:                Tvardk[k][1] =m; /* m 1 for V1*/
                   11924:                /* Tvard[k11][1] =m; /\* n 4 for V4*\/ */
                   11925:                Tvardk[k][2] =n; /* n 4 for V4*/                
                   11926:                /* Tvard[k11][2] =n; /\* n 4 for V4*\/ */
                   11927:              }else{ /* combination Vn*Vm doesn't exist we create it (no age)*/
                   11928:                existcomb[n][m]=k1;
                   11929:                existcomb[m][n]=k1;
                   11930:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
                   11931:                                                    because this model-covariate is a construction we invent a new column
                   11932:                                                    which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   11933:                                                    If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
                   11934:                                                    thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   11935:                                                    Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
                   11936:                /* Please remark that the new variables are model dependent */
                   11937:                /* If we have 4 variable but the model uses only 3, like in
                   11938:                 * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   11939:                 *  k=     1     2      3   4     5        6        7       8
                   11940:                 * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   11941:                 * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   11942:                 * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   11943:                 */
                   11944:                /* We need to feed some variables like TvarVV, but later on next loop because of ncovv (k2) is not correct */
                   11945:                Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 +V6*V2*age  */
                   11946:                Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
                   11947:                Tvard[k1][1] =m; /* m 1 for V1*/
                   11948:                Tvardk[k][1] =m; /* m 1 for V1*/
                   11949:                Tvard[k1][2] =n; /* n 4 for V4*/
                   11950:                Tvardk[k][2] =n; /* n 4 for V4*/
                   11951:                k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   11952:                /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   11953:                /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
                   11954:                /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
                   11955:                /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   11956:                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 */
                   11957:                  for (i=1; i<=lastobs;i++){/* For fixed product */
                   11958:                    /* Computes the new covariate which is a product of
                   11959:                       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   11960:                    covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   11961:                  }
                   11962:                  /* TvarVV[k2]=n; */
                   11963:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11964:                  /* TvarVV[k2+1]=m; */
                   11965:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11966:                }else{ /* not FixedV */
                   11967:                  /* TvarVV[k2]=n; */
                   11968:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11969:                  /* TvarVV[k2+1]=m; */
                   11970:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   11971:                }                 
                   11972:              }  /* End of creation of Vn*Vm if not created by age*Vn*Vm earlier  */
                   11973:            } /*  End of product Vn*Vm */
                   11974:           } /* End of age*double product or simple product */
                   11975:        }else { /* not a product */
                   11976:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   11977:          /*  scanf("%d",i);*/
                   11978:          cutl(strd,strc,strb,'V');
                   11979:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   11980:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   11981:          Tvar[k]=atoi(strd);
                   11982:          Typevar[k]=0;  /* 0 for simple covariates */
                   11983:        }
                   11984:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
                   11985:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   11986:                                  scanf("%d",i);*/
                   11987:       } /* end of loop + on total covariates */
1.2     ! brouard  11988: 
        !          11989:       
1.1       brouard  11990:     } /* end if strlen(modelsave == 0) age*age might exist */
                   11991:   } /* end if strlen(model == 0) */
                   11992:   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  */
                   11993: 
                   11994:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   11995:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   11996:   
                   11997:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   11998:      printf("cptcovprod=%d ", cptcovprod);
                   11999:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   12000:      scanf("%d ",i);*/
                   12001: 
                   12002: 
                   12003: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   12004:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
                   12005: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   12006:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   12007:    k =           1    2   3     4       5       6      7      8        9
                   12008:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
                   12009:    Typevar[k]=   0    0   0     2       1       0      2      1        0
                   12010:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   12011:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   12012:          Tmodelind[combination of covar]=k;
                   12013: */  
                   12014: /* Dispatching between quantitative and time varying covariates */
                   12015:   /* If Tvar[k] >ncovcol it is a product */
                   12016:   /* Tvar[k] is the value n of Vn with n varying for 1 to nvcol, or p  Vp=Vn*Vm for product */
                   12017:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
                   12018:   printf("Model=1+age+%s\n\
                   12019: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product, 3 for double product with age \n\
                   12020: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   12021: 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);
                   12022:   fprintf(ficlog,"Model=1+age+%s\n\
                   12023: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product, 3 for double product with age  \n\
                   12024: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   12025: 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);
                   12026:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
                   12027:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
1.2     ! brouard  12028: 
        !          12029: 
        !          12030:   /* Second loop for calculating  Fixed[k], Dummy[k]*/
        !          12031: 
        !          12032:   
1.1       brouard  12033:   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 */
                   12034:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
                   12035:       Fixed[k]= 0;
                   12036:       Dummy[k]= 0;
                   12037:       ncoveff++;
                   12038:       ncovf++;
                   12039:       nsd++;
                   12040:       modell[k].maintype= FTYPE;
                   12041:       TvarsD[nsd]=Tvar[k];
                   12042:       TvarsDind[nsd]=k;
                   12043:       TnsdVar[Tvar[k]]=nsd;
                   12044:       TvarF[ncovf]=Tvar[k];
                   12045:       TvarFind[ncovf]=k;
                   12046:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   12047:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   12048:     /* }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /\* Product of fixed dummy (<=ncovcol) covariates For a fixed product k is higher than ncovcol *\/ */
                   12049:     }else if( Tvar[k] <=ncovcol+nqv && Typevar[k]==0){/* Remind that product Vn*Vm are added in k Only simple fixed quantitative variable */
                   12050:       Fixed[k]= 0;
                   12051:       Dummy[k]= 1;
                   12052:       nqfveff++;
                   12053:       modell[k].maintype= FTYPE;
                   12054:       modell[k].subtype= FQ;
                   12055:       nsq++;
                   12056:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   12057:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
                   12058:       ncovf++;
                   12059:       TvarF[ncovf]=Tvar[k];
                   12060:       TvarFind[ncovf]=k;
                   12061:       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 */
                   12062:       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 */
                   12063:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
                   12064:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   12065:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   12066:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   12067:       ncovvt++;
                   12068:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   12069:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   12070: 
                   12071:       Fixed[k]= 1;
                   12072:       Dummy[k]= 0;
                   12073:       ntveff++; /* Only simple time varying dummy variable */
                   12074:       modell[k].maintype= VTYPE;
                   12075:       modell[k].subtype= VD;
                   12076:       nsd++;
                   12077:       TvarsD[nsd]=Tvar[k];
                   12078:       TvarsDind[nsd]=k;
                   12079:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
                   12080:       ncovv++; /* Only simple time varying variables */
                   12081:       TvarV[ncovv]=Tvar[k];
                   12082:       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 */
                   12083:       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 */
                   12084:       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 */
                   12085:       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);
                   12086:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
                   12087:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
                   12088:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   12089:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   12090:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   12091:       ncovvt++;
                   12092:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   12093:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   12094:       
                   12095:       Fixed[k]= 1;
                   12096:       Dummy[k]= 1;
                   12097:       nqtveff++;
                   12098:       modell[k].maintype= VTYPE;
                   12099:       modell[k].subtype= VQ;
                   12100:       ncovv++; /* Only simple time varying variables */
                   12101:       nsq++;
                   12102:       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) */
                   12103:       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) */
                   12104:       TvarV[ncovv]=Tvar[k];
                   12105:       TvarVind[ncovv]=k; /* TvarVind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Any time varying singele */
                   12106:       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 */
                   12107:       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 */
                   12108:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   12109:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   12110:       /* 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); */
                   12111:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
                   12112:     }else if (Typevar[k] == 1) {  /* product with age */
                   12113:       ncova++;
                   12114:       TvarA[ncova]=Tvar[k];
                   12115:       TvarAind[ncova]=k;
                   12116:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   12117:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   12118:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
                   12119:        Fixed[k]= 2;
                   12120:        Dummy[k]= 2;
                   12121:        modell[k].maintype= ATYPE;
                   12122:        modell[k].subtype= APFD;
                   12123:        ncovta++;
                   12124:        TvarAVVA[ncovta]=Tvar[k]; /*  (2)age*V3 */
                   12125:        TvarAVVAind[ncovta]=k;
                   12126:        /* ncoveff++; */
                   12127:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
                   12128:        Fixed[k]= 2;
                   12129:        Dummy[k]= 3;
                   12130:        modell[k].maintype= ATYPE;
                   12131:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   12132:        ncovta++;
                   12133:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   12134:        TvarAVVAind[ncovta]=k;
                   12135:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
                   12136:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
                   12137:        Fixed[k]= 3;
                   12138:        Dummy[k]= 2;
                   12139:        modell[k].maintype= ATYPE;
                   12140:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   12141:        ncovva++;
                   12142:        TvarVVA[ncovva]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   12143:        TvarVVAind[ncovva]=k;
                   12144:        ncovta++;
                   12145:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   12146:        TvarAVVAind[ncovta]=k;
                   12147:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
                   12148:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
                   12149:        Fixed[k]= 3;
                   12150:        Dummy[k]= 3;
                   12151:        modell[k].maintype= ATYPE;
                   12152:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   12153:        ncovva++;
                   12154:        TvarVVA[ncovva]=Tvar[k]; /*   */
                   12155:        TvarVVAind[ncovva]=k;
                   12156:        ncovta++;
                   12157:        TvarAVVA[ncovta]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   12158:        TvarAVVAind[ncovta]=k;
                   12159:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
                   12160:       }
                   12161:     }else if( Tposprod[k]>0  &&  Typevar[k]==2){  /* Detects if fixed product no age Vm*Vn */
                   12162:       printf("MEMORY ERRORR k=%d  Tposprod[k]=%d, Typevar[k]=%d\n ",k, Tposprod[k], Typevar[k]);
                   12163:       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 */
                   12164:       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]]);
                   12165:        Fixed[k]= 0;
                   12166:        Dummy[k]= 0;
                   12167:        ncoveff++;
                   12168:        ncovf++;
                   12169:        /* ncovv++; */
                   12170:        /* TvarVV[ncovv]=Tvardk[k][1]; */
                   12171:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   12172:        /* ncovv++; */
                   12173:        /* TvarVV[ncovv]=Tvardk[k][2]; */
                   12174:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   12175:        modell[k].maintype= FTYPE;
                   12176:        TvarF[ncovf]=Tvar[k];
                   12177:        /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
                   12178:        TvarFind[ncovf]=k;
                   12179:        TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   12180:        TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   12181:       }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  */
                   12182:        /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   12183:        /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   12184:        /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   12185:        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 */
                   12186:        ncovvt++;
                   12187:        TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   12188:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   12189:        ncovvt++;
                   12190:        TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   12191:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   12192:        
                   12193:        /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   12194:        /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   12195:        
                   12196:        if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   12197:          if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
                   12198:            Fixed[k]= 1;
                   12199:            Dummy[k]= 0;
                   12200:            modell[k].maintype= FTYPE;
                   12201:            modell[k].subtype= FPDD;            /*      Product fixed dummy * fixed dummy */
                   12202:            ncovf++; /* Fixed variables without age */
                   12203:            TvarF[ncovf]=Tvar[k];
                   12204:            TvarFind[ncovf]=k;
                   12205:          }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   12206:            Fixed[k]= 0;  /* Fixed product */
                   12207:            Dummy[k]= 1;
                   12208:            modell[k].maintype= FTYPE;
                   12209:            modell[k].subtype= FPDQ;            /*      Product fixed dummy * fixed quantitative */
                   12210:            ncovf++; /* Varying variables without age */
                   12211:            TvarF[ncovf]=Tvar[k];
                   12212:            TvarFind[ncovf]=k;
                   12213:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
                   12214:            Fixed[k]= 1;
                   12215:            Dummy[k]= 0;
                   12216:            modell[k].maintype= VTYPE;
                   12217:            modell[k].subtype= VPDD;            /*      Product fixed dummy * varying dummy */
                   12218:            ncovv++; /* Varying variables without age */
                   12219:            TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   12220:            TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   12221:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
                   12222:            Fixed[k]= 1;
                   12223:            Dummy[k]= 1;
                   12224:            modell[k].maintype= VTYPE;
                   12225:            modell[k].subtype= VPDQ;            /*      Product fixed dummy * varying quantitative */
                   12226:            ncovv++; /* Varying variables without age */
                   12227:            TvarV[ncovv]=Tvar[k];
                   12228:            TvarVind[ncovv]=k;
                   12229:          }
                   12230:        }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   12231:          if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   12232:            Fixed[k]= 0;  /*  Fixed product */
                   12233:            Dummy[k]= 1;
                   12234:            modell[k].maintype= FTYPE;
                   12235:            modell[k].subtype= FPDQ;            /*      Product fixed quantitative * fixed dummy */
                   12236:            ncovf++; /* Fixed variables without age */
                   12237:            TvarF[ncovf]=Tvar[k];
                   12238:            TvarFind[ncovf]=k;
                   12239:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
                   12240:            Fixed[k]= 1;
                   12241:            Dummy[k]= 1;
                   12242:            modell[k].maintype= VTYPE;
                   12243:            modell[k].subtype= VPDQ;            /*      Product fixed quantitative * varying dummy */
                   12244:            ncovv++; /* Varying variables without age */
                   12245:            TvarV[ncovv]=Tvar[k];
                   12246:            TvarVind[ncovv]=k;
                   12247:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
                   12248:            Fixed[k]= 1;
                   12249:            Dummy[k]= 1;
                   12250:            modell[k].maintype= VTYPE;
                   12251:            modell[k].subtype= VPQQ;            /*      Product fixed quantitative * varying quantitative */
                   12252:            ncovv++; /* Varying variables without age */
                   12253:            TvarV[ncovv]=Tvar[k];
                   12254:            TvarVind[ncovv]=k;
                   12255:            ncovv++; /* Varying variables without age */
                   12256:            TvarV[ncovv]=Tvar[k];
                   12257:            TvarVind[ncovv]=k;
                   12258:          }
                   12259:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
                   12260:          if(Tvard[k1][2] <=ncovcol){
                   12261:            Fixed[k]= 1;
                   12262:            Dummy[k]= 1;
                   12263:            modell[k].maintype= VTYPE;
                   12264:            modell[k].subtype= VPDD;            /*      Product time varying dummy * fixed dummy */
                   12265:            ncovv++; /* Varying variables without age */
                   12266:            TvarV[ncovv]=Tvar[k];
                   12267:            TvarVind[ncovv]=k;
                   12268:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   12269:            Fixed[k]= 1;
                   12270:            Dummy[k]= 1;
                   12271:            modell[k].maintype= VTYPE;
                   12272:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * fixed quantitative */
                   12273:            ncovv++; /* Varying variables without age */
                   12274:            TvarV[ncovv]=Tvar[k];
                   12275:            TvarVind[ncovv]=k;
                   12276:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   12277:            Fixed[k]= 1;
                   12278:            Dummy[k]= 0;
                   12279:            modell[k].maintype= VTYPE;
                   12280:            modell[k].subtype= VPDD;            /*      Product time varying dummy * time varying dummy */
                   12281:            ncovv++; /* Varying variables without age */
                   12282:            TvarV[ncovv]=Tvar[k];
                   12283:            TvarVind[ncovv]=k;
                   12284:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   12285:            Fixed[k]= 1;
                   12286:            Dummy[k]= 1;
                   12287:            modell[k].maintype= VTYPE;
                   12288:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * time varying quantitative */
                   12289:            ncovv++; /* Varying variables without age */
                   12290:            TvarV[ncovv]=Tvar[k];
                   12291:            TvarVind[ncovv]=k;
                   12292:          }
                   12293:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
                   12294:          if(Tvard[k1][2] <=ncovcol){
                   12295:            Fixed[k]= 1;
                   12296:            Dummy[k]= 1;
                   12297:            modell[k].maintype= VTYPE;
                   12298:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * fixed dummy */
                   12299:            ncovv++; /* Varying variables without age */
                   12300:            TvarV[ncovv]=Tvar[k];
                   12301:            TvarVind[ncovv]=k;
                   12302:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   12303:            Fixed[k]= 1;
                   12304:            Dummy[k]= 1;
                   12305:            modell[k].maintype= VTYPE;
                   12306:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * fixed quantitative */
                   12307:            ncovv++; /* Varying variables without age */
                   12308:            TvarV[ncovv]=Tvar[k];
                   12309:            TvarVind[ncovv]=k;
                   12310:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   12311:            Fixed[k]= 1;
                   12312:            Dummy[k]= 1;
                   12313:            modell[k].maintype= VTYPE;
                   12314:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * time varying dummy */
                   12315:            ncovv++; /* Varying variables without age */
                   12316:            TvarV[ncovv]=Tvar[k];
                   12317:            TvarVind[ncovv]=k;
                   12318:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   12319:            Fixed[k]= 1;
                   12320:            Dummy[k]= 1;
                   12321:            modell[k].maintype= VTYPE;
                   12322:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * time varying quantitative */
                   12323:            ncovv++; /* Varying variables without age */
                   12324:            TvarV[ncovv]=Tvar[k];
                   12325:            TvarVind[ncovv]=k;
                   12326:          }
                   12327:        }else{
                   12328:          printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12329:          fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12330:        } /*end k1*/
                   12331:       }
                   12332:     }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  */
                   12333:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   12334:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   12335:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   12336:       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 */
                   12337:       ncova++;
                   12338:       TvarA[ncova]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   12339:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   12340:       ncova++;
                   12341:       TvarA[ncova]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   12342:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   12343: 
                   12344:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   12345:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   12346:       if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){
                   12347:        ncovta++;
                   12348:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12349:        TvarAVVAind[ncovta]=k;
                   12350:        ncovta++;
                   12351:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12352:        TvarAVVAind[ncovta]=k;
                   12353:       }else{
                   12354:        ncovva++;  /* HERY  reached */
                   12355:        TvarVVA[ncovva]=Tvard[k1][1]; /*  age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4  */
                   12356:        TvarVVAind[ncovva]=k;
                   12357:        ncovva++;
                   12358:        TvarVVA[ncovva]=Tvard[k1][2]; /*   */
                   12359:        TvarVVAind[ncovva]=k;
                   12360:        ncovta++;
                   12361:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12362:        TvarAVVAind[ncovta]=k;
                   12363:        ncovta++;
                   12364:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12365:        TvarAVVAind[ncovta]=k;
                   12366:       }
                   12367:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   12368:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
                   12369:          Fixed[k]= 2;
                   12370:          Dummy[k]= 2;
                   12371:          modell[k].maintype= FTYPE;
                   12372:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   12373:          /* TvarF[ncova]=Tvar[k];   /\* Problem to solve *\/ */
                   12374:          /* TvarFind[ncova]=k; */
                   12375:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   12376:          Fixed[k]= 2;  /* Fixed product */
                   12377:          Dummy[k]= 3;
                   12378:          modell[k].maintype= FTYPE;
                   12379:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   12380:          /* TvarF[ncova]=Tvar[k]; */
                   12381:          /* TvarFind[ncova]=k; */
                   12382:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
                   12383:          Fixed[k]= 3;
                   12384:          Dummy[k]= 2;
                   12385:          modell[k].maintype= VTYPE;
                   12386:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   12387:          TvarV[ncova]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   12388:          TvarVind[ncova]=k;/* TvarVind[1]=5 */ 
                   12389:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
                   12390:          Fixed[k]= 3;
                   12391:          Dummy[k]= 3;
                   12392:          modell[k].maintype= VTYPE;
                   12393:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   12394:          /* ncovv++; /\* Varying variables without age *\/ */
                   12395:          /* TvarV[ncovv]=Tvar[k]; */
                   12396:          /* TvarVind[ncovv]=k; */
                   12397:        }
                   12398:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   12399:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   12400:          Fixed[k]= 2;  /*  Fixed product */
                   12401:          Dummy[k]= 2;
                   12402:          modell[k].maintype= FTYPE;
                   12403:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   12404:          /* ncova++; /\* Fixed variables with age *\/ */
                   12405:          /* TvarF[ncovf]=Tvar[k]; */
                   12406:          /* TvarFind[ncovf]=k; */
                   12407:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
                   12408:          Fixed[k]= 2;
                   12409:          Dummy[k]= 3;
                   12410:          modell[k].maintype= VTYPE;
                   12411:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   12412:          /* ncova++; /\* Varying variables with age *\/ */
                   12413:          /* TvarV[ncova]=Tvar[k]; */
                   12414:          /* TvarVind[ncova]=k; */
                   12415:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
                   12416:          Fixed[k]= 3;
                   12417:          Dummy[k]= 2;
                   12418:          modell[k].maintype= VTYPE;
                   12419:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   12420:          ncova++; /* Varying variables without age */
                   12421:          TvarV[ncova]=Tvar[k];
                   12422:          TvarVind[ncova]=k;
                   12423:          /* ncova++; /\* Varying variables without age *\/ */
                   12424:          /* TvarV[ncova]=Tvar[k]; */
                   12425:          /* TvarVind[ncova]=k; */
                   12426:        }
                   12427:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
                   12428:        if(Tvard[k1][2] <=ncovcol){
                   12429:          Fixed[k]= 2;
                   12430:          Dummy[k]= 2;
                   12431:          modell[k].maintype= VTYPE;
                   12432:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   12433:          /* ncova++; /\* Varying variables with age *\/ */
                   12434:          /* TvarV[ncova]=Tvar[k]; */
                   12435:          /* TvarVind[ncova]=k; */
                   12436:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   12437:          Fixed[k]= 2;
                   12438:          Dummy[k]= 3;
                   12439:          modell[k].maintype= VTYPE;
                   12440:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   12441:          /* ncova++; /\* Varying variables with age *\/ */
                   12442:          /* TvarV[ncova]=Tvar[k]; */
                   12443:          /* TvarVind[ncova]=k; */
                   12444:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   12445:          Fixed[k]= 3;
                   12446:          Dummy[k]= 2;
                   12447:          modell[k].maintype= VTYPE;
                   12448:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   12449:          /* ncova++; /\* Varying variables with age *\/ */
                   12450:          /* TvarV[ncova]=Tvar[k]; */
                   12451:          /* TvarVind[ncova]=k; */
                   12452:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   12453:          Fixed[k]= 3;
                   12454:          Dummy[k]= 3;
                   12455:          modell[k].maintype= VTYPE;
                   12456:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   12457:          /* ncova++; /\* Varying variables with age *\/ */
                   12458:          /* TvarV[ncova]=Tvar[k]; */
                   12459:          /* TvarVind[ncova]=k; */
                   12460:        }
                   12461:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
                   12462:        if(Tvard[k1][2] <=ncovcol){
                   12463:          Fixed[k]= 2;
                   12464:          Dummy[k]= 2;
                   12465:          modell[k].maintype= VTYPE;
                   12466:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   12467:          /* ncova++; /\* Varying variables with age *\/ */
                   12468:          /* TvarV[ncova]=Tvar[k]; */
                   12469:          /* TvarVind[ncova]=k; */
                   12470:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   12471:          Fixed[k]= 2;
                   12472:          Dummy[k]= 3;
                   12473:          modell[k].maintype= VTYPE;
                   12474:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   12475:          /* ncova++; /\* Varying variables with age *\/ */
                   12476:          /* TvarV[ncova]=Tvar[k]; */
                   12477:          /* TvarVind[ncova]=k; */
                   12478:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   12479:          Fixed[k]= 3;
                   12480:          Dummy[k]= 2;
                   12481:          modell[k].maintype= VTYPE;
                   12482:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   12483:          /* ncova++; /\* Varying variables with age *\/ */
                   12484:          /* TvarV[ncova]=Tvar[k]; */
                   12485:          /* TvarVind[ncova]=k; */
                   12486:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   12487:          Fixed[k]= 3;
                   12488:          Dummy[k]= 3;
                   12489:          modell[k].maintype= VTYPE;
                   12490:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   12491:          /* ncova++; /\* Varying variables with age *\/ */
                   12492:          /* TvarV[ncova]=Tvar[k]; */
                   12493:          /* TvarVind[ncova]=k; */
                   12494:        }
                   12495:       }else{
                   12496:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12497:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12498:       } /*end k1*/
                   12499:     } else{
                   12500:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   12501:       fprintf(ficlog,"Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   12502:     }
                   12503:     /* 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]); */
                   12504:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
                   12505:     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]);
                   12506:   }
                   12507:   ncovvta=ncovva;
                   12508:   /* Searching for doublons in the model */
                   12509:   for(k1=1; k1<= cptcovt;k1++){
                   12510:     for(k2=1; k2 <k1;k2++){
                   12511:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   12512:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
                   12513:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   12514:          if(Tvar[k1]==Tvar[k2]){
                   12515:            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]);
                   12516:            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);
                   12517:            return(1);
                   12518:          }
                   12519:        }else if (Typevar[k1] ==2){
                   12520:          k3=Tposprod[k1];
                   12521:          k4=Tposprod[k2];
                   12522:          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])) ){
                   12523:            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]]);
                   12524:            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);
                   12525:            return(1);
                   12526:          }
                   12527:        }
                   12528:       }
                   12529:     }
                   12530:   }
                   12531:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   12532:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   12533:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   12534:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
                   12535: 
                   12536:   free_imatrix(existcomb,1,NCOVMAX,1,NCOVMAX);
                   12537:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
                   12538:   /*endread:*/
                   12539:   printf("Exiting decodemodel: ");
                   12540:   return (1);
                   12541: }
                   12542: 
                   12543: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
                   12544: {/* Check ages at death */
                   12545:   int i, m;
                   12546:   int firstone=0;
                   12547:   
                   12548:   for (i=1; i<=imx; i++) {
                   12549:     for(m=2; (m<= maxwav); m++) {
                   12550:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   12551:        anint[m][i]=9999;
                   12552:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   12553:          s[m][i]=-1;
                   12554:       }
                   12555:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
                   12556:        *nberr = *nberr + 1;
                   12557:        if(firstone == 0){
                   12558:          firstone=1;
                   12559:        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);
                   12560:        }
                   12561:        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);
                   12562:        s[m][i]=-1;  /* Droping the death status */
                   12563:       }
                   12564:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
                   12565:        (*nberr)++;
                   12566:        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);
                   12567:        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);
                   12568:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   12569:       }
                   12570:     }
                   12571:   }
                   12572: 
                   12573:   for (i=1; i<=imx; i++)  {
                   12574:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   12575:     for(m=firstpass; (m<= lastpass); m++){
                   12576:       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 */
                   12577:        if (s[m][i] >= nlstate+1) {
                   12578:          if(agedc[i]>0){
                   12579:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
                   12580:              agev[m][i]=agedc[i];
                   12581:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
                   12582:            }else {
                   12583:              if ((int)andc[i]!=9999){
                   12584:                nbwarn++;
                   12585:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   12586:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   12587:                agev[m][i]=-1;
                   12588:              }
                   12589:            }
                   12590:          } /* agedc > 0 */
                   12591:        } /* end if */
                   12592:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   12593:                                 years but with the precision of a month */
                   12594:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   12595:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   12596:            agev[m][i]=1;
                   12597:          else if(agev[m][i] < *agemin){ 
                   12598:            *agemin=agev[m][i];
                   12599:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   12600:          }
                   12601:          else if(agev[m][i] >*agemax){
                   12602:            *agemax=agev[m][i];
                   12603:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
                   12604:          }
                   12605:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   12606:          /*     agev[m][i] = age[i]+2*m;*/
                   12607:        } /* en if 9*/
                   12608:        else { /* =9 */
                   12609:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
                   12610:          agev[m][i]=1;
                   12611:          s[m][i]=-1;
                   12612:        }
                   12613:       }
                   12614:       else if(s[m][i]==0) /*= 0 Unknown */
                   12615:        agev[m][i]=1;
                   12616:       else{
                   12617:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   12618:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   12619:        agev[m][i]=0;
                   12620:       }
                   12621:     } /* End for lastpass */
                   12622:   }
                   12623:     
                   12624:   for (i=1; i<=imx; i++)  {
                   12625:     for(m=firstpass; (m<=lastpass); m++){
                   12626:       if (s[m][i] > (nlstate+ndeath)) {
                   12627:        (*nberr)++;
                   12628:        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);     
                   12629:        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);     
                   12630:        return 1;
                   12631:       }
                   12632:     }
                   12633:   }
                   12634: 
                   12635:   /*for (i=1; i<=imx; i++){
                   12636:   for (m=firstpass; (m<lastpass); m++){
                   12637:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   12638: }
                   12639: 
                   12640: }*/
                   12641: 
                   12642: 
                   12643:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   12644:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
                   12645: 
                   12646:   return (0);
                   12647:  /* endread:*/
                   12648:     printf("Exiting calandcheckages: ");
                   12649:     return (1);
                   12650: }
                   12651: 
                   12652: #if defined(_MSC_VER)
                   12653: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   12654: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   12655: //#include "stdafx.h"
                   12656: //#include <stdio.h>
                   12657: //#include <tchar.h>
                   12658: //#include <windows.h>
                   12659: //#include <iostream>
                   12660: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   12661: 
                   12662: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   12663: 
                   12664: BOOL IsWow64()
                   12665: {
                   12666:        BOOL bIsWow64 = FALSE;
                   12667: 
                   12668:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   12669:        //  (HANDLE, PBOOL);
                   12670: 
                   12671:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   12672: 
                   12673:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   12674:        const char funcName[] = "IsWow64Process";
                   12675:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   12676:                GetProcAddress(module, funcName);
                   12677: 
                   12678:        if (NULL != fnIsWow64Process)
                   12679:        {
                   12680:                if (!fnIsWow64Process(GetCurrentProcess(),
                   12681:                        &bIsWow64))
                   12682:                        //throw std::exception("Unknown error");
                   12683:                        printf("Unknown error\n");
                   12684:        }
                   12685:        return bIsWow64 != FALSE;
                   12686: }
                   12687: #endif
                   12688: 
                   12689: void syscompilerinfo(int logged)
                   12690: {
                   12691: #include <stdint.h>
                   12692: 
                   12693:   /* #include "syscompilerinfo.h"*/
                   12694:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   12695:    /* /GS /W3 /Gy
                   12696:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   12697:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   12698:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
                   12699:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   12700:    */ 
                   12701:    /* 64 bits */
                   12702:    /*
                   12703:      /GS /W3 /Gy
                   12704:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   12705:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   12706:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   12707:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   12708:    /* Optimization are useless and O3 is slower than O2 */
                   12709:    /*
                   12710:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   12711:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   12712:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   12713:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   12714:    */
                   12715:    /* Link is */ /* /OUT:"visual studio
                   12716:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   12717:       /PDB:"visual studio
                   12718:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   12719:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   12720:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   12721:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   12722:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   12723:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   12724:       uiAccess='false'"
                   12725:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   12726:       /NOLOGO /TLBID:1
                   12727:    */
                   12728: 
                   12729: 
                   12730: #if defined __INTEL_COMPILER
                   12731: #if defined(__GNUC__)
                   12732:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   12733: #endif
                   12734: #elif defined(__GNUC__) 
                   12735: #ifndef  __APPLE__
                   12736: #include <gnu/libc-version.h>  /* Only on gnu */
                   12737: #endif
                   12738:    struct utsname sysInfo;
                   12739:    int cross = CROSS;
                   12740:    if (cross){
                   12741:           printf("Cross-");
                   12742:           if(logged) fprintf(ficlog, "Cross-");
                   12743:    }
                   12744: #endif
                   12745: 
                   12746:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
                   12747: #if defined(__clang__)
                   12748:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
                   12749: #endif
                   12750: #if defined(__ICC) || defined(__INTEL_COMPILER)
                   12751:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
                   12752: #endif
                   12753: #if defined(__GNUC__) || defined(__GNUG__)
                   12754:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
                   12755: #endif
                   12756: #if defined(__HP_cc) || defined(__HP_aCC)
                   12757:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
                   12758: #endif
                   12759: #if defined(__IBMC__) || defined(__IBMCPP__)
                   12760:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
                   12761: #endif
                   12762: #if defined(_MSC_VER)
                   12763:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
                   12764: #endif
                   12765: #if defined(__PGI)
                   12766:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
                   12767: #endif
                   12768: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
                   12769:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
                   12770: #endif
                   12771:    printf(" for "); if (logged) fprintf(ficlog, " for ");
                   12772:    
                   12773: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   12774: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   12775:     // Windows (x64 and x86)
                   12776:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
                   12777: #elif __unix__ // all unices, not all compilers
                   12778:     // Unix
                   12779:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
                   12780: #elif __linux__
                   12781:     // linux
                   12782:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
                   12783: #elif __APPLE__
                   12784:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
                   12785:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
                   12786: #endif
                   12787: 
                   12788: /*  __MINGW32__          */
                   12789: /*  __CYGWIN__  */
                   12790: /* __MINGW64__  */
                   12791: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   12792: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   12793: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   12794: /* _WIN64  // Defined for applications for Win64. */
                   12795: /* _M_X64 // Defined for compilations that target x64 processors. */
                   12796: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
                   12797: 
                   12798: #if UINTPTR_MAX == 0xffffffff
                   12799:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
                   12800: #elif UINTPTR_MAX == 0xffffffffffffffff
                   12801:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
                   12802: #else
                   12803:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
                   12804: #endif
                   12805: 
                   12806: #if defined(__GNUC__)
                   12807: # if defined(__GNUC_PATCHLEVEL__)
                   12808: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   12809:                             + __GNUC_MINOR__ * 100 \
                   12810:                             + __GNUC_PATCHLEVEL__)
                   12811: # else
                   12812: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   12813:                             + __GNUC_MINOR__ * 100)
                   12814: # endif
                   12815:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
                   12816:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
                   12817: 
                   12818:    if (uname(&sysInfo) != -1) {
                   12819:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
                   12820:         if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
                   12821:    }
                   12822:    else
                   12823:       perror("uname() error");
                   12824:    //#ifndef __INTEL_COMPILER 
                   12825: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
                   12826:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
                   12827:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
                   12828: #endif
                   12829: #endif
                   12830: 
                   12831:    //   void main ()
                   12832:    //   {
                   12833: #if defined(_MSC_VER)
                   12834:    if (IsWow64()){
                   12835:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   12836:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   12837:    }
                   12838:    else{
                   12839:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   12840:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   12841:    }
                   12842:    //     printf("\nPress Enter to continue...");
                   12843:    //     getchar();
                   12844:    //   }
                   12845: 
                   12846: #endif
                   12847:    
                   12848: 
                   12849: }
                   12850: 
                   12851: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
                   12852:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
                   12853:   /* Computes the prevalence limit for each combination of the dummy covariates */
                   12854:   int i, j, k, i1, k4=0, nres=0 ;
                   12855:   /* double ftolpl = 1.e-10; */
                   12856:   double age, agebase, agelim;
                   12857:   double tot;
                   12858: 
                   12859:   strcpy(filerespl,"PL_");
                   12860:   strcat(filerespl,fileresu);
                   12861:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   12862:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   12863:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   12864:   }
                   12865:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   12866:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   12867:   pstamp(ficrespl);
                   12868:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
                   12869:   fprintf(ficrespl,"#Age ");
                   12870:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   12871:   fprintf(ficrespl,"\n");
                   12872:   
                   12873:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   12874: 
                   12875:   agebase=ageminpar;
                   12876:   agelim=agemaxpar;
                   12877: 
                   12878:   /* i1=pow(2,ncoveff); */
                   12879:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   12880:   if (cptcovn < 1){i1=1;}
                   12881: 
                   12882:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
                   12883:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   12884:       k=TKresult[nres];
                   12885:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   12886:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   12887:       /*       continue; */
                   12888: 
                   12889:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   12890:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   12891:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   12892:       /* k=k+1; */
                   12893:       /* to clean */
                   12894:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
                   12895:       fprintf(ficrespl,"#******");
                   12896:       printf("#******");
                   12897:       fprintf(ficlog,"#******");
                   12898:       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) */
                   12899:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
                   12900:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12901:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12902:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12903:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12904:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12905:       }
                   12906:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   12907:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12908:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12909:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   12910:       /* } */
                   12911:       fprintf(ficrespl,"******\n");
                   12912:       printf("******\n");
                   12913:       fprintf(ficlog,"******\n");
                   12914:       if(invalidvarcomb[k]){
                   12915:        printf("\nCombination (%d) ignored because no case \n",k); 
                   12916:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   12917:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   12918:        continue;
                   12919:       }
                   12920: 
                   12921:       fprintf(ficrespl,"#Age ");
                   12922:       /* for(j=1;j<=cptcoveff;j++) { */
                   12923:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12924:       /* } */
                   12925:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   12926:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12927:       }
                   12928:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   12929:       fprintf(ficrespl,"Total Years_to_converge\n");
                   12930:     
                   12931:       for (age=agebase; age<=agelim; age++){
                   12932:        /* for (age=agebase; age<=agebase; age++){ */
                   12933:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   12934:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
                   12935:        fprintf(ficrespl,"%.0f ",age );
                   12936:        /* for(j=1;j<=cptcoveff;j++) */
                   12937:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12938:        for(j=1;j<=cptcovs;j++)
                   12939:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   12940:        tot=0.;
                   12941:        for(i=1; i<=nlstate;i++){
                   12942:          tot +=  prlim[i][i];
                   12943:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   12944:        }
                   12945:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   12946:       } /* Age */
                   12947:       /* was end of cptcod */
                   12948:     } /* nres */
                   12949:   /* } /\* for each combination *\/ */
                   12950:   return 0;
                   12951: }
                   12952: 
                   12953: 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){
                   12954:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
                   12955:        
                   12956:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   12957:    * at any age between ageminpar and agemaxpar
                   12958:         */
                   12959:   int i, j, k, i1, nres=0 ;
                   12960:   /* double ftolpl = 1.e-10; */
                   12961:   double age, agebase, agelim;
                   12962:   double tot;
                   12963:   /* double ***mobaverage; */
                   12964:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
                   12965: 
                   12966:   strcpy(fileresplb,"PLB_");
                   12967:   strcat(fileresplb,fileresu);
                   12968:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
                   12969:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   12970:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   12971:   }
                   12972:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   12973:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
                   12974:   pstamp(ficresplb);
                   12975:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
                   12976:   fprintf(ficresplb,"#Age ");
                   12977:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   12978:   fprintf(ficresplb,"\n");
                   12979:   
                   12980:   
                   12981:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   12982:   
                   12983:   agebase=ageminpar;
                   12984:   agelim=agemaxpar;
                   12985:   
                   12986:   
                   12987:   i1=pow(2,cptcoveff);
                   12988:   if (cptcovn < 1){i1=1;}
                   12989:   
                   12990:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   12991:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12992:       k=TKresult[nres];
                   12993:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   12994:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   12995:      /*        continue; */
                   12996:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
                   12997:       fprintf(ficresplb,"#******");
                   12998:       printf("#******");
                   12999:       fprintf(ficlog,"#******");
                   13000:       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) */
                   13001:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   13002:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   13003:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   13004:       }
                   13005:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   13006:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   13007:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   13008:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   13009:       /* } */
                   13010:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   13011:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   13012:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   13013:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   13014:       /* } */
                   13015:       fprintf(ficresplb,"******\n");
                   13016:       printf("******\n");
                   13017:       fprintf(ficlog,"******\n");
                   13018:       if(invalidvarcomb[k]){
                   13019:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   13020:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   13021:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   13022:        continue;
                   13023:       }
                   13024:     
                   13025:       fprintf(ficresplb,"#Age ");
                   13026:       for(j=1;j<=cptcovs;j++) {
                   13027:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   13028:       }
                   13029:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   13030:       fprintf(ficresplb,"Total Years_to_converge\n");
                   13031:     
                   13032:     
                   13033:       for (age=agebase; age<=agelim; age++){
                   13034:        /* for (age=agebase; age<=agebase; age++){ */
                   13035:        if(mobilavproj > 0){
                   13036:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   13037:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   13038:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
                   13039:        }else if (mobilavproj == 0){
                   13040:          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);
                   13041:          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);
                   13042:          exit(1);
                   13043:        }else{
                   13044:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   13045:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
                   13046:          /* printf("TOTOT\n"); */
                   13047:           /* exit(1); */
                   13048:        }
                   13049:        fprintf(ficresplb,"%.0f ",age );
                   13050:        for(j=1;j<=cptcovs;j++)
                   13051:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   13052:        tot=0.;
                   13053:        for(i=1; i<=nlstate;i++){
                   13054:          tot +=  bprlim[i][i];
                   13055:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   13056:        }
                   13057:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   13058:       } /* Age */
                   13059:       /* was end of cptcod */
                   13060:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
                   13061:     /* } /\* end of any combination *\/ */
                   13062:   } /* end of nres */  
                   13063:   /* hBijx(p, bage, fage); */
                   13064:   /* fclose(ficrespijb); */
                   13065:   
                   13066:   return 0;
                   13067: }
                   13068:  
                   13069: int hPijx(double *p, int bage, int fage){
                   13070:     /*------------- h Pij x at various ages ------------*/
                   13071:   /* to be optimized with precov */
                   13072:   int stepsize;
                   13073:   int agelim;
                   13074:   int hstepm;
                   13075:   int nhstepm;
                   13076:   int h, i, i1, j, k, k4, nres=0;
                   13077: 
                   13078:   double agedeb;
                   13079:   double ***p3mat;
                   13080: 
                   13081:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   13082:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   13083:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   13084:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   13085:   }
                   13086:   printf("Computing pij: result on file '%s' \n", filerespij);
                   13087:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   13088:   
                   13089:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   13090:   /*if (stepm<=24) stepsize=2;*/
                   13091:   
                   13092:   agelim=AGESUP;
                   13093:   hstepm=stepsize*YEARM; /* Every year of age */
                   13094:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   13095:   
                   13096:   /* hstepm=1;   aff par mois*/
                   13097:   pstamp(ficrespij);
                   13098:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   13099:   i1= pow(2,cptcoveff);
                   13100:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   13101:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   13102:   /*   k=k+1;  */
                   13103:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   13104:     k=TKresult[nres];
                   13105:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   13106:     /* for(k=1; k<=i1;k++){ */
                   13107:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   13108:     /*         continue; */
                   13109:     fprintf(ficrespij,"\n#****** ");
                   13110:     for(j=1;j<=cptcovs;j++){
                   13111:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   13112:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   13113:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   13114:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   13115:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   13116:     }
                   13117:     fprintf(ficrespij,"******\n");
                   13118:     
                   13119:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   13120:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   13121:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   13122:       
                   13123:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   13124:       
                   13125:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   13126:       oldm=oldms;savm=savms;
                   13127:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   13128:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   13129:       for(i=1; i<=nlstate;i++)
                   13130:        for(j=1; j<=nlstate+ndeath;j++)
                   13131:          fprintf(ficrespij," %1d-%1d",i,j);
                   13132:       fprintf(ficrespij,"\n");
                   13133:       for (h=0; h<=nhstepm; h++){
                   13134:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   13135:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
                   13136:        for(i=1; i<=nlstate;i++)
                   13137:          for(j=1; j<=nlstate+ndeath;j++)
                   13138:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
                   13139:        fprintf(ficrespij,"\n");
                   13140:       }
                   13141:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   13142:       fprintf(ficrespij,"\n");
                   13143:     }
                   13144:   }
                   13145:   /*}*/
                   13146:   return 0;
                   13147: }
                   13148:  
                   13149:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
                   13150:     /*------------- h Bij x at various ages ------------*/
                   13151:     /* To be optimized with precov */
                   13152:   int stepsize;
                   13153:   /* int agelim; */
                   13154:        int ageminl;
                   13155:   int hstepm;
                   13156:   int nhstepm;
                   13157:   int h, i, i1, j, k, nres;
                   13158:        
                   13159:   double agedeb;
                   13160:   double ***p3mat;
                   13161:        
                   13162:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   13163:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   13164:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   13165:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   13166:   }
                   13167:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   13168:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   13169:   
                   13170:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   13171:   /*if (stepm<=24) stepsize=2;*/
                   13172:   
                   13173:   /* agelim=AGESUP; */
                   13174:   ageminl=AGEINF; /* was 30 */
                   13175:   hstepm=stepsize*YEARM; /* Every year of age */
                   13176:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   13177:   
                   13178:   /* hstepm=1;   aff par mois*/
                   13179:   pstamp(ficrespijb);
                   13180:   fprintf(ficrespijb,"#****** h Bij x Back probability to be in state i at age x-h being in j at x: B1j+B2j+...=1 ");
                   13181:   i1= pow(2,cptcoveff);
                   13182:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   13183:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   13184:   /*   k=k+1;  */
                   13185:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   13186:     k=TKresult[nres];
                   13187:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   13188:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   13189:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   13190:     /*         continue; */
                   13191:     fprintf(ficrespijb,"\n#****** ");
                   13192:     for(j=1;j<=cptcovs;j++){
                   13193:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   13194:       /* for(j=1;j<=cptcoveff;j++) */
                   13195:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   13196:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   13197:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   13198:     }
                   13199:     fprintf(ficrespijb,"******\n");
                   13200:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   13201:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   13202:       continue;
                   13203:     }
                   13204:     
                   13205:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   13206:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   13207:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   13208:       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 */
                   13209:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   13210:       
                   13211:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   13212:       
                   13213:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   13214:       /* and memory limitations if stepm is small */
                   13215:       
                   13216:       /* oldm=oldms;savm=savms; */
                   13217:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   13218:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   13219:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   13220:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   13221:       for(i=1; i<=nlstate;i++)
                   13222:        for(j=1; j<=nlstate+ndeath;j++)
                   13223:          fprintf(ficrespijb," %1d-%1d",i,j);
                   13224:       fprintf(ficrespijb,"\n");
                   13225:       for (h=0; h<=nhstepm; h++){
                   13226:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   13227:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   13228:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   13229:        for(i=1; i<=nlstate;i++)
                   13230:          for(j=1; j<=nlstate+ndeath;j++)
                   13231:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
                   13232:        fprintf(ficrespijb,"\n");
                   13233:       }
                   13234:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   13235:       fprintf(ficrespijb,"\n");
                   13236:     } /* end age deb */
                   13237:     /* } /\* end combination *\/ */
                   13238:   } /* end nres */
                   13239:   return 0;
                   13240:  } /*  hBijx */
                   13241: 
                   13242: 
                   13243: /***********************************************/
                   13244: /**************** Main Program *****************/
                   13245: /***********************************************/
                   13246: 
                   13247: int main(int argc, char *argv[])
                   13248: {
                   13249: #ifdef GSL
                   13250:   const gsl_multimin_fminimizer_type *T;
                   13251:   size_t iteri = 0, it;
                   13252:   int rval = GSL_CONTINUE;
                   13253:   int status = GSL_SUCCESS;
                   13254:   double ssval;
                   13255: #endif
                   13256:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
                   13257:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   13258:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
                   13259:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
                   13260:   int jj, ll, li, lj, lk;
                   13261:   int numlinepar=0; /* Current linenumber of parameter file */
                   13262:   int num_filled;
                   13263:   int itimes;
                   13264:   int NDIM=2;
                   13265:   int vpopbased=0;
                   13266:   int nres=0;
                   13267:   int endishere=0;
                   13268:   int noffset=0;
                   13269:   int ncurrv=0; /* Temporary variable */
                   13270:   
                   13271:   char ca[32], cb[32];
                   13272:   /*  FILE *fichtm; *//* Html File */
                   13273:   /* FILE *ficgp;*/ /*Gnuplot File */
                   13274:   struct stat info;
                   13275:   double agedeb=0.;
                   13276: 
                   13277:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
                   13278:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
                   13279: 
                   13280:   double fret;
                   13281:   double dum=0.; /* Dummy variable */
                   13282:   double ***p3mat;
                   13283:   /* double ***mobaverage; */
                   13284:   double wald;
                   13285: 
1.2     ! brouard  13286:   char line[MAXLINE], linetmp[MAXLINE];
1.1       brouard  13287:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   13288: 
                   13289:   char  modeltemp[MAXLINE];
                   13290:   char resultline[MAXLINE], resultlineori[MAXLINE];
                   13291:   
                   13292:   char pathr[MAXLINE], pathimach[MAXLINE]; 
                   13293:   char *tok, *val; /* pathtot */
                   13294:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
                   13295:   int c,  h , cpt, c2;
                   13296:   int jl=0;
                   13297:   int i1, j1, jk, stepsize=0;
                   13298:   int count=0;
                   13299: 
                   13300:   int *tab; 
                   13301:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   13302:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   13303:   /* double anprojf, mprojf, jprojf; */
                   13304:   /* double jintmean,mintmean,aintmean;   */
                   13305:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   13306:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   13307:   double yrfproj= 10.0; /* Number of years of forward projections */
                   13308:   double yrbproj= 10.0; /* Number of years of backward projections */
                   13309:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
                   13310:   int mobilav=0,popforecast=0;
                   13311:   int hstepm=0, nhstepm=0;
                   13312:   int agemortsup;
                   13313:   float  sumlpop=0.;
                   13314:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   13315:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   13316: 
                   13317:   double bage=0, fage=110., age, agelim=0., agebase=0.;
                   13318:   double ftolpl=FTOL;
                   13319:   double **prlim;
                   13320:   double **bprlim;
                   13321:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   13322:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
                   13323:   double ***paramstart; /* Matrix of starting parameter values */
                   13324:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
                   13325:   double **matcov; /* Matrix of covariance */
                   13326:   double **hess; /* Hessian matrix */
                   13327:   double ***delti3; /* Scale */
                   13328:   double *delti; /* Scale */
                   13329:   double ***eij, ***vareij;
                   13330:   double **varpl; /* Variances of prevalence limits by age */
                   13331: 
                   13332:   double *epj, vepp;
                   13333: 
                   13334:   double dateprev1, dateprev2;
                   13335:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   13336:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   13337: 
                   13338: 
                   13339:   double **ximort;
                   13340:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
                   13341:   int *dcwave;
                   13342: 
                   13343:   char z[1]="c";
                   13344: 
                   13345:   /*char  *strt;*/
                   13346:   char strtend[80];
                   13347: 
                   13348: 
                   13349: /*   setlocale (LC_ALL, ""); */
                   13350: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   13351: /*   textdomain (PACKAGE); */
                   13352: /*   setlocale (LC_CTYPE, ""); */
                   13353: /*   setlocale (LC_MESSAGES, ""); */
                   13354: 
                   13355:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
                   13356:   rstart_time = time(NULL);  
                   13357:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   13358:   start_time = *localtime(&rstart_time);
                   13359:   curr_time=start_time;
                   13360:   /*tml = *localtime(&start_time.tm_sec);*/
                   13361:   /* strcpy(strstart,asctime(&tml)); */
                   13362:   strcpy(strstart,asctime(&start_time));
                   13363: 
                   13364: /*  printf("Localtime (at start)=%s",strstart); */
                   13365: /*  tp.tm_sec = tp.tm_sec +86400; */
                   13366: /*  tm = *localtime(&start_time.tm_sec); */
                   13367: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   13368: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   13369: /*   tmg.tm_hour=tmg.tm_hour + 1; */
                   13370: /*   tp.tm_sec = mktime(&tmg); */
                   13371: /*   strt=asctime(&tmg); */
                   13372: /*   printf("Time(after) =%s",strstart);  */
                   13373: /*  (void) time (&time_value);
                   13374: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   13375: *  tm = *localtime(&time_value);
                   13376: *  strstart=asctime(&tm);
                   13377: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   13378: */
                   13379: 
                   13380:   nberr=0; /* Number of errors and warnings */
                   13381:   nbwarn=0;
                   13382: #ifdef WIN32
                   13383:   _getcwd(pathcd, size);
                   13384: #else
                   13385:   getcwd(pathcd, size);
                   13386: #endif
                   13387:   syscompilerinfo(0);
1.2     ! brouard  13388:   printf("\nIMaCh prax version %s, %s\n%s",version, copyright, fullversion);
1.1       brouard  13389:   if(argc <=1){
                   13390:     printf("\nEnter the parameter file name: ");
                   13391:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   13392:       printf("ERROR Empty parameter file name\n");
                   13393:       goto end;
                   13394:     }
                   13395:     i=strlen(pathr);
                   13396:     if(pathr[i-1]=='\n')
                   13397:       pathr[i-1]='\0';
                   13398:     i=strlen(pathr);
                   13399:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
                   13400:       pathr[i-1]='\0';
                   13401:     }
                   13402:     i=strlen(pathr);
                   13403:     if( i==0 ){
                   13404:       printf("ERROR Empty parameter file name\n");
                   13405:       goto end;
                   13406:     }
                   13407:     for (tok = pathr; tok != NULL; ){
                   13408:       printf("Pathr |%s|\n",pathr);
                   13409:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   13410:       printf("val= |%s| pathr=%s\n",val,pathr);
                   13411:       strcpy (pathtot, val);
                   13412:       if(pathr[0] == '\0') break; /* Dirty */
                   13413:     }
                   13414:   }
                   13415:   else if (argc<=2){
                   13416:     strcpy(pathtot,argv[1]);
                   13417:   }
                   13418:   else{
                   13419:     strcpy(pathtot,argv[1]);
                   13420:     strcpy(z,argv[2]);
                   13421:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
                   13422:   }
                   13423:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   13424:   /*cygwin_split_path(pathtot,path,optionfile);
                   13425:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   13426:   /* cutv(path,optionfile,pathtot,'\\');*/
                   13427: 
                   13428:   /* Split argv[0], imach program to get pathimach */
                   13429:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   13430:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   13431:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   13432:  /*   strcpy(pathimach,argv[0]); */
                   13433:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   13434:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   13435:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
                   13436: #ifdef WIN32
                   13437:   _chdir(path); /* Can be a relative path */
                   13438:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   13439: #else
                   13440:   chdir(path); /* Can be a relative path */
                   13441:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   13442: #endif
                   13443:   printf("Current directory %s!\n",pathcd);
                   13444:   strcpy(command,"mkdir ");
                   13445:   strcat(command,optionfilefiname);
                   13446:   if((outcmd=system(command)) != 0){
                   13447:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
                   13448:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   13449:     /* fclose(ficlog); */
                   13450: /*     exit(1); */
                   13451:   }
                   13452: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   13453: /*     perror("mkdir"); */
                   13454: /*   } */
                   13455: 
                   13456:   /*-------- arguments in the command line --------*/
                   13457: 
                   13458:   /* Main Log file */
                   13459:   strcat(filelog, optionfilefiname);
                   13460:   strcat(filelog,".log");    /* */
                   13461:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   13462:     printf("Problem with logfile %s\n",filelog);
                   13463:     goto end;
                   13464:   }
                   13465:   fprintf(ficlog,"Log filename:%s\n",filelog);
                   13466:   fprintf(ficlog,"Version %s %s",version,fullversion);
                   13467:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   13468:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   13469:  path=%s \n\
                   13470:  optionfile=%s\n\
                   13471:  optionfilext=%s\n\
                   13472:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
                   13473: 
                   13474:   syscompilerinfo(1);
                   13475: 
                   13476:   printf("Local time (at start):%s",strstart);
                   13477:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   13478:   fflush(ficlog);
                   13479: /*   (void) gettimeofday(&curr_time,&tzp); */
                   13480: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
                   13481: 
                   13482:   /* */
                   13483:   strcpy(fileres,"r");
                   13484:   strcat(fileres, optionfilefiname);
                   13485:   strcat(fileresu, optionfilefiname); /* Without r in front */
                   13486:   strcat(fileres,".txt");    /* Other files have txt extension */
                   13487:   strcat(fileresu,".txt");    /* Other files have txt extension */
                   13488: 
                   13489:   /* Main ---------arguments file --------*/
                   13490: 
                   13491:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
                   13492:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   13493:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   13494:     fflush(ficlog);
                   13495:     /* goto end; */
                   13496:     exit(70); 
                   13497:   }
                   13498: 
                   13499:   strcpy(filereso,"o");
                   13500:   strcat(filereso,fileresu);
                   13501:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   13502:     printf("Problem with Output resultfile: %s\n", filereso);
                   13503:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   13504:     fflush(ficlog);
                   13505:     goto end;
                   13506:   }
                   13507:       /*-------- Rewriting parameter file ----------*/
                   13508:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   13509:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   13510:   strcat(rfileres,".");    /* */
                   13511:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   13512:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   13513:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   13514:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   13515:     fflush(ficlog);
                   13516:     goto end;
                   13517:   }
                   13518:   fprintf(ficres,"#IMaCh %s\n",version);
                   13519: 
                   13520:                                      
                   13521:   /* Reads comments: lines beginning with '#' */
                   13522:   numlinepar=0;
                   13523:   /* Is it a BOM UTF-8 Windows file? */
                   13524:   /* First parameter line */
                   13525:   while(fgets(line, MAXLINE, ficpar)) {
                   13526:     noffset=0;
                   13527:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   13528:     {
                   13529:       noffset=noffset+3;
                   13530:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   13531:     }
                   13532: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   13533:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   13534:     {
                   13535:       noffset=noffset+2;
                   13536:       printf("# File is an UTF16BE BOM file\n");
                   13537:     }
                   13538:     else if( line[0] == 0 && line[1] == 0)
                   13539:     {
                   13540:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   13541:        noffset=noffset+4;
                   13542:        printf("# File is an UTF16BE BOM file\n");
                   13543:       }
                   13544:     } else{
                   13545:       ;/*printf(" Not a BOM file\n");*/
                   13546:     }
                   13547:   
                   13548:     /* If line starts with a # it is a comment */
                   13549:     if (line[noffset] == '#') {
                   13550:       numlinepar++;
                   13551:       fputs(line,stdout);
                   13552:       fputs(line,ficparo);
                   13553:       fputs(line,ficres);
                   13554:       fputs(line,ficlog);
                   13555:       continue;
                   13556:     }else
                   13557:       break;
                   13558:   }
                   13559:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   13560:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   13561:     if (num_filled != 5) {
                   13562:       printf("Should be 5 parameters\n");
                   13563:       fprintf(ficlog,"Should be 5 parameters\n");
                   13564:     }
                   13565:     numlinepar++;
                   13566:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13567:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13568:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13569:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13570:   }
                   13571:   /* Second parameter line */
                   13572:   while(fgets(line, MAXLINE, ficpar)) {
                   13573:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   13574:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
                   13575:     if (line[0] == '#') {
                   13576:       numlinepar++;
                   13577:       printf("%s",line);
                   13578:       fprintf(ficres,"%s",line);
                   13579:       fprintf(ficparo,"%s",line);
                   13580:       fprintf(ficlog,"%s",line);
                   13581:       continue;
                   13582:     }else
                   13583:       break;
                   13584:   }
                   13585:   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", \
                   13586:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   13587:     if (num_filled != 11) {
                   13588:       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");
                   13589:       printf("but line=%s\n",line);
                   13590:       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");
                   13591:       fprintf(ficlog,"but line=%s\n",line);
                   13592:     }
                   13593:     if( lastpass > maxwav){
                   13594:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   13595:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   13596:       fflush(ficlog);
                   13597:       goto end;
                   13598:     }
                   13599:       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);
                   13600:     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);
                   13601:     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);
                   13602:     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);
                   13603:   }
                   13604:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   13605:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   13606:   /* Third parameter line */
                   13607:   while(fgets(line, MAXLINE, ficpar)) {
                   13608:     /* If line starts with a # it is a comment */
                   13609:     if (line[0] == '#') {
                   13610:       numlinepar++;
                   13611:       printf("%s",line);
                   13612:       fprintf(ficres,"%s",line);
                   13613:       fprintf(ficparo,"%s",line);
                   13614:       fprintf(ficlog,"%s",line);
                   13615:       continue;
                   13616:     }else
                   13617:       break;
                   13618:   }
1.2     ! brouard  13619:   if((num_filled=sscanf(line,"model=%[^.\n]", model)) !=EOF){ /* Every character after model but dot and  return */
        !          13620:     if (num_filled != 1){
        !          13621:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
        !          13622:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
        !          13623:       model[0]='\0';
        !          13624:       goto end;
        !          13625:     }else{
        !          13626:       trimbtab(linetmp,line); /* Trims multiple blanks in line */
        !          13627:       strcpy(line, linetmp);
        !          13628:     }
        !          13629:   }
        !          13630:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){ /* Every character after 1+age but dot and  return */
1.1       brouard  13631:     if (num_filled != 1){
                   13632:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13633:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13634:       model[0]='\0';
                   13635:       goto end;
                   13636:     }
                   13637:     else{
                   13638:       if (model[0]=='+'){
                   13639:        for(i=1; i<=strlen(model);i++)
                   13640:          modeltemp[i-1]=model[i];
                   13641:        strcpy(model,modeltemp); 
                   13642:       }
                   13643:     }
                   13644:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
                   13645:     printf("model=1+age+%s\n",model);fflush(stdout);
                   13646:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   13647:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   13648:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
                   13649:   }
                   13650:   /* 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); */
                   13651:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   13652:   /* 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); */
                   13653:   /* 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); */
                   13654:   /* 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); */
                   13655:   fflush(ficlog);
                   13656:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   13657:   if(model[0]=='#'){
                   13658:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   13659:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   13660:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
                   13661:     if(mle != -1){
                   13662:       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");
                   13663:       exit(1);
                   13664:     }
                   13665:   }
                   13666:   while((c=getc(ficpar))=='#' && c!= EOF){
                   13667:     ungetc(c,ficpar);
                   13668:     fgets(line, MAXLINE, ficpar);
                   13669:     numlinepar++;
                   13670:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   13671:       z[0]=line[1];
                   13672:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
                   13673:       debugILK=1;printf("DebugILK\n");
                   13674:     }
                   13675:     /* printf("****line [1] = %c \n",line[1]); */
                   13676:     fputs(line, stdout);
                   13677:     //puts(line);
                   13678:     fputs(line,ficparo);
                   13679:     fputs(line,ficlog);
                   13680:   }
                   13681:   ungetc(c,ficpar);
                   13682: 
                   13683:    
                   13684:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   13685:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   13686:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
                   13687:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
                   13688:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
                   13689:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   13690:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   13691:      v1+v2*age+v2*v3 makes cptcovn = 3
                   13692:   */
                   13693:   if (strlen(model)>1) 
                   13694:     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*/
                   13695:   else
                   13696:     ncovmodel=2; /* Constant and age */
                   13697:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   13698:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
                   13699:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   13700:     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);
                   13701:     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);
                   13702:     fflush(stdout);
                   13703:     fclose (ficlog);
                   13704:     goto end;
                   13705:   }
                   13706:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13707:   delti=delti3[1][1];
                   13708:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   13709:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   13710: /* We could also provide initial parameters values giving by simple logistic regression 
                   13711:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   13712:       /* for(i=1;i<nlstate;i++){ */
                   13713:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13714:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13715:       /* } */
                   13716:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   13717:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   13718:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   13719:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   13720:     fclose (ficparo);
                   13721:     fclose (ficlog);
                   13722:     goto end;
                   13723:     exit(0);
                   13724:   }  else if(mle==-5) { /* Main Wizard */
                   13725:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   13726:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   13727:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   13728:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13729:     matcov=matrix(1,npar,1,npar);
                   13730:     hess=matrix(1,npar,1,npar);
                   13731:   }  else{ /* Begin of mle != -1 or -5 */
                   13732:     /* Read guessed parameters */
                   13733:     /* Reads comments: lines beginning with '#' */
                   13734:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13735:       ungetc(c,ficpar);
                   13736:       fgets(line, MAXLINE, ficpar);
                   13737:       numlinepar++;
                   13738:       fputs(line,stdout);
                   13739:       fputs(line,ficparo);
                   13740:       fputs(line,ficlog);
                   13741:     }
                   13742:     ungetc(c,ficpar);
                   13743:     
                   13744:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13745:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13746:     for(i=1; i <=nlstate; i++){
                   13747:       j=0;
                   13748:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   13749:        if(jj==i) continue;
                   13750:        j++;
                   13751:        while((c=getc(ficpar))=='#' && c!= EOF){
                   13752:          ungetc(c,ficpar);
                   13753:          fgets(line, MAXLINE, ficpar);
                   13754:          numlinepar++;
                   13755:          fputs(line,stdout);
                   13756:          fputs(line,ficparo);
                   13757:          fputs(line,ficlog);
                   13758:        }
                   13759:        ungetc(c,ficpar);
                   13760:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   13761:        if ((i1 != i) || (j1 != jj)){
                   13762:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   13763: It might be a problem of design; if ncovcol and the model are correct\n \
                   13764: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   13765:          exit(1);
                   13766:        }
                   13767:        fprintf(ficparo,"%1d%1d",i1,j1);
                   13768:        if(mle==1)
                   13769:          printf("%1d%1d",i,jj);
                   13770:        fprintf(ficlog,"%1d%1d",i,jj);
                   13771:        for(k=1; k<=ncovmodel;k++){
                   13772:          fscanf(ficpar," %lf",&param[i][j][k]);
                   13773:          if(mle==1){
                   13774:            printf(" %lf",param[i][j][k]);
                   13775:            fprintf(ficlog," %lf",param[i][j][k]);
                   13776:          }
                   13777:          else
                   13778:            fprintf(ficlog," %lf",param[i][j][k]);
                   13779:          fprintf(ficparo," %lf",param[i][j][k]);
                   13780:        }
                   13781:        fscanf(ficpar,"\n");
                   13782:        numlinepar++;
                   13783:        if(mle==1)
                   13784:          printf("\n");
                   13785:        fprintf(ficlog,"\n");
                   13786:        fprintf(ficparo,"\n");
                   13787:       }
                   13788:     }  
                   13789:     fflush(ficlog);
                   13790:     
                   13791:     /* Reads parameters values */
                   13792:     p=param[1][1];
                   13793:     pstart=paramstart[1][1];
                   13794:     
                   13795:     /* Reads comments: lines beginning with '#' */
                   13796:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13797:       ungetc(c,ficpar);
                   13798:       fgets(line, MAXLINE, ficpar);
                   13799:       numlinepar++;
                   13800:       fputs(line,stdout);
                   13801:       fputs(line,ficparo);
                   13802:       fputs(line,ficlog);
                   13803:     }
                   13804:     ungetc(c,ficpar);
                   13805: 
                   13806:     for(i=1; i <=nlstate; i++){
                   13807:       for(j=1; j <=nlstate+ndeath-1; j++){
                   13808:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   13809:        if ( (i1-i) * (j1-j) != 0){
                   13810:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   13811:          exit(1);
                   13812:        }
                   13813:        printf("%1d%1d",i,j);
                   13814:        fprintf(ficparo,"%1d%1d",i1,j1);
                   13815:        fprintf(ficlog,"%1d%1d",i1,j1);
                   13816:        for(k=1; k<=ncovmodel;k++){
                   13817:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   13818:          printf(" %le",delti3[i][j][k]);
                   13819:          fprintf(ficparo," %le",delti3[i][j][k]);
                   13820:          fprintf(ficlog," %le",delti3[i][j][k]);
                   13821:        }
                   13822:        fscanf(ficpar,"\n");
                   13823:        numlinepar++;
                   13824:        printf("\n");
                   13825:        fprintf(ficparo,"\n");
                   13826:        fprintf(ficlog,"\n");
                   13827:       }
                   13828:     }
                   13829:     fflush(ficlog);
                   13830:     
                   13831:     /* Reads covariance matrix */
                   13832:     delti=delti3[1][1];
                   13833:                
                   13834:                
                   13835:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   13836:                
                   13837:     /* Reads comments: lines beginning with '#' */
                   13838:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13839:       ungetc(c,ficpar);
                   13840:       fgets(line, MAXLINE, ficpar);
                   13841:       numlinepar++;
                   13842:       fputs(line,stdout);
                   13843:       fputs(line,ficparo);
                   13844:       fputs(line,ficlog);
                   13845:     }
                   13846:     ungetc(c,ficpar);
                   13847:                
                   13848:     matcov=matrix(1,npar,1,npar);
                   13849:     hess=matrix(1,npar,1,npar);
                   13850:     for(i=1; i <=npar; i++)
                   13851:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   13852:                
                   13853:     /* Scans npar lines */
                   13854:     for(i=1; i <=npar; i++){
                   13855:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
                   13856:       if(count != 3){
                   13857:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   13858: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   13859: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   13860:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   13861: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   13862: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   13863:        exit(1);
                   13864:       }else{
                   13865:        if(mle==1)
                   13866:          printf("%1d%1d%d",i1,j1,jk);
                   13867:       }
                   13868:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   13869:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
                   13870:       for(j=1; j <=i; j++){
                   13871:        fscanf(ficpar," %le",&matcov[i][j]);
                   13872:        if(mle==1){
                   13873:          printf(" %.5le",matcov[i][j]);
                   13874:        }
                   13875:        fprintf(ficlog," %.5le",matcov[i][j]);
                   13876:        fprintf(ficparo," %.5le",matcov[i][j]);
                   13877:       }
                   13878:       fscanf(ficpar,"\n");
                   13879:       numlinepar++;
                   13880:       if(mle==1)
                   13881:                                printf("\n");
                   13882:       fprintf(ficlog,"\n");
                   13883:       fprintf(ficparo,"\n");
                   13884:     }
                   13885:     /* End of read covariance matrix npar lines */
                   13886:     for(i=1; i <=npar; i++)
                   13887:       for(j=i+1;j<=npar;j++)
                   13888:        matcov[i][j]=matcov[j][i];
                   13889:     
                   13890:     if(mle==1)
                   13891:       printf("\n");
                   13892:     fprintf(ficlog,"\n");
                   13893:     
                   13894:     fflush(ficlog);
                   13895:     
                   13896:   }    /* End of mle != -3 */
                   13897:   
                   13898:   /*  Main data
                   13899:    */
                   13900:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   13901:   /* num=lvector(1,n); */
                   13902:   /* moisnais=vector(1,n); */
                   13903:   /* annais=vector(1,n); */
                   13904:   /* moisdc=vector(1,n); */
                   13905:   /* andc=vector(1,n); */
                   13906:   /* weight=vector(1,n); */
                   13907:   /* agedc=vector(1,n); */
                   13908:   /* cod=ivector(1,n); */
                   13909:   /* for(i=1;i<=n;i++){ */
                   13910:   num=lvector(firstobs,lastobs);
                   13911:   moisnais=vector(firstobs,lastobs);
                   13912:   annais=vector(firstobs,lastobs);
                   13913:   moisdc=vector(firstobs,lastobs);
                   13914:   andc=vector(firstobs,lastobs);
                   13915:   weight=vector(firstobs,lastobs);
                   13916:   agedc=vector(firstobs,lastobs);
                   13917:   cod=ivector(firstobs,lastobs);
                   13918:   for(i=firstobs;i<=lastobs;i++){
                   13919:     num[i]=0;
                   13920:     moisnais[i]=0;
                   13921:     annais[i]=0;
                   13922:     moisdc[i]=0;
                   13923:     andc[i]=0;
                   13924:     agedc[i]=0;
                   13925:     cod[i]=0;
                   13926:     weight[i]=1.0; /* Equal weights, 1 by default */
                   13927:   }
                   13928:   mint=matrix(1,maxwav,firstobs,lastobs);
                   13929:   anint=matrix(1,maxwav,firstobs,lastobs);
                   13930:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
                   13931:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
                   13932:   tab=ivector(1,NCOVMAX);
                   13933:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
                   13934:   ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
                   13935: 
                   13936:   /* Reads data from file datafile */
                   13937:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   13938:     goto end;
                   13939: 
                   13940:   /* Calculation of the number of parameters from char model */
                   13941:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   13942:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   13943:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   13944:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   13945:        k=1 Tvar[1]=2 (from V2)
                   13946:   */
                   13947:   
                   13948:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   13949:   TvarsDind=ivector(1,NCOVMAX); /*  */
                   13950:   TnsdVar=ivector(1,NCOVMAX); /*  */
                   13951:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
                   13952:   TvarsD=ivector(1,NCOVMAX); /*  */
                   13953:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   13954:   TvarsQ=ivector(1,NCOVMAX); /*  */
                   13955:   TvarF=ivector(1,NCOVMAX); /*  */
                   13956:   TvarFind=ivector(1,NCOVMAX); /*  */
                   13957:   TvarV=ivector(1,NCOVMAX); /*  */
                   13958:   TvarVind=ivector(1,NCOVMAX); /*  */
                   13959:   TvarA=ivector(1,NCOVMAX); /*  */
                   13960:   TvarAind=ivector(1,NCOVMAX); /*  */
                   13961:   TvarFD=ivector(1,NCOVMAX); /*  */
                   13962:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   13963:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   13964:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   13965:   TvarVD=ivector(1,NCOVMAX); /*  */
                   13966:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   13967:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   13968:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   13969:   TvarVV=ivector(1,NCOVMAX); /*  */
                   13970:   TvarVVind=ivector(1,NCOVMAX); /*  */
                   13971:   TvarVVA=ivector(1,NCOVMAX); /*  */
                   13972:   TvarVVAind=ivector(1,NCOVMAX); /*  */
                   13973:   TvarAVVA=ivector(1,NCOVMAX); /*  */
                   13974:   TvarAVVAind=ivector(1,NCOVMAX); /*  */
                   13975: 
                   13976:   Tvalsel=vector(1,NCOVMAX); /*  */
                   13977:   Tvarsel=ivector(1,NCOVMAX); /*  */
                   13978:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   13979:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   13980:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
                   13981:   DummyV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   13982:   FixedV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   13983: 
                   13984:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   13985:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   13986:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   13987:   */
                   13988:   /* For model-covariate k tells which data-covariate to use but
                   13989:     because this model-covariate is a construction we invent a new column
                   13990:     ncovcol + k1
                   13991:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   13992:     Tvar[3=V1*V4]=4+1 etc */
                   13993:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   13994:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
                   13995:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   13996:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   13997:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
                   13998:   */
                   13999:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   14000:   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
                   14001:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   14002:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.2     ! brouard  14003:   Tvardk=imatrix(0,NCOVMAX,1,2);
1.1       brouard  14004:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
                   14005:                         4 covariates (3 plus signs)
                   14006:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   14007:                           */  
                   14008:   for(i=1;i<NCOVMAX;i++)
                   14009:     Tage[i]=0;
                   14010:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
                   14011:                                * individual dummy, fixed or varying:
                   14012:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   14013:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   14014:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   14015:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   14016:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   14017:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   14018:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
                   14019:                                * individual quantitative, fixed or varying:
                   14020:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   14021:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   14022:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
                   14023: 
                   14024: /* Probably useless zeroes */
                   14025:   for(i=1;i<NCOVMAX;i++){
                   14026:     DummyV[i]=0;
                   14027:     FixedV[i]=0;
                   14028:   }
                   14029: 
                   14030:   for(i=1; i <=ncovcol;i++){
                   14031:     DummyV[i]=0;
                   14032:     FixedV[i]=0;
                   14033:   }
                   14034:   for(i=ncovcol+1; i <=ncovcol+nqv;i++){
                   14035:     DummyV[i]=1;
                   14036:     FixedV[i]=0;
                   14037:   }
                   14038:   for(i=ncovcol+nqv+1; i <=ncovcol+nqv+ntv;i++){
                   14039:     DummyV[i]=0;
                   14040:     FixedV[i]=1;
                   14041:   }
                   14042:   for(i=ncovcol+nqv+ntv+1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   14043:     DummyV[i]=1;
                   14044:     FixedV[i]=1;
                   14045:   }
                   14046:   for(i=1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   14047:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",i,i,DummyV[i],i,FixedV[i]);
                   14048:     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]);
                   14049:   }
                   14050: 
                   14051: 
                   14052: 
                   14053: /* Main decodemodel */
                   14054: 
                   14055: 
                   14056:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
                   14057:     goto end;
                   14058: 
                   14059:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   14060:     nbwarn++;
                   14061:     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); 
                   14062:     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); 
                   14063:   }
                   14064:     /*  if(mle==1){*/
                   14065:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   14066:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
                   14067:   }
                   14068: 
                   14069:     /*-calculation of age at interview from date of interview and age at death -*/
                   14070:   agev=matrix(1,maxwav,1,imx);
                   14071: 
                   14072:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   14073:     goto end;
                   14074: 
                   14075: 
                   14076:   agegomp=(int)agemin;
                   14077:   free_vector(moisnais,firstobs,lastobs);
                   14078:   free_vector(annais,firstobs,lastobs);
                   14079:   /* free_matrix(mint,1,maxwav,1,n);
                   14080:      free_matrix(anint,1,maxwav,1,n);*/
                   14081:   /* free_vector(moisdc,1,n); */
                   14082:   /* free_vector(andc,1,n); */
                   14083:   /* */
                   14084:   
                   14085:   wav=ivector(1,imx);
                   14086:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   14087:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   14088:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   14089:   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.*/
                   14090:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   14091:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
                   14092:    
                   14093:   /* Concatenates waves */
                   14094:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   14095:      Death is a valid wave (if date is known).
                   14096:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   14097:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   14098:      and mw[mi+1][i]. dh depends on stepm.
                   14099:   */
                   14100: 
                   14101:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
                   14102:   /* Concatenates waves */
                   14103:  
                   14104:   free_vector(moisdc,firstobs,lastobs);
                   14105:   free_vector(andc,firstobs,lastobs);
                   14106: 
                   14107:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   14108:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   14109:   ncodemax[1]=1;
                   14110:   Ndum =ivector(-1,NCOVMAX);  
                   14111:   cptcoveff=0;
                   14112:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   14113:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; as well as calculate cptcoveff or number of total effective dummy covariates*/
                   14114:   }
                   14115:   
                   14116:   ncovcombmax=pow(2,cptcoveff);
                   14117:   invalidvarcomb=ivector(0, ncovcombmax); 
                   14118:   for(i=0;i<ncovcombmax;i++)
                   14119:     invalidvarcomb[i]=0;
                   14120:   
                   14121:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
                   14122:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
                   14123:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
                   14124:   
                   14125:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
                   14126:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
                   14127:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
                   14128:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   14129:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   14130:    * (currently 0 or 1) in the data.
                   14131:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   14132:    * corresponding modality (h,j).
                   14133:    */
                   14134: 
                   14135:   h=0;
                   14136:   /*if (cptcovn > 0) */
                   14137:   m=pow(2,cptcoveff);
                   14138:  
                   14139:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
                   14140:           * For k=4 covariates, h goes from 1 to m=2**k
                   14141:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   14142:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   14143:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   14144:           *______________________________   *______________________
                   14145:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   14146:           *     2     2     1     1     1   *     1     0  0  0  1 
                   14147:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   14148:           *     4     2     2     1     1   *     3     0  0  1  1 
                   14149:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   14150:           *     6     2     1     2     1   *     5     0  1  0  1 
                   14151:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   14152:           *     8     2     2     2     1   *     7     0  1  1  1 
                   14153:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   14154:           *    10     2     1     1     2   *     9     1  0  0  1 
                   14155:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   14156:           *    12     2     2     1     2   *    11     1  0  1  1 
                   14157:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   14158:           *    14     2     1     2     2   *    13     1  1  0  1 
                   14159:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   14160:           *    16     2     2     2     2   *    15     1  1  1  1          
                   14161:           */                                     
                   14162:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
                   14163:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   14164:      * and the value of each covariate?
                   14165:      * V1=1, V2=1, V3=2, V4=1 ?
                   14166:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   14167:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   14168:      * In order to get the real value in the data, we use nbcode
                   14169:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   14170:      * We are keeping this crazy system in order to be able (in the future?) 
                   14171:      * to have more than 2 values (0 or 1) for a covariate.
                   14172:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   14173:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   14174:      *              bbbbbbbb
                   14175:      *              76543210     
                   14176:      *   h-1        00000101 (6-1=5)
                   14177:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
                   14178:      *           &
                   14179:      *     1        00000001 (1)
                   14180:      *              00000000        = 1 & ((h-1) >> (k-1))
                   14181:      *          +1= 00000001 =1 
                   14182:      *
                   14183:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   14184:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   14185:      *    >>k'            11
                   14186:      *          &   00000001
                   14187:      *            = 00000001
                   14188:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   14189:      * Reverse h=6 and m=16?
                   14190:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   14191:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   14192:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   14193:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   14194:      * V3=decodtabm(14,3,2**4)=2
                   14195:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   14196:      *(h-1) >> (j-1)    0011 =13 >> 2
                   14197:      *          &1 000000001
                   14198:      *           = 000000001
                   14199:      *         +1= 000000010 =2
                   14200:      *                  2211
                   14201:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   14202:      *                  V3=2
                   14203:                 * codtabm and decodtabm are identical
                   14204:      */
                   14205: 
                   14206: 
                   14207:  free_ivector(Ndum,-1,NCOVMAX);
                   14208: 
                   14209: 
                   14210:     
                   14211:   /* Initialisation of ----------- gnuplot -------------*/
                   14212:   strcpy(optionfilegnuplot,optionfilefiname);
                   14213:   if(mle==-3)
                   14214:     strcat(optionfilegnuplot,"-MORT_");
                   14215:   strcat(optionfilegnuplot,".gp");
                   14216: 
                   14217:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   14218:     printf("Problem with file %s",optionfilegnuplot);
                   14219:   }
                   14220:   else{
                   14221:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
                   14222:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
                   14223:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   14224:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
                   14225:   }
                   14226:   /*  fclose(ficgp);*/
                   14227: 
                   14228: 
                   14229:   /* Initialisation of --------- index.htm --------*/
                   14230: 
                   14231:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   14232:   if(mle==-3)
                   14233:     strcat(optionfilehtm,"-MORT_");
                   14234:   strcat(optionfilehtm,".htm");
                   14235:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
                   14236:     printf("Problem with %s \n",optionfilehtm);
                   14237:     exit(0);
                   14238:   }
                   14239: 
                   14240:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   14241:   strcat(optionfilehtmcov,"-cov.htm");
                   14242:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   14243:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   14244:   }
                   14245:   else{
                   14246:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   14247: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   14248: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
                   14249:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   14250:   }
                   14251: 
                   14252:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   14253: <title>IMaCh %s</title></head>\n\
                   14254:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   14255: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   14256: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   14257: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   14258: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   14259:   
                   14260:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
                   14261: <font size=\"2\">IMaCh-%s <br> %s</font> \
                   14262: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   14263: 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\
                   14264: \n\
                   14265: <hr  size=\"2\" color=\"#EC5E5E\">\
                   14266:  <ul><li><h4>Parameter files</h4>\n\
                   14267:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   14268:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   14269:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   14270:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   14271:  - Date and time at start: %s</ul>\n",\
                   14272:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
                   14273:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   14274:          fileres,fileres,\
                   14275:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   14276:   fflush(fichtm);
                   14277: 
                   14278:   strcpy(pathr,path);
                   14279:   strcat(pathr,optionfilefiname);
                   14280: #ifdef WIN32
                   14281:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   14282: #else
                   14283:   chdir(optionfilefiname); /* Move to directory named optionfile */
                   14284: #endif
                   14285:          
                   14286:   
                   14287:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   14288:                 and for any valid combination of covariates
                   14289:      and prints on file fileres'p'. */
                   14290:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
                   14291:              firstpass, lastpass,  stepm,  weightopt, model);
                   14292: 
                   14293:   fprintf(fichtm,"\n");
                   14294:   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",\
                   14295:          ftol, stepm);
                   14296:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   14297:   ncurrv=1;
                   14298:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   14299:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   14300:   ncurrv=i;
                   14301:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
                   14302:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
                   14303:   ncurrv=i;
                   14304:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
                   14305:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
                   14306:   ncurrv=i;
                   14307:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   14308:   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", \
                   14309:           nlstate, ndeath, maxwav, mle, weightopt);
                   14310: 
                   14311:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   14312: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   14313: 
                   14314:   
                   14315:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
                   14316: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   14317: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   14318:   imx,agemin,agemax,jmin,jmax,jmean);
                   14319:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14320:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14321:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14322:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14323:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   14324: 
                   14325:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   14326:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   14327:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   14328: 
                   14329:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
                   14330:   /* For mortality only */
                   14331:   if (mle==-3){
                   14332:     ximort=matrix(1,NDIM,1,NDIM); 
                   14333:     for(i=1;i<=NDIM;i++)
                   14334:       for(j=1;j<=NDIM;j++)
                   14335:        ximort[i][j]=0.;
                   14336:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
                   14337:     cens=ivector(firstobs,lastobs);
                   14338:     ageexmed=vector(firstobs,lastobs);
                   14339:     agecens=vector(firstobs,lastobs);
                   14340:     dcwave=ivector(firstobs,lastobs);
                   14341:                
                   14342:     for (i=1; i<=imx; i++){
                   14343:       dcwave[i]=-1;
                   14344:       for (m=firstpass; m<=lastpass; m++)
                   14345:        if (s[m][i]>nlstate) {
                   14346:          dcwave[i]=m;
                   14347:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   14348:          break;
                   14349:        }
                   14350:     }
                   14351:     
                   14352:     for (i=1; i<=imx; i++) {
                   14353:       if (wav[i]>0){
                   14354:        ageexmed[i]=agev[mw[1][i]][i];
                   14355:        j=wav[i];
                   14356:        agecens[i]=1.; 
                   14357:        
                   14358:        if (ageexmed[i]> 1 && wav[i] > 0){
                   14359:          agecens[i]=agev[mw[j][i]][i];
                   14360:          cens[i]= 1;
                   14361:        }else if (ageexmed[i]< 1) 
                   14362:          cens[i]= -1;
                   14363:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   14364:          cens[i]=0 ;
                   14365:       }
                   14366:       else cens[i]=-1;
                   14367:     }
                   14368:     
                   14369:     for (i=1;i<=NDIM;i++) {
                   14370:       for (j=1;j<=NDIM;j++)
                   14371:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   14372:     }
                   14373:     
                   14374:     p[1]=0.0268; p[NDIM]=0.083;
                   14375:     /* printf("%lf %lf", p[1], p[2]); */
                   14376:     
                   14377:     
                   14378: #ifdef GSL
                   14379:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
                   14380: #else
                   14381:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
                   14382: #endif
                   14383:     strcpy(filerespow,"POW-MORT_"); 
                   14384:     strcat(filerespow,fileresu);
                   14385:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   14386:       printf("Problem with resultfile: %s\n", filerespow);
                   14387:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   14388:     }
                   14389: #ifdef GSL
                   14390:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
                   14391: #else
                   14392:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   14393: #endif
                   14394:     /*  for (i=1;i<=nlstate;i++)
                   14395:        for(j=1;j<=nlstate+ndeath;j++)
                   14396:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   14397:     */
                   14398:     fprintf(ficrespow,"\n");
                   14399: #ifdef GSL
                   14400:     /* gsl starts here */ 
                   14401:     T = gsl_multimin_fminimizer_nmsimplex;
                   14402:     gsl_multimin_fminimizer *sfm = NULL;
                   14403:     gsl_vector *ss, *x;
                   14404:     gsl_multimin_function minex_func;
                   14405: 
                   14406:     /* Initial vertex size vector */
                   14407:     ss = gsl_vector_alloc (NDIM);
                   14408:     
                   14409:     if (ss == NULL){
                   14410:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   14411:     }
                   14412:     /* Set all step sizes to 1 */
                   14413:     gsl_vector_set_all (ss, 0.001);
                   14414: 
                   14415:     /* Starting point */
                   14416:     
                   14417:     x = gsl_vector_alloc (NDIM);
                   14418:     
                   14419:     if (x == NULL){
                   14420:       gsl_vector_free(ss);
                   14421:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   14422:     }
                   14423:   
                   14424:     /* Initialize method and iterate */
                   14425:     /*     p[1]=0.0268; p[NDIM]=0.083; */
                   14426:     /*     gsl_vector_set(x, 0, 0.0268); */
                   14427:     /*     gsl_vector_set(x, 1, 0.083); */
                   14428:     gsl_vector_set(x, 0, p[1]);
                   14429:     gsl_vector_set(x, 1, p[2]);
                   14430: 
                   14431:     minex_func.f = &gompertz_f;
                   14432:     minex_func.n = NDIM;
                   14433:     minex_func.params = (void *)&p; /* ??? */
                   14434:     
                   14435:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   14436:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   14437:     
                   14438:     printf("Iterations beginning .....\n\n");
                   14439:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   14440: 
                   14441:     iteri=0;
                   14442:     while (rval == GSL_CONTINUE){
                   14443:       iteri++;
                   14444:       status = gsl_multimin_fminimizer_iterate(sfm);
                   14445:       
                   14446:       if (status) printf("error: %s\n", gsl_strerror (status));
                   14447:       fflush(0);
                   14448:       
                   14449:       if (status) 
                   14450:         break;
                   14451:       
                   14452:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   14453:       ssval = gsl_multimin_fminimizer_size (sfm);
                   14454:       
                   14455:       if (rval == GSL_SUCCESS)
                   14456:         printf ("converged to a local maximum at\n");
                   14457:       
                   14458:       printf("%5d ", iteri);
                   14459:       for (it = 0; it < NDIM; it++){
                   14460:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   14461:       }
                   14462:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   14463:     }
                   14464:     
                   14465:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   14466:     
                   14467:     gsl_vector_free(x); /* initial values */
                   14468:     gsl_vector_free(ss); /* inital step size */
                   14469:     for (it=0; it<NDIM; it++){
                   14470:       p[it+1]=gsl_vector_get(sfm->x,it);
                   14471:       fprintf(ficrespow," %.12lf", p[it]);
                   14472:     }
                   14473:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   14474: #endif
                   14475: #ifdef POWELL
                   14476:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   14477: #endif  
                   14478:     fclose(ficrespow);
                   14479:     
                   14480:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
                   14481: 
                   14482:     for(i=1; i <=NDIM; i++)
                   14483:       for(j=i+1;j<=NDIM;j++)
                   14484:                                matcov[i][j]=matcov[j][i];
                   14485:     
                   14486:     printf("\nCovariance matrix\n ");
                   14487:     fprintf(ficlog,"\nCovariance matrix\n ");
                   14488:     for(i=1; i <=NDIM; i++) {
                   14489:       for(j=1;j<=NDIM;j++){ 
                   14490:                                printf("%f ",matcov[i][j]);
                   14491:                                fprintf(ficlog,"%f ",matcov[i][j]);
                   14492:       }
                   14493:       printf("\n ");  fprintf(ficlog,"\n ");
                   14494:     }
                   14495:     
                   14496:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
                   14497:     for (i=1;i<=NDIM;i++) {
                   14498:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   14499:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   14500:     }
                   14501:     lsurv=vector(agegomp,AGESUP);
                   14502:     lpop=vector(agegomp,AGESUP);
                   14503:     tpop=vector(agegomp,AGESUP);
                   14504:     lsurv[agegomp]=100000;
                   14505:     
                   14506:     for (k=agegomp;k<=AGESUP;k++) {
                   14507:       agemortsup=k;
                   14508:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   14509:     }
                   14510:     
                   14511:     for (k=agegomp;k<agemortsup;k++)
                   14512:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   14513:     
                   14514:     for (k=agegomp;k<agemortsup;k++){
                   14515:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   14516:       sumlpop=sumlpop+lpop[k];
                   14517:     }
                   14518:     
                   14519:     tpop[agegomp]=sumlpop;
                   14520:     for (k=agegomp;k<(agemortsup-3);k++){
                   14521:       /*  tpop[k+1]=2;*/
                   14522:       tpop[k+1]=tpop[k]-lpop[k];
                   14523:     }
                   14524:     
                   14525:     
                   14526:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   14527:     for (k=agegomp;k<(agemortsup-2);k++) 
                   14528:       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]);
                   14529:     
                   14530:     
                   14531:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   14532:                ageminpar=50;
                   14533:                agemaxpar=100;
                   14534:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   14535:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   14536: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14537: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   14538:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   14539: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14540: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   14541:     }else{
                   14542:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   14543:                        fprintf(ficlog,"Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   14544:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   14545:                }
                   14546:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
                   14547:                     stepm, weightopt,\
                   14548:                     model,imx,p,matcov,agemortsup);
                   14549:     
                   14550:     free_vector(lsurv,agegomp,AGESUP);
                   14551:     free_vector(lpop,agegomp,AGESUP);
                   14552:     free_vector(tpop,agegomp,AGESUP);
                   14553:     free_matrix(ximort,1,NDIM,1,NDIM);
                   14554:     free_ivector(dcwave,firstobs,lastobs);
                   14555:     free_vector(agecens,firstobs,lastobs);
                   14556:     free_vector(ageexmed,firstobs,lastobs);
                   14557:     free_ivector(cens,firstobs,lastobs);
                   14558: #ifdef GSL
                   14559: #endif
                   14560:   } /* Endof if mle==-3 mortality only */
                   14561:   /* Standard  */
                   14562:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   14563:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   14564:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   14565:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   14566:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   14567:     for (k=1; k<=npar;k++)
                   14568:       printf(" %d %8.5f",k,p[k]);
                   14569:     printf("\n");
                   14570:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   14571:       /* mlikeli uses func not funcone */
                   14572:       /* for(i=1;i<nlstate;i++){ */
                   14573:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   14574:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   14575:       /* } */
                   14576:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   14577:     }
                   14578:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   14579:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   14580:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   14581:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   14582:     }
                   14583:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
                   14584:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   14585:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   14586:           /* exit(0); */
                   14587:     for (k=1; k<=npar;k++)
                   14588:       printf(" %d %8.5f",k,p[k]);
                   14589:     printf("\n");
                   14590:     
                   14591:     /*--------- results files --------------*/
                   14592:     /* 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); */
                   14593:     
                   14594:     
                   14595:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   14596:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
                   14597:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   14598: 
                   14599:     printf("#model=  1      +     age ");
                   14600:     fprintf(ficres,"#model=  1      +     age ");
                   14601:     fprintf(ficlog,"#model=  1      +     age ");
                   14602:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   14603: </ul>", model);
                   14604: 
                   14605:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   14606:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   14607:     if(nagesqr==1){
                   14608:       printf("  + age*age  ");
                   14609:       fprintf(ficres,"  + age*age  ");
                   14610:       fprintf(ficlog,"  + age*age  ");
                   14611:       fprintf(fichtm, "<th>+ age*age</th>");
                   14612:     }
                   14613:     for(j=1;j <=ncovmodel-2;j++){
                   14614:       if(Typevar[j]==0) {
                   14615:        printf("  +      V%d  ",Tvar[j]);
                   14616:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   14617:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   14618:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   14619:       }else if(Typevar[j]==1) {
                   14620:        printf("  +    V%d*age ",Tvar[j]);
                   14621:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   14622:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   14623:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   14624:       }else if(Typevar[j]==2) {
                   14625:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14626:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14627:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14628:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14629:       }else if(Typevar[j]==3) { /* TO VERIFY */
                   14630:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14631:        fprintf(ficres,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14632:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14633:        fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14634:       }
                   14635:     }
                   14636:     printf("\n");
                   14637:     fprintf(ficres,"\n");
                   14638:     fprintf(ficlog,"\n");
                   14639:     fprintf(fichtm, "</tr>");
                   14640:     fprintf(fichtm, "\n");
                   14641:     
                   14642:     
                   14643:     for(i=1,jk=1; i <=nlstate; i++){
                   14644:       for(k=1; k <=(nlstate+ndeath); k++){
                   14645:        if (k != i) {
                   14646:          fprintf(fichtm, "<tr>");
                   14647:          printf("%d%d ",i,k);
                   14648:          fprintf(ficlog,"%d%d ",i,k);
                   14649:          fprintf(ficres,"%1d%1d ",i,k);
                   14650:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
                   14651:          for(j=1; j <=ncovmodel; j++){
                   14652:            printf("%12.7f ",p[jk]);
                   14653:            fprintf(ficlog,"%12.7f ",p[jk]);
                   14654:            fprintf(ficres,"%12.7f ",p[jk]);
                   14655:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
                   14656:            jk++; 
                   14657:          }
                   14658:          printf("\n");
                   14659:          fprintf(ficlog,"\n");
                   14660:          fprintf(ficres,"\n");
                   14661:          fprintf(fichtm, "</tr>\n");
                   14662:        }
                   14663:       }
                   14664:     }
                   14665:     /* fprintf(fichtm,"</tr>\n"); */
                   14666:     fprintf(fichtm,"</table>\n");
                   14667:     fprintf(fichtm, "\n");
                   14668: 
                   14669:     if(mle != 0){
                   14670:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
                   14671:       ftolhess=ftol; /* Usually correct */
                   14672:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   14673:       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");
                   14674:       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");
                   14675:       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);
                   14676:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   14677:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   14678:       if(nagesqr==1){
                   14679:        printf("  + age*age  ");
                   14680:        fprintf(ficres,"  + age*age  ");
                   14681:        fprintf(ficlog,"  + age*age  ");
                   14682:        fprintf(fichtm, "<th>+ age*age</th>");
                   14683:       }
                   14684:       for(j=1;j <=ncovmodel-2;j++){
                   14685:        if(Typevar[j]==0) {
                   14686:          printf("  +      V%d  ",Tvar[j]);
                   14687:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   14688:        }else if(Typevar[j]==1) {
                   14689:          printf("  +    V%d*age ",Tvar[j]);
                   14690:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   14691:        }else if(Typevar[j]==2) {
                   14692:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14693:        }else if(Typevar[j]==3) { /* TO VERIFY */
                   14694:          fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14695:        }
                   14696:       }
                   14697:       fprintf(fichtm, "</tr>\n");
                   14698:  
                   14699:       for(i=1,jk=1; i <=nlstate; i++){
                   14700:        for(k=1; k <=(nlstate+ndeath); k++){
                   14701:          if (k != i) {
                   14702:            fprintf(fichtm, "<tr valign=top>");
                   14703:            printf("%d%d ",i,k);
                   14704:            fprintf(ficlog,"%d%d ",i,k);
                   14705:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
                   14706:            for(j=1; j <=ncovmodel; j++){
                   14707:              wald=p[jk]/sqrt(matcov[jk][jk]);
                   14708:              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]));
                   14709:              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]));
                   14710:              if(fabs(wald) > 1.96){
                   14711:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   14712:              }else{
                   14713:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   14714:              }
                   14715:              fprintf(fichtm,"W=%8.3f</br>",wald);
                   14716:              fprintf(fichtm,"[%12.7f;%12.7f]</br></td>", p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
                   14717:              jk++; 
                   14718:            }
                   14719:            printf("\n");
                   14720:            fprintf(ficlog,"\n");
                   14721:            fprintf(fichtm, "</tr>\n");
                   14722:          }
                   14723:        }
                   14724:       }
                   14725:     } /* end of hesscov and Wald tests */
                   14726:     fprintf(fichtm,"</table>\n");
                   14727:     
                   14728:     /*  */
                   14729:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   14730:     printf("# Scales (for hessian or gradient estimation)\n");
                   14731:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   14732:     for(i=1,jk=1; i <=nlstate; i++){
                   14733:       for(j=1; j <=nlstate+ndeath; j++){
                   14734:        if (j!=i) {
                   14735:          fprintf(ficres,"%1d%1d",i,j);
                   14736:          printf("%1d%1d",i,j);
                   14737:          fprintf(ficlog,"%1d%1d",i,j);
                   14738:          for(k=1; k<=ncovmodel;k++){
                   14739:            printf(" %.5e",delti[jk]);
                   14740:            fprintf(ficlog," %.5e",delti[jk]);
                   14741:            fprintf(ficres," %.5e",delti[jk]);
                   14742:            jk++;
                   14743:          }
                   14744:          printf("\n");
                   14745:          fprintf(ficlog,"\n");
                   14746:          fprintf(ficres,"\n");
                   14747:        }
                   14748:       }
                   14749:     }
                   14750:     
                   14751:     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");
                   14752:     if(mle >= 1) /* Too big for the screen */
                   14753:       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");
                   14754:     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");
                   14755:     /* # 121 Var(a12)\n\ */
                   14756:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   14757:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   14758:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   14759:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   14760:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   14761:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   14762:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   14763:     
                   14764:     
                   14765:     /* Just to have a covariance matrix which will be more understandable
                   14766:        even is we still don't want to manage dictionary of variables
                   14767:     */
                   14768:     for(itimes=1;itimes<=2;itimes++){
                   14769:       jj=0;
                   14770:       for(i=1; i <=nlstate; i++){
                   14771:        for(j=1; j <=nlstate+ndeath; j++){
                   14772:          if(j==i) continue;
                   14773:          for(k=1; k<=ncovmodel;k++){
                   14774:            jj++;
                   14775:            ca[0]= k+'a'-1;ca[1]='\0';
                   14776:            if(itimes==1){
                   14777:              if(mle>=1)
                   14778:                printf("#%1d%1d%d",i,j,k);
                   14779:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   14780:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   14781:            }else{
                   14782:              if(mle>=1)
                   14783:                printf("%1d%1d%d",i,j,k);
                   14784:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   14785:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   14786:            }
                   14787:            ll=0;
                   14788:            for(li=1;li <=nlstate; li++){
                   14789:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   14790:                if(lj==li) continue;
                   14791:                for(lk=1;lk<=ncovmodel;lk++){
                   14792:                  ll++;
                   14793:                  if(ll<=jj){
                   14794:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   14795:                    if(ll<jj){
                   14796:                      if(itimes==1){
                   14797:                        if(mle>=1)
                   14798:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14799:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14800:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   14801:                      }else{
                   14802:                        if(mle>=1)
                   14803:                          printf(" %.5e",matcov[jj][ll]); 
                   14804:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   14805:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   14806:                      }
                   14807:                    }else{
                   14808:                      if(itimes==1){
                   14809:                        if(mle>=1)
                   14810:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   14811:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   14812:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   14813:                      }else{
                   14814:                        if(mle>=1)
                   14815:                          printf(" %.7e",matcov[jj][ll]); 
                   14816:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   14817:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   14818:                      }
                   14819:                    }
                   14820:                  }
                   14821:                } /* end lk */
                   14822:              } /* end lj */
                   14823:            } /* end li */
                   14824:            if(mle>=1)
                   14825:              printf("\n");
                   14826:            fprintf(ficlog,"\n");
                   14827:            fprintf(ficres,"\n");
                   14828:            numlinepar++;
                   14829:          } /* end k*/
                   14830:        } /*end j */
                   14831:       } /* end i */
                   14832:     } /* end itimes */
                   14833:     
                   14834:     fflush(ficlog);
                   14835:     fflush(ficres);
                   14836:     while(fgets(line, MAXLINE, ficpar)) {
                   14837:       /* If line starts with a # it is a comment */
                   14838:       if (line[0] == '#') {
                   14839:        numlinepar++;
                   14840:        fputs(line,stdout);
                   14841:        fputs(line,ficparo);
                   14842:        fputs(line,ficlog);
                   14843:        fputs(line,ficres);
                   14844:        continue;
                   14845:       }else
                   14846:        break;
                   14847:     }
                   14848:     
                   14849:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   14850:     /*   ungetc(c,ficpar); */
                   14851:     /*   fgets(line, MAXLINE, ficpar); */
                   14852:     /*   fputs(line,stdout); */
                   14853:     /*   fputs(line,ficparo); */
                   14854:     /* } */
                   14855:     /* ungetc(c,ficpar); */
                   14856:     
                   14857:     estepm=0;
                   14858:     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){
                   14859:       
                   14860:       if (num_filled != 6) {
                   14861:        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);
                   14862:        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);
                   14863:        goto end;
                   14864:       }
                   14865:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   14866:     }
                   14867:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   14868:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   14869:     
                   14870:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
                   14871:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   14872:     if (fage <= 2) {
                   14873:       bage = ageminpar;
                   14874:       fage = agemaxpar;
                   14875:     }
                   14876:     
                   14877:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   14878:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   14879:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   14880:                
                   14881:     /* Other stuffs, more or less useful */    
                   14882:     while(fgets(line, MAXLINE, ficpar)) {
                   14883:       /* If line starts with a # it is a comment */
                   14884:       if (line[0] == '#') {
                   14885:        numlinepar++;
                   14886:        fputs(line,stdout);
                   14887:        fputs(line,ficparo);
                   14888:        fputs(line,ficlog);
                   14889:        fputs(line,ficres);
                   14890:        continue;
                   14891:       }else
                   14892:        break;
                   14893:     }
                   14894: 
                   14895:     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){
                   14896:       
                   14897:       if (num_filled != 7) {
                   14898:        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);
                   14899:        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);
                   14900:        goto end;
                   14901:       }
                   14902:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   14903:       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);
                   14904:       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);
                   14905:       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);
                   14906:     }
                   14907: 
                   14908:     while(fgets(line, MAXLINE, ficpar)) {
                   14909:       /* If line starts with a # it is a comment */
                   14910:       if (line[0] == '#') {
                   14911:        numlinepar++;
                   14912:        fputs(line,stdout);
                   14913:        fputs(line,ficparo);
                   14914:        fputs(line,ficlog);
                   14915:        fputs(line,ficres);
                   14916:        continue;
                   14917:       }else
                   14918:        break;
                   14919:     }
                   14920:     
                   14921:     
                   14922:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   14923:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   14924:     
                   14925:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   14926:       if (num_filled != 1) {
                   14927:        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);
                   14928:        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);
                   14929:        goto end;
                   14930:       }
                   14931:       printf("pop_based=%d\n",popbased);
                   14932:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   14933:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   14934:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   14935:     }
                   14936:      
                   14937:     /* Results */
                   14938:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   14939:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   14940:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
                   14941:     endishere=0;
                   14942:     nresult=0;
                   14943:     parameterline=0;
                   14944:     do{
                   14945:       if(!fgets(line, MAXLINE, ficpar)){
                   14946:        endishere=1;
                   14947:        parameterline=15;
                   14948:       }else if (line[0] == '#') {
                   14949:        /* If line starts with a # it is a comment */
                   14950:        numlinepar++;
                   14951:        fputs(line,stdout);
                   14952:        fputs(line,ficparo);
                   14953:        fputs(line,ficlog);
                   14954:        fputs(line,ficres);
                   14955:        continue;
                   14956:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   14957:        parameterline=11;
                   14958:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
                   14959:        parameterline=12;
                   14960:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
                   14961:        parameterline=13;
                   14962:       }
                   14963:       else{
                   14964:        parameterline=14;
                   14965:       }
                   14966:       switch (parameterline){ /* =0 only if only comments */
                   14967:       case 11:
                   14968:        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)){
                   14969:                  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);
                   14970:          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);
                   14971:          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);
                   14972:          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);
                   14973:          /* day and month of proj2 are not used but only year anproj2.*/
                   14974:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   14975:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
                   14976:           prvforecast = 1;
                   14977:        } 
                   14978:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
                   14979:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14980:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14981:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   14982:           prvforecast = 2;
                   14983:        }
                   14984:        else {
                   14985:          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);
                   14986:          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);
                   14987:          goto end;
                   14988:        }
                   14989:        break;
                   14990:       case 12:
                   14991:        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)){
                   14992:           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);
                   14993:          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);
                   14994:          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);
                   14995:          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);
                   14996:          /* day and month of back2 are not used but only year anback2.*/
                   14997:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   14998:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
                   14999:           prvbackcast = 1;
                   15000:        } 
                   15001:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
                   15002:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   15003:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   15004:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   15005:           prvbackcast = 2;
                   15006:        }
                   15007:        else {
                   15008:          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);
                   15009:          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);
                   15010:          goto end;
                   15011:        }
                   15012:        break;
                   15013:       case 13:
                   15014:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
                   15015:        nresult++; /* Sum of resultlines */
                   15016:        /* printf("Result %d: result:%s\n",nresult, resultlineori); */
                   15017:        /* removefirstspace(&resultlineori); */
                   15018:        
                   15019:        if(strstr(resultlineori,"v") !=0){
                   15020:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   15021:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   15022:          return 1;
                   15023:        }
                   15024:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
                   15025:        /* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
                   15026:        if(nresult > MAXRESULTLINESPONE-1){
                   15027:          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);
                   15028:          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);
                   15029:          goto end;
                   15030:        }
                   15031:        
                   15032:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
                   15033:          fprintf(ficparo,"result: %s\n",resultline);
                   15034:          fprintf(ficres,"result: %s\n",resultline);
                   15035:          fprintf(ficlog,"result: %s\n",resultline);
                   15036:        } else
                   15037:          goto end;
                   15038:        break;
                   15039:       case 14:
                   15040:        printf("Error: Unknown command '%s'\n",line);
                   15041:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
                   15042:        if(line[0] == ' ' || line[0] == '\n'){
                   15043:          printf("It should not be an empty line '%s'\n",line);
                   15044:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   15045:        }         
                   15046:        if(ncovmodel >=2 && nresult==0 ){
                   15047:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   15048:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   15049:        }
                   15050:        /* goto end; */
                   15051:        break;
                   15052:       case 15:
                   15053:        printf("End of resultlines.\n");
                   15054:        fprintf(ficlog,"End of resultlines.\n");
                   15055:        break;
                   15056:       default: /* parameterline =0 */
                   15057:        nresult=1;
                   15058:        decoderesult(".",nresult ); /* No covariate */
                   15059:       } /* End switch parameterline */
                   15060:     }while(endishere==0); /* End do */
                   15061:     
                   15062:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   15063:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
                   15064:     
                   15065:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   15066:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
                   15067:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   15068: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   15069: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   15070:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   15071: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   15072: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   15073:     }else{
                   15074:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
                   15075:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   15076:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   15077:       if(prvforecast==1){
                   15078:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   15079:         jprojd=jproj1;
                   15080:         mprojd=mproj1;
                   15081:         anprojd=anproj1;
                   15082:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   15083:         jprojf=jproj2;
                   15084:         mprojf=mproj2;
                   15085:         anprojf=anproj2;
                   15086:       } else if(prvforecast == 2){
                   15087:         dateprojd=dateintmean;
                   15088:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   15089:         dateprojf=dateintmean+yrfproj;
                   15090:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   15091:       }
                   15092:       if(prvbackcast==1){
                   15093:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   15094:         jbackd=jback1;
                   15095:         mbackd=mback1;
                   15096:         anbackd=anback1;
                   15097:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   15098:         jbackf=jback2;
                   15099:         mbackf=mback2;
                   15100:         anbackf=anback2;
                   15101:       } else if(prvbackcast == 2){
                   15102:         datebackd=dateintmean;
                   15103:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   15104:         datebackf=dateintmean-yrbproj;
                   15105:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   15106:       }
                   15107:       
1.2     ! brouard  15108:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);/* HERE valgrind Tvard*/
1.1       brouard  15109:     }
                   15110:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
                   15111:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   15112:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
                   15113:                
                   15114:     /*------------ free_vector  -------------*/
                   15115:     /*  chdir(path); */
                   15116:                
                   15117:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   15118:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   15119:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   15120:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
                   15121:     free_lvector(num,firstobs,lastobs);
                   15122:     free_vector(agedc,firstobs,lastobs);
                   15123:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   15124:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   15125:     fclose(ficparo);
                   15126:     fclose(ficres);
                   15127:                
                   15128:                
                   15129:     /* Other results (useful)*/
                   15130:                
                   15131:                
                   15132:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   15133:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   15134:     prlim=matrix(1,nlstate,1,nlstate);
                   15135:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
                   15136:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
                   15137:     fclose(ficrespl);
                   15138: 
                   15139:     /*------------- h Pij x at various ages ------------*/
                   15140:     /*#include "hpijx.h"*/
                   15141:     /** 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?*/
                   15142:     /* calls hpxij with combination k */
                   15143:     hPijx(p, bage, fage);
                   15144:     fclose(ficrespij);
                   15145:     
                   15146:     /* ncovcombmax=  pow(2,cptcoveff); */
                   15147:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
                   15148:     k=1;
                   15149:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   15150:     
                   15151:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   15152:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   15153:     for(i=AGEINF;i<=AGESUP;i++)
                   15154:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
                   15155:        for(k=1;k<=ncovcombmax;k++)
                   15156:          probs[i][j][k]=0.;
                   15157:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   15158:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   15159:     if (mobilav!=0 ||mobilavproj !=0 ) {
                   15160:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   15161:       for(i=AGEINF;i<=AGESUP;i++)
                   15162:        for(j=1;j<=nlstate+ndeath;j++)
                   15163:          for(k=1;k<=ncovcombmax;k++)
                   15164:            mobaverages[i][j][k]=0.;
                   15165:       mobaverage=mobaverages;
                   15166:       if (mobilav!=0) {
                   15167:        printf("Movingaveraging observed prevalence\n");
                   15168:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
                   15169:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   15170:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   15171:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   15172:        }
                   15173:       } else if (mobilavproj !=0) {
                   15174:        printf("Movingaveraging projected observed prevalence\n");
                   15175:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
                   15176:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   15177:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   15178:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   15179:        }
                   15180:       }else{
                   15181:        printf("Internal error moving average\n");
                   15182:        fflush(stdout);
                   15183:        exit(1);
                   15184:       }
                   15185:     }/* end if moving average */
                   15186:     
                   15187:     /*---------- Forecasting ------------------*/
                   15188:     if(prevfcast==1){ 
                   15189:       /*   /\*    if(stepm ==1){*\/ */
                   15190:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   15191:       /*This done previously after freqsummary.*/
                   15192:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   15193:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   15194:       
                   15195:       /* } else if (prvforecast==2){ */
                   15196:       /*   /\*    if(stepm ==1){*\/ */
                   15197:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   15198:       /* } */
                   15199:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   15200:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
                   15201:     }
                   15202: 
                   15203:     /* Prevbcasting */
                   15204:     if(prevbcast==1){
                   15205:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   15206:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   15207:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   15208: 
                   15209:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   15210: 
                   15211:       bprlim=matrix(1,nlstate,1,nlstate);
                   15212: 
                   15213:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   15214:       fclose(ficresplb);
                   15215: 
                   15216:       hBijx(p, bage, fage, mobaverage);
                   15217:       fclose(ficrespijb);
                   15218: 
                   15219:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   15220:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   15221:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   15222:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   15223:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   15224:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   15225: 
                   15226:       
                   15227:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
                   15228: 
                   15229:       
                   15230:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   15231:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   15232:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   15233:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   15234:     }    /* end  Prevbcasting */
                   15235:  
                   15236:  
                   15237:     /* ------ Other prevalence ratios------------ */
                   15238: 
                   15239:     free_ivector(wav,1,imx);
                   15240:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   15241:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   15242:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
                   15243:                
                   15244:                
                   15245:     /*---------- Health expectancies, no variances ------------*/
                   15246:                
                   15247:     strcpy(filerese,"E_");
                   15248:     strcat(filerese,fileresu);
                   15249:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   15250:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   15251:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   15252:     }
                   15253:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   15254:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
                   15255: 
                   15256:     pstamp(ficreseij);
                   15257:                
1.2     ! brouard  15258:     /* i1=pow(2,cptcoveff); /\* Number of combination of dummy covariates *\/ */
        !          15259:     /* if (cptcovn < 1){i1=1;} */
1.1       brouard  15260:     
1.2     ! brouard  15261:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
        !          15262:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
        !          15263:       /* if(i1 != 1 && TKresult[nres]!= k) */
        !          15264:       /*       continue; */
1.1       brouard  15265:       fprintf(ficreseij,"\n#****** ");
                   15266:       printf("\n#****** ");
1.2     ! brouard  15267:       for(j=1;j<=cptcovs;j++){
        !          15268:       /* for(j=1;j<=cptcoveff;j++) { */
        !          15269:        /* fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
        !          15270:        fprintf(ficreseij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
        !          15271:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
        !          15272:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.1       brouard  15273:       }
                   15274:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   15275:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   15276:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
                   15277:       }
                   15278:       fprintf(ficreseij,"******\n");
                   15279:       printf("******\n");
                   15280:       
                   15281:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15282:       oldm=oldms;savm=savms;
                   15283:       /* printf("HELLO Entering evsij bage=%d fage=%d k=%d estepm=%d nres=%d\n",(int) bage, (int)fage, k, estepm, nres); */
                   15284:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
                   15285:       
                   15286:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   15287:     }
                   15288:     fclose(ficreseij);
                   15289:     printf("done evsij\n");fflush(stdout);
                   15290:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
                   15291: 
                   15292:                
                   15293:     /*---------- State-specific expectancies and variances ------------*/
                   15294:     /* Should be moved in a function */                
                   15295:     strcpy(filerest,"T_");
                   15296:     strcat(filerest,fileresu);
                   15297:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   15298:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   15299:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   15300:     }
                   15301:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   15302:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
                   15303:     strcpy(fileresstde,"STDE_");
                   15304:     strcat(fileresstde,fileresu);
                   15305:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   15306:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   15307:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   15308:     }
                   15309:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   15310:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   15311: 
                   15312:     strcpy(filerescve,"CVE_");
                   15313:     strcat(filerescve,fileresu);
                   15314:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   15315:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   15316:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   15317:     }
                   15318:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   15319:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   15320: 
                   15321:     strcpy(fileresv,"V_");
                   15322:     strcat(fileresv,fileresu);
                   15323:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   15324:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   15325:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   15326:     }
                   15327:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   15328:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
                   15329: 
                   15330:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   15331:     if (cptcovn < 1){i1=1;}
                   15332:     
                   15333:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   15334:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   15335:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   15336:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   15337:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   15338:       /* */
                   15339:       if(i1 != 1 && TKresult[nres]!= k) /* TKresult[nres] is the combination of this nres resultline. All the i1 combinations are not output */
                   15340:        continue;
1.2     ! brouard  15341:       printf("\n# model %s \n#****** Result for:", model);  /* HERE model is empty */
1.1       brouard  15342:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   15343:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
                   15344:       /* It might not be a good idea to mix dummies and quantitative */
                   15345:       /* 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 *\/ */
                   15346:       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 */
                   15347:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   15348:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   15349:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   15350:         * (V5 is quanti) V4 and V3 are dummies
                   15351:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   15352:         *                                                              l=1 l=2
                   15353:         *                                                           k=1  1   1   0   0
                   15354:         *                                                           k=2  2   1   1   0
                   15355:         *                                                           k=3 [1] [2]  0   1
                   15356:         *                                                           k=4  2   2   1   1
                   15357:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   15358:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   15359:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   15360:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   15361:         */
                   15362:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   15363:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   15364: /* We give up with the combinations!! */
                   15365:        /* if(debugILK) */
                   15366:        /*   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 *\/ */
                   15367: 
                   15368:        if(Dummy[modelresult[nres][j]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to j in resultline  */
                   15369:          /* 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] */
                   15370:          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  */
                   15371:          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  */
                   15372:          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  */
                   15373:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   15374:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   15375:          }else{
                   15376:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   15377:          }
                   15378:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15379:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15380:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   15381:          /* For each selected (single) quantitative value */
                   15382:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   15383:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   15384:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   15385:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   15386:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   15387:          }else{
                   15388:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   15389:          }
                   15390:        }else{
                   15391:          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 */
                   15392:          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 */
                   15393:          exit(1);
                   15394:        }
                   15395:       } /* End loop for each variable in the resultline */
                   15396:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   15397:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   15398:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   15399:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   15400:       /* }      */
                   15401:       fprintf(ficrest,"******\n");
                   15402:       fprintf(ficlog,"******\n");
                   15403:       printf("******\n");
                   15404:       
                   15405:       fprintf(ficresstdeij,"\n#****** ");
                   15406:       fprintf(ficrescveij,"\n#****** ");
                   15407:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   15408:       /* But it won't be sorted and depends on how the resultline is ordered */
                   15409:       for(j=1;j<=cptcoveff;j++) {
                   15410:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   15411:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15412:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15413:       }
                   15414:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value, TvarsQind gives the position of a quantitative in model equation  */
                   15415:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   15416:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   15417:       }        
                   15418:       fprintf(ficresstdeij,"******\n");
                   15419:       fprintf(ficrescveij,"******\n");
                   15420:       
                   15421:       fprintf(ficresvij,"\n#****** ");
                   15422:       /* pstamp(ficresvij); */
                   15423:       for(j=1;j<=cptcoveff;j++) 
                   15424:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   15425:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
                   15426:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   15427:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
                   15428:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
                   15429:       }        
                   15430:       fprintf(ficresvij,"******\n");
                   15431:       
                   15432:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15433:       oldm=oldms;savm=savms;
                   15434:       printf(" cvevsij ");
                   15435:       fprintf(ficlog, " cvevsij ");
                   15436:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
                   15437:       printf(" end cvevsij \n ");
                   15438:       fprintf(ficlog, " end cvevsij \n ");
                   15439:       
                   15440:       /*
                   15441:        */
                   15442:       /* goto endfree; */
                   15443:       
                   15444:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15445:       pstamp(ficrest);
                   15446:       
                   15447:       epj=vector(1,nlstate+1);
                   15448:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   15449:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   15450:        cptcod= 0; /* To be deleted */
                   15451:        printf("varevsij vpopbased=%d \n",vpopbased);
                   15452:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
                   15453:        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 */
                   15454:        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 ");
                   15455:        if(vpopbased==1)
                   15456:          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);
                   15457:        else
                   15458:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
                   15459:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
                   15460:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   15461:        fprintf(ficrest,"\n");
                   15462:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   15463:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   15464:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
                   15465:        for(age=bage; age <=fage ;age++){
                   15466:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
                   15467:          if (vpopbased==1) {
                   15468:            if(mobilav ==0){
                   15469:              for(i=1; i<=nlstate;i++)
                   15470:                prlim[i][i]=probs[(int)age][i][k];
                   15471:            }else{ /* mobilav */ 
                   15472:              for(i=1; i<=nlstate;i++)
                   15473:                prlim[i][i]=mobaverage[(int)age][i][k];
                   15474:            }
                   15475:          }
                   15476:          
                   15477:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   15478:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   15479:          /* printf(" age %4.0f ",age); */
                   15480:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   15481:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   15482:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   15483:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   15484:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   15485:            }
                   15486:            epj[nlstate+1] +=epj[j];
                   15487:          }
                   15488:          /* printf(" age %4.0f \n",age); */
                   15489:          
                   15490:          for(i=1, vepp=0.;i <=nlstate;i++)
                   15491:            for(j=1;j <=nlstate;j++)
                   15492:              vepp += vareij[i][j][(int)age];
                   15493:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   15494:          for(j=1;j <=nlstate;j++){
                   15495:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   15496:          }
                   15497:          fprintf(ficrest,"\n");
                   15498:        }
                   15499:       } /* End vpopbased */
                   15500:       free_vector(epj,1,nlstate+1);
                   15501:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   15502:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   15503:       printf("done selection\n");fflush(stdout);
                   15504:       fprintf(ficlog,"done selection\n");fflush(ficlog);
                   15505:       
                   15506:     } /* End k selection or end covariate selection for nres */
                   15507: 
                   15508:     printf("done State-specific expectancies\n");fflush(stdout);
                   15509:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   15510: 
                   15511:     /* variance-covariance of forward period prevalence */
                   15512:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
                   15513: 
                   15514:     
                   15515:     free_vector(weight,firstobs,lastobs);
1.2     ! brouard  15516:     free_imatrix(Tvardk,0,NCOVMAX,1,2);
1.1       brouard  15517:     free_imatrix(Tvard,1,NCOVMAX,1,2);
                   15518:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   15519:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   15520:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   15521:     free_ivector(cod,firstobs,lastobs);
                   15522:     free_ivector(tab,1,NCOVMAX);
                   15523:     fclose(ficresstdeij);
                   15524:     fclose(ficrescveij);
                   15525:     fclose(ficresvij);
                   15526:     fclose(ficrest);
                   15527:     fclose(ficpar);
                   15528:     
                   15529:     
                   15530:     /*---------- End : free ----------------*/
                   15531:     if (mobilav!=0 ||mobilavproj !=0)
                   15532:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   15533:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   15534:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   15535:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   15536:   }  /* mle==-3 arrives here for freeing */
                   15537:   /* endfree:*/
                   15538:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   15539:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   15540:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   15541:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
                   15542:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
                   15543:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   15544:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   15545:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
                   15546:   free_matrix(matcov,1,npar,1,npar);
                   15547:   free_matrix(hess,1,npar,1,npar);
                   15548:   /*free_vector(delti,1,npar);*/
                   15549:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   15550:   free_matrix(agev,1,maxwav,1,imx);
                   15551:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   15552:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   15553:   
                   15554:   free_ivector(ncodemax,1,NCOVMAX);
                   15555:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   15556:   free_ivector(Dummy,-1,NCOVMAX);
                   15557:   free_ivector(Fixed,-1,NCOVMAX);
                   15558:   free_ivector(DummyV,-1,NCOVMAX);
                   15559:   free_ivector(FixedV,-1,NCOVMAX);
                   15560:   free_ivector(Typevar,-1,NCOVMAX);
                   15561:   free_ivector(Tvar,1,NCOVMAX);
                   15562:   free_ivector(TvarsQ,1,NCOVMAX);
                   15563:   free_ivector(TvarsQind,1,NCOVMAX);
                   15564:   free_ivector(TvarsD,1,NCOVMAX);
                   15565:   free_ivector(TnsdVar,1,NCOVMAX);
                   15566:   free_ivector(TvarsDind,1,NCOVMAX);
                   15567:   free_ivector(TvarFD,1,NCOVMAX);
                   15568:   free_ivector(TvarFDind,1,NCOVMAX);
                   15569:   free_ivector(TvarF,1,NCOVMAX);
                   15570:   free_ivector(TvarFind,1,NCOVMAX);
                   15571:   free_ivector(TvarV,1,NCOVMAX);
                   15572:   free_ivector(TvarVind,1,NCOVMAX);
                   15573:   free_ivector(TvarA,1,NCOVMAX);
                   15574:   free_ivector(TvarAind,1,NCOVMAX);
                   15575:   free_ivector(TvarFQ,1,NCOVMAX);
                   15576:   free_ivector(TvarFQind,1,NCOVMAX);
                   15577:   free_ivector(TvarVD,1,NCOVMAX);
                   15578:   free_ivector(TvarVDind,1,NCOVMAX);
                   15579:   free_ivector(TvarVQ,1,NCOVMAX);
                   15580:   free_ivector(TvarVQind,1,NCOVMAX);
                   15581:   free_ivector(TvarAVVA,1,NCOVMAX);
                   15582:   free_ivector(TvarAVVAind,1,NCOVMAX);
                   15583:   free_ivector(TvarVVA,1,NCOVMAX);
                   15584:   free_ivector(TvarVVAind,1,NCOVMAX);
                   15585:   free_ivector(TvarVV,1,NCOVMAX);
                   15586:   free_ivector(TvarVVind,1,NCOVMAX);
                   15587:   
                   15588:   free_ivector(Tvarsel,1,NCOVMAX);
                   15589:   free_vector(Tvalsel,1,NCOVMAX);
                   15590:   free_ivector(Tposprod,1,NCOVMAX);
                   15591:   free_ivector(Tprod,1,NCOVMAX);
                   15592:   free_ivector(Tvaraff,1,NCOVMAX);
                   15593:   free_ivector(invalidvarcomb,0,ncovcombmax);
                   15594:   free_ivector(Tage,1,NCOVMAX);
                   15595:   free_ivector(Tmodelind,1,NCOVMAX);
                   15596:   free_ivector(TmodelInvind,1,NCOVMAX);
                   15597:   free_ivector(TmodelInvQind,1,NCOVMAX);
                   15598: 
                   15599:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   15600: 
                   15601:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   15602:   /* free_imatrix(codtab,1,100,1,10); */
                   15603:   fflush(fichtm);
                   15604:   fflush(ficgp);
                   15605:   
                   15606:   
                   15607:   if((nberr >0) || (nbwarn>0)){
                   15608:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   15609:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d. Please look at the log file for details.\n",nberr,nbwarn);
                   15610:   }else{
                   15611:     printf("End of Imach\n");
                   15612:     fprintf(ficlog,"End of Imach\n");
                   15613:   }
                   15614:   printf("See log file on %s\n",filelog);
                   15615:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
                   15616:   /*(void) gettimeofday(&end_time,&tzp);*/
                   15617:   rend_time = time(NULL);  
                   15618:   end_time = *localtime(&rend_time);
                   15619:   /* tml = *localtime(&end_time.tm_sec); */
                   15620:   strcpy(strtend,asctime(&end_time));
                   15621:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   15622:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
                   15623:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   15624:   
                   15625:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   15626:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   15627:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   15628:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   15629: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   15630:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   15631:   fclose(fichtm);
                   15632:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   15633:   fclose(fichtmcov);
                   15634:   fclose(ficgp);
                   15635:   fclose(ficlog);
                   15636:   /*------ End -----------*/
                   15637:   
                   15638: 
                   15639: /* Executes gnuplot */
                   15640:   
                   15641:   printf("Before Current directory %s!\n",pathcd);
                   15642: #ifdef WIN32
                   15643:   if (_chdir(pathcd) != 0)
                   15644:     printf("Can't move to directory %s!\n",path);
                   15645:   if(_getcwd(pathcd,MAXLINE) > 0)
                   15646: #else
                   15647:     if(chdir(pathcd) != 0)
                   15648:       printf("Can't move to directory %s!\n", path);
                   15649:   if (getcwd(pathcd, MAXLINE) > 0)
                   15650: #endif 
                   15651:     printf("Current directory %s!\n",pathcd);
                   15652:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   15653:   sprintf(plotcmd,"gnuplot");
                   15654: #ifdef _WIN32
                   15655:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   15656: #endif
                   15657:   if(!stat(plotcmd,&info)){
                   15658:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
                   15659:     if(!stat(getenv("GNUPLOTBIN"),&info)){
                   15660:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
                   15661:     }else
                   15662:       strcpy(pplotcmd,plotcmd);
                   15663: #ifdef __unix
                   15664:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   15665:     if(!stat(plotcmd,&info)){
                   15666:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
                   15667:     }else
                   15668:       strcpy(pplotcmd,plotcmd);
                   15669: #endif
                   15670:   }else
                   15671:     strcpy(pplotcmd,plotcmd);
                   15672:   
                   15673:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
                   15674:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
                   15675:   strcpy(pplotcmd,plotcmd);
                   15676:   
                   15677:   if((outcmd=system(plotcmd)) != 0){
                   15678:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
                   15679:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
                   15680:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
                   15681:     if((outcmd=system(plotcmd)) != 0){
                   15682:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
                   15683:       strcpy(plotcmd,pplotcmd);
                   15684:     }
                   15685:   }
                   15686:   printf(" Successful, please wait...");
                   15687:   while (z[0] != 'q') {
                   15688:     /* chdir(path); */
                   15689:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
                   15690:     scanf("%s",z);
                   15691: /*     if (z[0] == 'c') system("./imach"); */
                   15692:     if (z[0] == 'e') {
                   15693: #ifdef __APPLE__
                   15694:       sprintf(pplotcmd, "open %s", optionfilehtm);
                   15695: #elif __linux
                   15696:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
                   15697: #else
                   15698:       sprintf(pplotcmd, "%s", optionfilehtm);
                   15699: #endif
                   15700:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   15701:       system(pplotcmd);
                   15702:     }
                   15703:     else if (z[0] == 'g') system(plotcmd);
                   15704:     else if (z[0] == 'q') exit(0);
                   15705:   }
                   15706: end:
                   15707:   while (z[0] != 'q') {
                   15708:     printf("\nType  q for exiting: "); fflush(stdout);
                   15709:     scanf("%s",z);
                   15710:   }
                   15711:   printf("End\n");
                   15712:   exit(0);
                   15713: }

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