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

1.5     ! brouard     1: /* $Id: imachprax.c,v 1.4 2023/06/22 12:50:51 brouard Exp $
1.1       brouard     2:   $State: Exp $
1.3       brouard     3:   $Log: imachprax.c,v $
1.5     ! brouard     4:   Revision 1.4  2023/06/22 12:50:51  brouard
        !             5:   Summary: stil on going
        !             6: 
1.4       brouard     7:   Revision 1.3  2023/06/22 11:28:07  brouard
                      8:   *** empty log message ***
                      9: 
1.3       brouard    10:   Revision 1.2  2023/06/22 11:22:40  brouard
                     11:   Summary: with svd but not working yet
                     12: 
1.2       brouard    13:   Revision 1.353  2023/05/08 18:48:22  brouard
                     14:   *** empty log message ***
                     15: 
                     16:   Revision 1.352  2023/04/29 10:46:21  brouard
                     17:   *** empty log message ***
                     18: 
                     19:   Revision 1.351  2023/04/29 10:43:47  brouard
                     20:   Summary: 099r45
                     21: 
                     22:   Revision 1.350  2023/04/24 11:38:06  brouard
                     23:   *** empty log message ***
                     24: 
                     25:   Revision 1.349  2023/01/31 09:19:37  brouard
                     26:   Summary: Improvements in models with age*Vn*Vm
                     27: 
1.1       brouard    28:   Revision 1.347  2022/09/18 14:36:44  brouard
                     29:   Summary: version 0.99r42
                     30: 
                     31:   Revision 1.346  2022/09/16 13:52:36  brouard
                     32:   * src/imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     33: 
                     34:   Revision 1.345  2022/09/16 13:40:11  brouard
                     35:   Summary: Version 0.99r41
                     36: 
                     37:   * imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     38: 
                     39:   Revision 1.344  2022/09/14 19:33:30  brouard
                     40:   Summary: version 0.99r40
                     41: 
                     42:   * imach.c (Module): Fixing names of variables in T_ (thanks to Feinuo)
                     43: 
                     44:   Revision 1.343  2022/09/14 14:22:16  brouard
                     45:   Summary: version 0.99r39
                     46: 
                     47:   * imach.c (Module): Version 0.99r39 with colored dummy covariates
                     48:   (fixed or time varying), using new last columns of
                     49:   ILK_parameter.txt file.
                     50: 
                     51:   Revision 1.342  2022/09/11 19:54:09  brouard
                     52:   Summary: 0.99r38
                     53: 
                     54:   * imach.c (Module): Adding timevarying products of any kinds,
                     55:   should work before shifting cotvar from ncovcol+nqv columns in
                     56:   order to have a correspondance between the column of cotvar and
                     57:   the id of column.
                     58:   (Module): Some cleaning and adding covariates in ILK.txt
                     59: 
                     60:   Revision 1.341  2022/09/11 07:58:42  brouard
                     61:   Summary: Version 0.99r38
                     62: 
                     63:   After adding change in cotvar.
                     64: 
                     65:   Revision 1.340  2022/09/11 07:53:11  brouard
                     66:   Summary: Version imach 0.99r37
                     67: 
                     68:   * imach.c (Module): Adding timevarying products of any kinds,
                     69:   should work before shifting cotvar from ncovcol+nqv columns in
                     70:   order to have a correspondance between the column of cotvar and
                     71:   the id of column.
                     72: 
                     73:   Revision 1.339  2022/09/09 17:55:22  brouard
                     74:   Summary: version 0.99r37
                     75: 
                     76:   * imach.c (Module): Many improvements for fixing products of fixed
                     77:   timevarying as well as fixed * fixed, and test with quantitative
                     78:   covariate.
                     79: 
                     80:   Revision 1.338  2022/09/04 17:40:33  brouard
                     81:   Summary: 0.99r36
                     82: 
                     83:   * imach.c (Module): Now the easy runs i.e. without result or
                     84:   model=1+age only did not work. The defautl combination should be 1
                     85:   and not 0 because everything hasn't been tranformed yet.
                     86: 
                     87:   Revision 1.337  2022/09/02 14:26:02  brouard
                     88:   Summary: version 0.99r35
                     89: 
                     90:   * src/imach.c: Version 0.99r35 because it outputs same results with
                     91:   1+age+V1+V1*age for females and 1+age for females only
                     92:   (education=1 noweight)
                     93: 
                     94:   Revision 1.336  2022/08/31 09:52:36  brouard
                     95:   *** empty log message ***
                     96: 
                     97:   Revision 1.335  2022/08/31 08:23:16  brouard
                     98:   Summary: improvements...
                     99: 
                    100:   Revision 1.334  2022/08/25 09:08:41  brouard
                    101:   Summary: In progress for quantitative
                    102: 
                    103:   Revision 1.333  2022/08/21 09:10:30  brouard
                    104:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    105:   reassigning covariates: my first idea was that people will always
                    106:   use the first covariate V1 into the model but in fact they are
                    107:   producing data with many covariates and can use an equation model
                    108:   with some of the covariate; it means that in a model V2+V3 instead
                    109:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    110:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    111:   the equation model is restricted to two variables only (V2, V3)
                    112:   and the combination for V2 should be codtabm(k,1) instead of
                    113:   (codtabm(k,2), and the code should be
                    114:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    115:   made. All of these should be simplified once a day like we did in
                    116:   hpxij() for example by using precov[nres] which is computed in
                    117:   decoderesult for each nres of each resultline. Loop should be done
                    118:   on the equation model globally by distinguishing only product with
                    119:   age (which are changing with age) and no more on type of
                    120:   covariates, single dummies, single covariates.
                    121: 
                    122:   Revision 1.332  2022/08/21 09:06:25  brouard
                    123:   Summary: Version 0.99r33
                    124: 
                    125:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    126:   reassigning covariates: my first idea was that people will always
                    127:   use the first covariate V1 into the model but in fact they are
                    128:   producing data with many covariates and can use an equation model
                    129:   with some of the covariate; it means that in a model V2+V3 instead
                    130:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    131:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    132:   the equation model is restricted to two variables only (V2, V3)
                    133:   and the combination for V2 should be codtabm(k,1) instead of
                    134:   (codtabm(k,2), and the code should be
                    135:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    136:   made. All of these should be simplified once a day like we did in
                    137:   hpxij() for example by using precov[nres] which is computed in
                    138:   decoderesult for each nres of each resultline. Loop should be done
                    139:   on the equation model globally by distinguishing only product with
                    140:   age (which are changing with age) and no more on type of
                    141:   covariates, single dummies, single covariates.
                    142: 
                    143:   Revision 1.331  2022/08/07 05:40:09  brouard
                    144:   *** empty log message ***
                    145: 
                    146:   Revision 1.330  2022/08/06 07:18:25  brouard
                    147:   Summary: last 0.99r31
                    148: 
                    149:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                    150: 
                    151:   Revision 1.329  2022/08/03 17:29:54  brouard
                    152:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                    153: 
                    154:   Revision 1.328  2022/07/27 17:40:48  brouard
                    155:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                    156: 
                    157:   Revision 1.327  2022/07/27 14:47:35  brouard
                    158:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                    159: 
                    160:   Revision 1.326  2022/07/26 17:33:55  brouard
                    161:   Summary: some test with nres=1
                    162: 
                    163:   Revision 1.325  2022/07/25 14:27:23  brouard
                    164:   Summary: r30
                    165: 
                    166:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                    167:   coredumped, revealed by Feiuno, thank you.
                    168: 
                    169:   Revision 1.324  2022/07/23 17:44:26  brouard
                    170:   *** empty log message ***
                    171: 
                    172:   Revision 1.323  2022/07/22 12:30:08  brouard
                    173:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    174: 
                    175:   Revision 1.322  2022/07/22 12:27:48  brouard
                    176:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    177: 
                    178:   Revision 1.321  2022/07/22 12:04:24  brouard
                    179:   Summary: r28
                    180: 
                    181:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    182: 
                    183:   Revision 1.320  2022/06/02 05:10:11  brouard
                    184:   *** empty log message ***
                    185: 
                    186:   Revision 1.319  2022/06/02 04:45:11  brouard
                    187:   * imach.c (Module): Adding the Wald tests from the log to the main
                    188:   htm for better display of the maximum likelihood estimators.
                    189: 
                    190:   Revision 1.318  2022/05/24 08:10:59  brouard
                    191:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    192:   of confidencce intervals with product in the equation modelC
                    193: 
                    194:   Revision 1.317  2022/05/15 15:06:23  brouard
                    195:   * imach.c (Module):  Some minor improvements
                    196: 
                    197:   Revision 1.316  2022/05/11 15:11:31  brouard
                    198:   Summary: r27
                    199: 
                    200:   Revision 1.315  2022/05/11 15:06:32  brouard
                    201:   *** empty log message ***
                    202: 
                    203:   Revision 1.314  2022/04/13 17:43:09  brouard
                    204:   * imach.c (Module): Adding link to text data files
                    205: 
                    206:   Revision 1.313  2022/04/11 15:57:42  brouard
                    207:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    208: 
                    209:   Revision 1.312  2022/04/05 21:24:39  brouard
                    210:   *** empty log message ***
                    211: 
                    212:   Revision 1.311  2022/04/05 21:03:51  brouard
                    213:   Summary: Fixed quantitative covariates
                    214: 
                    215:          Fixed covariates (dummy or quantitative)
                    216:        with missing values have never been allowed but are ERRORS and
                    217:        program quits. Standard deviations of fixed covariates were
                    218:        wrongly computed. Mean and standard deviations of time varying
                    219:        covariates are still not computed.
                    220: 
                    221:   Revision 1.310  2022/03/17 08:45:53  brouard
                    222:   Summary: 99r25
                    223: 
                    224:   Improving detection of errors: result lines should be compatible with
                    225:   the model.
                    226: 
                    227:   Revision 1.309  2021/05/20 12:39:14  brouard
                    228:   Summary: Version 0.99r24
                    229: 
                    230:   Revision 1.308  2021/03/31 13:11:57  brouard
                    231:   Summary: Version 0.99r23
                    232: 
                    233: 
                    234:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    235: 
                    236:   Revision 1.307  2021/03/08 18:11:32  brouard
                    237:   Summary: 0.99r22 fixed bug on result:
                    238: 
                    239:   Revision 1.306  2021/02/20 15:44:02  brouard
                    240:   Summary: Version 0.99r21
                    241: 
                    242:   * imach.c (Module): Fix bug on quitting after result lines!
                    243:   (Module): Version 0.99r21
                    244: 
                    245:   Revision 1.305  2021/02/20 15:28:30  brouard
                    246:   * imach.c (Module): Fix bug on quitting after result lines!
                    247: 
                    248:   Revision 1.304  2021/02/12 11:34:20  brouard
                    249:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    250: 
                    251:   Revision 1.303  2021/02/11 19:50:15  brouard
                    252:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    253: 
                    254:   Revision 1.302  2020/02/22 21:00:05  brouard
                    255:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    256:   and life table from the data without any state)
                    257: 
                    258:   Revision 1.301  2019/06/04 13:51:20  brouard
                    259:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    260: 
                    261:   Revision 1.300  2019/05/22 19:09:45  brouard
                    262:   Summary: version 0.99r19 of May 2019
                    263: 
                    264:   Revision 1.299  2019/05/22 18:37:08  brouard
                    265:   Summary: Cleaned 0.99r19
                    266: 
                    267:   Revision 1.298  2019/05/22 18:19:56  brouard
                    268:   *** empty log message ***
                    269: 
                    270:   Revision 1.297  2019/05/22 17:56:10  brouard
                    271:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    272: 
                    273:   Revision 1.296  2019/05/20 13:03:18  brouard
                    274:   Summary: Projection syntax simplified
                    275: 
                    276: 
                    277:   We can now start projections, forward or backward, from the mean date
                    278:   of inteviews up to or down to a number of years of projection:
                    279:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    280:   or
                    281:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    282:   or
                    283:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    284:   or
                    285:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    286: 
                    287:   Revision 1.295  2019/05/18 09:52:50  brouard
                    288:   Summary: doxygen tex bug
                    289: 
                    290:   Revision 1.294  2019/05/16 14:54:33  brouard
                    291:   Summary: There was some wrong lines added
                    292: 
                    293:   Revision 1.293  2019/05/09 15:17:34  brouard
                    294:   *** empty log message ***
                    295: 
                    296:   Revision 1.292  2019/05/09 14:17:20  brouard
                    297:   Summary: Some updates
                    298: 
                    299:   Revision 1.291  2019/05/09 13:44:18  brouard
                    300:   Summary: Before ncovmax
                    301: 
                    302:   Revision 1.290  2019/05/09 13:39:37  brouard
                    303:   Summary: 0.99r18 unlimited number of individuals
                    304: 
                    305:   The number n which was limited to 20,000 cases is now unlimited, from firstobs to lastobs. If the number is too for the virtual memory, probably an error will occur.
                    306: 
                    307:   Revision 1.289  2018/12/13 09:16:26  brouard
                    308:   Summary: Bug for young ages (<-30) will be in r17
                    309: 
                    310:   Revision 1.288  2018/05/02 20:58:27  brouard
                    311:   Summary: Some bugs fixed
                    312: 
                    313:   Revision 1.287  2018/05/01 17:57:25  brouard
                    314:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    315: 
                    316:   Revision 1.286  2018/04/27 14:27:04  brouard
                    317:   Summary: some minor bugs
                    318: 
                    319:   Revision 1.285  2018/04/21 21:02:16  brouard
                    320:   Summary: Some bugs fixed, valgrind tested
                    321: 
                    322:   Revision 1.284  2018/04/20 05:22:13  brouard
                    323:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    324: 
                    325:   Revision 1.283  2018/04/19 14:49:16  brouard
                    326:   Summary: Some minor bugs fixed
                    327: 
                    328:   Revision 1.282  2018/02/27 22:50:02  brouard
                    329:   *** empty log message ***
                    330: 
                    331:   Revision 1.281  2018/02/27 19:25:23  brouard
                    332:   Summary: Adding second argument for quitting
                    333: 
                    334:   Revision 1.280  2018/02/21 07:58:13  brouard
                    335:   Summary: 0.99r15
                    336: 
                    337:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    338: 
                    339:   Revision 1.279  2017/07/20 13:35:01  brouard
                    340:   Summary: temporary working
                    341: 
                    342:   Revision 1.278  2017/07/19 14:09:02  brouard
                    343:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    344: 
                    345:   Revision 1.277  2017/07/17 08:53:49  brouard
                    346:   Summary: BOM files can be read now
                    347: 
                    348:   Revision 1.276  2017/06/30 15:48:31  brouard
                    349:   Summary: Graphs improvements
                    350: 
                    351:   Revision 1.275  2017/06/30 13:39:33  brouard
                    352:   Summary: Saito's color
                    353: 
                    354:   Revision 1.274  2017/06/29 09:47:08  brouard
                    355:   Summary: Version 0.99r14
                    356: 
                    357:   Revision 1.273  2017/06/27 11:06:02  brouard
                    358:   Summary: More documentation on projections
                    359: 
                    360:   Revision 1.272  2017/06/27 10:22:40  brouard
                    361:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    362: 
                    363:   Revision 1.271  2017/06/27 10:17:50  brouard
                    364:   Summary: Some bug with rint
                    365: 
                    366:   Revision 1.270  2017/05/24 05:45:29  brouard
                    367:   *** empty log message ***
                    368: 
                    369:   Revision 1.269  2017/05/23 08:39:25  brouard
                    370:   Summary: Code into subroutine, cleanings
                    371: 
                    372:   Revision 1.268  2017/05/18 20:09:32  brouard
                    373:   Summary: backprojection and confidence intervals of backprevalence
                    374: 
                    375:   Revision 1.267  2017/05/13 10:25:05  brouard
                    376:   Summary: temporary save for backprojection
                    377: 
                    378:   Revision 1.266  2017/05/13 07:26:12  brouard
                    379:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    380: 
                    381:   Revision 1.265  2017/04/26 16:22:11  brouard
                    382:   Summary: imach 0.99r13 Some bugs fixed
                    383: 
                    384:   Revision 1.264  2017/04/26 06:01:29  brouard
                    385:   Summary: Labels in graphs
                    386: 
                    387:   Revision 1.263  2017/04/24 15:23:15  brouard
                    388:   Summary: to save
                    389: 
                    390:   Revision 1.262  2017/04/18 16:48:12  brouard
                    391:   *** empty log message ***
                    392: 
                    393:   Revision 1.261  2017/04/05 10:14:09  brouard
                    394:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    395: 
                    396:   Revision 1.260  2017/04/04 17:46:59  brouard
                    397:   Summary: Gnuplot indexations fixed (humm)
                    398: 
                    399:   Revision 1.259  2017/04/04 13:01:16  brouard
                    400:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    401: 
                    402:   Revision 1.258  2017/04/03 10:17:47  brouard
                    403:   Summary: Version 0.99r12
                    404: 
                    405:   Some cleanings, conformed with updated documentation.
                    406: 
                    407:   Revision 1.257  2017/03/29 16:53:30  brouard
                    408:   Summary: Temp
                    409: 
                    410:   Revision 1.256  2017/03/27 05:50:23  brouard
                    411:   Summary: Temporary
                    412: 
                    413:   Revision 1.255  2017/03/08 16:02:28  brouard
                    414:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    415: 
                    416:   Revision 1.254  2017/03/08 07:13:00  brouard
                    417:   Summary: Fixing data parameter line
                    418: 
                    419:   Revision 1.253  2016/12/15 11:59:41  brouard
                    420:   Summary: 0.99 in progress
                    421: 
                    422:   Revision 1.252  2016/09/15 21:15:37  brouard
                    423:   *** empty log message ***
                    424: 
                    425:   Revision 1.251  2016/09/15 15:01:13  brouard
                    426:   Summary: not working
                    427: 
                    428:   Revision 1.250  2016/09/08 16:07:27  brouard
                    429:   Summary: continue
                    430: 
                    431:   Revision 1.249  2016/09/07 17:14:18  brouard
                    432:   Summary: Starting values from frequencies
                    433: 
                    434:   Revision 1.248  2016/09/07 14:10:18  brouard
                    435:   *** empty log message ***
                    436: 
                    437:   Revision 1.247  2016/09/02 11:11:21  brouard
                    438:   *** empty log message ***
                    439: 
                    440:   Revision 1.246  2016/09/02 08:49:22  brouard
                    441:   *** empty log message ***
                    442: 
                    443:   Revision 1.245  2016/09/02 07:25:01  brouard
                    444:   *** empty log message ***
                    445: 
                    446:   Revision 1.244  2016/09/02 07:17:34  brouard
                    447:   *** empty log message ***
                    448: 
                    449:   Revision 1.243  2016/09/02 06:45:35  brouard
                    450:   *** empty log message ***
                    451: 
                    452:   Revision 1.242  2016/08/30 15:01:20  brouard
                    453:   Summary: Fixing a lots
                    454: 
                    455:   Revision 1.241  2016/08/29 17:17:25  brouard
                    456:   Summary: gnuplot problem in Back projection to fix
                    457: 
                    458:   Revision 1.240  2016/08/29 07:53:18  brouard
                    459:   Summary: Better
                    460: 
                    461:   Revision 1.239  2016/08/26 15:51:03  brouard
                    462:   Summary: Improvement in Powell output in order to copy and paste
                    463: 
                    464:   Author:
                    465: 
                    466:   Revision 1.238  2016/08/26 14:23:35  brouard
                    467:   Summary: Starting tests of 0.99
                    468: 
                    469:   Revision 1.237  2016/08/26 09:20:19  brouard
                    470:   Summary: to valgrind
                    471: 
                    472:   Revision 1.236  2016/08/25 10:50:18  brouard
                    473:   *** empty log message ***
                    474: 
                    475:   Revision 1.235  2016/08/25 06:59:23  brouard
                    476:   *** empty log message ***
                    477: 
                    478:   Revision 1.234  2016/08/23 16:51:20  brouard
                    479:   *** empty log message ***
                    480: 
                    481:   Revision 1.233  2016/08/23 07:40:50  brouard
                    482:   Summary: not working
                    483: 
                    484:   Revision 1.232  2016/08/22 14:20:21  brouard
                    485:   Summary: not working
                    486: 
                    487:   Revision 1.231  2016/08/22 07:17:15  brouard
                    488:   Summary: not working
                    489: 
                    490:   Revision 1.230  2016/08/22 06:55:53  brouard
                    491:   Summary: Not working
                    492: 
                    493:   Revision 1.229  2016/07/23 09:45:53  brouard
                    494:   Summary: Completing for func too
                    495: 
                    496:   Revision 1.228  2016/07/22 17:45:30  brouard
                    497:   Summary: Fixing some arrays, still debugging
                    498: 
                    499:   Revision 1.226  2016/07/12 18:42:34  brouard
                    500:   Summary: temp
                    501: 
                    502:   Revision 1.225  2016/07/12 08:40:03  brouard
                    503:   Summary: saving but not running
                    504: 
                    505:   Revision 1.224  2016/07/01 13:16:01  brouard
                    506:   Summary: Fixes
                    507: 
                    508:   Revision 1.223  2016/02/19 09:23:35  brouard
                    509:   Summary: temporary
                    510: 
                    511:   Revision 1.222  2016/02/17 08:14:50  brouard
                    512:   Summary: Probably last 0.98 stable version 0.98r6
                    513: 
                    514:   Revision 1.221  2016/02/15 23:35:36  brouard
                    515:   Summary: minor bug
                    516: 
                    517:   Revision 1.219  2016/02/15 00:48:12  brouard
                    518:   *** empty log message ***
                    519: 
                    520:   Revision 1.218  2016/02/12 11:29:23  brouard
                    521:   Summary: 0.99 Back projections
                    522: 
                    523:   Revision 1.217  2015/12/23 17:18:31  brouard
                    524:   Summary: Experimental backcast
                    525: 
                    526:   Revision 1.216  2015/12/18 17:32:11  brouard
                    527:   Summary: 0.98r4 Warning and status=-2
                    528: 
                    529:   Version 0.98r4 is now:
                    530:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    531:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    532:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    533: 
                    534:   Revision 1.215  2015/12/16 08:52:24  brouard
                    535:   Summary: 0.98r4 working
                    536: 
                    537:   Revision 1.214  2015/12/16 06:57:54  brouard
                    538:   Summary: temporary not working
                    539: 
                    540:   Revision 1.213  2015/12/11 18:22:17  brouard
                    541:   Summary: 0.98r4
                    542: 
                    543:   Revision 1.212  2015/11/21 12:47:24  brouard
                    544:   Summary: minor typo
                    545: 
                    546:   Revision 1.211  2015/11/21 12:41:11  brouard
                    547:   Summary: 0.98r3 with some graph of projected cross-sectional
                    548: 
                    549:   Author: Nicolas Brouard
                    550: 
                    551:   Revision 1.210  2015/11/18 17:41:20  brouard
                    552:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
                    553:   Summary: Adding ftolpl parameter
                    554:   Author: N Brouard
                    555: 
                    556:   We had difficulties to get smoothed confidence intervals. It was due
                    557:   to the period prevalence which wasn't computed accurately. The inner
                    558:   parameter ftolpl is now an outer parameter of the .imach parameter
                    559:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    560:   computation are long.
                    561: 
                    562:   Revision 1.208  2015/11/17 14:31:57  brouard
                    563:   Summary: temporary
                    564: 
                    565:   Revision 1.207  2015/10/27 17:36:57  brouard
                    566:   *** empty log message ***
                    567: 
                    568:   Revision 1.206  2015/10/24 07:14:11  brouard
                    569:   *** empty log message ***
                    570: 
                    571:   Revision 1.205  2015/10/23 15:50:53  brouard
                    572:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    573: 
                    574:   Revision 1.204  2015/10/01 16:20:26  brouard
                    575:   Summary: Some new graphs of contribution to likelihood
                    576: 
                    577:   Revision 1.203  2015/09/30 17:45:14  brouard
                    578:   Summary: looking at better estimation of the hessian
                    579: 
                    580:   Also a better criteria for convergence to the period prevalence And
                    581:   therefore adding the number of years needed to converge. (The
                    582:   prevalence in any alive state shold sum to one
                    583: 
                    584:   Revision 1.202  2015/09/22 19:45:16  brouard
                    585:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    586: 
                    587:   Revision 1.201  2015/09/15 17:34:58  brouard
                    588:   Summary: 0.98r0
                    589: 
                    590:   - Some new graphs like suvival functions
                    591:   - Some bugs fixed like model=1+age+V2.
                    592: 
                    593:   Revision 1.200  2015/09/09 16:53:55  brouard
                    594:   Summary: Big bug thanks to Flavia
                    595: 
                    596:   Even model=1+age+V2. did not work anymore
                    597: 
                    598:   Revision 1.199  2015/09/07 14:09:23  brouard
                    599:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    600: 
                    601:   Revision 1.198  2015/09/03 07:14:39  brouard
                    602:   Summary: 0.98q5 Flavia
                    603: 
                    604:   Revision 1.197  2015/09/01 18:24:39  brouard
                    605:   *** empty log message ***
                    606: 
                    607:   Revision 1.196  2015/08/18 23:17:52  brouard
                    608:   Summary: 0.98q5
                    609: 
                    610:   Revision 1.195  2015/08/18 16:28:39  brouard
                    611:   Summary: Adding a hack for testing purpose
                    612: 
                    613:   After reading the title, ftol and model lines, if the comment line has
                    614:   a q, starting with #q, the answer at the end of the run is quit. It
                    615:   permits to run test files in batch with ctest. The former workaround was
                    616:   $ echo q | imach foo.imach
                    617: 
                    618:   Revision 1.194  2015/08/18 13:32:00  brouard
                    619:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    620: 
                    621:   Revision 1.193  2015/08/04 07:17:42  brouard
                    622:   Summary: 0.98q4
                    623: 
                    624:   Revision 1.192  2015/07/16 16:49:02  brouard
                    625:   Summary: Fixing some outputs
                    626: 
                    627:   Revision 1.191  2015/07/14 10:00:33  brouard
                    628:   Summary: Some fixes
                    629: 
                    630:   Revision 1.190  2015/05/05 08:51:13  brouard
                    631:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    632: 
                    633:   Fix 1+age+.
                    634: 
                    635:   Revision 1.189  2015/04/30 14:45:16  brouard
                    636:   Summary: 0.98q2
                    637: 
                    638:   Revision 1.188  2015/04/30 08:27:53  brouard
                    639:   *** empty log message ***
                    640: 
                    641:   Revision 1.187  2015/04/29 09:11:15  brouard
                    642:   *** empty log message ***
                    643: 
                    644:   Revision 1.186  2015/04/23 12:01:52  brouard
                    645:   Summary: V1*age is working now, version 0.98q1
                    646: 
                    647:   Some codes had been disabled in order to simplify and Vn*age was
                    648:   working in the optimization phase, ie, giving correct MLE parameters,
                    649:   but, as usual, outputs were not correct and program core dumped.
                    650: 
                    651:   Revision 1.185  2015/03/11 13:26:42  brouard
                    652:   Summary: Inclusion of compile and links command line for Intel Compiler
                    653: 
                    654:   Revision 1.184  2015/03/11 11:52:39  brouard
                    655:   Summary: Back from Windows 8. Intel Compiler
                    656: 
                    657:   Revision 1.183  2015/03/10 20:34:32  brouard
                    658:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    659: 
                    660:   We use directest instead of original Powell test; probably no
                    661:   incidence on the results, but better justifications;
                    662:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    663:   wrong results.
                    664: 
                    665:   Revision 1.182  2015/02/12 08:19:57  brouard
                    666:   Summary: Trying to keep directest which seems simpler and more general
                    667:   Author: Nicolas Brouard
                    668: 
                    669:   Revision 1.181  2015/02/11 23:22:24  brouard
                    670:   Summary: Comments on Powell added
                    671: 
                    672:   Author:
                    673: 
                    674:   Revision 1.180  2015/02/11 17:33:45  brouard
                    675:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    676: 
                    677:   Revision 1.179  2015/01/04 09:57:06  brouard
                    678:   Summary: back to OS/X
                    679: 
                    680:   Revision 1.178  2015/01/04 09:35:48  brouard
                    681:   *** empty log message ***
                    682: 
                    683:   Revision 1.177  2015/01/03 18:40:56  brouard
                    684:   Summary: Still testing ilc32 on OSX
                    685: 
                    686:   Revision 1.176  2015/01/03 16:45:04  brouard
                    687:   *** empty log message ***
                    688: 
                    689:   Revision 1.175  2015/01/03 16:33:42  brouard
                    690:   *** empty log message ***
                    691: 
                    692:   Revision 1.174  2015/01/03 16:15:49  brouard
                    693:   Summary: Still in cross-compilation
                    694: 
                    695:   Revision 1.173  2015/01/03 12:06:26  brouard
                    696:   Summary: trying to detect cross-compilation
                    697: 
                    698:   Revision 1.172  2014/12/27 12:07:47  brouard
                    699:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    700: 
                    701:   Revision 1.171  2014/12/23 13:26:59  brouard
                    702:   Summary: Back from Visual C
                    703: 
                    704:   Still problem with utsname.h on Windows
                    705: 
                    706:   Revision 1.170  2014/12/23 11:17:12  brouard
                    707:   Summary: Cleaning some \%% back to %%
                    708: 
                    709:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    710: 
                    711:   Revision 1.169  2014/12/22 23:08:31  brouard
                    712:   Summary: 0.98p
                    713: 
                    714:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    715: 
                    716:   Revision 1.168  2014/12/22 15:17:42  brouard
                    717:   Summary: update
                    718: 
                    719:   Revision 1.167  2014/12/22 13:50:56  brouard
                    720:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    721: 
                    722:   Testing on Linux 64
                    723: 
                    724:   Revision 1.166  2014/12/22 11:40:47  brouard
                    725:   *** empty log message ***
                    726: 
                    727:   Revision 1.165  2014/12/16 11:20:36  brouard
                    728:   Summary: After compiling on Visual C
                    729: 
                    730:   * imach.c (Module): Merging 1.61 to 1.162
                    731: 
                    732:   Revision 1.164  2014/12/16 10:52:11  brouard
                    733:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    734: 
                    735:   * imach.c (Module): Merging 1.61 to 1.162
                    736: 
                    737:   Revision 1.163  2014/12/16 10:30:11  brouard
                    738:   * imach.c (Module): Merging 1.61 to 1.162
                    739: 
                    740:   Revision 1.162  2014/09/25 11:43:39  brouard
                    741:   Summary: temporary backup 0.99!
                    742: 
                    743:   Revision 1.1  2014/09/16 11:06:58  brouard
                    744:   Summary: With some code (wrong) for nlopt
                    745: 
                    746:   Author:
                    747: 
                    748:   Revision 1.161  2014/09/15 20:41:41  brouard
                    749:   Summary: Problem with macro SQR on Intel compiler
                    750: 
                    751:   Revision 1.160  2014/09/02 09:24:05  brouard
                    752:   *** empty log message ***
                    753: 
                    754:   Revision 1.159  2014/09/01 10:34:10  brouard
                    755:   Summary: WIN32
                    756:   Author: Brouard
                    757: 
                    758:   Revision 1.158  2014/08/27 17:11:51  brouard
                    759:   *** empty log message ***
                    760: 
                    761:   Revision 1.157  2014/08/27 16:26:55  brouard
                    762:   Summary: Preparing windows Visual studio version
                    763:   Author: Brouard
                    764: 
                    765:   In order to compile on Visual studio, time.h is now correct and time_t
                    766:   and tm struct should be used. difftime should be used but sometimes I
                    767:   just make the differences in raw time format (time(&now).
                    768:   Trying to suppress #ifdef LINUX
                    769:   Add xdg-open for __linux in order to open default browser.
                    770: 
                    771:   Revision 1.156  2014/08/25 20:10:10  brouard
                    772:   *** empty log message ***
                    773: 
                    774:   Revision 1.155  2014/08/25 18:32:34  brouard
                    775:   Summary: New compile, minor changes
                    776:   Author: Brouard
                    777: 
                    778:   Revision 1.154  2014/06/20 17:32:08  brouard
                    779:   Summary: Outputs now all graphs of convergence to period prevalence
                    780: 
                    781:   Revision 1.153  2014/06/20 16:45:46  brouard
                    782:   Summary: If 3 live state, convergence to period prevalence on same graph
                    783:   Author: Brouard
                    784: 
                    785:   Revision 1.152  2014/06/18 17:54:09  brouard
                    786:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    787: 
                    788:   Revision 1.151  2014/06/18 16:43:30  brouard
                    789:   *** empty log message ***
                    790: 
                    791:   Revision 1.150  2014/06/18 16:42:35  brouard
                    792:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    793:   Author: brouard
                    794: 
                    795:   Revision 1.149  2014/06/18 15:51:14  brouard
                    796:   Summary: Some fixes in parameter files errors
                    797:   Author: Nicolas Brouard
                    798: 
                    799:   Revision 1.148  2014/06/17 17:38:48  brouard
                    800:   Summary: Nothing new
                    801:   Author: Brouard
                    802: 
                    803:   Just a new packaging for OS/X version 0.98nS
                    804: 
                    805:   Revision 1.147  2014/06/16 10:33:11  brouard
                    806:   *** empty log message ***
                    807: 
                    808:   Revision 1.146  2014/06/16 10:20:28  brouard
                    809:   Summary: Merge
                    810:   Author: Brouard
                    811: 
                    812:   Merge, before building revised version.
                    813: 
                    814:   Revision 1.145  2014/06/10 21:23:15  brouard
                    815:   Summary: Debugging with valgrind
                    816:   Author: Nicolas Brouard
                    817: 
                    818:   Lot of changes in order to output the results with some covariates
                    819:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    820:   improve the code.
                    821:   No more memory valgrind error but a lot has to be done in order to
                    822:   continue the work of splitting the code into subroutines.
                    823:   Also, decodemodel has been improved. Tricode is still not
                    824:   optimal. nbcode should be improved. Documentation has been added in
                    825:   the source code.
                    826: 
                    827:   Revision 1.143  2014/01/26 09:45:38  brouard
                    828:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    829: 
                    830:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    831:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    832: 
                    833:   Revision 1.142  2014/01/26 03:57:36  brouard
                    834:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    835: 
                    836:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    837: 
                    838:   Revision 1.141  2014/01/26 02:42:01  brouard
                    839:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    840: 
                    841:   Revision 1.140  2011/09/02 10:37:54  brouard
                    842:   Summary: times.h is ok with mingw32 now.
                    843: 
                    844:   Revision 1.139  2010/06/14 07:50:17  brouard
                    845:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    846:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    847: 
                    848:   Revision 1.138  2010/04/30 18:19:40  brouard
                    849:   *** empty log message ***
                    850: 
                    851:   Revision 1.137  2010/04/29 18:11:38  brouard
                    852:   (Module): Checking covariates for more complex models
                    853:   than V1+V2. A lot of change to be done. Unstable.
                    854: 
                    855:   Revision 1.136  2010/04/26 20:30:53  brouard
                    856:   (Module): merging some libgsl code. Fixing computation
                    857:   of likelione (using inter/intrapolation if mle = 0) in order to
                    858:   get same likelihood as if mle=1.
                    859:   Some cleaning of code and comments added.
                    860: 
                    861:   Revision 1.135  2009/10/29 15:33:14  brouard
                    862:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    863: 
                    864:   Revision 1.134  2009/10/29 13:18:53  brouard
                    865:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    866: 
                    867:   Revision 1.133  2009/07/06 10:21:25  brouard
                    868:   just nforces
                    869: 
                    870:   Revision 1.132  2009/07/06 08:22:05  brouard
                    871:   Many tings
                    872: 
                    873:   Revision 1.131  2009/06/20 16:22:47  brouard
                    874:   Some dimensions resccaled
                    875: 
                    876:   Revision 1.130  2009/05/26 06:44:34  brouard
                    877:   (Module): Max Covariate is now set to 20 instead of 8. A
                    878:   lot of cleaning with variables initialized to 0. Trying to make
                    879:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    880: 
                    881:   Revision 1.129  2007/08/31 13:49:27  lievre
                    882:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    883: 
                    884:   Revision 1.128  2006/06/30 13:02:05  brouard
                    885:   (Module): Clarifications on computing e.j
                    886: 
                    887:   Revision 1.127  2006/04/28 18:11:50  brouard
                    888:   (Module): Yes the sum of survivors was wrong since
                    889:   imach-114 because nhstepm was no more computed in the age
                    890:   loop. Now we define nhstepma in the age loop.
                    891:   (Module): In order to speed up (in case of numerous covariates) we
                    892:   compute health expectancies (without variances) in a first step
                    893:   and then all the health expectancies with variances or standard
                    894:   deviation (needs data from the Hessian matrices) which slows the
                    895:   computation.
                    896:   In the future we should be able to stop the program is only health
                    897:   expectancies and graph are needed without standard deviations.
                    898: 
                    899:   Revision 1.126  2006/04/28 17:23:28  brouard
                    900:   (Module): Yes the sum of survivors was wrong since
                    901:   imach-114 because nhstepm was no more computed in the age
                    902:   loop. Now we define nhstepma in the age loop.
                    903:   Version 0.98h
                    904: 
                    905:   Revision 1.125  2006/04/04 15:20:31  lievre
                    906:   Errors in calculation of health expectancies. Age was not initialized.
                    907:   Forecasting file added.
                    908: 
                    909:   Revision 1.124  2006/03/22 17:13:53  lievre
                    910:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    911:   The log-likelihood is printed in the log file
                    912: 
                    913:   Revision 1.123  2006/03/20 10:52:43  brouard
                    914:   * imach.c (Module): <title> changed, corresponds to .htm file
                    915:   name. <head> headers where missing.
                    916: 
                    917:   * imach.c (Module): Weights can have a decimal point as for
                    918:   English (a comma might work with a correct LC_NUMERIC environment,
                    919:   otherwise the weight is truncated).
                    920:   Modification of warning when the covariates values are not 0 or
                    921:   1.
                    922:   Version 0.98g
                    923: 
                    924:   Revision 1.122  2006/03/20 09:45:41  brouard
                    925:   (Module): Weights can have a decimal point as for
                    926:   English (a comma might work with a correct LC_NUMERIC environment,
                    927:   otherwise the weight is truncated).
                    928:   Modification of warning when the covariates values are not 0 or
                    929:   1.
                    930:   Version 0.98g
                    931: 
                    932:   Revision 1.121  2006/03/16 17:45:01  lievre
                    933:   * imach.c (Module): Comments concerning covariates added
                    934: 
                    935:   * imach.c (Module): refinements in the computation of lli if
                    936:   status=-2 in order to have more reliable computation if stepm is
                    937:   not 1 month. Version 0.98f
                    938: 
                    939:   Revision 1.120  2006/03/16 15:10:38  lievre
                    940:   (Module): refinements in the computation of lli if
                    941:   status=-2 in order to have more reliable computation if stepm is
                    942:   not 1 month. Version 0.98f
                    943: 
                    944:   Revision 1.119  2006/03/15 17:42:26  brouard
                    945:   (Module): Bug if status = -2, the loglikelihood was
                    946:   computed as likelihood omitting the logarithm. Version O.98e
                    947: 
                    948:   Revision 1.118  2006/03/14 18:20:07  brouard
                    949:   (Module): varevsij Comments added explaining the second
                    950:   table of variances if popbased=1 .
                    951:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    952:   (Module): Function pstamp added
                    953:   (Module): Version 0.98d
                    954: 
                    955:   Revision 1.117  2006/03/14 17:16:22  brouard
                    956:   (Module): varevsij Comments added explaining the second
                    957:   table of variances if popbased=1 .
                    958:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    959:   (Module): Function pstamp added
                    960:   (Module): Version 0.98d
                    961: 
                    962:   Revision 1.116  2006/03/06 10:29:27  brouard
                    963:   (Module): Variance-covariance wrong links and
                    964:   varian-covariance of ej. is needed (Saito).
                    965: 
                    966:   Revision 1.115  2006/02/27 12:17:45  brouard
                    967:   (Module): One freematrix added in mlikeli! 0.98c
                    968: 
                    969:   Revision 1.114  2006/02/26 12:57:58  brouard
                    970:   (Module): Some improvements in processing parameter
                    971:   filename with strsep.
                    972: 
                    973:   Revision 1.113  2006/02/24 14:20:24  brouard
                    974:   (Module): Memory leaks checks with valgrind and:
                    975:   datafile was not closed, some imatrix were not freed and on matrix
                    976:   allocation too.
                    977: 
                    978:   Revision 1.112  2006/01/30 09:55:26  brouard
                    979:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    980: 
                    981:   Revision 1.111  2006/01/25 20:38:18  brouard
                    982:   (Module): Lots of cleaning and bugs added (Gompertz)
                    983:   (Module): Comments can be added in data file. Missing date values
                    984:   can be a simple dot '.'.
                    985: 
                    986:   Revision 1.110  2006/01/25 00:51:50  brouard
                    987:   (Module): Lots of cleaning and bugs added (Gompertz)
                    988: 
                    989:   Revision 1.109  2006/01/24 19:37:15  brouard
                    990:   (Module): Comments (lines starting with a #) are allowed in data.
                    991: 
                    992:   Revision 1.108  2006/01/19 18:05:42  lievre
                    993:   Gnuplot problem appeared...
                    994:   To be fixed
                    995: 
                    996:   Revision 1.107  2006/01/19 16:20:37  brouard
                    997:   Test existence of gnuplot in imach path
                    998: 
                    999:   Revision 1.106  2006/01/19 13:24:36  brouard
                   1000:   Some cleaning and links added in html output
                   1001: 
                   1002:   Revision 1.105  2006/01/05 20:23:19  lievre
                   1003:   *** empty log message ***
                   1004: 
                   1005:   Revision 1.104  2005/09/30 16:11:43  lievre
                   1006:   (Module): sump fixed, loop imx fixed, and simplifications.
                   1007:   (Module): If the status is missing at the last wave but we know
                   1008:   that the person is alive, then we can code his/her status as -2
                   1009:   (instead of missing=-1 in earlier versions) and his/her
                   1010:   contributions to the likelihood is 1 - Prob of dying from last
                   1011:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                   1012:   the healthy state at last known wave). Version is 0.98
                   1013: 
                   1014:   Revision 1.103  2005/09/30 15:54:49  lievre
                   1015:   (Module): sump fixed, loop imx fixed, and simplifications.
                   1016: 
                   1017:   Revision 1.102  2004/09/15 17:31:30  brouard
                   1018:   Add the possibility to read data file including tab characters.
                   1019: 
                   1020:   Revision 1.101  2004/09/15 10:38:38  brouard
                   1021:   Fix on curr_time
                   1022: 
                   1023:   Revision 1.100  2004/07/12 18:29:06  brouard
                   1024:   Add version for Mac OS X. Just define UNIX in Makefile
                   1025: 
                   1026:   Revision 1.99  2004/06/05 08:57:40  brouard
                   1027:   *** empty log message ***
                   1028: 
                   1029:   Revision 1.98  2004/05/16 15:05:56  brouard
                   1030:   New version 0.97 . First attempt to estimate force of mortality
                   1031:   directly from the data i.e. without the need of knowing the health
                   1032:   state at each age, but using a Gompertz model: log u =a + b*age .
                   1033:   This is the basic analysis of mortality and should be done before any
                   1034:   other analysis, in order to test if the mortality estimated from the
                   1035:   cross-longitudinal survey is different from the mortality estimated
                   1036:   from other sources like vital statistic data.
                   1037: 
                   1038:   The same imach parameter file can be used but the option for mle should be -3.
                   1039: 
                   1040:   Agnès, who wrote this part of the code, tried to keep most of the
                   1041:   former routines in order to include the new code within the former code.
                   1042: 
                   1043:   The output is very simple: only an estimate of the intercept and of
                   1044:   the slope with 95% confident intervals.
                   1045: 
                   1046:   Current limitations:
                   1047:   A) Even if you enter covariates, i.e. with the
                   1048:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                   1049:   B) There is no computation of Life Expectancy nor Life Table.
                   1050: 
                   1051:   Revision 1.97  2004/02/20 13:25:42  lievre
                   1052:   Version 0.96d. Population forecasting command line is (temporarily)
                   1053:   suppressed.
                   1054: 
                   1055:   Revision 1.96  2003/07/15 15:38:55  brouard
                   1056:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                   1057:   rewritten within the same printf. Workaround: many printfs.
                   1058: 
                   1059:   Revision 1.95  2003/07/08 07:54:34  brouard
                   1060:   * imach.c (Repository):
                   1061:   (Repository): Using imachwizard code to output a more meaningful covariance
                   1062:   matrix (cov(a12,c31) instead of numbers.
                   1063: 
                   1064:   Revision 1.94  2003/06/27 13:00:02  brouard
                   1065:   Just cleaning
                   1066: 
                   1067:   Revision 1.93  2003/06/25 16:33:55  brouard
                   1068:   (Module): On windows (cygwin) function asctime_r doesn't
                   1069:   exist so I changed back to asctime which exists.
                   1070:   (Module): Version 0.96b
                   1071: 
                   1072:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1073:   (Module): On windows (cygwin) function asctime_r doesn't
                   1074:   exist so I changed back to asctime which exists.
                   1075: 
                   1076:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1077:   * imach.c (Repository): Duplicated warning errors corrected.
                   1078:   (Repository): Elapsed time after each iteration is now output. It
                   1079:   helps to forecast when convergence will be reached. Elapsed time
                   1080:   is stamped in powell.  We created a new html file for the graphs
                   1081:   concerning matrix of covariance. It has extension -cov.htm.
                   1082: 
                   1083:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1084:   (Module): Some bugs corrected for windows. Also, when
                   1085:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1086:   of the covariance matrix to be input.
                   1087: 
                   1088:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1089:   (Module): Some bugs corrected for windows. Also, when
                   1090:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1091:   of the covariance matrix to be input.
                   1092: 
                   1093:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1094:   * imach.c (Repository): Create a sub-directory where all the secondary files are. Only imach, htm, gp and r(imach) are on the main directory. Correct time and other things.
                   1095: 
                   1096:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1097:   Version 0.96
                   1098: 
                   1099:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1100:   (Module): Change position of html and gnuplot routines and added
                   1101:   routine fileappend.
                   1102: 
                   1103:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1104:   * imach.c (Repository): Check when date of death was earlier that
                   1105:   current date of interview. It may happen when the death was just
                   1106:   prior to the death. In this case, dh was negative and likelihood
                   1107:   was wrong (infinity). We still send an "Error" but patch by
                   1108:   assuming that the date of death was just one stepm after the
                   1109:   interview.
                   1110:   (Repository): Because some people have very long ID (first column)
                   1111:   we changed int to long in num[] and we added a new lvector for
                   1112:   memory allocation. But we also truncated to 8 characters (left
                   1113:   truncation)
                   1114:   (Repository): No more line truncation errors.
                   1115: 
                   1116:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1117:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1118:   place. It differs from routine "prevalence" which may be called
                   1119:   many times. Probs is memory consuming and must be used with
                   1120:   parcimony.
                   1121:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1122: 
                   1123:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1124:   *** empty log message ***
                   1125: 
                   1126:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1127:   Add log in  imach.c and  fullversion number is now printed.
                   1128: 
                   1129: */
                   1130: /*
                   1131:    Interpolated Markov Chain
                   1132: 
                   1133:   Short summary of the programme:
                   1134:   
                   1135:   This program computes Healthy Life Expectancies or State-specific
                   1136:   (if states aren't health statuses) Expectancies from
                   1137:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1138: 
                   1139:   -1- a first survey ("cross") where individuals from different ages
                   1140:   are interviewed on their health status or degree of disability (in
                   1141:   the case of a health survey which is our main interest)
                   1142: 
                   1143:   -2- at least a second wave of interviews ("longitudinal") which
                   1144:   measure each change (if any) in individual health status.  Health
                   1145:   expectancies are computed from the time spent in each health state
                   1146:   according to a model. More health states you consider, more time is
                   1147:   necessary to reach the Maximum Likelihood of the parameters involved
                   1148:   in the model.  The simplest model is the multinomial logistic model
                   1149:   where pij is the probability to be observed in state j at the second
                   1150:   wave conditional to be observed in state i at the first
                   1151:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1152:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1153:   have a more complex model than "constant and age", you should modify
                   1154:   the program where the markup *Covariates have to be included here
                   1155:   again* invites you to do it.  More covariates you add, slower the
                   1156:   convergence.
                   1157: 
                   1158:   The advantage of this computer programme, compared to a simple
                   1159:   multinomial logistic model, is clear when the delay between waves is not
                   1160:   identical for each individual. Also, if a individual missed an
                   1161:   intermediate interview, the information is lost, but taken into
                   1162:   account using an interpolation or extrapolation.  
                   1163: 
                   1164:   hPijx is the probability to be observed in state i at age x+h
                   1165:   conditional to the observed state i at age x. The delay 'h' can be
                   1166:   split into an exact number (nh*stepm) of unobserved intermediate
                   1167:   states. This elementary transition (by month, quarter,
                   1168:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1169:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1170:   and the contribution of each individual to the likelihood is simply
                   1171:   hPijx.
                   1172: 
                   1173:   Also this programme outputs the covariance matrix of the parameters but also
                   1174:   of the life expectancies. It also computes the period (stable) prevalence.
                   1175: 
                   1176: Back prevalence and projections:
                   1177: 
                   1178:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1179:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1180:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1181:    mobilavproj)
                   1182: 
                   1183:     Computes the back prevalence limit for any combination of
                   1184:     covariate values k at any age between ageminpar and agemaxpar and
                   1185:     returns it in **bprlim. In the loops,
                   1186: 
                   1187:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1188:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1189: 
                   1190:    - hBijx Back Probability to be in state i at age x-h being in j at x
                   1191:    Computes for any combination of covariates k and any age between bage and fage 
                   1192:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1193:                        oldm=oldms;savm=savms;
                   1194: 
                   1195:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
                   1196:      Computes the transition matrix starting at age 'age' over
                   1197:      'nhstepm*hstepm*stepm' months (i.e. until
                   1198:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   1199:      nhstepm*hstepm matrices. 
                   1200: 
                   1201:      Returns p3mat[i][j][h] after calling
                   1202:      p3mat[i][j][h]=matprod2(newm,
                   1203:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1204:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1205:      oldm);
                   1206: 
                   1207: Important routines
                   1208: 
                   1209: - func (or funcone), computes logit (pij) distinguishing
                   1210:   o fixed variables (single or product dummies or quantitative);
                   1211:   o varying variables by:
                   1212:    (1) wave (single, product dummies, quantitative), 
                   1213:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1214:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1215:        % varying dummy (not done) or quantitative (not done);
                   1216: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1217:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1218: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
                   1219:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
                   1220:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
                   1221: 
                   1222: 
                   1223:   
                   1224:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1225:            Institut national d'études démographiques, Paris.
                   1226:   This software have been partly granted by Euro-REVES, a concerted action
                   1227:   from the European Union.
                   1228:   It is copyrighted identically to a GNU software product, ie programme and
                   1229:   software can be distributed freely for non commercial use. Latest version
                   1230:   can be accessed at http://euroreves.ined.fr/imach .
                   1231: 
                   1232:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1233:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1234:   
                   1235:   **********************************************************************/
                   1236: /*
                   1237:   main
                   1238:   read parameterfile
                   1239:   read datafile
                   1240:   concatwav
                   1241:   freqsummary
                   1242:   if (mle >= 1)
                   1243:     mlikeli
                   1244:   print results files
                   1245:   if mle==1 
                   1246:      computes hessian
                   1247:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1248:       begin-prev-date,...
                   1249:   open gnuplot file
                   1250:   open html file
                   1251:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1252:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1253:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1254:     freexexit2 possible for memory heap.
                   1255: 
                   1256:   h Pij x                         | pij_nom  ficrestpij
                   1257:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1258:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1259:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1260: 
                   1261:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1262:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1263:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1264:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1265:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1266: 
                   1267:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1268:   health expectancies
                   1269:   Variance-covariance of DFLE
                   1270:   prevalence()
                   1271:    movingaverage()
                   1272:   varevsij() 
                   1273:   if popbased==1 varevsij(,popbased)
                   1274:   total life expectancies
                   1275:   Variance of period (stable) prevalence
                   1276:  end
                   1277: */
                   1278: 
                   1279: /* #define DEBUG */
                   1280: /* #define DEBUGBRENT */
                   1281: /* #define DEBUGLINMIN */
                   1282: /* #define DEBUGHESS */
                   1283: #define DEBUGHESSIJ
                   1284: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
                   1285: #define POWELL /* Instead of NLOPT */
                   1286: #define POWELLNOF3INFF1TEST /* Skip test */
                   1287: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1288: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
                   1289: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.3       brouard  1290: /* #define POWELLORIGINCONJUGATE  /\* Don't use conjugate but biggest decrease if valuable *\/ */
1.5     ! brouard  1291: /* #define NOTMINFIT */
1.1       brouard  1292: 
                   1293: #include <math.h>
                   1294: #include <stdio.h>
                   1295: #include <stdlib.h>
                   1296: #include <string.h>
                   1297: #include <ctype.h>
                   1298: 
                   1299: #ifdef _WIN32
                   1300: #include <io.h>
                   1301: #include <windows.h>
                   1302: #include <tchar.h>
                   1303: #else
                   1304: #include <unistd.h>
                   1305: #endif
                   1306: 
                   1307: #include <limits.h>
                   1308: #include <sys/types.h>
                   1309: 
                   1310: #if defined(__GNUC__)
                   1311: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1312: #endif
                   1313: 
                   1314: #include <sys/stat.h>
                   1315: #include <errno.h>
                   1316: /* extern int errno; */
                   1317: 
                   1318: /* #ifdef LINUX */
                   1319: /* #include <time.h> */
                   1320: /* #include "timeval.h" */
                   1321: /* #else */
                   1322: /* #include <sys/time.h> */
                   1323: /* #endif */
                   1324: 
                   1325: #include <time.h>
                   1326: 
                   1327: #ifdef GSL
                   1328: #include <gsl/gsl_errno.h>
                   1329: #include <gsl/gsl_multimin.h>
                   1330: #endif
                   1331: 
                   1332: 
                   1333: #ifdef NLOPT
                   1334: #include <nlopt.h>
                   1335: typedef struct {
                   1336:   double (* function)(double [] );
                   1337: } myfunc_data ;
                   1338: #endif
                   1339: 
                   1340: /* #include <libintl.h> */
                   1341: /* #define _(String) gettext (String) */
                   1342: 
                   1343: #define MAXLINE 16384 /* Was 256 and 1024 and 2048. Overflow with 312 with 2 states and 4 covariates. Should be ok */
                   1344: 
                   1345: #define GNUPLOTPROGRAM "gnuplot"
                   1346: #define GNUPLOTVERSION 5.1
                   1347: double gnuplotversion=GNUPLOTVERSION;
                   1348: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                   1349: #define FILENAMELENGTH 256
                   1350: 
                   1351: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1352: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1353: 
                   1354: #define MAXPARM 216 /**< Maximum number of parameters for the optimization was 128 */
                   1355: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
                   1356: 
                   1357: #define NINTERVMAX 8
                   1358: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1359: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                   1360: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
                   1361: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   1362: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1363: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
                   1364: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
                   1365: #define YEARM 12. /**< Number of months per year */
                   1366: /* #define AGESUP 130 */
                   1367: /* #define AGESUP 150 */
                   1368: #define AGESUP 200
                   1369: #define AGEINF 0
                   1370: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
                   1371: #define AGEBASE 40
                   1372: #define AGEOVERFLOW 1.e20
                   1373: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
                   1374: #ifdef _WIN32
                   1375: #define DIRSEPARATOR '\\'
                   1376: #define CHARSEPARATOR "\\"
                   1377: #define ODIRSEPARATOR '/'
                   1378: #else
                   1379: #define DIRSEPARATOR '/'
                   1380: #define CHARSEPARATOR "/"
                   1381: #define ODIRSEPARATOR '\\'
                   1382: #endif
                   1383: 
1.5     ! brouard  1384: /* $Id: imachprax.c,v 1.4 2023/06/22 12:50:51 brouard Exp $ */
1.1       brouard  1385: /* $State: Exp $ */
                   1386: #include "version.h"
                   1387: char version[]=__IMACH_VERSION__;
1.2       brouard  1388: 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";
1.5     ! brouard  1389: char fullversion[]="$Revision: 1.4 $ $Date: 2023/06/22 12:50:51 $"; 
1.1       brouard  1390: char strstart[80];
                   1391: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
                   1392: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
                   1393: int debugILK=0; /* debugILK is set by a #d in a comment line */
                   1394: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
                   1395: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1396: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   1397: int cptcovn=0; /**< cptcovn decodemodel: number of covariates k of the models excluding age*products =6 and age*age but including products */
                   1398: int cptcovt=0; /**< cptcovt: total number of covariates of the model (2) nbocc(+)+1 = 8 excepting constant and age and age*age */
                   1399: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1400: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
                   1401: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1402: int cptcovprodage=0; /**< Number of fixed covariates with age: V3*age or V2*V3*age 1 */
                   1403: int cptcovprodvage=0; /**< Number of varying covariates with age: V7*age or V7*V6*age */
                   1404: int cptcovdageprod=0; /**< Number of doubleproducts with age, since 0.99r44 only: age*Vn*Vm for gnuplot printing*/
                   1405: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                   1406: 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) */
                   1407: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1408: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
                   1409: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
                   1410: 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 */
                   1411: 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 */
                   1412: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (single or product, dummy or quantitative) in the model */
                   1413: 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 */
                   1414: int nsd=0; /**< Total number of single dummy variables (output) */
                   1415: int nsq=0; /**< Total number of single quantitative variables (output) */
                   1416: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
                   1417: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
                   1418: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1419: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
                   1420: int cptcov=0; /* Working variable */
                   1421: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
                   1422: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
                   1423: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
                   1424: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
                   1425: int nlstate=2; /* Number of live states */
                   1426: int ndeath=1; /* Number of dead states */
                   1427: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
                   1428: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1429: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
                   1430: int popbased=0;
                   1431: 
                   1432: int *wav; /* Number of waves for this individuual 0 is possible */
                   1433: int maxwav=0; /* Maxim number of waves */
                   1434: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1435: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1436: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
                   1437:                   to the likelihood and the sum of weights (done by funcone)*/
                   1438: int mle=1, weightopt=0;
                   1439: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1440: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1441: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1442:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
                   1443: int countcallfunc=0;  /* Count the number of calls to func */
                   1444: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1445: 
                   1446: double jmean=1; /* Mean space between 2 waves */
                   1447: double **matprod2(); /* test */
                   1448: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1449: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
                   1450: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1451: 
                   1452: /*FILE *fic ; */ /* Used in readdata only */
                   1453: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
                   1454: FILE *ficlog, *ficrespow;
                   1455: int globpr=0; /* Global variable for printing or not */
                   1456: double fretone; /* Only one call to likelihood */
                   1457: long ipmx=0; /* Number of contributions */
                   1458: double sw; /* Sum of weights */
                   1459: char filerespow[FILENAMELENGTH];
                   1460: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1461: FILE *ficresilk;
                   1462: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1463: FILE *ficresprobmorprev;
                   1464: FILE *fichtm, *fichtmcov; /* Html File */
                   1465: FILE *ficreseij;
                   1466: char filerese[FILENAMELENGTH];
                   1467: FILE *ficresstdeij;
                   1468: char fileresstde[FILENAMELENGTH];
                   1469: FILE *ficrescveij;
                   1470: char filerescve[FILENAMELENGTH];
                   1471: FILE  *ficresvij;
                   1472: char fileresv[FILENAMELENGTH];
                   1473: 
                   1474: char title[MAXLINE];
                   1475: char model[MAXLINE]; /**< The model line */
                   1476: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
                   1477: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1478: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1479: char command[FILENAMELENGTH];
                   1480: int  outcmd=0;
                   1481: 
                   1482: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
                   1483: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
                   1484: char filelog[FILENAMELENGTH]; /* Log file */
                   1485: char filerest[FILENAMELENGTH];
                   1486: char fileregp[FILENAMELENGTH];
                   1487: char popfile[FILENAMELENGTH];
                   1488: 
                   1489: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1490: 
                   1491: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1492: /* struct timezone tzp; */
                   1493: /* extern int gettimeofday(); */
                   1494: struct tm tml, *gmtime(), *localtime();
                   1495: 
                   1496: extern time_t time();
                   1497: 
                   1498: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1499: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
1.2       brouard  1500: time_t   rlast_btime; /* raw time */
1.1       brouard  1501: struct tm tm;
                   1502: 
                   1503: char strcurr[80], strfor[80];
                   1504: 
                   1505: char *endptr;
                   1506: long lval;
                   1507: double dval;
                   1508: 
                   1509: #define NR_END 1
                   1510: #define FREE_ARG char*
                   1511: #define FTOL 1.0e-10
                   1512: 
                   1513: #define NRANSI 
                   1514: #define ITMAX 200
                   1515: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
                   1516: 
                   1517: #define TOL 2.0e-4 
                   1518: 
                   1519: #define CGOLD 0.3819660 
                   1520: #define ZEPS 1.0e-10 
                   1521: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1522: 
                   1523: #define GOLD 1.618034 
                   1524: #define GLIMIT 100.0 
                   1525: #define TINY 1.0e-20 
                   1526: 
                   1527: static double maxarg1,maxarg2;
                   1528: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1529: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1530:   
                   1531: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1532: #define rint(a) floor(a+0.5)
                   1533: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
                   1534: #define mytinydouble 1.0e-16
                   1535: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1536: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1537: /* static double dsqrarg; */
                   1538: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
                   1539: static double sqrarg;
                   1540: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1541: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1542: int agegomp= AGEGOMP;
                   1543: 
                   1544: int imx; 
                   1545: int stepm=1;
                   1546: /* Stepm, step in month: minimum step interpolation*/
                   1547: 
                   1548: int estepm;
                   1549: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1550: 
                   1551: int m,nb;
                   1552: long *num;
                   1553: int firstpass=0, lastpass=4,*cod, *cens;
                   1554: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1555:                   covariate for which somebody answered excluding 
                   1556:                   undefined. Usually 2: 0 and 1. */
                   1557: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1558:                             covariate for which somebody answered including 
                   1559:                             undefined. Usually 3: -1, 0 and 1. */
                   1560: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                   1561: double **pmmij, ***probs; /* Global pointer */
                   1562: double ***mobaverage, ***mobaverages; /* New global variable */
                   1563: double **precov; /* New global variable to store for each resultline, values of model covariates given by the resultlines (in order to speed up)  */
                   1564: double *ageexmed,*agecens;
                   1565: double dateintmean=0;
                   1566:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1567:   double anprojf, mprojf, jprojf;
                   1568: 
                   1569:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1570:   double anbackf, mbackf, jbackf;
                   1571:   double jintmean,mintmean,aintmean;  
                   1572: double *weight;
                   1573: int **s; /* Status */
                   1574: double *agedc;
                   1575: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
                   1576:                  * covar=matrix(0,NCOVMAX,1,n); 
                   1577:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
                   1578: double **coqvar; /* Fixed quantitative covariate nqv */
                   1579: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
                   1580: double ***cotqvar; /* Time varying quantitative covariate itqv */
                   1581: double  idx; 
                   1582: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
                   1583: /* Some documentation */
                   1584:       /*   Design original data
                   1585:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1586:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1587:        *                                                             ntv=3     nqtv=1
                   1588:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
                   1589:        * For time varying covariate, quanti or dummies
                   1590:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
                   1591:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
                   1592:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1593:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
                   1594:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
                   1595:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1596:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1597:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1598:        */
                   1599: /* According to the model, more columns can be added to covar by the product of covariates */
                   1600: /* 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
                   1601:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1602:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1603: */
                   1604: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1+V4*V3*age */
                   1605: /*    kmodel  1  2   3    4     5     6    7     8     9    10 */
                   1606: /*Typevar[k]=  0  0   0   2     1    0    2     1     0    3 *//*0 for simple covariate (dummy, quantitative,*/
                   1607:                                                                /* fixed or varying), 1 for age product, 2 for*/
                   1608:                                                                /* product without age, 3 for age and double product   */
                   1609: /*Dummy[k]=    1  0   0   1     3    1    1     2     0     3  *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1610:                                                                 /*(single or product without age), 2 dummy*/
                   1611:                                                                /* with age product, 3 quant with age product*/
                   1612: /*Tvar[k]=     5  4   3   6     5    2    7     1     1     6 */
                   1613: /*    nsd         1   2                               3 */ /* Counting single dummies covar fixed or tv */
                   1614: /*TnsdVar[Tvar]   1   2                               3 */ 
                   1615: /*Tvaraff[nsd]    4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1616: /*TvarsD[nsd]     4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1617: /*TvarsDind[nsd]  2   3                               9 */ /* position K of single dummy cova */
                   1618: /*    nsq      1                     2                  */ /* Counting single quantit tv */
                   1619: /* TvarsQ[k]   5                     2                  */ /* Number of single quantitative cova */
                   1620: /* TvarsQind   1                     6                  */ /* position K of single quantitative cova */
                   1621: /* Tprod[i]=k             1               2             */ /* Position in model of the ith prod without age */
                   1622: /* cptcovage                    1               2         3 */ /* Counting cov*age in the model equation */
                   1623: /* Tage[cptcovage]=k            5               8         10 */ /* Position in the model of ith cov*age */
1.2       brouard  1624: /* 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"*/
                   1625: /*  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}*/
                   1626: /*  p Tvard[2][1]@21 = {7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0 <repeats 11 times>} */
                   1627: /* 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}*/
                   1628: /* 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  1629: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2               */ /* Position in model of the ith prod without age */
                   1630: /* 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*/
                   1631: /* 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 */
                   1632: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
                   1633: /* Type                    */
                   1634: /* V         1  2  3  4  5 */
                   1635: /*           F  F  V  V  V */
                   1636: /*           D  Q  D  D  Q */
                   1637: /*                         */
                   1638: int *TvarsD;
                   1639: int *TnsdVar;
                   1640: int *TvarsDind;
                   1641: int *TvarsQ;
                   1642: int *TvarsQind;
                   1643: 
                   1644: #define MAXRESULTLINESPONE 10+1
                   1645: int nresult=0;
                   1646: int parameterline=0; /* # of the parameter (type) line */
                   1647: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1648: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1649: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1650: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
                   1651: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1652: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
                   1653: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
                   1654: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   1655: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
                   1656: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
                   1657: 
                   1658: /* 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
                   1659:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1660:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1661: */
                   1662: /* 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 *\/ */
                   1663: 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 */
                   1664: 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 */
                   1665: 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 */
                   1666: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1667: 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 */
                   1668: int *TvarAind; /**< TvarindA[1]=5, TvarAind[2]=8  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1669: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1670: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1671: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1672: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1673: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1674: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1675: 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 */
                   1676: 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 */
                   1677: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1678: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1679: int *TvarVVA; /* We count ncovvt time varying covariates (single or products with age) and put their name into TvarVVA */
                   1680: int *TvarVVAind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1681: int *TvarAVVA; /* We count ALL ncovta time varying covariates (single or products with age) and put their name into TvarVVA */
                   1682: int *TvarAVVAind; /* We count ALL ncovta time varying covariates (single or products without age) and put their name into TvarVV */
                   1683:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   1684:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age */
                   1685:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1686:       /* TvarVV={3,1,3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */        
                   1687:       /* 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 */              
                   1688: int *Tvarsel; /**< Selected covariates for output */
                   1689: double *Tvalsel; /**< Selected modality value of covariate for output */
                   1690: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product, 3 age*Vn*Vm */
                   1691: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1692: 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 */ 
                   1693: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1694: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
                   1695: int *Tage;
                   1696: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
                   1697: 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*/
                   1698: 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*/ 
                   1699: 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  */
                   1700: int *Ndum; /** Freq of modality (tricode */
                   1701: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
                   1702: int **Tvard;
                   1703: int **Tvardk;
                   1704: int *Tprod;/**< Gives the k position of the k1 product */
                   1705: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
                   1706: int *Tposprod; /**< Gives the k1 product from the k position */
                   1707:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1708:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
                   1709: int cptcovprod, *Tvaraff, *invalidvarcomb;
                   1710: double *lsurv, *lpop, *tpop;
                   1711: 
                   1712: #define FD 1; /* Fixed dummy covariate */
                   1713: #define FQ 2; /* Fixed quantitative covariate */
                   1714: #define FP 3; /* Fixed product covariate */
                   1715: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1716: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1717: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1718: #define VD 10; /* Varying dummy covariate */
                   1719: #define VQ 11; /* Varying quantitative covariate */
                   1720: #define VP 12; /* Varying product covariate */
                   1721: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1722: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1723: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1724: #define APFD 16; /* Age product * fixed dummy covariate */
                   1725: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1726: #define APVD 18; /* Age product * varying dummy covariate */
                   1727: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1728: 
                   1729: #define FTYPE 1; /* Fixed covariate */
                   1730: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1731: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1732: 
                   1733: struct kmodel{
                   1734:        int maintype; /* main type */
                   1735:        int subtype; /* subtype */
                   1736: };
                   1737: struct kmodel modell[NCOVMAX];
                   1738: 
                   1739: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1740: double ftolhess; /**< Tolerance for computing hessian */
                   1741: 
                   1742: /**************** split *************************/
                   1743: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1744: {
                   1745:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1746:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1747:   */ 
                   1748:   char *ss;                            /* pointer */
                   1749:   int  l1=0, l2=0;                             /* length counters */
                   1750: 
                   1751:   l1 = strlen(path );                  /* length of path */
                   1752:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1753:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1754:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1755:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1756:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1757:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1758:     /* get current working directory */
                   1759:     /*    extern  char* getcwd ( char *buf , int len);*/
                   1760: #ifdef WIN32
                   1761:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1762: #else
                   1763:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1764: #endif
                   1765:       return( GLOCK_ERROR_GETCWD );
                   1766:     }
                   1767:     /* got dirc from getcwd*/
                   1768:     printf(" DIRC = %s \n",dirc);
                   1769:   } else {                             /* strip directory from path */
                   1770:     ss++;                              /* after this, the filename */
                   1771:     l2 = strlen( ss );                 /* length of filename */
                   1772:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1773:     strcpy( name, ss );                /* save file name */
                   1774:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
                   1775:     dirc[l1-l2] = '\0';                        /* add zero */
                   1776:     printf(" DIRC2 = %s \n",dirc);
                   1777:   }
                   1778:   /* We add a separator at the end of dirc if not exists */
                   1779:   l1 = strlen( dirc );                 /* length of directory */
                   1780:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1781:     dirc[l1] =  DIRSEPARATOR;
                   1782:     dirc[l1+1] = 0; 
                   1783:     printf(" DIRC3 = %s \n",dirc);
                   1784:   }
                   1785:   ss = strrchr( name, '.' );           /* find last / */
                   1786:   if (ss >0){
                   1787:     ss++;
                   1788:     strcpy(ext,ss);                    /* save extension */
                   1789:     l1= strlen( name);
                   1790:     l2= strlen(ss)+1;
                   1791:     strncpy( finame, name, l1-l2);
                   1792:     finame[l1-l2]= 0;
                   1793:   }
                   1794: 
                   1795:   return( 0 );                         /* we're done */
                   1796: }
                   1797: 
                   1798: 
                   1799: /******************************************/
                   1800: 
                   1801: void replace_back_to_slash(char *s, char*t)
                   1802: {
                   1803:   int i;
                   1804:   int lg=0;
                   1805:   i=0;
                   1806:   lg=strlen(t);
                   1807:   for(i=0; i<= lg; i++) {
                   1808:     (s[i] = t[i]);
                   1809:     if (t[i]== '\\') s[i]='/';
                   1810:   }
                   1811: }
                   1812: 
                   1813: char *trimbb(char *out, char *in)
                   1814: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
                   1815:   char *s;
                   1816:   s=out;
                   1817:   while (*in != '\0'){
                   1818:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
                   1819:       in++;
                   1820:     }
                   1821:     *out++ = *in++;
                   1822:   }
                   1823:   *out='\0';
                   1824:   return s;
                   1825: }
                   1826: 
1.2       brouard  1827: char *trimbtab(char *out, char *in)
                   1828: { /* Trim  blanks or tabs in line but keeps first blanks if line starts with blanks */
                   1829:   char *s;
                   1830:   s=out;
                   1831:   while (*in != '\0'){
                   1832:     while( (*in == ' ' || *in == '\t')){ /* && *(in+1) != '\0'){*/
                   1833:       in++;
                   1834:     }
                   1835:     *out++ = *in++;
                   1836:   }
                   1837:   *out='\0';
                   1838:   return s;
                   1839: }
                   1840: 
1.1       brouard  1841: /* char *substrchaine(char *out, char *in, char *chain) */
                   1842: /* { */
                   1843: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1844: /*   char *s, *t; */
                   1845: /*   t=in;s=out; */
                   1846: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1847: /*     *out++ = *in++; */
                   1848: /*   } */
                   1849: 
                   1850: /*   /\* *in matches *chain *\/ */
                   1851: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1852: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1853: /*   } */
                   1854: /*   in--; chain--; */
                   1855: /*   while ( (*in != '\0')){ */
                   1856: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1857: /*     *out++ = *in++; */
                   1858: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1859: /*   } */
                   1860: /*   *out='\0'; */
                   1861: /*   out=s; */
                   1862: /*   return out; */
                   1863: /* } */
                   1864: char *substrchaine(char *out, char *in, char *chain)
                   1865: {
                   1866:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1867:   /* in="V1+V1*age+age*age+V2", chain="+age*age" out="V1+V1*age+V2" */
                   1868: 
                   1869:   char *strloc;
                   1870: 
                   1871:   strcpy (out, in);                   /* out="V1+V1*age+age*age+V2" */
                   1872:   strloc = strstr(out, chain); /* strloc points to out at "+age*age+V2"  */
                   1873:   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" */
                   1874:   if(strloc != NULL){ 
                   1875:     /* will affect out */ /* strloc+strlen(chain)=|+V2 = "V1+V1*age+age*age|+V2" */ /* Will also work in Unicodek */
                   1876:     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)*/
                   1877:     /* equivalent to strcpy (strloc, strloc +strlen(chain)) if no overlap; Copies from "+V2" to V1+V1*age+ */
                   1878:   }
                   1879:   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" */
                   1880:   return out;
                   1881: }
                   1882: 
                   1883: 
                   1884: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1885: {
                   1886:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
                   1887:      and alocc starts after first occurence of char 'occ' : ex cutl(blocc,alocc,"abcdef2ghi2j",'2')
                   1888:      gives alocc="abcdef" and blocc="ghi2j".
                   1889:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1890:   */
                   1891:   char *s, *t;
                   1892:   t=in;s=in;
                   1893:   while ((*in != occ) && (*in != '\0')){
                   1894:     *alocc++ = *in++;
                   1895:   }
                   1896:   if( *in == occ){
                   1897:     *(alocc)='\0';
                   1898:     s=++in;
                   1899:   }
                   1900:  
                   1901:   if (s == t) {/* occ not found */
                   1902:     *(alocc-(in-s))='\0';
                   1903:     in=s;
                   1904:   }
                   1905:   while ( *in != '\0'){
                   1906:     *blocc++ = *in++;
                   1907:   }
                   1908: 
                   1909:   *blocc='\0';
                   1910:   return t;
                   1911: }
                   1912: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1913: {
                   1914:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
                   1915:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1916:      gives blocc="abcdef2ghi" and alocc="j".
                   1917:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1918:   */
                   1919:   char *s, *t;
                   1920:   t=in;s=in;
                   1921:   while (*in != '\0'){
                   1922:     while( *in == occ){
                   1923:       *blocc++ = *in++;
                   1924:       s=in;
                   1925:     }
                   1926:     *blocc++ = *in++;
                   1927:   }
                   1928:   if (s == t) /* occ not found */
                   1929:     *(blocc-(in-s))='\0';
                   1930:   else
                   1931:     *(blocc-(in-s)-1)='\0';
                   1932:   in=s;
                   1933:   while ( *in != '\0'){
                   1934:     *alocc++ = *in++;
                   1935:   }
                   1936: 
                   1937:   *alocc='\0';
                   1938:   return s;
                   1939: }
                   1940: 
                   1941: int nbocc(char *s, char occ)
                   1942: {
                   1943:   int i,j=0;
                   1944:   int lg=20;
                   1945:   i=0;
                   1946:   lg=strlen(s);
                   1947:   for(i=0; i<= lg; i++) {
                   1948:     if  (s[i] == occ ) j++;
                   1949:   }
                   1950:   return j;
                   1951: }
                   1952: 
                   1953: int nboccstr(char *textin, char *chain)
                   1954: {
                   1955:   /* Counts the number of occurence of "chain"  in string textin */
                   1956:   /*  in="+V7*V4+age*V2+age*V3+age*V4"  chain="age" */
                   1957:   char *strloc;
                   1958:   
                   1959:   int i,j=0;
                   1960: 
                   1961:   i=0;
                   1962: 
                   1963:   strloc=textin; /* strloc points to "^+V7*V4+age+..." in textin */
                   1964:   for(;;) {
                   1965:     strloc= strstr(strloc,chain); /* strloc points to first character of chain in textin if found. Example strloc points^ to "+V7*V4+^age" in textin  */
                   1966:     if(strloc != NULL){
                   1967:       strloc = strloc+strlen(chain); /* strloc points to "+V7*V4+age^" in textin */
                   1968:       j++;
                   1969:     }else
                   1970:       break;
                   1971:   }
                   1972:   return j;
                   1973:   
                   1974: }
                   1975: /* void cutv(char *u,char *v, char*t, char occ) */
                   1976: /* { */
                   1977: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1978: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1979: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1980: /*   int i,lg,j,p=0; */
                   1981: /*   i=0; */
                   1982: /*   lg=strlen(t); */
                   1983: /*   for(j=0; j<=lg-1; j++) { */
                   1984: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1985: /*   } */
                   1986: 
                   1987: /*   for(j=0; j<p; j++) { */
                   1988: /*     (u[j] = t[j]); */
                   1989: /*   } */
                   1990: /*      u[p]='\0'; */
                   1991: 
                   1992: /*    for(j=0; j<= lg; j++) { */
                   1993: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1994: /*   } */
                   1995: /* } */
                   1996: 
                   1997: #ifdef _WIN32
                   1998: char * strsep(char **pp, const char *delim)
                   1999: {
                   2000:   char *p, *q;
                   2001:          
                   2002:   if ((p = *pp) == NULL)
                   2003:     return 0;
                   2004:   if ((q = strpbrk (p, delim)) != NULL)
                   2005:   {
                   2006:     *pp = q + 1;
                   2007:     *q = '\0';
                   2008:   }
                   2009:   else
                   2010:     *pp = 0;
                   2011:   return p;
                   2012: }
                   2013: #endif
                   2014: 
                   2015: /********************** nrerror ********************/
                   2016: 
                   2017: void nrerror(char error_text[])
                   2018: {
                   2019:   fprintf(stderr,"ERREUR ...\n");
                   2020:   fprintf(stderr,"%s\n",error_text);
                   2021:   exit(EXIT_FAILURE);
                   2022: }
                   2023: /*********************** vector *******************/
                   2024: double *vector(int nl, int nh)
                   2025: {
                   2026:   double *v;
                   2027:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   2028:   if (!v) nrerror("allocation failure in vector");
                   2029:   return v-nl+NR_END;
                   2030: }
                   2031: 
                   2032: /************************ free vector ******************/
                   2033: void free_vector(double*v, int nl, int nh)
                   2034: {
                   2035:   free((FREE_ARG)(v+nl-NR_END));
                   2036: }
                   2037: 
                   2038: /************************ivector *******************************/
                   2039: int *ivector(long nl,long nh)
                   2040: {
                   2041:   int *v;
                   2042:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   2043:   if (!v) nrerror("allocation failure in ivector");
                   2044:   return v-nl+NR_END;
                   2045: }
                   2046: 
                   2047: /******************free ivector **************************/
                   2048: void free_ivector(int *v, long nl, long nh)
                   2049: {
                   2050:   free((FREE_ARG)(v+nl-NR_END));
                   2051: }
                   2052: 
                   2053: /************************lvector *******************************/
                   2054: long *lvector(long nl,long nh)
                   2055: {
                   2056:   long *v;
                   2057:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   2058:   if (!v) nrerror("allocation failure in ivector");
                   2059:   return v-nl+NR_END;
                   2060: }
                   2061: 
                   2062: /******************free lvector **************************/
                   2063: void free_lvector(long *v, long nl, long nh)
                   2064: {
                   2065:   free((FREE_ARG)(v+nl-NR_END));
                   2066: }
                   2067: 
                   2068: /******************* imatrix *******************************/
                   2069: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   2070:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   2071: { 
                   2072:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   2073:   int **m; 
                   2074:   
                   2075:   /* allocate pointers to rows */ 
                   2076:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   2077:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   2078:   m += NR_END; 
                   2079:   m -= nrl; 
                   2080:   
                   2081:   
                   2082:   /* allocate rows and set pointers to them */ 
                   2083:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   2084:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   2085:   m[nrl] += NR_END; 
                   2086:   m[nrl] -= ncl; 
                   2087:   
                   2088:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   2089:   
                   2090:   /* return pointer to array of pointers to rows */ 
                   2091:   return m; 
                   2092: } 
                   2093: 
                   2094: /****************** free_imatrix *************************/
                   2095: void free_imatrix(m,nrl,nrh,ncl,nch)
                   2096:       int **m;
                   2097:       long nch,ncl,nrh,nrl; 
                   2098:      /* free an int matrix allocated by imatrix() */ 
                   2099: { 
                   2100:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   2101:   free((FREE_ARG) (m+nrl-NR_END)); 
                   2102: } 
                   2103: 
                   2104: /******************* matrix *******************************/
                   2105: double **matrix(long nrl, long nrh, long ncl, long nch)
                   2106: {
                   2107:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   2108:   double **m;
                   2109: 
                   2110:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2111:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2112:   m += NR_END;
                   2113:   m -= nrl;
                   2114: 
                   2115:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2116:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2117:   m[nrl] += NR_END;
                   2118:   m[nrl] -= ncl;
                   2119: 
                   2120:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2121:   return m;
                   2122:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2123: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2124: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
                   2125:    */
                   2126: }
                   2127: 
                   2128: /*************************free matrix ************************/
                   2129: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2130: {
                   2131:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2132:   free((FREE_ARG)(m+nrl-NR_END));
                   2133: }
                   2134: 
                   2135: /******************* ma3x *******************************/
                   2136: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2137: {
                   2138:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2139:   double ***m;
                   2140: 
                   2141:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2142:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2143:   m += NR_END;
                   2144:   m -= nrl;
                   2145: 
                   2146:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2147:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2148:   m[nrl] += NR_END;
                   2149:   m[nrl] -= ncl;
                   2150: 
                   2151:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2152: 
                   2153:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2154:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2155:   m[nrl][ncl] += NR_END;
                   2156:   m[nrl][ncl] -= nll;
                   2157:   for (j=ncl+1; j<=nch; j++) 
                   2158:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2159:   
                   2160:   for (i=nrl+1; i<=nrh; i++) {
                   2161:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2162:     for (j=ncl+1; j<=nch; j++) 
                   2163:       m[i][j]=m[i][j-1]+nlay;
                   2164:   }
                   2165:   return m; 
                   2166:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2167:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2168:   */
                   2169: }
                   2170: 
                   2171: /*************************free ma3x ************************/
                   2172: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2173: {
                   2174:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2175:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2176:   free((FREE_ARG)(m+nrl-NR_END));
                   2177: }
                   2178: 
                   2179: /*************** function subdirf ***********/
                   2180: char *subdirf(char fileres[])
                   2181: {
                   2182:   /* Caution optionfilefiname is hidden */
                   2183:   strcpy(tmpout,optionfilefiname);
                   2184:   strcat(tmpout,"/"); /* Add to the right */
                   2185:   strcat(tmpout,fileres);
                   2186:   return tmpout;
                   2187: }
                   2188: 
                   2189: /*************** function subdirf2 ***********/
                   2190: char *subdirf2(char fileres[], char *preop)
                   2191: {
                   2192:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2193:  Errors in subdirf, 2, 3 while printing tmpout is
                   2194:  rewritten within the same printf. Workaround: many printfs */
                   2195:   /* Caution optionfilefiname is hidden */
                   2196:   strcpy(tmpout,optionfilefiname);
                   2197:   strcat(tmpout,"/");
                   2198:   strcat(tmpout,preop);
                   2199:   strcat(tmpout,fileres);
                   2200:   return tmpout;
                   2201: }
                   2202: 
                   2203: /*************** function subdirf3 ***********/
                   2204: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2205: {
                   2206:   
                   2207:   /* Caution optionfilefiname is hidden */
                   2208:   strcpy(tmpout,optionfilefiname);
                   2209:   strcat(tmpout,"/");
                   2210:   strcat(tmpout,preop);
                   2211:   strcat(tmpout,preop2);
                   2212:   strcat(tmpout,fileres);
                   2213:   return tmpout;
                   2214: }
                   2215:  
                   2216: /*************** function subdirfext ***********/
                   2217: char *subdirfext(char fileres[], char *preop, char *postop)
                   2218: {
                   2219:   
                   2220:   strcpy(tmpout,preop);
                   2221:   strcat(tmpout,fileres);
                   2222:   strcat(tmpout,postop);
                   2223:   return tmpout;
                   2224: }
                   2225: 
                   2226: /*************** function subdirfext3 ***********/
                   2227: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2228: {
                   2229:   
                   2230:   /* Caution optionfilefiname is hidden */
                   2231:   strcpy(tmpout,optionfilefiname);
                   2232:   strcat(tmpout,"/");
                   2233:   strcat(tmpout,preop);
                   2234:   strcat(tmpout,fileres);
                   2235:   strcat(tmpout,postop);
                   2236:   return tmpout;
                   2237: }
                   2238:  
                   2239: char *asc_diff_time(long time_sec, char ascdiff[])
                   2240: {
                   2241:   long sec_left, days, hours, minutes;
                   2242:   days = (time_sec) / (60*60*24);
                   2243:   sec_left = (time_sec) % (60*60*24);
                   2244:   hours = (sec_left) / (60*60) ;
                   2245:   sec_left = (sec_left) %(60*60);
                   2246:   minutes = (sec_left) /60;
                   2247:   sec_left = (sec_left) % (60);
                   2248:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2249:   return ascdiff;
                   2250: }
                   2251: 
                   2252: /***************** f1dim *************************/
                   2253: extern int ncom; 
                   2254: extern double *pcom,*xicom;
                   2255: extern double (*nrfunc)(double []); 
                   2256:  
                   2257: double f1dim(double x) 
                   2258: { 
                   2259:   int j; 
                   2260:   double f;
                   2261:   double *xt; 
                   2262:  
                   2263:   xt=vector(1,ncom); 
                   2264:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2265:   f=(*nrfunc)(xt); 
                   2266:   free_vector(xt,1,ncom); 
                   2267:   return f; 
                   2268: } 
                   2269: 
                   2270: /*****************brent *************************/
                   2271: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
                   2272: {
                   2273:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2274:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2275:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2276:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2277:    * returned function value. 
                   2278:   */
                   2279:   int iter; 
                   2280:   double a,b,d,etemp;
                   2281:   double fu=0,fv,fw,fx;
                   2282:   double ftemp=0.;
                   2283:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2284:   double e=0.0; 
                   2285:  
                   2286:   a=(ax < cx ? ax : cx); 
                   2287:   b=(ax > cx ? ax : cx); 
                   2288:   x=w=v=bx; 
                   2289:   fw=fv=fx=(*f)(x); 
                   2290:   for (iter=1;iter<=ITMAX;iter++) { 
                   2291:     xm=0.5*(a+b); 
                   2292:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2293:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2294:     printf(".");fflush(stdout);
                   2295:     fprintf(ficlog,".");fflush(ficlog);
                   2296: #ifdef DEBUGBRENT
                   2297:     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);
                   2298:     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);
                   2299:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2300: #endif
                   2301:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2302:       *xmin=x; 
                   2303:       return fx; 
                   2304:     } 
                   2305:     ftemp=fu;
                   2306:     if (fabs(e) > tol1) { 
                   2307:       r=(x-w)*(fx-fv); 
                   2308:       q=(x-v)*(fx-fw); 
                   2309:       p=(x-v)*q-(x-w)*r; 
                   2310:       q=2.0*(q-r); 
                   2311:       if (q > 0.0) p = -p; 
                   2312:       q=fabs(q); 
                   2313:       etemp=e; 
                   2314:       e=d; 
                   2315:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   2316:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2317:       else { 
                   2318:                                d=p/q; 
                   2319:                                u=x+d; 
                   2320:                                if (u-a < tol2 || b-u < tol2) 
                   2321:                                        d=SIGN(tol1,xm-x); 
                   2322:       } 
                   2323:     } else { 
                   2324:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2325:     } 
                   2326:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2327:     fu=(*f)(u); 
                   2328:     if (fu <= fx) { 
                   2329:       if (u >= x) a=x; else b=x; 
                   2330:       SHFT(v,w,x,u) 
                   2331:       SHFT(fv,fw,fx,fu) 
                   2332:     } else { 
                   2333:       if (u < x) a=u; else b=u; 
                   2334:       if (fu <= fw || w == x) { 
                   2335:                                v=w; 
                   2336:                                w=u; 
                   2337:                                fv=fw; 
                   2338:                                fw=fu; 
                   2339:       } else if (fu <= fv || v == x || v == w) { 
                   2340:                                v=u; 
                   2341:                                fv=fu; 
                   2342:       } 
                   2343:     } 
                   2344:   } 
                   2345:   nrerror("Too many iterations in brent"); 
                   2346:   *xmin=x; 
                   2347:   return fx; 
                   2348: } 
                   2349: 
                   2350: /****************** mnbrak ***********************/
                   2351: 
                   2352: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2353:            double (*func)(double)) 
                   2354: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2355: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2356: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2357: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2358:    */
                   2359:   double ulim,u,r,q, dum;
                   2360:   double fu; 
                   2361: 
                   2362:   double scale=10.;
                   2363:   int iterscale=0;
                   2364: 
                   2365:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2366:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2367: 
                   2368: 
                   2369:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2370:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2371:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2372:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2373:   /* } */
                   2374: 
                   2375:   if (*fb > *fa) { 
                   2376:     SHFT(dum,*ax,*bx,dum) 
                   2377:     SHFT(dum,*fb,*fa,dum) 
                   2378:   } 
                   2379:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2380:   *fc=(*func)(*cx); 
                   2381: #ifdef DEBUG
                   2382:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2383:   fprintf(ficlog,"mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2384: #endif
                   2385:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc. If fc=inf it exits and if flat fb=fc it exits too.*/
                   2386:     r=(*bx-*ax)*(*fb-*fc); 
                   2387:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
                   2388:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
                   2389:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2390:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2391:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
                   2392:       fu=(*func)(u); 
                   2393: #ifdef DEBUG
                   2394:       /* f(x)=A(x-u)**2+f(u) */
                   2395:       double A, fparabu; 
                   2396:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2397:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2398:       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);
                   2399:       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);
                   2400:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2401:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2402:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2403:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
                   2404: #endif 
                   2405: #ifdef MNBRAKORIGINAL
                   2406: #else
                   2407: /*       if (fu > *fc) { */
                   2408: /* #ifdef DEBUG */
                   2409: /*       printf("mnbrak4  fu > fc \n"); */
                   2410: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2411: /* #endif */
                   2412: /*     /\* 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 *\\/  *\/ */
                   2413: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2414: /*     dum=u; /\* Shifting c and u *\/ */
                   2415: /*     u = *cx; */
                   2416: /*     *cx = dum; */
                   2417: /*     dum = fu; */
                   2418: /*     fu = *fc; */
                   2419: /*     *fc =dum; */
                   2420: /*       } else { /\* end *\/ */
                   2421: /* #ifdef DEBUG */
                   2422: /*       printf("mnbrak3  fu < fc \n"); */
                   2423: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2424: /* #endif */
                   2425: /*     dum=u; /\* Shifting c and u *\/ */
                   2426: /*     u = *cx; */
                   2427: /*     *cx = dum; */
                   2428: /*     dum = fu; */
                   2429: /*     fu = *fc; */
                   2430: /*     *fc =dum; */
                   2431: /*       } */
                   2432: #ifdef DEBUGMNBRAK
                   2433:                 double A, fparabu; 
                   2434:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2435:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2436:      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);
                   2437:      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);
                   2438: #endif
                   2439:       dum=u; /* Shifting c and u */
                   2440:       u = *cx;
                   2441:       *cx = dum;
                   2442:       dum = fu;
                   2443:       fu = *fc;
                   2444:       *fc =dum;
                   2445: #endif
                   2446:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
                   2447: #ifdef DEBUG
                   2448:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2449:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2450: #endif
                   2451:       fu=(*func)(u); 
                   2452:       if (fu < *fc) { 
                   2453: #ifdef DEBUG
                   2454:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2455:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2456: #endif
                   2457:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2458:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2459: #ifdef DEBUG
                   2460:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
                   2461: #endif
                   2462:       } 
                   2463:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
                   2464: #ifdef DEBUG
                   2465:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2466:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2467: #endif
                   2468:       u=ulim; 
                   2469:       fu=(*func)(u); 
                   2470:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2471: #ifdef DEBUG
                   2472:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2473:       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);
                   2474: #endif
                   2475:       u=(*cx)+GOLD*(*cx-*bx); 
                   2476:       fu=(*func)(u); 
                   2477: #ifdef DEBUG
                   2478:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2479:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2480: #endif
                   2481:     } /* end tests */
                   2482:     SHFT(*ax,*bx,*cx,u) 
                   2483:     SHFT(*fa,*fb,*fc,fu) 
                   2484: #ifdef DEBUG
                   2485:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2486:       fprintf(ficlog, "\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2487: #endif
                   2488:   } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
                   2489: } 
                   2490: 
                   2491: /*************** linmin ************************/
                   2492: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2493: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2494: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2495: the value of func at the returned location p . This is actually all accomplished by calling the
                   2496: routines mnbrak and brent .*/
                   2497: int ncom; 
                   2498: double *pcom,*xicom;
                   2499: double (*nrfunc)(double []); 
                   2500:  
                   2501: #ifdef LINMINORIGINAL
                   2502: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   2503: #else
                   2504: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2505: #endif
                   2506: { 
                   2507:   double brent(double ax, double bx, double cx, 
                   2508:               double (*f)(double), double tol, double *xmin); 
                   2509:   double f1dim(double x); 
                   2510:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2511:              double *fc, double (*func)(double)); 
                   2512:   int j; 
                   2513:   double xx,xmin,bx,ax; 
                   2514:   double fx,fb,fa;
                   2515: 
                   2516: #ifdef LINMINORIGINAL
                   2517: #else
                   2518:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2519: #endif
                   2520:   
                   2521:   ncom=n; 
                   2522:   pcom=vector(1,n); 
                   2523:   xicom=vector(1,n); 
                   2524:   nrfunc=func; 
                   2525:   for (j=1;j<=n;j++) { 
                   2526:     pcom[j]=p[j]; 
                   2527:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
                   2528:   } 
                   2529: 
                   2530: #ifdef LINMINORIGINAL
                   2531:   xx=1.;
                   2532: #else
                   2533:   axs=0.0;
                   2534:   xxs=1.;
                   2535:   do{
                   2536:     xx= xxs;
                   2537: #endif
                   2538:     ax=0.;
                   2539:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2540:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2541:     /* 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))   */
                   2542:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2543:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2544:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2545:     /* 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]]*/
                   2546: #ifdef LINMINORIGINAL
                   2547: #else
                   2548:     if (fx != fx){
                   2549:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2550:                        printf("|");
                   2551:                        fprintf(ficlog,"|");
                   2552: #ifdef DEBUGLINMIN
                   2553:                        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);
                   2554: #endif
                   2555:     }
                   2556:   }while(fx != fx && xxs > 1.e-5);
                   2557: #endif
                   2558:   
                   2559: #ifdef DEBUGLINMIN
                   2560:   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);
                   2561:   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);
                   2562: #endif
                   2563: #ifdef LINMINORIGINAL
                   2564: #else
                   2565:   if(fb == fx){ /* Flat function in the direction */
                   2566:     xmin=xx;
                   2567:     *flat=1;
                   2568:   }else{
                   2569:     *flat=0;
                   2570: #endif
                   2571:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
                   2572:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2573:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2574:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2575:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2576:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
                   2577: #ifdef DEBUG
                   2578:   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);
                   2579:   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);
                   2580: #endif
                   2581: #ifdef LINMINORIGINAL
                   2582: #else
                   2583:                        }
                   2584: #endif
                   2585: #ifdef DEBUGLINMIN
                   2586:   printf("linmin end ");
                   2587:   fprintf(ficlog,"linmin end ");
                   2588: #endif
                   2589:   for (j=1;j<=n;j++) { 
                   2590: #ifdef LINMINORIGINAL
                   2591:     xi[j] *= xmin; 
                   2592: #else
                   2593: #ifdef DEBUGLINMIN
                   2594:     if(xxs <1.0)
                   2595:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2596: #endif
                   2597:     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) */
                   2598: #ifdef DEBUGLINMIN
                   2599:     if(xxs <1.0)
                   2600:       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 );
                   2601: #endif
                   2602: #endif
                   2603:     p[j] += xi[j]; /* Parameters values are updated accordingly */
                   2604:   } 
                   2605: #ifdef DEBUGLINMIN
                   2606:   printf("\n");
                   2607:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
                   2608:   fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
                   2609:   for (j=1;j<=n;j++) { 
                   2610:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2611:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2612:     if(j % ncovmodel == 0){
                   2613:       printf("\n");
                   2614:       fprintf(ficlog,"\n");
                   2615:     }
                   2616:   }
                   2617: #else
                   2618: #endif
                   2619:   free_vector(xicom,1,n); 
                   2620:   free_vector(pcom,1,n); 
                   2621: } 
                   2622: 
                   2623: /**** praxis ****/
1.5     ! brouard  2624: # include <float.h>
1.4       brouard  2625: 
                   2626: void transpose_in_place ( int n, double **a )
                   2627: 
                   2628: /******************************************************************************/
                   2629: /*
                   2630:   Purpose:
                   2631: 
                   2632:    TRANSPOSE_IN_PLACE transposes a square matrix in place.
                   2633:   Licensing:
                   2634:     This code is distributed under the GNU LGPL license.
                   2635: 
                   2636:     Input, int N, the number of rows and columns of the matrix A.
                   2637: 
                   2638:     Input/output, double A[N*N], the matrix to be transposed.
                   2639: */
                   2640: {
                   2641:   int i;
                   2642:   int j;
                   2643:   double t;
                   2644: 
                   2645:   /* for ( j = 0; j < n; j++ ){ */
                   2646:   /*   for ( i = 0; i < j; i++ ) { */
                   2647:   for ( j = 1; j <= n; j++ ){
                   2648:     for ( i = 1; i < j; i++ ) {
                   2649:       /* t        = a[i+j*n]; */
                   2650:       /* a[i+j*n] = a[j+i*n]; */
                   2651:       /* a[j+i*n] = t; */
                   2652:       t        = a[i][j];
                   2653:       a[i][j] = a[j][i];
                   2654:       a[j][i] = t;
                   2655:     }
                   2656:   }
                   2657:   return;
                   2658: }
                   2659: 
1.2       brouard  2660: double pythag( double x, double y )
1.1       brouard  2661: 
                   2662: /******************************************************************************/
                   2663: /*
                   2664:   Purpose:
1.2       brouard  2665:     R8_HYPOT returns the value of sqrt ( X^2 + Y^2 ).
1.1       brouard  2666:   Licensing:
                   2667:     This code is distributed under the GNU LGPL license.
                   2668:   Modified:
1.2       brouard  2669:     26 March 2012
1.1       brouard  2670:   Author:
1.2       brouard  2671:     John Burkardt
1.1       brouard  2672:   Parameters:
1.2       brouard  2673:     Input, double X, Y, the arguments.
                   2674:     Output, double R8_HYPOT, the value of sqrt ( X^2 + Y^2 ).
1.1       brouard  2675: */
                   2676: {
1.2       brouard  2677:   double a;
                   2678:   double b;
1.1       brouard  2679:   double value;
                   2680: 
1.2       brouard  2681:   if ( fabs ( x ) < fabs ( y ) )  {
                   2682:     a = fabs ( y );
                   2683:     b = fabs ( x );
                   2684:   }  else  {
                   2685:     a = fabs ( x );
                   2686:     b = fabs ( y );
1.1       brouard  2687:   }
                   2688: /*
1.2       brouard  2689:   A contains the larger value.
1.1       brouard  2690: */
1.2       brouard  2691:   if ( a == 0.0 )  {
                   2692:     value = 0.0;
                   2693:   }  else  {
                   2694:     value = a * sqrt ( 1.0 + ( b / a ) * ( b / a ) );
1.1       brouard  2695:   }
                   2696:   return value;
                   2697: }
                   2698: 
1.5     ! brouard  2699: void svsort ( int n, double d[], double **v ) 
        !          2700: 
        !          2701: /******************************************************************************/
        !          2702: /*
        !          2703:   Purpose:
        !          2704: 
        !          2705:     SVSORT descending sorts D and adjusts the corresponding columns of V.
        !          2706: 
        !          2707:   Discussion:
        !          2708:     A simple bubble sort is used on D.
        !          2709:     In our application, D contains singular values, and the columns of V are
        !          2710:     the corresponding right singular vectors.
        !          2711:   Author:
        !          2712:     Original FORTRAN77 version by Richard Brent.
        !          2713:     Richard Brent,
        !          2714:     Algorithms for Minimization with Derivatives,
        !          2715:     Prentice Hall, 1973,
        !          2716:     Reprinted by Dover, 2002.
        !          2717: 
        !          2718:   Parameters:
        !          2719:     Input, int N, the length of D, and the order of V.
        !          2720:     Input/output, double D[N], the vector to be sorted.  
        !          2721:     On output, the entries of D are in descending order.
        !          2722: 
        !          2723:     Input/output, double V[N,N], an N by N array to be adjusted 
        !          2724:     as D is sorted.  In particular, if the value that was in D(I) on input is
        !          2725:     moved to D(J) on output, then the input column V(*,I) is moved to
        !          2726:     the output column V(*,J).
        !          2727: */
        !          2728: {
        !          2729:   int i, j1, j2, j3;
        !          2730:   double t;
        !          2731: 
        !          2732:   for (j1 = 1; j1 < n; j1++) {
        !          2733:     /*
        !          2734:      * Find J3, the index of the largest entry in D[J1:N-1].
        !          2735:      * MAXLOC apparently requires its output to be an array.
        !          2736:     */
        !          2737:     j3 = j1;
        !          2738:     for (j2 = j1+1; j2 < n; j2++) {
        !          2739:       if (d[j3] < d[j2]) {
        !          2740:         j3 = j2;
        !          2741:       }
        !          2742:     }
        !          2743:     /*
        !          2744:      * If J1 != J3, swap D[J1] and D[J3], and columns J1 and J3 of V.
        !          2745:     */
        !          2746:     if (j1 != j3) {
        !          2747:       t     = d[j1];
        !          2748:       d[j1] = d[j3];
        !          2749:       d[j3] = t;
        !          2750:       for (i = 1; i <= n; i++) {
        !          2751:         t = v[i][j1];
        !          2752:         v[i][j1] = v[i][j3];
        !          2753:         v[i][j3] = t;
        !          2754:       } /* end i */
        !          2755:     } /* end j1 != j3 */
        !          2756:   } /* end j1 */
        !          2757:   return;
        !          2758: }
        !          2759: 
1.2       brouard  2760: /* void svdcmp(double **a, int m, int n, double w[], double **v)  */
1.4       brouard  2761: void svdminfit(double **a, int m, int n, double w[]) 
1.1       brouard  2762: {
1.4       brouard  2763:   /* From numerical recipes */
                   2764:   /* Given a matrix a[1..m][1..n], this routine computes its singular value */
                   2765:   /*   decomposition, A = U ·W ·V T . The matrix U replaces a on output. */
                   2766:   /*   The diagonal matrix of singular values W is out- put as a vector w[1..n]. */
                   2767:   /*   The matrix V (not the transpose V T ) is output as v[1..n][1..n]. */
                   2768:   
                   2769:   /* But in fact from Golub 1970 Algol60 */
                   2770: 
1.2       brouard  2771: /*   Computation of the singular values and complete orthogonal decom- */
                   2772: /* position of a real rectangular matrix A, */
                   2773: /* A = U diag (q) V^T, U^T U = V^T V =I , */
                   2774: /*     where the arrays a[1:m, 1:n], u[1:m, 1 :n], v[1:n, 1:n], q[1:n] re- */
                   2775: /* present A, U, V, q respectively. The actual parameters corresponding */
                   2776: /* to a, u, v may all be identical unless withu=withv = true . In this */
                   2777: /* case, the actual parameters corresponding to u and v must differ. */
                   2778: /* m >= n is assumed; */
                   2779:   
                   2780:   /* Simplified (as in praxis) in order to output only V (replacing A), w is the diagonal matrix q  */
                   2781: 
                   2782:   
                   2783:   double pythag(double a, double b); 
                   2784:   int flag,i,its,j,jj,k,l,nm; 
                   2785:   double anorm,c,f,g,h,s,scale,x,y,z,*rv1; 
                   2786:   
                   2787:   rv1=vector(1,n);
                   2788:   /* Householder's reduction to bidiagonal form; */
                   2789:   g=scale=anorm=0.0; 
                   2790:   for (i=1;i<=n;i++) { 
                   2791:     l=i+1; 
                   2792:     rv1[i]=scale*g; 
                   2793:     g=s=scale=0.0; 
                   2794:     if (i <= m) { 
                   2795:       for (k=i;k<=m;k++) scale += fabs(a[k][i]); 
                   2796:       if (scale) { 
                   2797:         for (k=i;k<=m;k++) { 
                   2798:           a[k][i] /= scale; 
                   2799:           s += a[k][i]*a[k][i]; 
                   2800:         } 
                   2801:         f=a[i][i]; 
                   2802:         g = -SIGN(sqrt(s),f); 
                   2803:         h=f*g-s; 
                   2804:         a[i][i]=f-g; 
                   2805:         for (j=l;j<=n;j++) { 
                   2806:           for (s=0.0,k=i;k<=m;k++) s += a[k][i]*a[k][j]; 
                   2807:           f=s/h; 
                   2808:           for (k=i;k<=m;k++) a[k][j] += f*a[k][i]; 
                   2809:         } 
                   2810:         for (k=i;k<=m;k++) a[k][i] *= scale; 
                   2811:       } 
                   2812:     } 
                   2813:     w[i]=scale *g; /* p 411*/
                   2814:     g=s=scale=0.0; 
                   2815:     if (i <= m && i != n) { 
                   2816:       for (k=l;k<=n;k++) scale += fabs(a[i][k]); 
                   2817:       if (scale) { 
                   2818:         for (k=l;k<=n;k++) { 
                   2819:           a[i][k] /= scale; 
                   2820:           s += a[i][k]*a[i][k]; 
                   2821:         } 
                   2822:         f=a[i][l]; 
                   2823:         g = -SIGN(sqrt(s),f); 
                   2824:         h=f*g-s; 
                   2825:         a[i][l]=f-g; 
                   2826:         for (k=l;k<=n;k++) rv1[k]=a[i][k]/h; 
                   2827:         for (j=l;j<=m;j++) { 
                   2828:           for (s=0.0,k=l;k<=n;k++) s += a[j][k]*a[i][k]; 
                   2829:           for (k=l;k<=n;k++) a[j][k] += s*rv1[k]; 
                   2830:         } 
                   2831:         for (k=l;k<=n;k++) a[i][k] *= scale; 
1.1       brouard  2832:       } 
                   2833:     }
1.2       brouard  2834:     /* y : = abs(q[i]) +abs(e[i]); if y > x then x : = y */
                   2835:     /* anorm=DMAX(anorm,(fabs(w[i])+fabs(rv1[i])));  */
                   2836:     anorm=FMAX(anorm,(fabs(w[i])+fabs(rv1[i]))); 
1.1       brouard  2837:   }
1.2       brouard  2838:   /* Comment accumulation of right-hand transformations */
                   2839:   for (i=n;i>=1;i--) { 
                   2840:     if (i < n) { 
                   2841:       if (g) { 
                   2842:         for (j=l;j<=n;j++) a[j][i]=(a[i][j]/a[i][l])/g; /* Double division to avoid possible underflow. */
                   2843:         /* for (j=l;j<=n;j++) v[j][i]=(a[i][j]/a[i][l])/g;  */
                   2844:         for (j=l;j<=n;j++) { 
                   2845:           /* for (s=0.0,k=l;k<=n;k++) s += a[i][k]*v[k][j];  */
                   2846:            for (s=0.0,k=l;k<=n;k++) s += a[i][k]*a[k][j];
                   2847:           /* for (k=l;k<=n;k++) v[k][j] += s*v[k][i];  */
                   2848:           for (k=l;k<=n;k++) a[k][j] += s*a[k][i]; 
                   2849:         } 
                   2850:       } 
                   2851:       /* for (j=l;j<=n;j++) v[i][j]=v[j][i]=0.0;  */
                   2852:       for (j=l;j<=n;j++) a[i][j]=a[j][i]=0.0; 
                   2853:     } 
                   2854:     /* v[i][i]=1.0;  */
                   2855:     a[i][i]=1.0; 
                   2856:     g=rv1[i]; 
                   2857:     l=i; 
                   2858:   } 
                   2859:  /* Comment accumulation of left-hand transformations; */
                   2860:  /* for (i=IMIN(m,n);i>=1;i--) {  */
                   2861:  for (i=FMIN(m,n);i>=1;i--) { 
                   2862:     l=i+1; 
                   2863:     g=w[i]; 
                   2864:     for (j=l;j<=n;j++) a[i][j]=0.0; 
                   2865:     if (g) { 
                   2866:       g=1.0/g; 
                   2867:       for (j=l;j<=n;j++) { 
                   2868:         for (s=0.0,k=l;k<=m;k++) s += a[k][i]*a[k][j]; 
                   2869:         f=(s/a[i][i])*g; 
                   2870:         for (k=i;k<=m;k++) a[k][j] += f*a[k][i]; 
                   2871:       } 
                   2872:       for (j=i;j<=m;j++) a[j][i] *= g; 
                   2873:     } else for (j=i;j<=m;j++) a[j][i]=0.0; 
                   2874:     ++a[i][i]; 
                   2875:   } 
                   2876: /* comment diagonalization of the bidiagonal form; */
                   2877:  for (k=n;k>=1;k--) { 
                   2878:     for (its=1;its<=30;its++) { /* Loop over singular values, and over allowed iterations. */
                   2879:       flag=1; 
                   2880:       for (l=k;l>=1;l--) { /* Test for splitting. */
                   2881:         nm=l-1;            /* Note that rv1[1] is always zero. */
                   2882:         if ((double)(fabs(rv1[l])+anorm) == anorm) { 
                   2883:           flag=0; 
                   2884:           break; 
                   2885:         } 
                   2886:         if ((double)(fabs(w[nm])+anorm) == anorm) break; 
                   2887:       } 
                   2888:       if (flag) { 
                   2889:         c=0.0;    /* Cancellation of rv1[l], if l > 1. */
                   2890:         s=1.0; 
                   2891:         for (i=l;i<=k;i++) { 
                   2892:           f=s*rv1[i]; 
                   2893:           rv1[i]=c*rv1[i]; 
                   2894:           if ((double)(fabs(f)+anorm) == anorm) break; 
                   2895:           g=w[i]; 
                   2896:           h=pythag(f,g); 
                   2897:           w[i]=h; 
                   2898:           h=1.0/h; 
                   2899:           c=g*h; 
                   2900:           s = -f*h; 
                   2901:           for (j=1;j<=m;j++) { 
                   2902:             y=a[j][nm]; 
                   2903:             z=a[j][i]; 
                   2904:             a[j][nm]=y*c+z*s; 
                   2905:             a[j][i]=z*c-y*s; 
                   2906:           } 
                   2907:         } 
                   2908:       } 
                   2909:       z=w[k]; 
                   2910:       if (l == k) { /* Convergence */
                   2911:         if (z < 0.0) { /* Singular value is made nonnegative. */   
                   2912:           w[k] = -z;   
                   2913:           /* for (j=1;j<=n;j++) v[j][k] = -v[j][k];  */
                   2914:           for (j=1;j<=n;j++) a[j][k] = -a[j][k]; 
                   2915:         } 
                   2916:         break; 
                   2917:       } 
1.4       brouard  2918:       if (its == 30) nrerror("no convergence in 30 svdcmp iterations"); 
1.2       brouard  2919:       x=w[l];  /* shift from bottom 2 x 2 minor; */
                   2920:       nm=k-1; 
                   2921:       y=w[nm]; 
                   2922:       g=rv1[nm]; 
                   2923:       h=rv1[k]; 
                   2924:       f=((y-z)*(y+z)+(g-h)*(g+h))/(2.0*h*y); 
                   2925:       g=pythag(f,1.0); 
                   2926:       /* g=dpythag(f,1.0);  */
                   2927:       f=((x-z)*(x+z)+h*((y/(f+SIGN(g,f)))-h))/x; 
                   2928:       c=s=1.0;  /* next QR transformation  */
                   2929:       for (j=l;j<=nm;j++) { 
                   2930:         i=j+1; 
                   2931:         g=rv1[i]; 
                   2932:         y=w[i]; 
                   2933:         h=s*g; 
                   2934:         g=c*g; 
                   2935:         /* z=dpythag(f,h);  */
                   2936:         z=pythag(f,h); 
                   2937:         rv1[j]=z; 
                   2938:         c=f/z; 
                   2939:         s=h/z; 
                   2940:         f=x*c+g*s; 
                   2941:         g = g*c-x*s; 
                   2942:         h=y*s; 
                   2943:         y *= c; 
                   2944: /* if withv then for j:= 1 step 1 until n do */
                   2945:         for (jj=1;jj<=n;jj++) { 
                   2946:           /* x=v[jj][j];  */
                   2947:           /* z=v[jj][i];  */
                   2948:           x=a[jj][j]; 
                   2949:           z=a[jj][i]; 
                   2950:           /* v[jj][j]=x*c+z*s;  */
                   2951:           /* v[jj][i]=z*c-x*s;  */
                   2952:           a[jj][j]=x*c+z*s; 
                   2953:           a[jj][i]=z*c-x*s; 
                   2954:         } 
                   2955:         /* z=dpythag(f,h);  */
                   2956:         z=pythag(f,h); 
                   2957:         w[j]=z; 
                   2958:         if (z) { 
                   2959:           z=1.0/z; 
                   2960:           c=f*z; 
                   2961:           s=h*z; 
                   2962:         } 
                   2963:         f=c*g+s*y; 
                   2964:         x=c*y-s*g;
                   2965:         /* if withu then for j:=1 step 1 until m do */
                   2966:         /* for (jj=1;jj<=m;jj++) {  */
                   2967:         /*   y=a[jj][j];  */
                   2968:         /*   z=a[jj][i];  */
                   2969:         /*   a[jj][j]=y*c+z*s;  */
                   2970:         /*   a[jj][i]=z*c-y*s;  */
                   2971:         /* }  */
                   2972:       } 
                   2973:       rv1[l]=0.0; 
                   2974:       rv1[k]=f; 
                   2975:       w[k]=x; 
                   2976:     } 
                   2977:   } 
                   2978:   free_vector(rv1,1,n); 
                   2979: } 
1.1       brouard  2980: 
                   2981: /* end praxis */
                   2982: 
                   2983: /*************** powell ************************/
                   2984: /*
                   2985: Minimization of a function func of n variables. Input consists in an initial starting point
                   2986: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2987: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2988: such that failure to decrease by more than this amount in one iteration signals doneness. On
                   2989: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2990: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2991:  */
                   2992: #ifdef LINMINORIGINAL
                   2993: #else
                   2994:        int *flatdir; /* Function is vanishing in that direction */
                   2995:        int flat=0, flatd=0; /* Function is vanishing in that direction */
                   2996: #endif
                   2997: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2998:            double (*func)(double [])) 
                   2999: { 
                   3000: #ifdef LINMINORIGINAL
                   3001:  void linmin(double p[], double xi[], int n, double *fret, 
                   3002:              double (*func)(double [])); 
                   3003: #else 
                   3004:  void linmin(double p[], double xi[], int n, double *fret,
                   3005:             double (*func)(double []),int *flat); 
                   3006: #endif
                   3007:  int i,ibig,j,jk,k; 
                   3008:   double del,t,*pt,*ptt,*xit;
                   3009:   double directest;
                   3010:   double fp,fptt;
                   3011:   double *xits;
                   3012:   int niterf, itmp;
1.2       brouard  3013:   int Bigter=0, nBigterf=1;
                   3014:   
1.1       brouard  3015:   pt=vector(1,n); 
                   3016:   ptt=vector(1,n); 
                   3017:   xit=vector(1,n); 
                   3018:   xits=vector(1,n); 
                   3019:   *fret=(*func)(p); 
                   3020:   for (j=1;j<=n;j++) pt[j]=p[j]; 
                   3021:   rcurr_time = time(NULL);
                   3022:   fp=(*fret); /* Initialisation */
                   3023:   for (*iter=1;;++(*iter)) { 
                   3024:     ibig=0; 
                   3025:     del=0.0; 
                   3026:     rlast_time=rcurr_time;
1.2       brouard  3027:     rlast_btime=rcurr_time;
1.1       brouard  3028:     /* (void) gettimeofday(&curr_time,&tzp); */
                   3029:     rcurr_time = time(NULL);  
                   3030:     curr_time = *localtime(&rcurr_time);
                   3031:     /* 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); */
                   3032:     /* 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.5     ! brouard  3033:     /* Bigter=(*iter - *iter % ncovmodel)/ncovmodel +1; /\* Big iteration, i.e on ncovmodel cycle *\/ */
        !          3034:     Bigter=(*iter - (*iter-1) % n)/n +1; /* Big iteration, i.e on ncovmodel cycle */
1.2       brouard  3035:     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);
                   3036:     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);
                   3037:     fprintf(ficrespow,"%d %d %.12f %d",*iter,Bigter, *fret,curr_time.tm_sec-start_time.tm_sec);
1.1       brouard  3038:     fp=(*fret); /* From former iteration or initial value */
                   3039:     for (i=1;i<=n;i++) {
                   3040:       fprintf(ficrespow," %.12lf", p[i]);
                   3041:     }
                   3042:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   3043:     printf("\n#model=  1      +     age ");
                   3044:     fprintf(ficlog,"\n#model=  1      +     age ");
                   3045:     if(nagesqr==1){
                   3046:        printf("  + age*age  ");
                   3047:        fprintf(ficlog,"  + age*age  ");
                   3048:     }
                   3049:     for(j=1;j <=ncovmodel-2;j++){
                   3050:       if(Typevar[j]==0) {
                   3051:        printf("  +      V%d  ",Tvar[j]);
                   3052:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   3053:       }else if(Typevar[j]==1) {
                   3054:        printf("  +    V%d*age ",Tvar[j]);
                   3055:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   3056:       }else if(Typevar[j]==2) {
                   3057:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   3058:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   3059:       }else if(Typevar[j]==3) {
                   3060:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   3061:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   3062:       }
                   3063:     }
                   3064:     printf("\n");
                   3065: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   3066: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
                   3067:     fprintf(ficlog,"\n");
                   3068:     for(i=1,jk=1; i <=nlstate; i++){
                   3069:       for(k=1; k <=(nlstate+ndeath); k++){
                   3070:        if (k != i) {
                   3071:          printf("%d%d ",i,k);
                   3072:          fprintf(ficlog,"%d%d ",i,k);
                   3073:          for(j=1; j <=ncovmodel; j++){
                   3074:            printf("%12.7f ",p[jk]);
                   3075:            fprintf(ficlog,"%12.7f ",p[jk]);
                   3076:            jk++; 
                   3077:          }
                   3078:          printf("\n");
                   3079:          fprintf(ficlog,"\n");
                   3080:        }
                   3081:       }
                   3082:     }
                   3083:     if(*iter <=3 && *iter >1){
                   3084:       tml = *localtime(&rcurr_time);
                   3085:       strcpy(strcurr,asctime(&tml));
                   3086:       rforecast_time=rcurr_time; 
                   3087:       itmp = strlen(strcurr);
                   3088:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   3089:        strcurr[itmp-1]='\0';
                   3090:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
                   3091:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.2       brouard  3092:       for(nBigterf=1;nBigterf<=31;nBigterf+=10){
                   3093:        niterf=nBigterf*ncovmodel;
                   3094:        /* rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time); */
1.1       brouard  3095:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   3096:        forecast_time = *localtime(&rforecast_time);
                   3097:        strcpy(strfor,asctime(&forecast_time));
                   3098:        itmp = strlen(strfor);
                   3099:        if(strfor[itmp-1]=='\n')
                   3100:          strfor[itmp-1]='\0';
1.2       brouard  3101:        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);
                   3102:        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  3103:       }
                   3104:     }
1.5     ! brouard  3105:     for (i=1;i<=n;i++) { /* For each direction i, maximisation after loading directions */
1.1       brouard  3106:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
                   3107:       fptt=(*fret); 
                   3108: #ifdef DEBUG
                   3109:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   3110:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   3111: #endif
                   3112:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
                   3113:       fprintf(ficlog,"%d",i);fflush(ficlog);
                   3114: #ifdef LINMINORIGINAL
1.5     ! brouard  3115:       linmin(p,xit,n,fret,func); /* New point i minimizing in direction xit i has coordinates p[j].*/
1.3       brouard  3116:       /* xit[j] gives the n coordinates of direction i as input.*/
                   3117:       /* *fret gives the maximum value on direction xit */
1.1       brouard  3118: #else
                   3119:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.5     ! brouard  3120:       flatdir[i]=flat; /* Function is vanishing in that direction i */
1.1       brouard  3121: #endif
1.5     ! brouard  3122:       /* Outputs are fret(new point p) p is updated and xit rescaled */
1.1       brouard  3123:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.5     ! brouard  3124:        /* because that direction will be replaced unless the gain del is small */
        !          3125:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
        !          3126:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
        !          3127:        /* with the new direction. */
        !          3128:        del=fabs(fptt-(*fret)); 
        !          3129:        ibig=i; 
1.1       brouard  3130:       } 
                   3131: #ifdef DEBUG
                   3132:       printf("%d %.12e",i,(*fret));
                   3133:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   3134:       for (j=1;j<=n;j++) {
1.5     ! brouard  3135:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
        !          3136:        printf(" x(%d)=%.12e",j,xit[j]);
        !          3137:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.1       brouard  3138:       }
                   3139:       for(j=1;j<=n;j++) {
1.5     ! brouard  3140:        printf(" p(%d)=%.12e",j,p[j]);
        !          3141:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.1       brouard  3142:       }
                   3143:       printf("\n");
                   3144:       fprintf(ficlog,"\n");
                   3145: #endif
                   3146:     } /* end loop on each direction i */
1.3       brouard  3147:     /* Convergence test will use last linmin estimation (fret) and compare to former iteration (fp) */ 
1.1       brouard  3148:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
                   3149:     for(j=1;j<=n;j++) {
                   3150:       if(flatdir[j] >0){
                   3151:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   3152:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   3153:       }
                   3154:       /* printf("\n"); */
                   3155:       /* fprintf(ficlog,"\n"); */
                   3156:     }
                   3157:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   3158:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
                   3159:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   3160:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   3161:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   3162:       /* decreased of more than 3.84  */
                   3163:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   3164:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   3165:       /* By adding 10 parameters more the gain should be 18.31 */
                   3166:                        
                   3167:       /* Starting the program with initial values given by a former maximization will simply change */
                   3168:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   3169:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   3170:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
                   3171: 
                   3172:       free_vector(xit,1,n); 
                   3173:       free_vector(xits,1,n); 
                   3174:       free_vector(ptt,1,n); 
                   3175:       free_vector(pt,1,n); 
                   3176:       return; 
                   3177:     } /* enough precision */ 
                   3178:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.5     ! brouard  3179:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0)=2Pn-P0 */
1.1       brouard  3180:       ptt[j]=2.0*p[j]-pt[j]; 
1.5     ! brouard  3181:       xit[j]=p[j]-pt[j]; /* Coordinate j of last direction xi_n=P_n-_0 */
        !          3182:       printf("\n %d xit=%12.7g p=%12.7g pt=%12.7g ",j,xit[j],p[j],pt[j]);
1.1       brouard  3183:       pt[j]=p[j]; 
1.5     ! brouard  3184:     }
        !          3185:     printf("\n");
1.1       brouard  3186:     fptt=(*func)(ptt); /* f_3 */
                   3187: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   3188:                if (*iter <=4) {
                   3189: #else
                   3190: #endif
                   3191: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
                   3192: #else
                   3193:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
                   3194: #endif
                   3195:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
                   3196:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
                   3197:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   3198:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   3199:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
                   3200:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   3201:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   3202:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
                   3203:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
                   3204:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   3205:       /* mu² and del² are equal when f3=f1 */
1.5     ! brouard  3206:       /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
        !          3207:       /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
        !          3208:       /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
        !          3209:       /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.1       brouard  3210: #ifdef NRCORIGINAL
                   3211:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   3212: #else
                   3213:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
                   3214:       t= t- del*SQR(fp-fptt);
                   3215: #endif
                   3216:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.5     ! brouard  3217:       printf(" t=%g, directest=%g\n",t, directest);
        !          3218: #ifdef POWELLNOTTRUECONJUGATE   /* Searching for IBIG and testing for replacement */  
1.1       brouard  3219: #ifdef POWELLORIGINAL
                   3220:       if (t < 0.0) { /* Then we use it for new direction */
1.5     ! brouard  3221: #else  /* Not POWELLOriginal but Brouard's */
1.1       brouard  3222:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.5     ! brouard  3223:        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);
1.1       brouard  3224:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   3225:         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);
                   3226:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   3227:       } 
1.5     ! brouard  3228:       if (directest < 0.0) { /* Then we use (P0, Pn) for new direction Xi_n or Xi_iBig */
        !          3229: #endif /* end POWELLOriginal */
        !          3230: #endif  /* POWELLNOTTRUECONJUGATE  else means systematic replacement by new direction P_0P_n */
1.1       brouard  3231: #ifdef LINMINORIGINAL
1.5     ! brouard  3232:        /* xit[j]=p[j]-pt[j] */
        !          3233:        printf("\n Computes min on P_0, P_n direction iter=%d Bigter=%d\n",*iter,Bigter);
        !          3234:        linmin(p,xit,n,fret,func); /* computes minimum on P_0,P_n direction: changes p and rescales xit.*/
        !          3235: #else  /* NOT LINMINORIGINAL but with searching for flat directions */
        !          3236:        printf("\n Flat Computes min on P_0, P_n direction iter=%d Bigter=%d\n",*iter,Bigter);
1.1       brouard  3237:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   3238:        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   3239: #endif
                   3240:        
1.5     ! brouard  3241: #ifdef POWELLNOTTRUECONJUGATE
        !          3242: #else
1.3       brouard  3243: #ifdef POWELLORIGINCONJUGATE
1.1       brouard  3244:        for (j=1;j<=n;j++) { 
                   3245:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   3246:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   3247:        }
1.3       brouard  3248: #else
1.5     ! brouard  3249:        for (i=1;i<=n-1;i++) { 
        !          3250:          for (j=1;j<=n;j++) { 
        !          3251:            xi[j][i]=xi[j][i+1]; /* Standard method of conjugate directions, not Powell who changes the nth direction by p0 pn . */
        !          3252:          }
        !          3253:        }
        !          3254:        for (j=1;j<=n;j++) { 
1.3       brouard  3255:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   3256:        }
1.5     ! brouard  3257: #endif         /* POWELLORIGINCONJUGATE*/
        !          3258: #endif  /*POWELLNOTTRUECONJUGATE*/
        !          3259:        printf(" Standard method of conjugate directions\n");
        !          3260:        printf("\n#A Before prax Bigter=%d model=  1      +     age ", Bigter);
        !          3261:        for(j=1;j<=n;j++){
        !          3262:          printf("%d \n",j);
        !          3263:          for(i=1;i<=n;i++){
        !          3264:            printf(" %f",xi[j][i]);
        !          3265:          }
        !          3266:        }
        !          3267:        printf("\n");
1.4       brouard  3268: 
1.5     ! brouard  3269: #ifdef NOTMINFIT
        !          3270: #else 
        !          3271:        if(*iter >n){
        !          3272:        /* if(Bigter >n){ */
        !          3273:          printf("\n#Before prax Bigter=%d model=  1      +     age ", Bigter);
        !          3274:          printf("\n");
        !          3275:          for(j=1;j<=n;j++){
        !          3276:            printf("%d \n",j);
        !          3277:            for(i=1;i<=n;i++){
        !          3278:              printf(" %f",xi[j][i]);
        !          3279:            }
        !          3280:          }
        !          3281:          printf("\n");
        !          3282:          /*
        !          3283:           * Calculate a new set of orthogonal directions before repeating
        !          3284:           * the main loop.
        !          3285:           * Transpose V for SVD (minfit) (because minfit returns the right V in ULV=A):
        !          3286:           */
        !          3287:          printf(" Bigter=%d Calculate a new set of orthogonal directions before repeating  the main loop.\n  Transpose V for MINFIT:...\n",Bigter);
        !          3288:          transpose_in_place ( n, xi );
        !          3289:          /*
        !          3290:            SVD/MINFIT finds the singular value decomposition of V.
        !          3291:            
        !          3292:            This gives the principal values and principal directions of the
        !          3293:            approximating quadratic form without squaring the condition number.
        !          3294:          */
        !          3295:          printf(" SVDMINFIT finds the singular value decomposition of V. \n This gives the principal values and principal directions of the\n  approximating quadratic form without squaring the condition number...\n");
        !          3296:          double *d; /* eigenvalues of principal directions */
        !          3297:          d=vector(1,n);
        !          3298:          
        !          3299:          
        !          3300:          svdminfit (xi, n, n, d ); /* In Brent's notation find d such that V=Q Diagonal(d) R, and Lambda=d^(-1/2) */
        !          3301:        
        !          3302:          printf("\n#After prax model=  1      +     age ");
        !          3303:          fprintf(ficlog,"\n#model=  1      +     age ");
        !          3304:          
        !          3305:          if(nagesqr==1){
        !          3306:            printf("  + age*age  ");
        !          3307:            fprintf(ficlog,"  + age*age  ");
        !          3308:          }
        !          3309:          for(j=1;j <=ncovmodel-2;j++){
        !          3310:            if(Typevar[j]==0) {
        !          3311:              printf("  +      V%d  ",Tvar[j]);
        !          3312:              fprintf(ficlog,"  +      V%d  ",Tvar[j]);
        !          3313:            }else if(Typevar[j]==1) {
        !          3314:              printf("  +    V%d*age ",Tvar[j]);
        !          3315:              fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
        !          3316:            }else if(Typevar[j]==2) {
        !          3317:              printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
        !          3318:              fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
        !          3319:            }else if(Typevar[j]==3) {
        !          3320:              printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
        !          3321:              fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
        !          3322:            }
        !          3323:          }
        !          3324:          printf("\n");
        !          3325:          fprintf(ficlog,"\n");
        !          3326:          for(i=1,jk=1; i <=nlstate; i++){
        !          3327:            for(k=1; k <=(nlstate+ndeath); k++){
        !          3328:              if (k != i) {
        !          3329:                printf("%d%d ",i,k);
        !          3330:                fprintf(ficlog,"%d%d ",i,k);
        !          3331:                for(j=1; j <=ncovmodel; j++){
        !          3332:                  printf("%12.7f ",p[jk]);
        !          3333:                  fprintf(ficlog,"%12.7f ",p[jk]);
        !          3334:                  jk++; 
        !          3335:                }
        !          3336:                printf("\n");
        !          3337:                fprintf(ficlog,"\n");
        !          3338:              }
        !          3339:            }
        !          3340:          }
        !          3341:          /* minfit ( n, vsmall, v, d ); */
        !          3342:          /* v is overwritten with R. */
        !          3343:          /*
        !          3344:            Heuristic numbers:
        !          3345:            If the axes may be badly scaled (which is to be avoided if
        !          3346:            possible), then set SCBD = 10.  Otherwise set SCBD = 1.
        !          3347:            
        !          3348:            If the problem is known to be ill-conditioned, initialize ILLC = true.
        !          3349:            KTM is the number of iterations without improvement before the
        !          3350:            algorithm terminates.  KTM = 4 is very cautious; usually KTM = 1
        !          3351:            is satisfactory.
        !          3352:          */
        !          3353:          double machep, small;
        !          3354:          double dmin;
        !          3355:          int illc=0; /*    Local, int ILLC, is TRUE if the system is ill-conditioned. */
        !          3356:          machep = DBL_EPSILON;
        !          3357:          small = machep * machep;
        !          3358:          /* m2 = dsqrt(machep); */
        !          3359:          
        !          3360:          /*
        !          3361:           * Sort the eigenvalues and eigenvectors.
        !          3362:           */
        !          3363:          printf(" Sort the eigenvalues and eigenvectors....\n");
        !          3364:          svsort ( n, d, xi );
        !          3365:          printf("Sorted Eigenvalues:\n");
        !          3366:          for(i=1; i<=n;i++){
        !          3367:            printf(" d[%d]=%g",i,d[i]);
        !          3368:          }
        !          3369:          printf("\n");
        !          3370:          /*
        !          3371:           * Determine the smallest eigenvalue.
        !          3372:           */
        !          3373:          printf("  Determine the smallest eigenvalue.\n");
        !          3374:          dmin = fmax ( d[n], small );
        !          3375:          /*
        !          3376:           * The ratio of the smallest to largest eigenvalue determines whether
        !          3377:           * the system is ill conditioned.
        !          3378:           */
        !          3379:          if ( dmin < sqrt(machep) * d[1] ) {  /* m2*d[0] */
        !          3380:            illc = 1;
        !          3381:          } else  {
        !          3382:            illc = 0;
        !          3383:          }
        !          3384:          printf("  The ratio of the smallest to largest eigenvalue determines whether\n \
        !          3385:   the system is ill conditioned=%d . dmin=%.12lf < m2=%.12lf * d[1]=%.12lf \n",illc, dmin,sqrt(machep), d[1]);
        !          3386:          /*    if ( 1.0 < scbd ) { */
        !          3387:          /*      r8vec_print ( n, z, "  The scale factors:" ); */
        !          3388:          /*    }  */
        !          3389:          /*    r8vec_print ( n, d, "  Principal values of the quadratic form:" ); */
        !          3390:          /* } */
        !          3391:          /* if ( 3 < prin ) { */
        !          3392:          /*    r8mat_print ( n, n, v, "  The principal axes:" ); */
        !          3393:          /* } */
        !          3394:          free_vector(d,1,n);   
        !          3395:          /*
        !          3396:           * The main loop ends here.
        !          3397:           */
        !          3398:          
        !          3399:          /* if ( 0 < prin ) */
        !          3400:          /* { */
        !          3401:          /*   r8vec_print ( n, x, "  X:" ); */
        !          3402:          /* } */
        !          3403:        }       
        !          3404: #endif  /* NOTMINFIT */
1.1       brouard  3405: #ifdef LINMINORIGINAL
                   3406: #else
                   3407:        for (j=1, flatd=0;j<=n;j++) {
                   3408:          if(flatdir[j]>0)
                   3409:            flatd++;
                   3410:        }
                   3411:        if(flatd >0){
                   3412:          printf("%d flat directions: ",flatd);
                   3413:          fprintf(ficlog,"%d flat directions :",flatd);
                   3414:          for (j=1;j<=n;j++) { 
                   3415:            if(flatdir[j]>0){
                   3416:              printf("%d ",j);
                   3417:              fprintf(ficlog,"%d ",j);
                   3418:            }
                   3419:          }
                   3420:          printf("\n");
                   3421:          fprintf(ficlog,"\n");
                   3422: #ifdef FLATSUP
                   3423:           free_vector(xit,1,n); 
                   3424:           free_vector(xits,1,n); 
                   3425:           free_vector(ptt,1,n); 
                   3426:           free_vector(pt,1,n); 
                   3427:           return;
                   3428: #endif
1.5     ! brouard  3429:        }  /* endif(flatd >0) */
1.1       brouard  3430: #endif
                   3431:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   3432:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.3       brouard  3433:   /* The minimization in direction $\xi_1$ gives $P_1$. From $P_1$ minimization in direction $\xi_2$ gives */
                   3434:   /* $P_2$. Minimization of line $P_2-P_1$ gives new starting point $P^{(1)}_0$ and direction $\xi_1$ is dropped and replaced by second */
                   3435:   /* direction $\xi_1^{(1)}=\xi_2$. Also second direction is replaced by new direction $\xi^{(1)}_2=P_2-P_0$. */
                   3436: 
                   3437:   /* At the second iteration, starting from $P_0^{(1)}$, minimization amongst $\xi^{(1)}_1$ gives point $P^{(1)}_1$. */
                   3438:   /* Minimization amongst $\xi^{(1)}_2=(P_2-P_0)$ gives point $P^{(1)}_2$.  As $P^{(2)}_1$ and */
                   3439:   /* $P^{(1)}_0$ are minimizing in the same direction $P^{(1)}_2 - P^{(1)}_1= P_2-P_0$, directions $P^{(1)}_2-P^{(1)}_0$ */
                   3440:   /* and $P_2-P_0$ (parallel to $\xi$ and $\xi^c$) are conjugate.  } */
1.5     ! brouard  3441: #ifdef POWELLNOTTRUECONJUGATE  
        !          3442:       } /* end of t or directest negative */
1.1       brouard  3443: #endif
                   3444: #ifdef POWELLNOF3INFF1TEST
                   3445: #else
                   3446:       } /* end if (fptt < fp)  */
                   3447: #endif
1.5     ! brouard  3448: #ifdef POWELLORIGINCONJUGATE
        !          3449:     } /* if (t < 0.0) */
        !          3450: #endif
1.1       brouard  3451: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   3452:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
                   3453: #else
                   3454: #endif
                   3455:                } /* loop iteration */ 
                   3456: } 
                   3457:   
                   3458: /**** Prevalence limit (stable or period prevalence)  ****************/
                   3459:   
                   3460:   double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij, int nres)
                   3461:   {
                   3462:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
                   3463:      *   (and selected quantitative values in nres)
                   3464:      *  by left multiplying the unit
                   3465:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   3466:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   3467:      * Wx is row vector: population in state 1, population in state 2, population dead
                   3468:      * or prevalence in state 1, prevalence in state 2, 0
                   3469:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   3470:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   3471:      * Output is prlim.
                   3472:      * Initial matrix pimij 
                   3473:      */
                   3474:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3475:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3476:   /*  0,                   0                  , 1} */
                   3477:   /*
                   3478:    * and after some iteration: */
                   3479:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3480:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3481:   /*  0,                   0                  , 1} */
                   3482:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3483:   /* {0.51571254859325999, 0.4842874514067399, */
                   3484:   /*  0.51326036147820708, 0.48673963852179264} */
                   3485:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3486:     
                   3487:     int i, ii,j,k, k1;
                   3488:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3489:   /* double **matprod2(); */ /* test */
                   3490:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
                   3491:   double **newm;
                   3492:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3493:   int ncvloop=0;
                   3494:   int first=0;
                   3495:   
                   3496:   min=vector(1,nlstate);
                   3497:   max=vector(1,nlstate);
                   3498:   meandiff=vector(1,nlstate);
                   3499: 
                   3500:        /* Starting with matrix unity */
                   3501:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3502:     for (j=1;j<=nlstate+ndeath;j++){
                   3503:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3504:     }
                   3505:   
                   3506:   cov[1]=1.;
                   3507:   
                   3508:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3509:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
                   3510:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
                   3511:     ncvloop++;
                   3512:     newm=savm;
                   3513:     /* Covariates have to be included here again */
                   3514:     cov[2]=agefin;
                   3515:      if(nagesqr==1){
                   3516:       cov[3]= agefin*agefin;
                   3517:      }
                   3518:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3519:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3520:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3521:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
                   3522:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3523:        }else{
                   3524:         cov[2+nagesqr+k1]=precov[nres][k1];
                   3525:        }
                   3526:      }/* End of loop on model equation */
                   3527:      
                   3528: /* Start of old code (replaced by a loop on position in the model equation */
                   3529:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   3530:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3531:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   3532:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   3533:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   3534:     /*    * k                  1        2      3    4      5      6     7        8 */
                   3535:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   3536:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   3537:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   3538:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   3539:     /*    *nsd=3                              (1)  (2)           (3) */
                   3540:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   3541:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   3542:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   3543:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   3544:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   3545:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   3546:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   3547:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   3548:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   3549:     /*    *TvarsDpType */
                   3550:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   3551:     /*    * nsd=1              (1)           (2) */
                   3552:     /*    *TvarsD[nsd]          3             2 */
                   3553:     /*    *TnsdVar           (3)=1          (2)=2 */
                   3554:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   3555:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   3556:     /*    *\/ */
                   3557:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   3558:     /*   /\* 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)); *\/ */
                   3559:     /* } */
                   3560:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   3561:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3562:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   3563:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3564:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   3565:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3566:     /*   /\* 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]); *\/ */
                   3567:     /* } */
                   3568:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3569:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   3570:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3571:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   3572:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   3573:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3574:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   3575:     /*   } */
                   3576:     /*   /\* 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]); *\/ */
                   3577:     /* } */
                   3578:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3579:     /*   /\* 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]); *\/ */
                   3580:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3581:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3582:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3583:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3584:     /*         }else{ */
                   3585:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3586:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   3587:     /*         } */
                   3588:     /*   }else{ */
                   3589:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3590:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3591:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   3592:     /*         }else{ */
                   3593:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3594:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   3595:     /*         } */
                   3596:     /*   } */
                   3597:     /* } /\* End product without age *\/ */
                   3598: /* ENd of old code */
                   3599:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3600:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3601:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3602:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3603:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
                   3604:     /* age and covariate values of ij are in 'cov' */
                   3605:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
                   3606:     
                   3607:     savm=oldm;
                   3608:     oldm=newm;
                   3609: 
                   3610:     for(j=1; j<=nlstate; j++){
                   3611:       max[j]=0.;
                   3612:       min[j]=1.;
                   3613:     }
                   3614:     for(i=1;i<=nlstate;i++){
                   3615:       sumnew=0;
                   3616:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   3617:       for(j=1; j<=nlstate; j++){ 
                   3618:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   3619:        max[j]=FMAX(max[j],prlim[i][j]);
                   3620:        min[j]=FMIN(min[j],prlim[i][j]);
                   3621:       }
                   3622:     }
                   3623: 
                   3624:     maxmax=0.;
                   3625:     for(j=1; j<=nlstate; j++){
                   3626:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   3627:       maxmax=FMAX(maxmax,meandiff[j]);
                   3628:       /* 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); */
                   3629:     } /* j loop */
                   3630:     *ncvyear= (int)age- (int)agefin;
                   3631:     /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3632:     if(maxmax < ftolpl){
                   3633:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3634:       free_vector(min,1,nlstate);
                   3635:       free_vector(max,1,nlstate);
                   3636:       free_vector(meandiff,1,nlstate);
                   3637:       return prlim;
                   3638:     }
                   3639:   } /* agefin loop */
                   3640:     /* After some age loop it doesn't converge */
                   3641:   if(!first){
                   3642:     first=1;
                   3643:     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);
                   3644:     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);
                   3645:   }else if (first >=1 && first <10){
                   3646:     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);
                   3647:     first++;
                   3648:   }else if (first ==10){
                   3649:     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);
                   3650:     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");
                   3651:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   3652:     first++;
                   3653:   }
                   3654: 
                   3655:   /* 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); */
                   3656:   free_vector(min,1,nlstate);
                   3657:   free_vector(max,1,nlstate);
                   3658:   free_vector(meandiff,1,nlstate);
                   3659:   
                   3660:   return prlim; /* should not reach here */
                   3661: }
                   3662: 
                   3663: 
                   3664:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3665: 
                   3666:  /* 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) */
                   3667:  /* 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) */
                   3668:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
                   3669: {
                   3670:   /* Computes the prevalence limit in each live state at age x and for covariate combination ij (<=2**cptcoveff) by left multiplying the unit
                   3671:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3672:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3673:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3674:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3675:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3676:   /* Initial matrix pimij */
                   3677:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3678:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3679:   /*  0,                   0                  , 1} */
                   3680:   /*
                   3681:    * and after some iteration: */
                   3682:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3683:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3684:   /*  0,                   0                  , 1} */
                   3685:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3686:   /* {0.51571254859325999, 0.4842874514067399, */
                   3687:   /*  0.51326036147820708, 0.48673963852179264} */
                   3688:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3689: 
                   3690:   int i, ii,j,k, k1;
                   3691:   int first=0;
                   3692:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3693:   /* double **matprod2(); */ /* test */
                   3694:   double **out, cov[NCOVMAX+1], **bmij();
                   3695:   double **newm;
                   3696:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3697:   double        **oldm, **savm;  /* for use */
                   3698: 
                   3699:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3700:   int ncvloop=0;
                   3701:   
                   3702:   min=vector(1,nlstate);
                   3703:   max=vector(1,nlstate);
                   3704:   meandiff=vector(1,nlstate);
                   3705: 
                   3706:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3707:   oldm=oldms; savm=savms;
                   3708:   
                   3709:   /* Starting with matrix unity */
                   3710:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3711:     for (j=1;j<=nlstate+ndeath;j++){
                   3712:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3713:     }
                   3714:   
                   3715:   cov[1]=1.;
                   3716:   
                   3717:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3718:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
                   3719:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3720:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3721:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
                   3722:     ncvloop++;
                   3723:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3724:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
                   3725:     /* Covariates have to be included here again */
                   3726:     cov[2]=agefin;
                   3727:     if(nagesqr==1){
                   3728:       cov[3]= agefin*agefin;;
                   3729:     }
                   3730:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3731:       if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
                   3732:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3733:       }else{
                   3734:        cov[2+nagesqr+k1]=precov[nres][k1];
                   3735:       }
                   3736:     }/* End of loop on model equation */
                   3737: 
                   3738: /* Old code */ 
                   3739: 
                   3740:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3741:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3742:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3743:     /*   /\* 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)); *\/ */
                   3744:     /* } */
                   3745:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3746:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3747:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3748:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3749:     /* /\* } *\/ */
                   3750:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3751:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3752:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3753:     /*   /\* 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]); *\/ */
                   3754:     /* } */
                   3755:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3756:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3757:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3758:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3759:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3760:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3761:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3762:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3763:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3764:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3765:     /*   } */
                   3766:     /*   /\* 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]); *\/ */
                   3767:     /* } */
                   3768:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3769:     /*   /\* 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]); *\/ */
                   3770:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3771:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3772:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3773:     /*         }else{ */
                   3774:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3775:     /*         } */
                   3776:     /*   }else{ */
                   3777:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3778:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3779:     /*         }else{ */
                   3780:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3781:     /*         } */
                   3782:     /*   } */
                   3783:     /* } */
                   3784:     
                   3785:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3786:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3787:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3788:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3789:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
                   3790:                /* ij should be linked to the correct index of cov */
                   3791:                /* age and covariate values ij are in 'cov', but we need to pass
                   3792:                 * ij for the observed prevalence at age and status and covariate
                   3793:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3794:                 */
                   3795:     /* 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 *\/ */
                   3796:     /* 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 *\/ */
                   3797:     out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij)); /* Bug Valgrind */
                   3798:     /* if((int)age == 86 || (int)age == 87){ */
                   3799:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3800:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3801:     /*         printf("%d newm= ",i); */
                   3802:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3803:     /*           printf("%f ",newm[i][j]); */
                   3804:     /*         } */
                   3805:     /*         printf("oldm * "); */
                   3806:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3807:     /*           printf("%f ",oldm[i][j]); */
                   3808:     /*         } */
                   3809:     /*         printf(" bmmij "); */
                   3810:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3811:     /*           printf("%f ",pmmij[i][j]); */
                   3812:     /*         } */
                   3813:     /*         printf("\n"); */
                   3814:     /*   } */
                   3815:     /* } */
                   3816:     savm=oldm;
                   3817:     oldm=newm;
                   3818: 
                   3819:     for(j=1; j<=nlstate; j++){
                   3820:       max[j]=0.;
                   3821:       min[j]=1.;
                   3822:     }
                   3823:     for(j=1; j<=nlstate; j++){ 
                   3824:       for(i=1;i<=nlstate;i++){
                   3825:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3826:        bprlim[i][j]= newm[i][j];
                   3827:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3828:        min[i]=FMIN(min[i],bprlim[i][j]);
                   3829:       }
                   3830:     }
                   3831:                
                   3832:     maxmax=0.;
                   3833:     for(i=1; i<=nlstate; i++){
                   3834:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
                   3835:       maxmax=FMAX(maxmax,meandiff[i]);
                   3836:       /* 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); */
                   3837:     } /* i loop */
                   3838:     *ncvyear= -( (int)age- (int)agefin);
                   3839:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3840:     if(maxmax < ftolpl){
                   3841:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3842:       free_vector(min,1,nlstate);
                   3843:       free_vector(max,1,nlstate);
                   3844:       free_vector(meandiff,1,nlstate);
                   3845:       return bprlim;
                   3846:     }
                   3847:   } /* agefin loop */
                   3848:     /* After some age loop it doesn't converge */
                   3849:   if(!first){
                   3850:     first=1;
                   3851:     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\
                   3852: 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);
                   3853:   }
                   3854:   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\
                   3855: 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);
                   3856:   /* 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); */
                   3857:   free_vector(min,1,nlstate);
                   3858:   free_vector(max,1,nlstate);
                   3859:   free_vector(meandiff,1,nlstate);
                   3860:   
                   3861:   return bprlim; /* should not reach here */
                   3862: }
                   3863: 
                   3864: /*************** transition probabilities ***************/ 
                   3865: 
                   3866: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3867: {
                   3868:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3869:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
                   3870:      model to the ncovmodel covariates (including constant and age).
                   3871:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3872:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3873:      ncth covariate in the global vector x is given by the formula:
                   3874:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3875:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3876:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3877:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3878:      Outputs ps[i][j] or probability to be observed in j being in i according to
                   3879:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3880:      Sum on j ps[i][j] should equal to 1.
                   3881:   */
                   3882:   double s1, lnpijopii;
                   3883:   /*double t34;*/
                   3884:   int i,j, nc, ii, jj;
                   3885: 
                   3886:   for(i=1; i<= nlstate; i++){
                   3887:     for(j=1; j<i;j++){
                   3888:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3889:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3890:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3891:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3892:       }
                   3893:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3894:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
                   3895:     }
                   3896:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3897:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3898:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3899:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3900:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3901:       }
                   3902:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3903:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
                   3904:     }
                   3905:   }
                   3906:   
                   3907:   for(i=1; i<= nlstate; i++){
                   3908:     s1=0;
                   3909:     for(j=1; j<i; j++){
                   3910:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
                   3911:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3912:     }
                   3913:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3914:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
                   3915:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3916:     }
                   3917:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3918:     ps[i][i]=1./(s1+1.);
                   3919:     /* Computing other pijs */
                   3920:     for(j=1; j<i; j++)
                   3921:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
                   3922:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3923:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3924:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3925:   } /* end i */
                   3926:   
                   3927:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3928:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3929:       ps[ii][jj]=0;
                   3930:       ps[ii][ii]=1;
                   3931:     }
                   3932:   }
                   3933: 
                   3934: 
                   3935:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3936:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3937:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3938:   /*   } */
                   3939:   /*   printf("\n "); */
                   3940:   /* } */
                   3941:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3942:   /*
                   3943:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3944:                goto end;*/
                   3945:   return ps; /* Pointer is unchanged since its call */
                   3946: }
                   3947: 
                   3948: /*************** backward transition probabilities ***************/ 
                   3949: 
                   3950:  /* 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 ) */
                   3951: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3952:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3953: {
                   3954:   /* Computes the backward probability at age agefin, cov[2], and covariate combination 'ij'. In fact cov is already filled and x too.
                   3955:    * Call to pmij(cov and x), call to cross prevalence, sums and inverses, left multiply, and returns in **ps as well as **bmij.
                   3956:    */
                   3957:   int i, ii, j,k;
                   3958:   
                   3959:   double **out, **pmij();
                   3960:   double sumnew=0.;
                   3961:   double agefin;
                   3962:   double k3=0.; /* constant of the w_x diagonal matrix (in order for B to sum to 1 even for death state) */
                   3963:   double **dnewm, **dsavm, **doldm;
                   3964:   double **bbmij;
                   3965:   
                   3966:   doldm=ddoldms; /* global pointers */
                   3967:   dnewm=ddnewms;
                   3968:   dsavm=ddsavms;
                   3969: 
                   3970:   /* Debug */
                   3971:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
                   3972:   agefin=cov[2];
                   3973:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
                   3974:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
                   3975:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3976:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3977: 
                   3978:   /* P_x */
                   3979:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
                   3980:   /* outputs pmmij which is a stochastic matrix in row */
                   3981: 
                   3982:   /* Diag(w_x) */
                   3983:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
                   3984:   sumnew=0.;
                   3985:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
                   3986:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
                   3987:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
                   3988:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3989:   }
                   3990:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3991:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3992:       for (j=1;j<=nlstate+ndeath;j++)
                   3993:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
                   3994:     }
                   3995:   }else{
                   3996:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3997:       for (j=1;j<=nlstate+ndeath;j++)
                   3998:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3999:     }
                   4000:     /* if(sumnew <0.9){ */
                   4001:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   4002:     /* } */
                   4003:   }
                   4004:   k3=0.0;  /* We put the last diagonal to 0 */
                   4005:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   4006:       doldm[ii][ii]= k3;
                   4007:   }
                   4008:   /* End doldm, At the end doldm is diag[(w_i)] */
                   4009:   
                   4010:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   4011:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
                   4012: 
                   4013:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
                   4014:   /* w1 p11 + w2 p21 only on live states N1./N..*N11/N1. + N2./N..*N21/N2.=(N11+N21)/N..=N.1/N.. */
                   4015:   for (j=1;j<=nlstate+ndeath;j++){
                   4016:     sumnew=0.;
                   4017:     for (ii=1;ii<=nlstate;ii++){
                   4018:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
                   4019:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
                   4020:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
                   4021:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   4022:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
                   4023:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   4024:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
                   4025:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   4026:        /* }else */
                   4027:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   4028:     } /*End ii */
                   4029:   } /* 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 */
                   4030: 
                   4031:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
                   4032:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
                   4033:   /* end bmij */
                   4034:   return ps; /*pointer is unchanged */
                   4035: }
                   4036: /*************** transition probabilities ***************/ 
                   4037: 
                   4038: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   4039: {
                   4040:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   4041:      computes the probability to be observed in state j being in state i by appying the
                   4042:      model to the ncovmodel covariates (including constant and age).
                   4043:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   4044:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   4045:      ncth covariate in the global vector x is given by the formula:
                   4046:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   4047:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   4048:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   4049:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   4050:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   4051:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   4052:   */
                   4053:   double s1, lnpijopii;
                   4054:   /*double t34;*/
                   4055:   int i,j, nc, ii, jj;
                   4056: 
                   4057:   for(i=1; i<= nlstate; i++){
                   4058:     for(j=1; j<i;j++){
                   4059:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   4060:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   4061:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   4062:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   4063:       }
                   4064:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   4065:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   4066:     }
                   4067:     for(j=i+1; j<=nlstate+ndeath;j++){
                   4068:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   4069:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   4070:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   4071:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   4072:       }
                   4073:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   4074:     }
                   4075:   }
                   4076:   
                   4077:   for(i=1; i<= nlstate; i++){
                   4078:     s1=0;
                   4079:     for(j=1; j<i; j++){
                   4080:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   4081:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   4082:     }
                   4083:     for(j=i+1; j<=nlstate+ndeath; j++){
                   4084:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   4085:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   4086:     }
                   4087:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   4088:     ps[i][i]=1./(s1+1.);
                   4089:     /* Computing other pijs */
                   4090:     for(j=1; j<i; j++)
                   4091:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   4092:     for(j=i+1; j<=nlstate+ndeath; j++)
                   4093:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   4094:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   4095:   } /* end i */
                   4096:   
                   4097:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   4098:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   4099:       ps[ii][jj]=0;
                   4100:       ps[ii][ii]=1;
                   4101:     }
                   4102:   }
                   4103:   /* Added for prevbcast */ /* Transposed matrix too */
                   4104:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   4105:     s1=0.;
                   4106:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   4107:       s1+=ps[ii][jj];
                   4108:     }
                   4109:     for(ii=1; ii<= nlstate; ii++){
                   4110:       ps[ii][jj]=ps[ii][jj]/s1;
                   4111:     }
                   4112:   }
                   4113:   /* Transposition */
                   4114:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   4115:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   4116:       s1=ps[ii][jj];
                   4117:       ps[ii][jj]=ps[jj][ii];
                   4118:       ps[jj][ii]=s1;
                   4119:     }
                   4120:   }
                   4121:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   4122:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   4123:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   4124:   /*   } */
                   4125:   /*   printf("\n "); */
                   4126:   /* } */
                   4127:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   4128:   /*
                   4129:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   4130:     goto end;*/
                   4131:   return ps;
                   4132: }
                   4133: 
                   4134: 
                   4135: /**************** Product of 2 matrices ******************/
                   4136: 
                   4137: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
                   4138: {
                   4139:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   4140:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   4141:   /* in, b, out are matrice of pointers which should have been initialized 
                   4142:      before: only the contents of out is modified. The function returns
                   4143:      a pointer to pointers identical to out */
                   4144:   int i, j, k;
                   4145:   for(i=nrl; i<= nrh; i++)
                   4146:     for(k=ncolol; k<=ncoloh; k++){
                   4147:       out[i][k]=0.;
                   4148:       for(j=ncl; j<=nch; j++)
                   4149:        out[i][k] +=in[i][j]*b[j][k];
                   4150:     }
                   4151:   return out;
                   4152: }
                   4153: 
                   4154: 
                   4155: /************* Higher Matrix Product ***************/
                   4156: 
                   4157: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij, int nres )
                   4158: {
                   4159:   /* Already optimized with precov.
                   4160:      Computes the transition matrix starting at age 'age' and dummies values in each resultline (loop on ij to find the corresponding combination) to over 
                   4161:      'nhstepm*hstepm*stepm' months (i.e. until
                   4162:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   4163:      nhstepm*hstepm matrices. 
                   4164:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   4165:      (typically every 2 years instead of every month which is too big 
                   4166:      for the memory).
                   4167:      Model is determined by parameters x and covariates have to be 
                   4168:      included manually here. 
                   4169: 
                   4170:      */
                   4171: 
                   4172:   int i, j, d, h, k, k1;
                   4173:   double **out, cov[NCOVMAX+1];
                   4174:   double **newm;
                   4175:   double agexact;
                   4176:   double agebegin, ageend;
                   4177: 
                   4178:   /* Hstepm could be zero and should return the unit matrix */
                   4179:   for (i=1;i<=nlstate+ndeath;i++)
                   4180:     for (j=1;j<=nlstate+ndeath;j++){
                   4181:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   4182:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   4183:     }
                   4184:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   4185:   for(h=1; h <=nhstepm; h++){
                   4186:     for(d=1; d <=hstepm; d++){
                   4187:       newm=savm;
                   4188:       /* Covariates have to be included here again */
                   4189:       cov[1]=1.;
                   4190:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
                   4191:       cov[2]=agexact;
                   4192:       if(nagesqr==1){
                   4193:        cov[3]= agexact*agexact;
                   4194:       }
                   4195:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   4196:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   4197:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   4198:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
                   4199:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   4200:        }else{
                   4201:          cov[2+nagesqr+k1]=precov[nres][k1];
                   4202:        }
                   4203:       }/* End of loop on model equation */
                   4204:        /* Old code */ 
                   4205: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   4206: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   4207: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   4208: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   4209: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   4210: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   4211: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   4212: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   4213: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   4214: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   4215: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   4216: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   4217: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   4218: /*       /\* 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]])); *\/ */
                   4219: /*       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); */
                   4220: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   4221: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   4222: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   4223: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   4224: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   4225: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   4226: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   4227: /*       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]]); */
                   4228: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   4229: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   4230: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   4231: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   4232: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   4233: /*       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]); */
                   4234: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   4235: 
                   4236: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   4237: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   4238: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   4239: /*       /\* *\/ */
                   4240: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   4241: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   4242: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   4243: /* /\*cptcovage=2                   1               2      *\/ */
                   4244: /* /\*Tage[k]=                      5               8      *\/  */
                   4245: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   4246: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   4247: /*       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]]); */
                   4248: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   4249: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   4250: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   4251: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   4252: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   4253: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   4254: /*       /\*   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); *\/ */
                   4255: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   4256: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   4257: /*       /\* } *\/ */
                   4258: /*       /\* 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]); *\/ */
                   4259: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   4260: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   4261: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   4262: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   4263: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   4264: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   4265: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   4266: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   4267: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
                   4268:          
                   4269: /*       /\* 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])]); *\/ */
                   4270: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   4271: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   4272: /*       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]]); */
                   4273: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   4274: 
                   4275: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   4276: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   4277: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   4278: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   4279: /*           /\* 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]])]; *\/ */
                   4280: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   4281: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   4282: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   4283: /*       /\*   } *\/ */
                   4284: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   4285: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   4286: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   4287: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   4288: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   4289: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   4290: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   4291: /*       /\*   } *\/ */
                   4292: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   4293: /*     }/\*end of products *\/ */
                   4294:       /* } /\* End of loop on model equation *\/ */
                   4295:       /* for (k=1; k<=cptcovn;k++)  */
                   4296:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   4297:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   4298:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   4299:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   4300:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   4301:       
                   4302:       
                   4303:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   4304:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   4305:       /* right multiplication of oldm by the current matrix */
                   4306:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   4307:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4308:       /* if((int)age == 70){ */
                   4309:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   4310:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   4311:       /*         printf("%d pmmij ",i); */
                   4312:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4313:       /*           printf("%f ",pmmij[i][j]); */
                   4314:       /*         } */
                   4315:       /*         printf(" oldm "); */
                   4316:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4317:       /*           printf("%f ",oldm[i][j]); */
                   4318:       /*         } */
                   4319:       /*         printf("\n"); */
                   4320:       /*       } */
                   4321:       /* } */
                   4322:       savm=oldm;
                   4323:       oldm=newm;
                   4324:     }
                   4325:     for(i=1; i<=nlstate+ndeath; i++)
                   4326:       for(j=1;j<=nlstate+ndeath;j++) {
                   4327:        po[i][j][h]=newm[i][j];
                   4328:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
                   4329:       }
                   4330:     /*printf("h=%d ",h);*/
                   4331:   } /* end h */
                   4332:   /*     printf("\n H=%d \n",h); */
                   4333:   return po;
                   4334: }
                   4335: 
                   4336: /************* Higher Back Matrix Product ***************/
                   4337: /* 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 ) */
                   4338: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij, int nres )
                   4339: {
                   4340:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   4341:      computes the transition matrix starting at age 'age' over
                   4342:      'nhstepm*hstepm*stepm' months (i.e. until
                   4343:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   4344:      nhstepm*hstepm matrices.
                   4345:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   4346:      (typically every 2 years instead of every month which is too big
                   4347:      for the memory).
                   4348:      Model is determined by parameters x and covariates have to be
                   4349:      included manually here. Then we use a call to bmij(x and cov)
                   4350:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
                   4351:   */
                   4352: 
                   4353:   int i, j, d, h, k, k1;
                   4354:   double **out, cov[NCOVMAX+1], **bmij();
                   4355:   double **newm, ***newmm;
                   4356:   double agexact;
                   4357:   double agebegin, ageend;
                   4358:   double **oldm, **savm;
                   4359: 
                   4360:   newmm=po; /* To be saved */
                   4361:   oldm=oldms;savm=savms; /* Global pointers */
                   4362:   /* Hstepm could be zero and should return the unit matrix */
                   4363:   for (i=1;i<=nlstate+ndeath;i++)
                   4364:     for (j=1;j<=nlstate+ndeath;j++){
                   4365:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   4366:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   4367:     }
                   4368:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   4369:   for(h=1; h <=nhstepm; h++){
                   4370:     for(d=1; d <=hstepm; d++){
                   4371:       newm=savm;
                   4372:       /* Covariates have to be included here again */
                   4373:       cov[1]=1.;
                   4374:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
                   4375:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   4376:         /* Debug */
                   4377:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
                   4378:       cov[2]=agexact;
                   4379:       if(nagesqr==1){
                   4380:        cov[3]= agexact*agexact;
                   4381:       }
                   4382:       /** New code */
                   4383:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   4384:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
                   4385:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   4386:        }else{
                   4387:          cov[2+nagesqr+k1]=precov[nres][k1];
                   4388:        }
                   4389:       }/* End of loop on model equation */
                   4390:       /** End of new code */
                   4391:   /** This was old code */
                   4392:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   4393:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   4394:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   4395:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   4396:       /*   /\* 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)); *\/ */
                   4397:       /* } */
                   4398:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   4399:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   4400:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   4401:       /*       /\* 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]); *\/ */
                   4402:       /* } */
                   4403:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   4404:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   4405:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   4406:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   4407:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   4408:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   4409:       /*       } */
                   4410:       /*       /\* 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]); *\/ */
                   4411:       /* } */
                   4412:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   4413:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   4414:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   4415:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   4416:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   4417:       /*         }else{ */
                   4418:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   4419:       /*         } */
                   4420:       /*       }else{ */
                   4421:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   4422:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   4423:       /*         }else{ */
                   4424:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   4425:       /*         } */
                   4426:       /*       } */
                   4427:       /* }                      */
                   4428:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   4429:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   4430: /** End of old code */
                   4431:       
                   4432:       /* Careful transposed matrix */
                   4433:       /* age is in cov[2], prevacurrent at beginning of transition. */
                   4434:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
                   4435:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
                   4436:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
                   4437:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
                   4438:       /* if((int)age == 70){ */
                   4439:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   4440:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   4441:       /*         printf("%d pmmij ",i); */
                   4442:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4443:       /*           printf("%f ",pmmij[i][j]); */
                   4444:       /*         } */
                   4445:       /*         printf(" oldm "); */
                   4446:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4447:       /*           printf("%f ",oldm[i][j]); */
                   4448:       /*         } */
                   4449:       /*         printf("\n"); */
                   4450:       /*       } */
                   4451:       /* } */
                   4452:       savm=oldm;
                   4453:       oldm=newm;
                   4454:     }
                   4455:     for(i=1; i<=nlstate+ndeath; i++)
                   4456:       for(j=1;j<=nlstate+ndeath;j++) {
                   4457:        po[i][j][h]=newm[i][j];
                   4458:        /* if(h==nhstepm) */
                   4459:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
                   4460:       }
                   4461:     /* printf("h=%d %.1f ",h, agexact); */
                   4462:   } /* end h */
                   4463:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
                   4464:   return po;
                   4465: }
                   4466: 
                   4467: 
                   4468: #ifdef NLOPT
                   4469:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   4470:   double fret;
                   4471:   double *xt;
                   4472:   int j;
                   4473:   myfunc_data *d2 = (myfunc_data *) pd;
                   4474: /* xt = (p1-1); */
                   4475:   xt=vector(1,n); 
                   4476:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   4477: 
                   4478:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   4479:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   4480:   printf("Function = %.12lf ",fret);
                   4481:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   4482:   printf("\n");
                   4483:  free_vector(xt,1,n);
                   4484:   return fret;
                   4485: }
                   4486: #endif
                   4487: 
                   4488: /*************** log-likelihood *************/
                   4489: double func( double *x)
                   4490: {
                   4491:   int i, ii, j, k, mi, d, kk, kf=0;
                   4492:   int ioffset=0;
                   4493:   int ipos=0,iposold=0,ncovv=0;
                   4494: 
                   4495:   double cotvarv, cotvarvold;
                   4496:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   4497:   double **out;
                   4498:   double lli; /* Individual log likelihood */
                   4499:   int s1, s2;
                   4500:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4501: 
                   4502:   double bbh, survp;
                   4503:   double agexact;
                   4504:   double agebegin, ageend;
                   4505:   /*extern weight */
                   4506:   /* We are differentiating ll according to initial status */
                   4507:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4508:   /*for(i=1;i<imx;i++) 
                   4509:     printf(" %d\n",s[4][i]);
                   4510:   */
                   4511: 
                   4512:   ++countcallfunc;
                   4513: 
                   4514:   cov[1]=1.;
                   4515: 
                   4516:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   4517:   ioffset=0;
1.2       brouard  4518:   if(mle==1){
                   4519:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4520:       /* Computes the values of the ncovmodel covariates of the model
                   4521:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4522:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4523:         to be observed in j being in i according to the model.
                   4524:       */
                   4525:       ioffset=2+nagesqr ;
                   4526:    /* Fixed */
                   4527:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummy or quant or prod */
                   4528:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   4529:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   4530:        /*  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 */
                   4531:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
                   4532:        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)*/
                   4533:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
                   4534:       }
                   4535:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   4536:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   4537:         has been calculated etc */
                   4538:       /* For an individual i, wav[i] gives the number of effective waves */
                   4539:       /* We compute the contribution to Likelihood of each effective transition
                   4540:         mw[mi][i] is real wave of the mi th effectve wave */
                   4541:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4542:         s2=s[mw[mi+1][i]][i];
                   4543:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i] because now is moved after nvocol+nqv 
                   4544:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   4545:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   4546:       */
                   4547:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.1       brouard  4548:       /* Wave varying (but not age varying) */
1.2       brouard  4549:        /* 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*\/ */
                   4550:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   4551:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4552:        /* } */
                   4553:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
                   4554:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   4555:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4556:          if(FixedV[itv]!=0){ /* Not a fixed covariate */
                   4557:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.1       brouard  4558:          }else{ /* fixed covariate */
                   4559:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4560:          }
                   4561:          if(ipos!=iposold){ /* Not a product or first of a product */
                   4562:            cotvarvold=cotvarv;
                   4563:          }else{ /* A second product */
                   4564:            cotvarv=cotvarv*cotvarvold;
                   4565:          }
                   4566:          iposold=ipos;
1.2       brouard  4567:          cov[ioffset+ipos]=cotvarv;
1.1       brouard  4568:        }
1.2       brouard  4569:        /* for products of time varying to be done */
                   4570:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4571:          for (j=1;j<=nlstate+ndeath;j++){
                   4572:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4573:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4574:          }
                   4575: 
                   4576:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4577:        ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4578:        for(d=0; d<dh[mi][i]; d++){
                   4579:          newm=savm;
                   4580:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4581:          cov[2]=agexact;
                   4582:          if(nagesqr==1)
                   4583:            cov[3]= agexact*agexact;  /* Should be changed here */
                   4584:          /* for (kk=1; kk<=cptcovage;kk++) { */
                   4585:          /*   if(!FixedV[Tvar[Tage[kk]]]) */
                   4586:          /*     cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /\* Tage[kk] gives the data-covariate associated with age *\/ */
                   4587:          /*   else */
                   4588:          /*     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) *\/  */
                   4589:          /* } */
                   4590:          for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   4591:            itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   4592:            ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   4593:            if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   4594:              cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   4595:            }else{ /* fixed covariate */
                   4596:              cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   4597:            }
                   4598:            if(ipos!=iposold){ /* Not a product or first of a product */
                   4599:              cotvarvold=cotvarv;
                   4600:            }else{ /* A second product */
                   4601:              cotvarv=cotvarv*cotvarvold;
                   4602:            }
                   4603:            iposold=ipos;
                   4604:            cov[ioffset+ipos]=cotvarv*agexact;
                   4605:            /* For products */
                   4606:          }
                   4607:          
                   4608:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4609:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4610:          savm=oldm;
                   4611:          oldm=newm;
                   4612:        } /* end mult */
1.1       brouard  4613:        
                   4614:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1.2       brouard  4615:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4616:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4617:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4618:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4619:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4620:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4621:         * probability in order to take into account the bias as a fraction of the way
                   4622:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4623:                                 * -stepm/2 to stepm/2 .
                   4624:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4625:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4626:                                 */
                   4627:        s1=s[mw[mi][i]][i];
                   4628:        s2=s[mw[mi+1][i]][i];
                   4629:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4630:        /* bias bh is positive if real duration
                   4631:         * is higher than the multiple of stepm and negative otherwise.
                   4632:         */
                   4633:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   4634:        if( s2 > nlstate){ 
                   4635:          /* i.e. if s2 is a death state and if the date of death is known 
                   4636:             then the contribution to the likelihood is the probability to 
                   4637:             die between last step unit time and current  step unit time, 
                   4638:             which is also equal to probability to die before dh 
                   4639:             minus probability to die before dh-stepm . 
                   4640:             In version up to 0.92 likelihood was computed
                   4641:             as if date of death was unknown. Death was treated as any other
                   4642:             health state: the date of the interview describes the actual state
                   4643:             and not the date of a change in health state. The former idea was
                   4644:             to consider that at each interview the state was recorded
                   4645:             (healthy, disable or death) and IMaCh was corrected; but when we
                   4646:             introduced the exact date of death then we should have modified
                   4647:             the contribution of an exact death to the likelihood. This new
                   4648:             contribution is smaller and very dependent of the step unit
                   4649:             stepm. It is no more the probability to die between last interview
                   4650:             and month of death but the probability to survive from last
                   4651:             interview up to one month before death multiplied by the
                   4652:             probability to die within a month. Thanks to Chris
                   4653:             Jackson for correcting this bug.  Former versions increased
                   4654:             mortality artificially. The bad side is that we add another loop
                   4655:             which slows down the processing. The difference can be up to 10%
                   4656:             lower mortality.
                   4657:          */
                   4658:          /* If, at the beginning of the maximization mostly, the
                   4659:             cumulative probability or probability to be dead is
                   4660:             constant (ie = 1) over time d, the difference is equal to
                   4661:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   4662:             s1 at precedent wave, to be dead a month before current
                   4663:             wave is equal to probability, being at state s1 at
                   4664:             precedent wave, to be dead at mont of the current
                   4665:             wave. Then the observed probability (that this person died)
                   4666:             is null according to current estimated parameter. In fact,
                   4667:             it should be very low but not zero otherwise the log go to
                   4668:             infinity.
                   4669:          */
1.1       brouard  4670: /* #ifdef INFINITYORIGINAL */
                   4671: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4672: /* #else */
                   4673: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   4674: /*         lli=log(mytinydouble); */
                   4675: /*       else */
                   4676: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4677: /* #endif */
1.2       brouard  4678:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4679:          
                   4680:        } else if  ( s2==-1 ) { /* alive */
                   4681:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4682:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4683:          /*survp += out[s1][j]; */
                   4684:          lli= log(survp);
                   4685:        }
                   4686:        /* else if  (s2==-4) {  */
                   4687:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   4688:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4689:        /*   lli= log(survp);  */
                   4690:        /* }  */
                   4691:        /* else if  (s2==-5) {  */
                   4692:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   4693:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4694:        /*   lli= log(survp);  */
                   4695:        /* }  */
                   4696:        else{
                   4697:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4698:          /*  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 */
                   4699:        } 
                   4700:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   4701:        /*if(lli ==000.0)*/
                   4702:        /* 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); */
                   4703:        ipmx +=1;
                   4704:        sw += weight[i];
                   4705:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4706:        /* if (lli < log(mytinydouble)){ */
                   4707:        /*   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); */
                   4708:        /*   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]); */
                   4709:        /* } */
                   4710:       } /* end of wave */
                   4711:     } /* end of individual */
                   4712:   }  else if(mle==2){
                   4713:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4714:       ioffset=2+nagesqr ;
                   4715:       for (k=1; k<=ncovf;k++)
                   4716:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
                   4717:       for(mi=1; mi<= wav[i]-1; mi++){
                   4718:        for(k=1; k <= ncovv ; k++){
                   4719:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; /* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   4720:        }
                   4721:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4722:          for (j=1;j<=nlstate+ndeath;j++){
                   4723:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4724:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4725:          }
                   4726:        for(d=0; d<=dh[mi][i]; d++){
                   4727:          newm=savm;
                   4728:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4729:          cov[2]=agexact;
                   4730:          if(nagesqr==1)
                   4731:            cov[3]= agexact*agexact;
                   4732:          for (kk=1; kk<=cptcovage;kk++) {
                   4733:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4734:          }
                   4735:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4736:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4737:          savm=oldm;
                   4738:          oldm=newm;
                   4739:        } /* end mult */
                   4740:       
                   4741:        s1=s[mw[mi][i]][i];
                   4742:        s2=s[mw[mi+1][i]][i];
                   4743:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4744:        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 */
                   4745:        ipmx +=1;
                   4746:        sw += weight[i];
                   4747:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4748:       } /* end of wave */
                   4749:     } /* end of individual */
                   4750:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4751:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4752:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4753:       for(mi=1; mi<= wav[i]-1; mi++){
                   4754:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4755:          for (j=1;j<=nlstate+ndeath;j++){
                   4756:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4757:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4758:          }
                   4759:        for(d=0; d<dh[mi][i]; d++){
                   4760:          newm=savm;
                   4761:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4762:          cov[2]=agexact;
                   4763:          if(nagesqr==1)
                   4764:            cov[3]= agexact*agexact;
                   4765:          for (kk=1; kk<=cptcovage;kk++) {
                   4766:            if(!FixedV[Tvar[Tage[kk]]])
                   4767:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4768:            else
                   4769:              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) */ 
                   4770:          }
                   4771:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4772:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4773:          savm=oldm;
                   4774:          oldm=newm;
                   4775:        } /* end mult */
                   4776:       
                   4777:        s1=s[mw[mi][i]][i];
                   4778:        s2=s[mw[mi+1][i]][i];
                   4779:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4780:        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 */
                   4781:        ipmx +=1;
                   4782:        sw += weight[i];
                   4783:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4784:       } /* end of wave */
                   4785:     } /* end of individual */
                   4786:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4787:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4788:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4789:       for(mi=1; mi<= wav[i]-1; mi++){
                   4790:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4791:          for (j=1;j<=nlstate+ndeath;j++){
                   4792:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4793:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4794:          }
                   4795:        for(d=0; d<dh[mi][i]; d++){
                   4796:          newm=savm;
                   4797:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4798:          cov[2]=agexact;
                   4799:          if(nagesqr==1)
                   4800:            cov[3]= agexact*agexact;
                   4801:          for (kk=1; kk<=cptcovage;kk++) {
                   4802:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4803:          }
                   4804:        
                   4805:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4806:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4807:          savm=oldm;
                   4808:          oldm=newm;
                   4809:        } /* end mult */
                   4810:       
                   4811:        s1=s[mw[mi][i]][i];
                   4812:        s2=s[mw[mi+1][i]][i];
                   4813:        if( s2 > nlstate){ 
                   4814:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4815:        } else if  ( s2==-1 ) { /* alive */
                   4816:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4817:            survp += out[s1][j];
                   4818:          lli= log(survp);
                   4819:        }else{
                   4820:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4821:        }
                   4822:        ipmx +=1;
                   4823:        sw += weight[i];
                   4824:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4825:        /* 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])); */
                   4826:       } /* end of wave */
                   4827:     } /* end of individual */
                   4828:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4829:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4830:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4831:       for(mi=1; mi<= wav[i]-1; mi++){
                   4832:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4833:          for (j=1;j<=nlstate+ndeath;j++){
                   4834:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4835:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4836:          }
                   4837:        for(d=0; d<dh[mi][i]; d++){
                   4838:          newm=savm;
                   4839:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4840:          cov[2]=agexact;
                   4841:          if(nagesqr==1)
                   4842:            cov[3]= agexact*agexact;
                   4843:          for (kk=1; kk<=cptcovage;kk++) {
                   4844:            if(!FixedV[Tvar[Tage[kk]]])
                   4845:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   4846:            else
                   4847:              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) */ 
                   4848:          }
1.1       brouard  4849:        
1.2       brouard  4850:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4851:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4852:          savm=oldm;
                   4853:          oldm=newm;
                   4854:        } /* end mult */
                   4855:       
                   4856:        s1=s[mw[mi][i]][i];
                   4857:        s2=s[mw[mi+1][i]][i];
                   4858:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4859:        ipmx +=1;
                   4860:        sw += weight[i];
                   4861:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4862:        /*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]);*/
                   4863:       } /* end of wave */
                   4864:     } /* end of individual */
                   4865:   } /* End of if */
1.1       brouard  4866:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4867:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4868:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4869:   return -l;
                   4870: }
                   4871: 
                   4872: /*************** log-likelihood *************/
                   4873: double funcone( double *x)
                   4874: {
                   4875:   /* Same as func but slower because of a lot of printf and if */
                   4876:   int i, ii, j, k, mi, d, kk, kv=0, kf=0;
                   4877:   int ioffset=0;
                   4878:   int ipos=0,iposold=0,ncovv=0;
                   4879: 
                   4880:   double cotvarv, cotvarvold;
                   4881:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   4882:   double **out;
                   4883:   double lli; /* Individual log likelihood */
                   4884:   double llt;
                   4885:   int s1, s2;
                   4886:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4887: 
                   4888:   double bbh, survp;
                   4889:   double agexact;
                   4890:   double agebegin, ageend;
                   4891:   /*extern weight */
                   4892:   /* We are differentiating ll according to initial status */
                   4893:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4894:   /*for(i=1;i<imx;i++) 
                   4895:     printf(" %d\n",s[4][i]);
                   4896:   */
                   4897:   cov[1]=1.;
                   4898: 
                   4899:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   4900:   ioffset=0;
                   4901:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4902:     /* Computes the values of the ncovmodel covariates of the model
                   4903:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4904:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4905:        to be observed in j being in i according to the model.
                   4906:     */
                   4907:     /* ioffset=2+nagesqr+cptcovage; */
                   4908:     ioffset=2+nagesqr;
                   4909:     /* Fixed */
                   4910:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
                   4911:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
                   4912:     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 */
                   4913:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   4914:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   4915:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
                   4916:       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)*/
                   4917: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4918: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4919: /*    cov[2+6]=covar[2][i]; V2  */
                   4920: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4921: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4922: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4923: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4924: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4925: /*    cov[2+9]=covar[1][i]; V1  */
                   4926:     }
1.2       brouard  4927:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   4928:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   4929:         has been calculated etc */
                   4930:       /* For an individual i, wav[i] gives the number of effective waves */
                   4931:       /* We compute the contribution to Likelihood of each effective transition
                   4932:         mw[mi][i] is real wave of the mi th effectve wave */
                   4933:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4934:         s2=s[mw[mi+1][i]][i];
                   4935:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
                   4936:       */
1.1       brouard  4937:     /* This part may be useless now because everythin should be in covar */
                   4938:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4939:     /*   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?)*\/ */
                   4940:     /* } */
                   4941:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4942:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4943:     /* } */
                   4944:     
                   4945: 
                   4946:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   4947:       /* 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 */
                   4948:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   4949:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   4950:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   4951:       /* } */
                   4952:       
                   4953:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   4954:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   4955:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   4956:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   4957:       /* We need the position of the time varying or product in the model */
                   4958:       /* 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 */            
                   4959:       /* TvarVV gives the variable name */
                   4960:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   4961:       *      k=         1   2     3     4         5        6        7       8        9
                   4962:       *  varying            1     2                                 3       4        5
                   4963:       *  ncovv              1     2                                3 4     5 6      7 8
                   4964:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
                   4965:       * TvarVVind           2     3                                7 7     8 8      9 9
                   4966:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   4967:       */
                   4968:       /* Other model ncovcol=5 nqv=0 ntv=3 nqtv=0 nlstate=3
                   4969:        * 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
                   4970:        * FixedV[ncovcol+qv+ntv+nqtv]       V5
                   4971:        * 3           V1  V2     V3    V4   V5 V6     V7  V8 V3*V2 V7*V2  V6*V3 V7*V3 V6*V4 V7*V4
                   4972:        *             0   0      0      0    0  1      1   1  0, 0, 1,1,   1, 0, 1, 0, 1, 0, 1, 0}
                   4973:        * 3           0   0      0      0    0  1      1   1  0,     1      1    1      1    1}
                   4974:        * model=          V2  +  V3  +  V4  +  V6  +  V7  +  V6*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4975:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4976:         *                +age*V6*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4977:        * model2=          V2  +  V3  +  V4  +  V6  +  V7  +  V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4978:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4979:         *                +age*V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4980:        * model3=          V2  +  V3  +  V4  +  V6  +  V7  + age*V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   4981:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   4982:         *                +V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   4983:        * kmodel           1     2      3      4      5        6         7         8         9        10        11    
                   4984:        *                  12       13      14      15       16
                   4985:        *                    17        18         19        20         21
                   4986:        * Tvar[kmodel]     2     3      4      6      7        9        10        11        12        13        14
                   4987:        *                   2       3        4       6        7
                   4988:        *                     9         11          12        13         14            
                   4989:        * cptcovage=5+5 total of covariates with age 
                   4990:        * Tage[cptcovage] age*V2=12      13      14      15       16
                   4991:        *1                   17            18         19        20         21 gives the position in model of covariates associated with age
                   4992:        *3 Tage[cptcovage] age*V3*V2=6  
                   4993:        *3                age*V2=12         13      14      15       16
                   4994:        *3                age*V6*V3=18      19    20   21
                   4995:        * Tvar[Tage[cptcovage]]    Tvar[12]=2      3      4       6         Tvar[16]=7(age*V7)
                   4996:        *     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
                   4997:        * 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
                   4998:        * 3 Tvar[Tage[cptcovage]]    Tvar[6]=9      Tvar[12]=2      3     4       6         Tvar[16]=7(age*V7)
                   4999:        * 3     Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   5000:        * 3 Tage[cptcovage] age*V3*V2=6   age*V2=12 age*V3 13    14      15       16
                   5001:        *                    age*V6*V3=18         19        20         21 gives the position in model of covariates associated with age
                   5002:        * 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
                   5003:        * Tvar=                {2, 3, 4, 6, 7,
                   5004:        *                       9, 10, 11, 12, 13, 14,
                   5005:        *              Tvar[12]=2, 3, 4, 6, 7,
                   5006:        *              Tvar[17]=9, 11, 12, 13, 14}
                   5007:        * Typevar[1]@21 = {0, 0, 0, 0, 0,
                   5008:        *                  2, 2, 2, 2, 2, 2,
                   5009:        * 3                3, 2, 2, 2, 2, 2,
                   5010:        *                  1, 1, 1, 1, 1, 
                   5011:        *                  3, 3, 3, 3, 3}
                   5012:        * 3                 2, 3, 3, 3, 3}
                   5013:        * 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
                   5014:        * p Tprod[1]@21 {6, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   5015:        * 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}
                   5016:        * 3 Tprod[1]@21 {17, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   5017:        * cptcovprod=11 (6+5)
                   5018:        * FixedV[Tvar[Tage[cptcovage]]]]  FixedV[2]=0      FixedV[3]=0      0      1          (age*V7)Tvar[16]=1 FixedV[absolute] not [kmodel]
                   5019:        *   FixedV[Tvar[17]=FixedV[age*V6*V2]=FixedV[9]=1        1         1          1         1  
                   5020:        * 3 FixedV[Tvar[17]=FixedV[age*V3*V2]=FixedV[9]=0        [11]=1         1          1         1  
                   5021:        * FixedV[]          V1=0     V2=0   V3=0  v4=0    V5=0  V6=1    V7=1 v8=1  OK then model dependent
                   5022:        *                   9=1  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   5023:        * 3                 9=0  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   5024:        * cptcovdageprod=5  for gnuplot printing
                   5025:        * cptcovprodvage=6 
                   5026:        * ncova=15           1        2       3       4       5
                   5027:        *                      6 7        8 9      10 11        12 13     14 15
                   5028:        * TvarA              2        3       4       6       7
                   5029:        *                      6 2        6 7       7 3          6 4       7 4
                   5030:        * TvaAind             12 12      13 13     14 14      15 15       16 16        
                   5031:        * ncovf            1     2      3
                   5032:        *                                    V6       V7      V6*V2     V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   5033:        * ncovvt=14                            1      2        3 4       5 6       7 8       9 10     11 12     13 14     
                   5034:        * TvarVV[1]@14 = itv               {V6=6,     7, V6*V2=6, 2,     7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   5035:        * TvarVVind[1]@14=                    {4,     5,       6, 6,     7, 7,     8, 8,      9, 9,   10, 10,   11, 11}
                   5036:        * 3 ncovvt=12                        V6       V7      V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   5037:        * 3 TvarVV[1]@12 = itv                {6,     7, V7*V2=7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   5038:        * 3                                    1      2        3  4      5  6      7  8      9 10     11 12
                   5039:        * TvarVVind[1]@12=         {V6 is in k=4,     5,  7,(4isV2)=7,   8, 8,      9, 9,   10,10,    11,11}TvarVVind[12]=k=11
                   5040:        * TvarV              6, 7, 9, 10, 11, 12, 13, 14
                   5041:        * 3 cptcovprodvage=6
                   5042:        * 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
                   5043:        * 3 TvarAVVA[1]@15= itva 3 2    2      3    4        6       7        6 3         7 3         6 4         7 4 
                   5044:        * 3 ncovta             1 2      3      4    5        6       7        8 9       10 11       12 13        14 15
1.3       brouard  5045:        *?TvarAVVAind[1]@15= V3 is in k=2 1 1  2    3        4       5        4,2         5,2,      4,3           5 3}TvarVVAind[]
1.1       brouard  5046:        * TvarAVVAind[1]@15= V3 is in k=6 6 12  13   14      15      16       18 18       19,19,     20,20        21,21}TvarVVAind[]
                   5047:        * 3 ncovvta=10     +age*V6 + age*V7 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   5048:        * 3 we want to compute =cotvar[mw[mi][i]][TvarVVA[ncovva]][i] at position TvarVVAind[ncovva]
                   5049:        * 3 TvarVVA[1]@10= itva   6       7        6 3         7 3         6 4         7 4 
                   5050:        * 3 ncovva                1       2        3 4         5 6         7 8         9 10
                   5051:        * TvarVVAind[1]@10= V6 is in k=4  5        8,8         9, 9,      10,10        11 11}TvarVVAind[]
                   5052:        * TvarVVAind[1]@10=       15       16     18,18        19,19,      20,20        21 21}TvarVVAind[]
                   5053:        * TvarVA              V3*V2=6 6 , 1, 2, 11, 12, 13, 14
                   5054:        * TvarFind[1]@14= {1,    2,     3,     0 <repeats 12 times>}
                   5055:        * Tvar[1]@21=     {2,    3,     4,    6,      7,      9,      10,        11,       12,      13,       14,
                   5056:        *                   2, 3, 4, 6, 7,
                   5057:        *                     6, 8, 9, 10, 11}
                   5058:        * TvarFind[itv]                        0      0       0
1.3       brouard  5059:        * FixedV[itv]                          1      1       1  0      1 0       1 0       1 0       0
                   5060:        *? FixedV[itv]                          1      1       1  0      1 0       1 0       1 0      1 0     1 0
1.1       brouard  5061:        * Tvar[TvarFind[ncovf]]=[1]=2 [2]=3 [4]=4
                   5062:        * Tvar[TvarFind[itv]]                [0]=?      ?ncovv 1 à ncovvt]
                   5063:        *   Not a fixed cotvar[mw][itv][i]     6       7      6  2      7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   5064:        *   fixed covar[itv]                  [6]     [7]    [6][2] 
                   5065:        */
1.2       brouard  5066: 
1.1       brouard  5067:       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 */
                   5068:        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  */
                   5069:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   5070:        /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   5071:        if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   5072:          /* printf("DEBUG ncovv=%d, Varying TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
                   5073:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   5074:          /* printf("DEBUG Varying cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
                   5075:        }else{ /* fixed covariate */
                   5076:          /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   5077:          /* printf("DEBUG ncovv=%d, Fixed TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
                   5078:          cotvarv=covar[itv][i];  /* Good: In V6*V3, 3 is fixed at position of the data */
                   5079:          /* printf("DEBUG Fixed cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
                   5080:        }
                   5081:        if(ipos!=iposold){ /* Not a product or first of a product */
                   5082:          cotvarvold=cotvarv;
                   5083:        }else{ /* A second product */
                   5084:          cotvarv=cotvarv*cotvarvold;
                   5085:        }
                   5086:        iposold=ipos;
                   5087:        cov[ioffset+ipos]=cotvarv;
                   5088:        /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   5089:        /* For products */
                   5090:       }
                   5091:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   5092:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   5093:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   5094:       /*       /\*           1  2   3      4      5                         *\/ */
                   5095:       /*       /\*itv           1                                           *\/ */
                   5096:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   5097:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   5098:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   5099:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   5100:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   5101:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   5102:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   5103:       /*       /\* 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]); *\/ */
                   5104:       /* } */
                   5105:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
                   5106:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   5107:       /*       /\* 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]); *\/ */
                   5108:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
                   5109:       /* } */
                   5110:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   5111:        for (j=1;j<=nlstate+ndeath;j++){
                   5112:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5113:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5114:        }
                   5115:       
                   5116:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   5117:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   5118:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
                   5119:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
                   5120:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   5121:          and mw[mi+1][i]. dh depends on stepm.*/
                   5122:        newm=savm;
                   5123:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
                   5124:        cov[2]=agexact;
                   5125:        if(nagesqr==1)
                   5126:          cov[3]= agexact*agexact;
1.2       brouard  5127:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   5128:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   5129:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.1       brouard  5130:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   5131:          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  5132:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   5133:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
1.1       brouard  5134:          }else{ /* fixed covariate */
                   5135:            /* 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  5136:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
1.1       brouard  5137:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   5138:          }
                   5139:          if(ipos!=iposold){ /* Not a product or first of a product */
                   5140:            cotvarvold=cotvarv;
                   5141:          }else{ /* A second product */
                   5142:            /* printf("DEBUG * \n"); */
                   5143:            cotvarv=cotvarv*cotvarvold;
                   5144:          }
                   5145:          iposold=ipos;
1.2       brouard  5146:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
1.1       brouard  5147:          cov[ioffset+ipos]=cotvarv*agexact;
                   5148:          /* For products */
                   5149:        }
                   5150: 
                   5151:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   5152:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   5153:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5154:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5155:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   5156:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   5157:        savm=oldm;
                   5158:        oldm=newm;
                   5159:       } /* end mult */
                   5160:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   5161:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   5162:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   5163:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   5164:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   5165:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   5166:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   5167:         * probability in order to take into account the bias as a fraction of the way
                   5168:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   5169:                                 * -stepm/2 to stepm/2 .
                   5170:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   5171:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   5172:                                 */
                   5173:       s1=s[mw[mi][i]][i];
                   5174:       s2=s[mw[mi+1][i]][i];
                   5175:       /* if(s2==-1){ */
                   5176:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
                   5177:       /*       /\* exit(1); *\/ */
                   5178:       /* } */
                   5179:       bbh=(double)bh[mi][i]/(double)stepm; 
                   5180:       /* bias is positive if real duration
                   5181:        * is higher than the multiple of stepm and negative otherwise.
                   5182:        */
                   5183:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   5184:        lli=log(out[s1][s2] - savm[s1][s2]);
                   5185:       } else if  ( s2==-1 ) { /* alive */
                   5186:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   5187:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   5188:        lli= log(survp);
                   5189:       }else if (mle==1){
                   5190:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   5191:       } else if(mle==2){
                   5192:        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 */
                   5193:       } else if(mle==3){  /* exponential inter-extrapolation */
                   5194:        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 */
                   5195:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   5196:        lli=log(out[s1][s2]); /* Original formula */
                   5197:       } else{  /* mle=0 back to 1 */
                   5198:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   5199:        /*lli=log(out[s1][s2]); */ /* Original formula */
                   5200:       } /* End of if */
                   5201:       ipmx +=1;
                   5202:       sw += weight[i];
                   5203:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5204:       /* Printing covariates values for each contribution for checking */
                   5205:       /* 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])); */
                   5206:       if(globpr){
                   5207:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
                   5208:  %11.6f %11.6f %11.6f ", \
                   5209:                num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
                   5210:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.2       brouard  5211:        /*      printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
1.1       brouard  5212:        /* %11.6f %11.6f %11.6f ", \ */
                   5213:        /*              num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   5214:        /*              2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
                   5215:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   5216:          llt +=ll[k]*gipmx/gsw;
                   5217:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   5218:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
                   5219:        }
                   5220:        fprintf(ficresilk," %10.6f ", -llt);
                   5221:        /* printf(" %10.6f\n", -llt); */
                   5222:        /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
                   5223:        /* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
                   5224:        for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   5225:          fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
                   5226:        }
                   5227:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   5228:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   5229:          if(ipos!=iposold){ /* Not a product or first of a product */
                   5230:            fprintf(ficresilk," %g",cov[ioffset+ipos]);
                   5231:            /* printf(" %g",cov[ioffset+ipos]); */
                   5232:          }else{
                   5233:            fprintf(ficresilk,"*");
                   5234:            /* printf("*"); */
                   5235:          }
                   5236:          iposold=ipos;
                   5237:        }
                   5238:        /* for (kk=1; kk<=cptcovage;kk++) { */
                   5239:        /*   if(!FixedV[Tvar[Tage[kk]]]){ */
                   5240:        /*     fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]); */
                   5241:        /*     /\* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); *\/ */
                   5242:        /*   }else{ */
                   5243:        /*     fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   5244:        /*     /\* printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\\/  *\/ */
                   5245:        /*   } */
                   5246:        /* } */
1.2       brouard  5247:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   5248:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   5249:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   5250:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   5251:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   5252:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   5253:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   5254:          }else{ /* fixed covariate */
                   5255:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   5256:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   5257:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   5258:          }
                   5259:          if(ipos!=iposold){ /* Not a product or first of a product */
                   5260:            cotvarvold=cotvarv;
                   5261:          }else{ /* A second product */
                   5262:            /* printf("DEBUG * \n"); */
                   5263:            cotvarv=cotvarv*cotvarvold;
                   5264:          }
                   5265:          cotvarv=cotvarv*agexact;
                   5266:          fprintf(ficresilk," %g*age",cotvarv);
                   5267:          iposold=ipos;
                   5268:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   5269:          cov[ioffset+ipos]=cotvarv;
                   5270:          /* For products */
                   5271:        }
1.1       brouard  5272:        /* printf("\n"); */
                   5273:        /* } /\*  End debugILK *\/ */
                   5274:        fprintf(ficresilk,"\n");
                   5275:       } /* End if globpr */
                   5276:     } /* end of wave */
                   5277:   } /* end of individual */
                   5278:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   5279: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   5280:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   5281:   if(globpr==0){ /* First time we count the contributions and weights */
                   5282:     gipmx=ipmx;
                   5283:     gsw=sw;
                   5284:   }
                   5285:   return -l;
                   5286: }
                   5287: 
                   5288: 
                   5289: /*************** function likelione ***********/
                   5290: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
                   5291: {
                   5292:   /* This routine should help understanding what is done with 
                   5293:      the selection of individuals/waves and
                   5294:      to check the exact contribution to the likelihood.
                   5295:      Plotting could be done.
                   5296:   */
                   5297:   void pstamp(FILE *ficres);
1.2       brouard  5298:   int k, kf, kk, kvar, ncovv, iposold, ipos;
1.1       brouard  5299: 
                   5300:   if(*globpri !=0){ /* Just counts and sums, no printings */
                   5301:     strcpy(fileresilk,"ILK_"); 
                   5302:     strcat(fileresilk,fileresu);
                   5303:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   5304:       printf("Problem with resultfile: %s\n", fileresilk);
                   5305:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   5306:     }
                   5307:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
                   5308:     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");
                   5309:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
                   5310:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   5311:     for(k=1; k<=nlstate; k++) 
                   5312:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   5313:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
                   5314: 
                   5315:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
1.2       brouard  5316:       for(kf=1;kf <= ncovf; kf++){
                   5317:        fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
                   5318:        /* printf("V%d",Tvar[TvarFind[kf]]); */
                   5319:       }
                   5320:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
                   5321:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   5322:        if(ipos!=iposold){ /* Not a product or first of a product */
                   5323:          /* printf(" %d",ipos); */
                   5324:          fprintf(ficresilk," V%d",TvarVV[ncovv]);
                   5325:        }else{
                   5326:          /* printf("*"); */
                   5327:          fprintf(ficresilk,"*");
                   5328:        }
                   5329:        iposold=ipos;
1.1       brouard  5330:       }
1.2       brouard  5331:       for (kk=1; kk<=cptcovage;kk++) {
                   5332:        if(!FixedV[Tvar[Tage[kk]]]){
                   5333:          /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
                   5334:          fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
                   5335:        }else{
                   5336:          fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   5337:          /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   5338:        }
1.1       brouard  5339:       }
                   5340:     /* } /\* End if debugILK *\/ */
                   5341:     /* printf("\n"); */
                   5342:     fprintf(ficresilk,"\n");
                   5343:   } /* End glogpri */
                   5344: 
                   5345:   *fretone=(*func)(p);
                   5346:   if(*globpri !=0){
                   5347:     fclose(ficresilk);
                   5348:     if (mle ==0)
                   5349:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   5350:     else if(mle >=1)
                   5351:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   5352:     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));
                   5353:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
                   5354:       
                   5355:     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> \
                   5356: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   5357:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
                   5358: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   5359:     
                   5360:     for (k=1; k<= nlstate ; k++) {
                   5361:       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 \
                   5362: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   5363:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.2       brouard  5364:         kvar=Tvar[TvarFind[kf]];  /* variable */
                   5365:         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]]);
                   5366:         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);
                   5367:         fprintf(fichtm,"<img src=\"%s-p%dj-%d.png\">",subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]);
1.1       brouard  5368:       }
                   5369:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
                   5370:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   5371:        kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   5372:        /* 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]); */
                   5373:        if(ipos!=iposold){ /* Not a product or first of a product */
                   5374:          /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   5375:          /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
                   5376:          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)  */
                   5377:            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> \
                   5378: <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);
                   5379:          } /* End only for dummies time varying (single?) */
                   5380:        }else{ /* Useless product */
                   5381:          /* printf("*"); */
                   5382:          /* fprintf(ficresilk,"*"); */ 
                   5383:        }
                   5384:        iposold=ipos;
                   5385:       } /* For each time varying covariate */
                   5386:     } /* End loop on states */
                   5387: 
                   5388: /*     if(debugILK){ */
                   5389: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
                   5390: /*     /\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
                   5391: /*     for (k=1; k<= nlstate ; k++) { */
                   5392: /*       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> \ */
                   5393: /* <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]]); */
                   5394: /*     } */
                   5395: /*       } */
                   5396: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
                   5397: /*     ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
                   5398: /*     kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
                   5399: /*     /\* 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]); *\/ */
                   5400: /*     if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
                   5401: /*       /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
                   5402: /*       /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
                   5403: /*       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)  *\/ */
                   5404: /*         for (k=1; k<= nlstate ; k++) { */
                   5405: /*           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> \ */
                   5406: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
                   5407: /*         } /\* End state *\/ */
                   5408: /*       } /\* End only for dummies time varying (single?) *\/ */
                   5409: /*     }else{ /\* Useless product *\/ */
                   5410: /*       /\* printf("*"); *\/ */
                   5411: /*       /\* fprintf(ficresilk,"*"); *\/  */
                   5412: /*     } */
                   5413: /*     iposold=ipos; */
                   5414: /*       } /\* For each time varying covariate *\/ */
                   5415: /*     }/\* End debugILK *\/ */
                   5416:     fflush(fichtm);
                   5417:   }/* End globpri */
                   5418:   return;
                   5419: }
                   5420: 
                   5421: 
                   5422: /*********** Maximum Likelihood Estimation ***************/
                   5423: 
                   5424: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   5425: {
                   5426:   int i,j,k, jk, jkk=0, iter=0;
                   5427:   double **xi;
                   5428:   double fret;
                   5429:   double fretone; /* Only one call to likelihood */
                   5430:   /*  char filerespow[FILENAMELENGTH];*/
                   5431:   
                   5432:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   5433: #ifdef NLOPT
                   5434:   int creturn;
                   5435:   nlopt_opt opt;
                   5436:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   5437:   double *lb;
                   5438:   double minf; /* the minimum objective value, upon return */
                   5439: 
                   5440:   myfunc_data dinst, *d = &dinst;
                   5441: #endif
                   5442: 
                   5443: 
                   5444:   xi=matrix(1,npar,1,npar);
1.3       brouard  5445:   for (i=1;i<=npar;i++)  /* Starting with canonical directions j=1,n xi[i=1,n][j] */
1.1       brouard  5446:     for (j=1;j<=npar;j++)
                   5447:       xi[i][j]=(i==j ? 1.0 : 0.0);
1.5     ! brouard  5448:   printf("Powell-prax\n");  fprintf(ficlog,"Powell-prax\n");
1.1       brouard  5449:   strcpy(filerespow,"POW_"); 
                   5450:   strcat(filerespow,fileres);
                   5451:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   5452:     printf("Problem with resultfile: %s\n", filerespow);
                   5453:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   5454:   }
                   5455:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   5456:   for (i=1;i<=nlstate;i++)
                   5457:     for(j=1;j<=nlstate+ndeath;j++)
                   5458:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   5459:   fprintf(ficrespow,"\n");
                   5460: #ifdef POWELL
                   5461: #ifdef LINMINORIGINAL
                   5462: #else /* LINMINORIGINAL */
                   5463:   
                   5464:   flatdir=ivector(1,npar); 
                   5465:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   5466: #endif /*LINMINORIGINAL */
                   5467: 
                   5468: #ifdef FLATSUP
                   5469:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   5470:   /* reorganizing p by suppressing flat directions */
                   5471:   for(i=1, jk=1; i <=nlstate; i++){
                   5472:     for(k=1; k <=(nlstate+ndeath); k++){
                   5473:       if (k != i) {
                   5474:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   5475:         if(flatdir[jk]==1){
                   5476:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   5477:         }
                   5478:         for(j=1; j <=ncovmodel; j++){
                   5479:           printf("%12.7f ",p[jk]);
                   5480:           jk++; 
                   5481:         }
                   5482:         printf("\n");
                   5483:       }
                   5484:     }
                   5485:   }
                   5486: /* skipping */
                   5487:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   5488:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   5489:     for(k=1; k <=(nlstate+ndeath); k++){
                   5490:       if (k != i) {
                   5491:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   5492:         if(flatdir[jk]==1){
                   5493:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   5494:           for(j=1; j <=ncovmodel;  jk++,j++){
                   5495:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   5496:             /*q[jjk]=p[jk];*/
                   5497:           }
                   5498:         }else{
                   5499:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   5500:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   5501:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   5502:             /*q[jjk]=p[jk];*/
                   5503:           }
                   5504:         }
                   5505:         printf("\n");
                   5506:       }
                   5507:       fflush(stdout);
                   5508:     }
                   5509:   }
                   5510:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   5511: #else  /* FLATSUP */
1.5     ! brouard  5512:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.1       brouard  5513: /*   praxis ( t0, h0, n, prin, x, beale_f ); */
1.4       brouard  5514: /*   int prin=4; */
                   5515: /*   double h0=0.25; */
                   5516: /* #include "praxis.h" */
1.1       brouard  5517:   /* Be careful that praxis start at x[0] and powell start at p[1] */
                   5518:    /* praxis ( ftol, h0, npar, prin, p, func ); */
1.4       brouard  5519: /* p1= (p+1); /\*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] *\/ */
                   5520: /* printf("Praxis \n"); */
                   5521: /* fprintf(ficlog, "Praxis \n");fflush(ficlog); */
                   5522: /* praxis ( ftol, h0, npar, prin, p1, func ); */
                   5523: /* printf("End Praxis\n"); */
1.1       brouard  5524: #endif  /* FLATSUP */
                   5525: 
                   5526: #ifdef LINMINORIGINAL
                   5527: #else
                   5528:       free_ivector(flatdir,1,npar); 
                   5529: #endif  /* LINMINORIGINAL*/
                   5530: #endif /* POWELL */
                   5531: 
                   5532: #ifdef NLOPT
                   5533: #ifdef NEWUOA
                   5534:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   5535: #else
                   5536:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   5537: #endif
                   5538:   lb=vector(0,npar-1);
                   5539:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   5540:   nlopt_set_lower_bounds(opt, lb);
                   5541:   nlopt_set_initial_step1(opt, 0.1);
                   5542:   
                   5543:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   5544:   d->function = func;
                   5545:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   5546:   nlopt_set_min_objective(opt, myfunc, d);
                   5547:   nlopt_set_xtol_rel(opt, ftol);
                   5548:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   5549:     printf("nlopt failed! %d\n",creturn); 
                   5550:   }
                   5551:   else {
                   5552:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   5553:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   5554:     iter=1; /* not equal */
                   5555:   }
                   5556:   nlopt_destroy(opt);
                   5557: #endif
                   5558: #ifdef FLATSUP
                   5559:   /* npared = npar -flatd/ncovmodel; */
                   5560:   /* xired= matrix(1,npared,1,npared); */
                   5561:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   5562:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   5563:   /* free_matrix(xire,1,npared,1,npared); */
                   5564: #else  /* FLATSUP */
                   5565: #endif /* FLATSUP */
                   5566:   free_matrix(xi,1,npar,1,npar);
                   5567:   fclose(ficrespow);
                   5568:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   5569:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   5570:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   5571: 
                   5572: }
                   5573: 
                   5574: /**** Computes Hessian and covariance matrix ***/
                   5575: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
                   5576: {
                   5577:   double  **a,**y,*x,pd;
                   5578:   /* double **hess; */
                   5579:   int i, j;
                   5580:   int *indx;
                   5581: 
                   5582:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
                   5583:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
                   5584:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   5585:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   5586:   double gompertz(double p[]);
                   5587:   /* hess=matrix(1,npar,1,npar); */
                   5588: 
                   5589:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   5590:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   5591:   for (i=1;i<=npar;i++){
                   5592:     printf("%d-",i);fflush(stdout);
                   5593:     fprintf(ficlog,"%d-",i);fflush(ficlog);
                   5594:    
                   5595:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   5596:     
                   5597:     /*  printf(" %f ",p[i]);
                   5598:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   5599:   }
                   5600:   
                   5601:   for (i=1;i<=npar;i++) {
                   5602:     for (j=1;j<=npar;j++)  {
                   5603:       if (j>i) { 
                   5604:        printf(".%d-%d",i,j);fflush(stdout);
                   5605:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   5606:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
                   5607:        
                   5608:        hess[j][i]=hess[i][j];    
                   5609:        /*printf(" %lf ",hess[i][j]);*/
                   5610:       }
                   5611:     }
                   5612:   }
                   5613:   printf("\n");
                   5614:   fprintf(ficlog,"\n");
                   5615: 
                   5616:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   5617:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   5618:   
                   5619:   a=matrix(1,npar,1,npar);
                   5620:   y=matrix(1,npar,1,npar);
                   5621:   x=vector(1,npar);
                   5622:   indx=ivector(1,npar);
                   5623:   for (i=1;i<=npar;i++)
                   5624:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   5625:   ludcmp(a,npar,indx,&pd);
                   5626: 
                   5627:   for (j=1;j<=npar;j++) {
                   5628:     for (i=1;i<=npar;i++) x[i]=0;
                   5629:     x[j]=1;
                   5630:     lubksb(a,npar,indx,x);
                   5631:     for (i=1;i<=npar;i++){ 
                   5632:       matcov[i][j]=x[i];
                   5633:     }
                   5634:   }
                   5635: 
                   5636:   printf("\n#Hessian matrix#\n");
                   5637:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   5638:   for (i=1;i<=npar;i++) { 
                   5639:     for (j=1;j<=npar;j++) { 
                   5640:       printf("%.6e ",hess[i][j]);
                   5641:       fprintf(ficlog,"%.6e ",hess[i][j]);
                   5642:     }
                   5643:     printf("\n");
                   5644:     fprintf(ficlog,"\n");
                   5645:   }
                   5646: 
                   5647:   /* printf("\n#Covariance matrix#\n"); */
                   5648:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   5649:   /* for (i=1;i<=npar;i++) {  */
                   5650:   /*   for (j=1;j<=npar;j++) {  */
                   5651:   /*     printf("%.6e ",matcov[i][j]); */
                   5652:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   5653:   /*   } */
                   5654:   /*   printf("\n"); */
                   5655:   /*   fprintf(ficlog,"\n"); */
                   5656:   /* } */
                   5657: 
                   5658:   /* Recompute Inverse */
                   5659:   /* for (i=1;i<=npar;i++) */
                   5660:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   5661:   /* ludcmp(a,npar,indx,&pd); */
                   5662: 
                   5663:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   5664: 
                   5665:   /* for (j=1;j<=npar;j++) { */
                   5666:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   5667:   /*   x[j]=1; */
                   5668:   /*   lubksb(a,npar,indx,x); */
                   5669:   /*   for (i=1;i<=npar;i++){  */
                   5670:   /*     y[i][j]=x[i]; */
                   5671:   /*     printf("%.3e ",y[i][j]); */
                   5672:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   5673:   /*   } */
                   5674:   /*   printf("\n"); */
                   5675:   /*   fprintf(ficlog,"\n"); */
                   5676:   /* } */
                   5677: 
                   5678:   /* Verifying the inverse matrix */
                   5679: #ifdef DEBUGHESS
                   5680:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
                   5681: 
                   5682:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   5683:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
                   5684: 
                   5685:   for (j=1;j<=npar;j++) {
                   5686:     for (i=1;i<=npar;i++){ 
                   5687:       printf("%.2f ",y[i][j]);
                   5688:       fprintf(ficlog,"%.2f ",y[i][j]);
                   5689:     }
                   5690:     printf("\n");
                   5691:     fprintf(ficlog,"\n");
                   5692:   }
                   5693: #endif
                   5694: 
                   5695:   free_matrix(a,1,npar,1,npar);
                   5696:   free_matrix(y,1,npar,1,npar);
                   5697:   free_vector(x,1,npar);
                   5698:   free_ivector(indx,1,npar);
                   5699:   /* free_matrix(hess,1,npar,1,npar); */
                   5700: 
                   5701: 
                   5702: }
                   5703: 
                   5704: /*************** hessian matrix ****************/
                   5705: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
                   5706: { /* Around values of x, computes the function func and returns the scales delti and hessian */
                   5707:   int i;
                   5708:   int l=1, lmax=20;
                   5709:   double k1,k2, res, fx;
                   5710:   double p2[MAXPARM+1]; /* identical to x */
                   5711:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   5712:   int k=0,kmax=10;
                   5713:   double l1;
                   5714: 
                   5715:   fx=func(x);
                   5716:   for (i=1;i<=npar;i++) p2[i]=x[i];
                   5717:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
                   5718:     l1=pow(10,l);
                   5719:     delts=delt;
                   5720:     for(k=1 ; k <kmax; k=k+1){
                   5721:       delt = delta*(l1*k);
                   5722:       p2[theta]=x[theta] +delt;
                   5723:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
                   5724:       p2[theta]=x[theta]-delt;
                   5725:       k2=func(p2)-fx;
                   5726:       /*res= (k1-2.0*fx+k2)/delt/delt; */
                   5727:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
                   5728:       
                   5729: #ifdef DEBUGHESSII
                   5730:       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);
                   5731:       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);
                   5732: #endif
                   5733:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   5734:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   5735:        k=kmax;
                   5736:       }
                   5737:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
                   5738:        k=kmax; l=lmax*10;
                   5739:       }
                   5740:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   5741:        delts=delt;
                   5742:       }
                   5743:     } /* End loop k */
                   5744:   }
                   5745:   delti[theta]=delts;
                   5746:   return res; 
                   5747:   
                   5748: }
                   5749: 
                   5750: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
                   5751: {
                   5752:   int i;
                   5753:   int l=1, lmax=20;
                   5754:   double k1,k2,k3,k4,res,fx;
                   5755:   double p2[MAXPARM+1];
                   5756:   int k, kmax=1;
                   5757:   double v1, v2, cv12, lc1, lc2;
                   5758: 
                   5759:   int firstime=0;
                   5760:   
                   5761:   fx=func(x);
                   5762:   for (k=1; k<=kmax; k=k+10) {
                   5763:     for (i=1;i<=npar;i++) p2[i]=x[i];
                   5764:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5765:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
                   5766:     k1=func(p2)-fx;
                   5767:   
                   5768:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   5769:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
                   5770:     k2=func(p2)-fx;
                   5771:   
                   5772:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5773:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
                   5774:     k3=func(p2)-fx;
                   5775:   
                   5776:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   5777:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
                   5778:     k4=func(p2)-fx;
                   5779:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   5780:     if(k1*k2*k3*k4 <0.){
                   5781:       firstime=1;
                   5782:       kmax=kmax+10;
                   5783:     }
                   5784:     if(kmax >=10 || firstime ==1){
                   5785:       /* What are the thetai and thetaj? thetai/ncovmodel thetai=(thetai-thetai%ncovmodel)/ncovmodel +thetai%ncovmodel=(line,pos)  */
                   5786:       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);
                   5787:       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);
                   5788:       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);
                   5789:       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);
                   5790:     }
                   5791: #ifdef DEBUGHESSIJ
                   5792:     v1=hess[thetai][thetai];
                   5793:     v2=hess[thetaj][thetaj];
                   5794:     cv12=res;
                   5795:     /* Computing eigen value of Hessian matrix */
                   5796:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5797:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5798:     if ((lc2 <0) || (lc1 <0) ){
                   5799:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5800:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   5801:       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);
                   5802:       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);
                   5803:     }
                   5804: #endif
                   5805:   }
                   5806:   return res;
                   5807: }
                   5808: 
                   5809:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   5810: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   5811: /* { */
                   5812: /*   int i; */
                   5813: /*   int l=1, lmax=20; */
                   5814: /*   double k1,k2,k3,k4,res,fx; */
                   5815: /*   double p2[MAXPARM+1]; */
                   5816: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   5817: /*   int k=0,kmax=10; */
                   5818: /*   double l1; */
                   5819:   
                   5820: /*   fx=func(x); */
                   5821: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   5822: /*     l1=pow(10,l); */
                   5823: /*     delts=delt; */
                   5824: /*     for(k=1 ; k <kmax; k=k+1){ */
                   5825: /*       delt = delti*(l1*k); */
                   5826: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   5827: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5828: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5829: /*       k1=func(p2)-fx; */
                   5830:       
                   5831: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   5832: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5833: /*       k2=func(p2)-fx; */
                   5834:       
                   5835: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5836: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   5837: /*       k3=func(p2)-fx; */
                   5838:       
                   5839: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   5840: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   5841: /*       k4=func(p2)-fx; */
                   5842: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   5843: /* #ifdef DEBUGHESSIJ */
                   5844: /*       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); */
                   5845: /*       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); */
                   5846: /* #endif */
                   5847: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   5848: /*     k=kmax; */
                   5849: /*       } */
                   5850: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   5851: /*     k=kmax; l=lmax*10; */
                   5852: /*       } */
                   5853: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   5854: /*     delts=delt; */
                   5855: /*       } */
                   5856: /*     } /\* End loop k *\/ */
                   5857: /*   } */
                   5858: /*   delti[theta]=delts; */
                   5859: /*   return res;  */
                   5860: /* } */
                   5861: 
                   5862: 
                   5863: /************** Inverse of matrix **************/
                   5864: void ludcmp(double **a, int n, int *indx, double *d) 
                   5865: { 
                   5866:   int i,imax,j,k; 
                   5867:   double big,dum,sum,temp; 
                   5868:   double *vv; 
                   5869:  
                   5870:   vv=vector(1,n); 
                   5871:   *d=1.0; 
                   5872:   for (i=1;i<=n;i++) { 
                   5873:     big=0.0; 
                   5874:     for (j=1;j<=n;j++) 
                   5875:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   5876:     if (big == 0.0){
                   5877:       printf(" Singular Hessian matrix at row %d:\n",i);
                   5878:       for (j=1;j<=n;j++) {
                   5879:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   5880:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   5881:       }
                   5882:       fflush(ficlog);
                   5883:       fclose(ficlog);
                   5884:       nrerror("Singular matrix in routine ludcmp"); 
                   5885:     }
                   5886:     vv[i]=1.0/big; 
                   5887:   } 
                   5888:   for (j=1;j<=n;j++) { 
                   5889:     for (i=1;i<j;i++) { 
                   5890:       sum=a[i][j]; 
                   5891:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   5892:       a[i][j]=sum; 
                   5893:     } 
                   5894:     big=0.0; 
                   5895:     for (i=j;i<=n;i++) { 
                   5896:       sum=a[i][j]; 
                   5897:       for (k=1;k<j;k++) 
                   5898:        sum -= a[i][k]*a[k][j]; 
                   5899:       a[i][j]=sum; 
                   5900:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   5901:        big=dum; 
                   5902:        imax=i; 
                   5903:       } 
                   5904:     } 
                   5905:     if (j != imax) { 
                   5906:       for (k=1;k<=n;k++) { 
                   5907:        dum=a[imax][k]; 
                   5908:        a[imax][k]=a[j][k]; 
                   5909:        a[j][k]=dum; 
                   5910:       } 
                   5911:       *d = -(*d); 
                   5912:       vv[imax]=vv[j]; 
                   5913:     } 
                   5914:     indx[j]=imax; 
                   5915:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   5916:     if (j != n) { 
                   5917:       dum=1.0/(a[j][j]); 
                   5918:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   5919:     } 
                   5920:   } 
                   5921:   free_vector(vv,1,n);  /* Doesn't work */
                   5922: ;
                   5923: } 
                   5924: 
                   5925: void lubksb(double **a, int n, int *indx, double b[]) 
                   5926: { 
                   5927:   int i,ii=0,ip,j; 
                   5928:   double sum; 
                   5929:  
                   5930:   for (i=1;i<=n;i++) { 
                   5931:     ip=indx[i]; 
                   5932:     sum=b[ip]; 
                   5933:     b[ip]=b[i]; 
                   5934:     if (ii) 
                   5935:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   5936:     else if (sum) ii=i; 
                   5937:     b[i]=sum; 
                   5938:   } 
                   5939:   for (i=n;i>=1;i--) { 
                   5940:     sum=b[i]; 
                   5941:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   5942:     b[i]=sum/a[i][i]; 
                   5943:   } 
                   5944: } 
                   5945: 
                   5946: void pstamp(FILE *fichier)
                   5947: {
                   5948:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
                   5949: }
                   5950: 
                   5951: void date2dmy(double date,double *day, double *month, double *year){
                   5952:   double yp=0., yp1=0., yp2=0.;
                   5953:   
                   5954:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   5955:                        fractional in yp1 */
                   5956:   *year=yp;
                   5957:   yp2=modf((yp1*12),&yp);
                   5958:   *month=yp;
                   5959:   yp1=modf((yp2*30.5),&yp);
                   5960:   *day=yp;
                   5961:   if(*day==0) *day=1;
                   5962:   if(*month==0) *month=1;
                   5963: }
                   5964: 
                   5965: 
                   5966: 
                   5967: /************ Frequencies ********************/
                   5968: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
                   5969:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   5970:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
                   5971: {  /* Some frequencies as well as proposing some starting values */
                   5972:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
                   5973:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
                   5974:   int iind=0, iage=0;
                   5975:   int mi; /* Effective wave */
                   5976:   int first;
                   5977:   double ***freq; /* Frequencies */
                   5978:   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 */
                   5979:   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);
                   5980:   double *meanq, *stdq, *idq;
                   5981:   double **meanqt;
                   5982:   double *pp, **prop, *posprop, *pospropt;
                   5983:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   5984:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   5985:   double agebegin, ageend;
                   5986:     
                   5987:   pp=vector(1,nlstate);
                   5988:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
                   5989:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   5990:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   5991:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   5992:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
                   5993:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
                   5994:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
                   5995:   meanqt=matrix(1,lastpass,1,nqtveff);
                   5996:   strcpy(fileresp,"P_");
                   5997:   strcat(fileresp,fileresu);
                   5998:   /*strcat(fileresphtm,fileresu);*/
                   5999:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   6000:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   6001:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   6002:     exit(0);
                   6003:   }
                   6004:   
                   6005:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   6006:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   6007:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   6008:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   6009:     fflush(ficlog);
                   6010:     exit(70); 
                   6011:   }
                   6012:   else{
                   6013:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   6014: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
                   6015: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
                   6016:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   6017:   }
                   6018:   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);
                   6019:   
                   6020:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   6021:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   6022:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   6023:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   6024:     fflush(ficlog);
                   6025:     exit(70); 
                   6026:   } else{
                   6027:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   6028: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
                   6029: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
                   6030:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   6031:   }
                   6032:   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);
                   6033:   
                   6034:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   6035:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   6036:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   6037:   j1=0;
                   6038:   
                   6039:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   6040:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
                   6041:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
                   6042:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   6043:   
                   6044:   
                   6045:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   6046:      reference=low_education V1=0,V2=0
                   6047:      med_educ                V1=1 V2=0, 
                   6048:      high_educ               V1=0 V2=1
                   6049:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
                   6050:   */
                   6051:   dateintsum=0;
                   6052:   k2cpt=0;
                   6053: 
                   6054:   if(cptcoveff == 0 )
                   6055:     nl=1;  /* Constant and age model only */
                   6056:   else
                   6057:     nl=2;
                   6058: 
                   6059:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   6060:   /* Loop on nj=1 or 2 if dummy covariates j!=0
                   6061:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
                   6062:    *     freq[s1][s2][iage] =0.
                   6063:    *     Loop on iind
                   6064:    *       ++freq[s1][s2][iage] weighted
                   6065:    *     end iind
                   6066:    *     if covariate and j!0
                   6067:    *       headers Variable on one line
                   6068:    *     endif cov j!=0
                   6069:    *     header of frequency table by age
                   6070:    *     Loop on age
                   6071:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   6072:    *       pos+=freq[s1][s2][iage] weighted
                   6073:    *       Loop on s1 initial state
                   6074:    *         fprintf(ficresp
                   6075:    *       end s1
                   6076:    *     end age
                   6077:    *     if j!=0 computes starting values
                   6078:    *     end compute starting values
                   6079:    *   end j1
                   6080:    * end nl 
                   6081:    */
                   6082:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   6083:     if(nj==1)
                   6084:       j=0;  /* First pass for the constant */
                   6085:     else{
                   6086:       j=cptcoveff; /* Other passes for the covariate values number of simple covariates in the model V2+V1 =2 (simple dummy fixed or time varying) */
                   6087:     }
                   6088:     first=1;
                   6089:     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 */
                   6090:       posproptt=0.;
                   6091:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
                   6092:        scanf("%d", i);*/
                   6093:       for (i=-5; i<=nlstate+ndeath; i++)  
                   6094:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
                   6095:          for(m=iagemin; m <= iagemax+3; m++)
                   6096:            freq[i][s2][m]=0;
                   6097:       
                   6098:       for (i=1; i<=nlstate; i++)  {
                   6099:        for(m=iagemin; m <= iagemax+3; m++)
                   6100:          prop[i][m]=0;
                   6101:        posprop[i]=0;
                   6102:        pospropt[i]=0;
                   6103:       }
                   6104:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
                   6105:         idq[z1]=0.;
                   6106:         meanq[z1]=0.;
                   6107:         stdq[z1]=0.;
                   6108:       }
                   6109:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   6110:       /*   for(m=1;m<=lastpass;m++){ */
                   6111:       /*         meanqt[m][z1]=0.; */
                   6112:       /*       } */
                   6113:       /* }       */
                   6114:       /* dateintsum=0; */
                   6115:       /* k2cpt=0; */
                   6116:       
                   6117:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
                   6118:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   6119:        bool=1;
                   6120:        if(j !=0){
                   6121:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
                   6122:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   6123:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
                   6124:                /* if(Tvaraff[z1] ==-20){ */
                   6125:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   6126:                /* }else  if(Tvaraff[z1] ==-10){ */
                   6127:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
                   6128:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
                   6129:                /* 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); */
                   6130:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
                   6131:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
                   6132:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
                   6133:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
                   6134:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
                   6135:                  /* 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", */
                   6136:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   6137:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   6138:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   6139:                } /* Onlyf fixed */
                   6140:              } /* end z1 */
                   6141:            } /* cptcoveff > 0 */
                   6142:          } /* end any */
                   6143:        }/* end j==0 */
                   6144:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
                   6145:          /* for(m=firstpass; m<=lastpass; m++){ */
                   6146:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
                   6147:            m=mw[mi][iind];
                   6148:            if(j!=0){
                   6149:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   6150:                for (z1=1; z1<=cptcoveff; z1++) {
                   6151:                  if( Fixed[Tmodelind[z1]]==1){
                   6152:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
                   6153:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
                   6154:                    if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality. If covariate's 
                   6155:                                                                                      value is -1, we don't select. It differs from the 
                   6156:                                                                                      constant and age model which counts them. */
                   6157:                      bool=0; /* not selected */
                   6158:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   6159:                    /* i1=Tvaraff[z1]; */
                   6160:                    /* i2=TnsdVar[i1]; */
                   6161:                    /* i3=nbcode[i1][i2]; */
                   6162:                    /* i4=covar[i1][iind]; */
                   6163:                    /* if(i4 != i3){ */
                   6164:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
                   6165:                      bool=0;
                   6166:                    }
                   6167:                  }
                   6168:                }
                   6169:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   6170:            } /* end j==0 */
                   6171:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
                   6172:            if(bool==1){ /*Selected */
                   6173:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   6174:                 and mw[mi+1][iind]. dh depends on stepm. */
                   6175:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   6176:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   6177:              if(m >=firstpass && m <=lastpass){
                   6178:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   6179:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   6180:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   6181:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   6182:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   6183:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   6184:                if (m<lastpass) {
                   6185:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   6186:                  /*   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]); */
                   6187:                  if(s[m][iind]==-1)
                   6188:                    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.));
                   6189:                  freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
                   6190:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   6191:                    if(!isnan(covar[ncovcol+z1][iind])){
                   6192:                      idq[z1]=idq[z1]+weight[iind];
                   6193:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   6194:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   6195:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
                   6196:                    }
                   6197:                  }
                   6198:                  /* if((int)agev[m][iind] == 55) */
                   6199:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   6200:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   6201:                  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 */
                   6202:                }
                   6203:              } /* end if between passes */  
                   6204:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   6205:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   6206:                k2cpt++;
                   6207:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
                   6208:              }
                   6209:            }else{
                   6210:              bool=1;
                   6211:            }/* end bool 2 */
                   6212:          } /* end m */
                   6213:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   6214:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   6215:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   6216:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   6217:          /* } */
                   6218:        } /* end bool */
                   6219:       } /* end iind = 1 to imx */
                   6220:       /* prop[s][age] is fed for any initial and valid live state as well as
                   6221:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   6222:       
                   6223:       
                   6224:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   6225:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
                   6226:         pstamp(ficresp);
                   6227:       if  (cptcoveff>0 && j!=0){
                   6228:         pstamp(ficresp);
                   6229:        printf( "\n#********** Variable "); 
                   6230:        fprintf(ficresp, "\n#********** Variable "); 
                   6231:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   6232:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   6233:        fprintf(ficlog, "\n#********** Variable "); 
                   6234:        for (z1=1; z1<=cptcoveff; z1++){
                   6235:          if(!FixedV[Tvaraff[z1]]){
                   6236:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   6237:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   6238:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   6239:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   6240:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   6241:          }else{
                   6242:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   6243:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   6244:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   6245:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   6246:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   6247:          }
                   6248:        }
                   6249:        printf( "**********\n#");
                   6250:        fprintf(ficresp, "**********\n#");
                   6251:        fprintf(ficresphtm, "**********</h3>\n");
                   6252:        fprintf(ficresphtmfr, "**********</h3>\n");
                   6253:        fprintf(ficlog, "**********\n");
                   6254:       }
                   6255:       /*
                   6256:        Printing means of quantitative variables if any
                   6257:       */
                   6258:       for (z1=1; z1<= nqfveff; z1++) {
                   6259:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
                   6260:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
                   6261:        if(weightopt==1){
                   6262:          printf(" Weighted mean and standard deviation of");
                   6263:          fprintf(ficlog," Weighted mean and standard deviation of");
                   6264:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   6265:        }
                   6266:        /* mu = \frac{w x}{\sum w}
                   6267:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   6268:        */
                   6269:        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]));
                   6270:        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]));
                   6271:        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]));
                   6272:       }
                   6273:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   6274:       /*       for(m=1;m<=lastpass;m++){ */
                   6275:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   6276:       /*   } */
                   6277:       /* } */
                   6278: 
                   6279:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
                   6280:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
                   6281:         fprintf(ficresp, " Age");
                   6282:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   6283:          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]]);
                   6284:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   6285:        }
                   6286:       for(i=1; i<=nlstate;i++) {
                   6287:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
                   6288:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   6289:       }
                   6290:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
                   6291:       fprintf(ficresphtm, "\n");
                   6292:       
                   6293:       /* Header of frequency table by age */
                   6294:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   6295:       fprintf(ficresphtmfr,"<th>Age</th> ");
                   6296:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   6297:        for(m=-1; m <=nlstate+ndeath; m++){
                   6298:          if(s2!=0 && m!=0)
                   6299:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
                   6300:        }
                   6301:       }
                   6302:       fprintf(ficresphtmfr, "\n");
                   6303:     
                   6304:       /* For each age */
                   6305:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   6306:        fprintf(ficresphtm,"<tr>");
                   6307:        if(iage==iagemax+1){
                   6308:          fprintf(ficlog,"1");
                   6309:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   6310:        }else if(iage==iagemax+2){
                   6311:          fprintf(ficlog,"0");
                   6312:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   6313:        }else if(iage==iagemax+3){
                   6314:          fprintf(ficlog,"Total");
                   6315:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   6316:        }else{
                   6317:          if(first==1){
                   6318:            first=0;
                   6319:            printf("See log file for details...\n");
                   6320:          }
                   6321:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   6322:          fprintf(ficlog,"Age %d", iage);
                   6323:        }
                   6324:        for(s1=1; s1 <=nlstate ; s1++){
                   6325:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   6326:            pp[s1] += freq[s1][m][iage]; 
                   6327:        }
                   6328:        for(s1=1; s1 <=nlstate ; s1++){
                   6329:          for(m=-1, pos=0; m <=0 ; m++)
                   6330:            pos += freq[s1][m][iage];
                   6331:          if(pp[s1]>=1.e-10){
                   6332:            if(first==1){
                   6333:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
                   6334:            }
                   6335:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
                   6336:          }else{
                   6337:            if(first==1)
                   6338:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   6339:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   6340:          }
                   6341:        }
                   6342:       
                   6343:        for(s1=1; s1 <=nlstate ; s1++){ 
                   6344:          /* posprop[s1]=0; */
                   6345:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   6346:            pp[s1] += freq[s1][m][iage];
                   6347:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   6348:       
                   6349:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   6350:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   6351:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   6352:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   6353:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   6354:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   6355:        }
                   6356:        
                   6357:        /* Writing ficresp */
                   6358:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   6359:           if( iage <= iagemax){
                   6360:            fprintf(ficresp," %d",iage);
                   6361:           }
                   6362:         }else if( nj==2){
                   6363:           if( iage <= iagemax){
                   6364:            fprintf(ficresp," %d",iage);
                   6365:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   6366:           }
                   6367:        }
                   6368:        for(s1=1; s1 <=nlstate ; s1++){
                   6369:          if(pos>=1.e-5){
                   6370:            if(first==1)
                   6371:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   6372:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   6373:          }else{
                   6374:            if(first==1)
                   6375:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   6376:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   6377:          }
                   6378:          if( iage <= iagemax){
                   6379:            if(pos>=1.e-5){
                   6380:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
                   6381:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   6382:               }else if( nj==2){
                   6383:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   6384:               }
                   6385:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   6386:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   6387:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   6388:            } else{
                   6389:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
                   6390:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
                   6391:            }
                   6392:          }
                   6393:          pospropt[s1] +=posprop[s1];
                   6394:        } /* end loop s1 */
                   6395:        /* pospropt=0.; */
                   6396:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   6397:          for(m=-1; m <=nlstate+ndeath; m++){
                   6398:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
                   6399:              if(first==1){
                   6400:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
                   6401:              }
                   6402:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   6403:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
                   6404:            }
                   6405:            if(s1!=0 && m!=0)
                   6406:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
                   6407:          }
                   6408:        } /* end loop s1 */
                   6409:        posproptt=0.; 
                   6410:        for(s1=1; s1 <=nlstate; s1++){
                   6411:          posproptt += pospropt[s1];
                   6412:        }
                   6413:        fprintf(ficresphtmfr,"</tr>\n ");
                   6414:        fprintf(ficresphtm,"</tr>\n");
                   6415:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
                   6416:          if(iage <= iagemax)
                   6417:            fprintf(ficresp,"\n");
                   6418:        }
                   6419:        if(first==1)
                   6420:          printf("Others in log...\n");
                   6421:        fprintf(ficlog,"\n");
                   6422:       } /* end loop age iage */
                   6423:       
                   6424:       fprintf(ficresphtm,"<tr><th>Tot</th>");
                   6425:       for(s1=1; s1 <=nlstate ; s1++){
                   6426:        if(posproptt < 1.e-5){
                   6427:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
                   6428:        }else{
                   6429:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
                   6430:        }
                   6431:       }
                   6432:       fprintf(ficresphtm,"</tr>\n");
                   6433:       fprintf(ficresphtm,"</table>\n");
                   6434:       fprintf(ficresphtmfr,"</table>\n");
                   6435:       if(posproptt < 1.e-5){
                   6436:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   6437:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   6438:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   6439:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
                   6440:        invalidvarcomb[j1]=1;
                   6441:       }else{
                   6442:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
                   6443:        invalidvarcomb[j1]=0;
                   6444:       }
                   6445:       fprintf(ficresphtmfr,"</table>\n");
                   6446:       fprintf(ficlog,"\n");
                   6447:       if(j!=0){
                   6448:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
                   6449:        for(i=1,s1=1; i <=nlstate; i++){
                   6450:          for(k=1; k <=(nlstate+ndeath); k++){
                   6451:            if (k != i) {
                   6452:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
                   6453:                if(jj==1){  /* Constant case (in fact cste + age) */
                   6454:                  if(j1==1){ /* All dummy covariates to zero */
                   6455:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   6456:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
                   6457:                    printf("%d%d ",i,k);
                   6458:                    fprintf(ficlog,"%d%d ",i,k);
                   6459:                    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]));
                   6460:                    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]));
                   6461:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   6462:                  }
                   6463:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   6464:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   6465:                    x[iage]= (double)iage;
                   6466:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
                   6467:                    /* printf("i=%d, k=%d, s1=%d, j1=%d, jj=%d, y[%d]=%f\n",i,k,s1,j1,jj, iage, y[iage]); */
                   6468:                  }
                   6469:                  /* Some are not finite, but linreg will ignore these ages */
                   6470:                  no=0;
                   6471:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
                   6472:                  pstart[s1]=b;
                   6473:                  pstart[s1-1]=a;
                   6474:                }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 */ 
                   6475:                  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]);
                   6476:                  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]);
                   6477:                  pstart[s1]= log((freq[i][k][iagemax+3]/freq[i][i][iagemax+3])/(freq[i][k][iagemax+4]/freq[i][i][iagemax+4]));
                   6478:                  printf("%d%d ",i,k);
                   6479:                  fprintf(ficlog,"%d%d ",i,k);
                   6480:                  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]));
                   6481:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   6482:                  ;
                   6483:                }
                   6484:                /* printf("%12.7f )", param[i][jj][k]); */
                   6485:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
                   6486:                s1++; 
                   6487:              } /* end jj */
                   6488:            } /* end k!= i */
                   6489:          } /* end k */
                   6490:        } /* end i, s1 */
                   6491:       } /* end j !=0 */
                   6492:     } /* end selected combination of covariate j1 */
                   6493:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   6494:       printf("#Freqsummary: Starting values for the constants:\n");
                   6495:       fprintf(ficlog,"\n");
                   6496:       for(i=1,s1=1; i <=nlstate; i++){
                   6497:        for(k=1; k <=(nlstate+ndeath); k++){
                   6498:          if (k != i) {
                   6499:            printf("%d%d ",i,k);
                   6500:            fprintf(ficlog,"%d%d ",i,k);
                   6501:            for(jj=1; jj <=ncovmodel; jj++){
                   6502:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
                   6503:              if(jj==1){ /* Age has to be done */
                   6504:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   6505:                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]));
                   6506:                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]));
                   6507:              }
                   6508:              /* printf("%12.7f )", param[i][jj][k]); */
                   6509:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
                   6510:              s1++; 
                   6511:            }
                   6512:            printf("\n");
                   6513:            fprintf(ficlog,"\n");
                   6514:          }
                   6515:        }
                   6516:       } /* end of state i */
                   6517:       printf("#Freqsummary\n");
                   6518:       fprintf(ficlog,"\n");
                   6519:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   6520:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   6521:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   6522:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   6523:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   6524:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   6525:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   6526:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   6527:          /* } */
                   6528:        }
                   6529:       } /* end loop s1 */
                   6530:       
                   6531:       printf("\n");
                   6532:       fprintf(ficlog,"\n");
                   6533:     } /* end j=0 */
                   6534:   } /* end j */
                   6535: 
                   6536:   if(mle == -2){  /* We want to use these values as starting values */
                   6537:     for(i=1, jk=1; i <=nlstate; i++){
                   6538:       for(j=1; j <=nlstate+ndeath; j++){
                   6539:        if(j!=i){
                   6540:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   6541:          printf("%1d%1d",i,j);
                   6542:          fprintf(ficparo,"%1d%1d",i,j);
                   6543:          for(k=1; k<=ncovmodel;k++){
                   6544:            /*    printf(" %lf",param[i][j][k]); */
                   6545:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   6546:            p[jk]=pstart[jk];
                   6547:            printf(" %f ",pstart[jk]);
                   6548:            fprintf(ficparo," %f ",pstart[jk]);
                   6549:            jk++;
                   6550:          }
                   6551:          printf("\n");
                   6552:          fprintf(ficparo,"\n");
                   6553:        }
                   6554:       }
                   6555:     }
                   6556:   } /* end mle=-2 */
                   6557:   dateintmean=dateintsum/k2cpt; 
                   6558:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
                   6559:   
                   6560:   fclose(ficresp);
                   6561:   fclose(ficresphtm);
                   6562:   fclose(ficresphtmfr);
                   6563:   free_vector(idq,1,nqfveff);
                   6564:   free_vector(meanq,1,nqfveff);
                   6565:   free_vector(stdq,1,nqfveff);
                   6566:   free_matrix(meanqt,1,lastpass,1,nqtveff);
                   6567:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   6568:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   6569:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   6570:   free_vector(pospropt,1,nlstate);
                   6571:   free_vector(posprop,1,nlstate);
                   6572:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   6573:   free_vector(pp,1,nlstate);
                   6574:   /* End of freqsummary */
                   6575: }
                   6576: 
                   6577: /* Simple linear regression */
                   6578: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   6579: 
                   6580:   /* y=a+bx regression */
                   6581:   double   sumx = 0.0;                        /* sum of x                      */
                   6582:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   6583:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   6584:   double   sumy = 0.0;                        /* sum of y                      */
                   6585:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   6586:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   6587:   double yhat;
                   6588:   
                   6589:   double denom=0;
                   6590:   int i;
                   6591:   int ne=*no;
                   6592:   
                   6593:   for ( i=ifi, ne=0;i<=ila;i++) {
                   6594:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   6595:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   6596:       continue;
                   6597:     }
                   6598:     ne=ne+1;
                   6599:     sumx  += x[i];       
                   6600:     sumx2 += x[i]*x[i];  
                   6601:     sumxy += x[i] * y[i];
                   6602:     sumy  += y[i];      
                   6603:     sumy2 += y[i]*y[i]; 
                   6604:     denom = (ne * sumx2 - sumx*sumx);
                   6605:     /* 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); */
                   6606:   } 
                   6607:   
                   6608:   denom = (ne * sumx2 - sumx*sumx);
                   6609:   if (denom == 0) {
                   6610:     // vertical, slope m is infinity
                   6611:     *b = INFINITY;
                   6612:     *a = 0;
                   6613:     if (r) *r = 0;
                   6614:     return 1;
                   6615:   }
                   6616:   
                   6617:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   6618:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   6619:   if (r!=NULL) {
                   6620:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   6621:       sqrt((sumx2 - sumx*sumx/ne) *
                   6622:           (sumy2 - sumy*sumy/ne));
                   6623:   }
                   6624:   *no=ne;
                   6625:   for ( i=ifi, ne=0;i<=ila;i++) {
                   6626:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   6627:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   6628:       continue;
                   6629:     }
                   6630:     ne=ne+1;
                   6631:     yhat = y[i] - *a -*b* x[i];
                   6632:     sume2  += yhat * yhat ;       
                   6633:     
                   6634:     denom = (ne * sumx2 - sumx*sumx);
                   6635:     /* 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); */
                   6636:   } 
                   6637:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   6638:   *sa= *sb * sqrt(sumx2/ne);
                   6639:   
                   6640:   return 0; 
                   6641: }
                   6642: 
                   6643: /************ Prevalence ********************/
                   6644: 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)
                   6645: {  
                   6646:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   6647:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   6648:      We still use firstpass and lastpass as another selection.
                   6649:   */
                   6650:  
                   6651:   int i, m, jk, j1, bool, z1,j, iv;
                   6652:   int mi; /* Effective wave */
                   6653:   int iage;
                   6654:   double agebegin, ageend;
                   6655: 
                   6656:   double **prop;
                   6657:   double posprop; 
                   6658:   double  y2; /* in fractional years */
                   6659:   int iagemin, iagemax;
                   6660:   int first; /** to stop verbosity which is redirected to log file */
                   6661: 
                   6662:   iagemin= (int) agemin;
                   6663:   iagemax= (int) agemax;
                   6664:   /*pp=vector(1,nlstate);*/
                   6665:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
                   6666:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   6667:   j1=0;
                   6668:   
                   6669:   /*j=cptcoveff;*/
                   6670:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   6671:   
                   6672:   first=0;
                   6673:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
                   6674:     for (i=1; i<=nlstate; i++)  
                   6675:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
                   6676:        prop[i][iage]=0.0;
                   6677:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   6678:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   6679:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   6680:     
                   6681:     for (i=1; i<=imx; i++) { /* Each individual */
                   6682:       bool=1;
                   6683:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   6684:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   6685:        m=mw[mi][i];
                   6686:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   6687:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   6688:        for (z1=1; z1<=cptcoveff; z1++){
                   6689:          if( Fixed[Tmodelind[z1]]==1){
                   6690:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   6691:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
                   6692:              bool=0;
                   6693:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   6694:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
                   6695:              bool=0;
                   6696:            }
                   6697:        }
                   6698:        if(bool==1){ /* Otherwise we skip that wave/person */
                   6699:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   6700:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   6701:          if(m >=firstpass && m <=lastpass){
                   6702:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   6703:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   6704:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   6705:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   6706:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
                   6707:                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); 
                   6708:                exit(1);
                   6709:              }
                   6710:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   6711:                /*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]]);*/
                   6712:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   6713:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   6714:              } /* end valid statuses */ 
                   6715:            } /* end selection of dates */
                   6716:          } /* end selection of waves */
                   6717:        } /* end bool */
                   6718:       } /* end wave */
                   6719:     } /* end individual */
                   6720:     for(i=iagemin; i <= iagemax+3; i++){  
                   6721:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   6722:        posprop += prop[jk][i]; 
                   6723:       } 
                   6724:       
                   6725:       for(jk=1; jk <=nlstate ; jk++){      
                   6726:        if( i <=  iagemax){ 
                   6727:          if(posprop>=1.e-5){ 
                   6728:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   6729:          } else{
                   6730:            if(!first){
                   6731:              first=1;
                   6732:              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]);
                   6733:            }else{
                   6734:              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]);
                   6735:            }
                   6736:          }
                   6737:        } 
                   6738:       }/* end jk */ 
                   6739:     }/* end i */ 
                   6740:      /*} *//* end i1 */
                   6741:   } /* end j1 */
                   6742:   
                   6743:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   6744:   /*free_vector(pp,1,nlstate);*/
                   6745:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   6746: }  /* End of prevalence */
                   6747: 
                   6748: /************* Waves Concatenation ***************/
                   6749: 
                   6750: 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)
                   6751: {
                   6752:   /* Concatenates waves: wav[i] is the number of effective (useful waves in the sense that a non interview is useless) of individual i.
                   6753:      Death is a valid wave (if date is known).
                   6754:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   6755:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   6756:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
                   6757:   */
                   6758: 
                   6759:   int i=0, mi=0, m=0, mli=0;
                   6760:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   6761:      double sum=0., jmean=0.;*/
                   6762:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
                   6763:   int j, k=0,jk, ju, jl;
                   6764:   double sum=0.;
                   6765:   first=0;
                   6766:   firstwo=0;
                   6767:   firsthree=0;
                   6768:   firstfour=0;
                   6769:   jmin=100000;
                   6770:   jmax=-1;
                   6771:   jmean=0.;
                   6772: 
                   6773: /* Treating live states */
                   6774:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
                   6775:     mi=0;  /* First valid wave */
                   6776:     mli=0; /* Last valid wave */
                   6777:     m=firstpass;  /* Loop on waves */
                   6778:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
                   6779:       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 */
                   6780:        mli=m-1;/* mw[++mi][i]=m-1; */
                   6781:       }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 */
                   6782:        mw[++mi][i]=m; /* Valid wave: incrementing mi and updating mi; mw[mi] is the wave number of mi_th valid transition   */
                   6783:        mli=m;
                   6784:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   6785:       if(m < lastpass){ /* m < lastpass, standard case */
                   6786:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
                   6787:       }
                   6788:       else{ /* m = lastpass, eventual special issue with warning */
                   6789: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
                   6790:        break;
                   6791: #else
                   6792:        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 */
                   6793:          if(firsthree == 0){
                   6794:            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);
                   6795:            firsthree=1;
                   6796:          }else if(firsthree >=1 && firsthree < 10){
                   6797:            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);
                   6798:            firsthree++;
                   6799:          }else if(firsthree == 10){
                   6800:            printf("Information, too many Information flags: no more reported to log either\n");
                   6801:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   6802:            firsthree++;
                   6803:          }else{
                   6804:            firsthree++;
                   6805:          }
                   6806:          mw[++mi][i]=m; /* Valid transition with unknown status */
                   6807:          mli=m;
                   6808:        }
                   6809:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   6810:          nbwarn++;
                   6811:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
                   6812:            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);
                   6813:            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);
                   6814:          }
                   6815:          break;
                   6816:        }
                   6817:        break;
                   6818: #endif
                   6819:       }/* End m >= lastpass */
                   6820:     }/* end while */
                   6821: 
                   6822:     /* mi is the last effective wave, m is lastpass, mw[j][i] gives the # of j-th effective wave for individual i */
                   6823:     /* After last pass */
                   6824: /* Treating death states */
                   6825:     if (s[m][i] > nlstate){  /* In a death state */
                   6826:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   6827:       /* } */
                   6828:       mi++;    /* Death is another wave */
                   6829:       /* if(mi==0)  never been interviewed correctly before death */
                   6830:       /* Only death is a correct wave */
                   6831:       mw[mi][i]=m;
                   6832:     } /* else not in a death state */
                   6833: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
                   6834:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
                   6835:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
                   6836:        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 */
                   6837:          nbwarn++;
                   6838:          if(firstfiv==0){
                   6839:            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 );
                   6840:            firstfiv=1;
                   6841:          }else{
                   6842:            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 );
                   6843:          }
                   6844:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   6845:        }else{ /* Month of Death occured afer last wave month, potential bias */
                   6846:          nberr++;
                   6847:          if(firstwo==0){
                   6848:            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 );
                   6849:            firstwo=1;
                   6850:          }
                   6851:          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 );
                   6852:        }
                   6853:       }else{ /* if date of interview is unknown */
                   6854:        /* death is known but not confirmed by death status at any wave */
                   6855:        if(firstfour==0){
                   6856:          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 );
                   6857:          firstfour=1;
                   6858:        }
                   6859:        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 );
                   6860:       }
                   6861:     } /* end if date of death is known */
                   6862: #endif
                   6863:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   6864:     /* wav[i]=mw[mi][i];   */
                   6865:     if(mi==0){
                   6866:       nbwarn++;
                   6867:       if(first==0){
                   6868:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   6869:        first=1;
                   6870:       }
                   6871:       if(first==1){
                   6872:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   6873:       }
                   6874:     } /* end mi==0 */
                   6875:   } /* End individuals */
                   6876:   /* wav and mw are no more changed */
                   6877:        
                   6878:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6879:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   6880: 
                   6881: 
                   6882:   for(i=1; i<=imx; i++){
                   6883:     for(mi=1; mi<wav[i];mi++){
                   6884:       if (stepm <=0)
                   6885:        dh[mi][i]=1;
                   6886:       else{
                   6887:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
                   6888:          if (agedc[i] < 2*AGESUP) {
                   6889:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   6890:            if(j==0) j=1;  /* Survives at least one month after exam */
                   6891:            else if(j<0){
                   6892:              nberr++;
1.5     ! brouard  6893:              printf("Error! Negative delay (%d to death) between waves %d and %d of individual %ld (around 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]);
1.1       brouard  6894:              j=1; /* Temporary Dangerous patch */
                   6895:              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);
1.5     ! brouard  6896:              fprintf(ficlog,"Error! Negative delay (%d to death) between waves %d and %d of individual %ld (around 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]);
1.1       brouard  6897:              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);
                   6898:            }
                   6899:            k=k+1;
                   6900:            if (j >= jmax){
                   6901:              jmax=j;
                   6902:              ijmax=i;
                   6903:            }
                   6904:            if (j <= jmin){
                   6905:              jmin=j;
                   6906:              ijmin=i;
                   6907:            }
                   6908:            sum=sum+j;
                   6909:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   6910:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   6911:          }
                   6912:        }
                   6913:        else{
                   6914:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   6915: /*       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]); */
                   6916:                                        
                   6917:          k=k+1;
                   6918:          if (j >= jmax) {
                   6919:            jmax=j;
                   6920:            ijmax=i;
                   6921:          }
                   6922:          else if (j <= jmin){
                   6923:            jmin=j;
                   6924:            ijmin=i;
                   6925:          }
                   6926:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   6927:          /*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]);*/
                   6928:          if(j<0){
                   6929:            nberr++;
1.5     ! brouard  6930:            printf("Error! Negative delay (%d) between waves %d and %d of individual %ld (around 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]);
        !          6931:            fprintf(ficlog,"Error! Negative delay (%d) between waves %d and %d of individual %ld (around 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]);
1.1       brouard  6932:          }
                   6933:          sum=sum+j;
                   6934:        }
                   6935:        jk= j/stepm;
                   6936:        jl= j -jk*stepm;
                   6937:        ju= j -(jk+1)*stepm;
                   6938:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   6939:          if(jl==0){
                   6940:            dh[mi][i]=jk;
                   6941:            bh[mi][i]=0;
                   6942:          }else{ /* We want a negative bias in order to only have interpolation ie
                   6943:                  * to avoid the price of an extra matrix product in likelihood */
                   6944:            dh[mi][i]=jk+1;
                   6945:            bh[mi][i]=ju;
                   6946:          }
                   6947:        }else{
                   6948:          if(jl <= -ju){
                   6949:            dh[mi][i]=jk;
                   6950:            bh[mi][i]=jl;       /* bias is positive if real duration
                   6951:                                 * is higher than the multiple of stepm and negative otherwise.
                   6952:                                 */
                   6953:          }
                   6954:          else{
                   6955:            dh[mi][i]=jk+1;
                   6956:            bh[mi][i]=ju;
                   6957:          }
                   6958:          if(dh[mi][i]==0){
                   6959:            dh[mi][i]=1; /* At least one step */
                   6960:            bh[mi][i]=ju; /* At least one step */
                   6961:            /*  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);*/
                   6962:          }
                   6963:        } /* end if mle */
                   6964:       }
                   6965:     } /* end wave */
                   6966:   }
                   6967:   jmean=sum/k;
                   6968:   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);
                   6969:   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);
                   6970: }
                   6971: 
                   6972: /*********** Tricode ****************************/
                   6973:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
                   6974:  {
                   6975:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   6976:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   6977:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   6978:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   6979:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   6980:     */
                   6981: 
                   6982:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   6983:    int modmaxcovj=0; /* Modality max of covariates j */
                   6984:    int cptcode=0; /* Modality max of covariates j */
                   6985:    int modmincovj=0; /* Modality min of covariates j */
                   6986: 
                   6987: 
                   6988:    /* cptcoveff=0;  */
                   6989:    /* *cptcov=0; */
                   6990:  
                   6991:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
                   6992:    for (k=1; k <= maxncov; k++)
                   6993:      for(j=1; j<=2; j++)
                   6994:        nbcode[k][j]=0; /* Valgrind */
                   6995: 
                   6996:    /* Loop on covariates without age and products and no quantitative variable */
                   6997:    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 */
                   6998:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   6999:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
                   7000:      if(Dummy[k]==0 && Typevar[k] !=1 && Typevar[k] != 3  && Typevar[k] != 2){ /* Dummy covariate and not age product nor fixed product */ 
                   7001:        switch(Fixed[k]) {
                   7002:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
                   7003:         modmaxcovj=0;
                   7004:         modmincovj=0;
                   7005:         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*/
                   7006:           /* 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])); */
                   7007:           ij=(int)(covar[Tvar[k]][i]);
                   7008:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   7009:            * If product of Vn*Vm, still boolean *:
                   7010:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   7011:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   7012:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   7013:              modality of the nth covariate of individual i. */
                   7014:           if (ij > modmaxcovj)
                   7015:             modmaxcovj=ij; 
                   7016:           else if (ij < modmincovj) 
                   7017:             modmincovj=ij; 
                   7018:           if (ij <0 || ij >1 ){
                   7019:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   7020:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   7021:             fflush(ficlog);
                   7022:             exit(1);
                   7023:           }
                   7024:           if ((ij < -1) || (ij > NCOVMAX)){
                   7025:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   7026:             exit(1);
                   7027:           }else
                   7028:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   7029:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   7030:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   7031:           /* getting the maximum value of the modality of the covariate
                   7032:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   7033:              female ies 1, then modmaxcovj=1.
                   7034:           */
                   7035:         } /* end for loop on individuals i */
                   7036:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   7037:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   7038:         cptcode=modmaxcovj;
                   7039:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   7040:         /*for (i=0; i<=cptcode; i++) {*/
                   7041:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   7042:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   7043:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   7044:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   7045:             if( j != -1){
                   7046:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   7047:                                  covariate for which somebody answered excluding 
                   7048:                                  undefined. Usually 2: 0 and 1. */
                   7049:             }
                   7050:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   7051:                                     covariate for which somebody answered including 
                   7052:                                     undefined. Usually 3: -1, 0 and 1. */
                   7053:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   7054:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   7055:         } /* Ndum[-1] number of undefined modalities */
                   7056:                        
                   7057:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   7058:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   7059:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   7060:         /* modmincovj=3; modmaxcovj = 7; */
                   7061:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   7062:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   7063:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   7064:         /* nbcode[Tvar[j]][ij]=k; */
                   7065:         /* nbcode[Tvar[j]][1]=0; */
                   7066:         /* nbcode[Tvar[j]][2]=1; */
                   7067:         /* nbcode[Tvar[j]][3]=2; */
                   7068:         /* To be continued (not working yet). */
                   7069:         ij=0; /* ij is similar to i but can jump over null modalities */
                   7070: 
                   7071:         /* 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*/
                   7072:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   7073:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   7074:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   7075:         /*, could be restored in the future */
                   7076:         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*/
                   7077:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   7078:             break;
                   7079:           }
                   7080:           ij++;
                   7081:           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*/
                   7082:           cptcode = ij; /* New max modality for covar j */
                   7083:         } /* end of loop on modality i=-1 to 1 or more */
                   7084:         break;
                   7085:        case 1: /* Testing on varying covariate, could be simple and
                   7086:                * should look at waves or product of fixed *
                   7087:                * varying. No time to test -1, assuming 0 and 1 only */
                   7088:         ij=0;
                   7089:         for(i=0; i<=1;i++){
                   7090:           nbcode[Tvar[k]][++ij]=i;
                   7091:         }
                   7092:         break;
                   7093:        default:
                   7094:         break;
                   7095:        } /* end switch */
                   7096:      } /* end dummy test */
                   7097:      if(Dummy[k]==1 && Typevar[k] !=1 && Typevar[k] !=3 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
                   7098:        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*/
                   7099:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   7100:           printf("Error k=%d \n",k);
                   7101:           exit(1);
                   7102:         }
                   7103:         if(isnan(covar[Tvar[k]][i])){
                   7104:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   7105:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   7106:           fflush(ficlog);
                   7107:           exit(1);
                   7108:          }
                   7109:        }
                   7110:      } /* end Quanti */
                   7111:    } /* 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*/  
                   7112:   
                   7113:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   7114:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   7115:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   7116:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   7117:      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 */ 
                   7118:      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 */
                   7119:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   7120:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   7121:   
                   7122:    ij=0;
                   7123:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   7124:    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 */
                   7125:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   7126:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   7127:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   7128:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   7129:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   7130:        /* Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product*/
                   7131:        /* If product not in single variable we don't print results */
                   7132:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   7133:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   7134:        /* k=       1    2   3     4       5       6      7       8        9  */
                   7135:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   7136:        /* ij            1    2                                            3  */  
                   7137:        /* Tvaraff[ij]=  4    3                                            1  */
                   7138:        /* Tmodelind[ij]=2    3                                            9  */
                   7139:        /* TmodelInvind[ij]=2 1                                            1  */
                   7140:        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*/
                   7141:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   7142:        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 */
                   7143:        if(Fixed[k]!=0)
                   7144:         anyvaryingduminmodel=1;
                   7145:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   7146:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   7147:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   7148:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   7149:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   7150:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   7151:      } 
                   7152:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   7153:    /* ij--; */
                   7154:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   7155:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
                   7156:                * because they can be excluded from the model and real
                   7157:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   7158:    for(j=ij+1; j<= cptcovt; j++){
                   7159:      Tvaraff[j]=0;
                   7160:      Tmodelind[j]=0;
                   7161:    }
                   7162:    for(j=ntveff+1; j<= cptcovt; j++){
                   7163:      TmodelInvind[j]=0;
                   7164:    }
                   7165:    /* To be sorted */
                   7166:    ;
                   7167:  }
                   7168: 
                   7169: 
                   7170: /*********** Health Expectancies ****************/
                   7171: 
                   7172:  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 )
                   7173: 
                   7174: {
                   7175:   /* Health expectancies, no variances */
                   7176:   /* cij is the combination in the list of combination of dummy covariates */
                   7177:   /* strstart is a string of time at start of computing */
                   7178:   int i, j, nhstepm, hstepm, h, nstepm;
                   7179:   int nhstepma, nstepma; /* Decreasing with age */
                   7180:   double age, agelim, hf;
                   7181:   double ***p3mat;
                   7182:   double eip;
                   7183: 
                   7184:   /* pstamp(ficreseij); */
                   7185:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   7186:   fprintf(ficreseij,"# Age");
                   7187:   for(i=1; i<=nlstate;i++){
                   7188:     for(j=1; j<=nlstate;j++){
                   7189:       fprintf(ficreseij," e%1d%1d ",i,j);
                   7190:     }
                   7191:     fprintf(ficreseij," e%1d. ",i);
                   7192:   }
                   7193:   fprintf(ficreseij,"\n");
                   7194: 
                   7195:   
                   7196:   if(estepm < stepm){
                   7197:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   7198:   }
                   7199:   else  hstepm=estepm;   
                   7200:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   7201:    * This is mainly to measure the difference between two models: for example
                   7202:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   7203:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   7204:    * progression in between and thus overestimating or underestimating according
                   7205:    * to the curvature of the survival function. If, for the same date, we 
                   7206:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   7207:    * to compare the new estimate of Life expectancy with the same linear 
                   7208:    * hypothesis. A more precise result, taking into account a more precise
                   7209:    * curvature will be obtained if estepm is as small as stepm. */
                   7210: 
                   7211:   /* For example we decided to compute the life expectancy with the smallest unit */
                   7212:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   7213:      nhstepm is the number of hstepm from age to agelim 
                   7214:      nstepm is the number of stepm from age to agelin. 
                   7215:      Look at hpijx to understand the reason which relies in memory size consideration
                   7216:      and note for a fixed period like estepm months */
                   7217:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   7218:      survival function given by stepm (the optimization length). Unfortunately it
                   7219:      means that if the survival funtion is printed only each two years of age and if
                   7220:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   7221:      results. So we changed our mind and took the option of the best precision.
                   7222:   */
                   7223:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   7224: 
                   7225:   agelim=AGESUP;
                   7226:   /* If stepm=6 months */
                   7227:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   7228:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   7229:     
                   7230: /* nhstepm age range expressed in number of stepm */
                   7231:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   7232:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   7233:   /* if (stepm >= YEARM) hstepm=1;*/
                   7234:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   7235:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7236: 
                   7237:   for (age=bage; age<=fage; age ++){ 
                   7238:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   7239:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   7240:     /* if (stepm >= YEARM) hstepm=1;*/
                   7241:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   7242: 
                   7243:     /* If stepm=6 months */
                   7244:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   7245:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   7246:     /* printf("HELLO evsij Entering hpxij age=%d cij=%d hstepm=%d x[1]=%f nres=%d\n",(int) age, cij, hstepm, x[1], nres); */
                   7247:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
                   7248:     
                   7249:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   7250:     
                   7251:     printf("%d|",(int)age);fflush(stdout);
                   7252:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   7253:     
                   7254:     /* Computing expectancies */
                   7255:     for(i=1; i<=nlstate;i++)
                   7256:       for(j=1; j<=nlstate;j++)
                   7257:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   7258:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   7259:          
                   7260:          /* 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]);*/
                   7261: 
                   7262:        }
                   7263: 
                   7264:     fprintf(ficreseij,"%3.0f",age );
                   7265:     for(i=1; i<=nlstate;i++){
                   7266:       eip=0;
                   7267:       for(j=1; j<=nlstate;j++){
                   7268:        eip +=eij[i][j][(int)age];
                   7269:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   7270:       }
                   7271:       fprintf(ficreseij,"%9.4f", eip );
                   7272:     }
                   7273:     fprintf(ficreseij,"\n");
                   7274:     
                   7275:   }
                   7276:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7277:   printf("\n");
                   7278:   fprintf(ficlog,"\n");
                   7279:   
                   7280: }
                   7281: 
                   7282:  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 )
                   7283: 
                   7284: {
                   7285:   /* Covariances of health expectancies eij and of total life expectancies according
                   7286:      to initial status i, ei. .
                   7287:   */
                   7288:   /* Very time consuming function, but already optimized with precov */
                   7289:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   7290:   int nhstepma, nstepma; /* Decreasing with age */
                   7291:   double age, agelim, hf;
                   7292:   double ***p3matp, ***p3matm, ***varhe;
                   7293:   double **dnewm,**doldm;
                   7294:   double *xp, *xm;
                   7295:   double **gp, **gm;
                   7296:   double ***gradg, ***trgradg;
                   7297:   int theta;
                   7298: 
                   7299:   double eip, vip;
                   7300: 
                   7301:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   7302:   xp=vector(1,npar);
                   7303:   xm=vector(1,npar);
                   7304:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   7305:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   7306:   
                   7307:   pstamp(ficresstdeij);
                   7308:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   7309:   fprintf(ficresstdeij,"# Age");
                   7310:   for(i=1; i<=nlstate;i++){
                   7311:     for(j=1; j<=nlstate;j++)
                   7312:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   7313:     fprintf(ficresstdeij," e%1d. ",i);
                   7314:   }
                   7315:   fprintf(ficresstdeij,"\n");
                   7316: 
                   7317:   pstamp(ficrescveij);
                   7318:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   7319:   fprintf(ficrescveij,"# Age");
                   7320:   for(i=1; i<=nlstate;i++)
                   7321:     for(j=1; j<=nlstate;j++){
                   7322:       cptj= (j-1)*nlstate+i;
                   7323:       for(i2=1; i2<=nlstate;i2++)
                   7324:        for(j2=1; j2<=nlstate;j2++){
                   7325:          cptj2= (j2-1)*nlstate+i2;
                   7326:          if(cptj2 <= cptj)
                   7327:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   7328:        }
                   7329:     }
                   7330:   fprintf(ficrescveij,"\n");
                   7331:   
                   7332:   if(estepm < stepm){
                   7333:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   7334:   }
                   7335:   else  hstepm=estepm;   
                   7336:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   7337:    * This is mainly to measure the difference between two models: for example
                   7338:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   7339:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   7340:    * progression in between and thus overestimating or underestimating according
                   7341:    * to the curvature of the survival function. If, for the same date, we 
                   7342:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   7343:    * to compare the new estimate of Life expectancy with the same linear 
                   7344:    * hypothesis. A more precise result, taking into account a more precise
                   7345:    * curvature will be obtained if estepm is as small as stepm. */
                   7346: 
                   7347:   /* For example we decided to compute the life expectancy with the smallest unit */
                   7348:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   7349:      nhstepm is the number of hstepm from age to agelim 
                   7350:      nstepm is the number of stepm from age to agelin. 
                   7351:      Look at hpijx to understand the reason of that which relies in memory size
                   7352:      and note for a fixed period like estepm months */
                   7353:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   7354:      survival function given by stepm (the optimization length). Unfortunately it
                   7355:      means that if the survival funtion is printed only each two years of age and if
                   7356:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   7357:      results. So we changed our mind and took the option of the best precision.
                   7358:   */
                   7359:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   7360: 
                   7361:   /* If stepm=6 months */
                   7362:   /* nhstepm age range expressed in number of stepm */
                   7363:   agelim=AGESUP;
                   7364:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   7365:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   7366:   /* if (stepm >= YEARM) hstepm=1;*/
                   7367:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   7368:   
                   7369:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7370:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7371:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   7372:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   7373:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   7374:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   7375: 
                   7376:   for (age=bage; age<=fage; age ++){ 
                   7377:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   7378:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   7379:     /* if (stepm >= YEARM) hstepm=1;*/
                   7380:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   7381:                
                   7382:     /* If stepm=6 months */
                   7383:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   7384:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   7385:     
                   7386:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   7387:                
                   7388:     /* Computing  Variances of health expectancies */
                   7389:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   7390:        decrease memory allocation */
                   7391:     for(theta=1; theta <=npar; theta++){
                   7392:       for(i=1; i<=npar; i++){ 
                   7393:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7394:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   7395:       }
                   7396:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   7397:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
                   7398:                        
                   7399:       for(j=1; j<= nlstate; j++){
                   7400:        for(i=1; i<=nlstate; i++){
                   7401:          for(h=0; h<=nhstepm-1; h++){
                   7402:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   7403:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   7404:          }
                   7405:        }
                   7406:       }
                   7407:                        
                   7408:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   7409:        for(h=0; h<=nhstepm-1; h++){
                   7410:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   7411:        }
                   7412:     }/* End theta */
                   7413:     
                   7414:     
                   7415:     for(h=0; h<=nhstepm-1; h++)
                   7416:       for(j=1; j<=nlstate*nlstate;j++)
                   7417:        for(theta=1; theta <=npar; theta++)
                   7418:          trgradg[h][j][theta]=gradg[h][theta][j];
                   7419:     
                   7420:                
                   7421:     for(ij=1;ij<=nlstate*nlstate;ij++)
                   7422:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   7423:        varhe[ij][ji][(int)age] =0.;
                   7424:                
                   7425:     printf("%d|",(int)age);fflush(stdout);
                   7426:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   7427:     for(h=0;h<=nhstepm-1;h++){
                   7428:       for(k=0;k<=nhstepm-1;k++){
                   7429:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   7430:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   7431:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   7432:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   7433:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   7434:       }
                   7435:     }
                   7436:     /* if((int)age ==50){ */
                   7437:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   7438:     /* } */
                   7439:     /* Computing expectancies */
                   7440:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
                   7441:     for(i=1; i<=nlstate;i++)
                   7442:       for(j=1; j<=nlstate;j++)
                   7443:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   7444:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   7445:                                        
                   7446:          /* 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]);*/
                   7447:                                        
                   7448:        }
                   7449: 
                   7450:     /* Standard deviation of expectancies ij */                
                   7451:     fprintf(ficresstdeij,"%3.0f",age );
                   7452:     for(i=1; i<=nlstate;i++){
                   7453:       eip=0.;
                   7454:       vip=0.;
                   7455:       for(j=1; j<=nlstate;j++){
                   7456:        eip += eij[i][j][(int)age];
                   7457:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   7458:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   7459:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   7460:       }
                   7461:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   7462:     }
                   7463:     fprintf(ficresstdeij,"\n");
                   7464:                
                   7465:     /* Variance of expectancies ij */          
                   7466:     fprintf(ficrescveij,"%3.0f",age );
                   7467:     for(i=1; i<=nlstate;i++)
                   7468:       for(j=1; j<=nlstate;j++){
                   7469:        cptj= (j-1)*nlstate+i;
                   7470:        for(i2=1; i2<=nlstate;i2++)
                   7471:          for(j2=1; j2<=nlstate;j2++){
                   7472:            cptj2= (j2-1)*nlstate+i2;
                   7473:            if(cptj2 <= cptj)
                   7474:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   7475:          }
                   7476:       }
                   7477:     fprintf(ficrescveij,"\n");
                   7478:                
                   7479:   }
                   7480:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   7481:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   7482:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   7483:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   7484:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7485:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7486:   printf("\n");
                   7487:   fprintf(ficlog,"\n");
                   7488:        
                   7489:   free_vector(xm,1,npar);
                   7490:   free_vector(xp,1,npar);
                   7491:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   7492:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   7493:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   7494: }
                   7495:  
                   7496: /************ Variance ******************/
                   7497:  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)
                   7498:  {
                   7499:    /** Variance of health expectancies 
                   7500:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   7501:     * double **newm;
                   7502:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   7503:     */
                   7504:   
                   7505:    /* int movingaverage(); */
                   7506:    double **dnewm,**doldm;
                   7507:    double **dnewmp,**doldmp;
                   7508:    int i, j, nhstepm, hstepm, h, nstepm ;
                   7509:    int first=0;
                   7510:    int k;
                   7511:    double *xp;
                   7512:    double **gp, **gm;  /**< for var eij */
                   7513:    double ***gradg, ***trgradg; /**< for var eij */
                   7514:    double **gradgp, **trgradgp; /**< for var p point j */
                   7515:    double *gpp, *gmp; /**< for var p point j */
                   7516:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
                   7517:    double ***p3mat;
                   7518:    double age,agelim, hf;
                   7519:    /* double ***mobaverage; */
                   7520:    int theta;
                   7521:    char digit[4];
                   7522:    char digitp[25];
                   7523: 
                   7524:    char fileresprobmorprev[FILENAMELENGTH];
                   7525: 
                   7526:    if(popbased==1){
                   7527:      if(mobilav!=0)
                   7528:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   7529:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   7530:    }
                   7531:    else 
                   7532:      strcpy(digitp,"-STABLBASED_");
                   7533: 
                   7534:    /* if (mobilav!=0) { */
                   7535:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7536:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   7537:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   7538:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   7539:    /*   } */
                   7540:    /* } */
                   7541: 
                   7542:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   7543:    sprintf(digit,"%-d",ij);
                   7544:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   7545:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   7546:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   7547:    strcat(fileresprobmorprev,fileresu);
                   7548:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   7549:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   7550:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   7551:    }
                   7552:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   7553:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   7554:    pstamp(ficresprobmorprev);
                   7555:    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);
                   7556:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   7557: 
                   7558:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   7559:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   7560:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   7561:    /* } */
                   7562:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
                   7563:      /* fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); */
                   7564:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   7565:    }
                   7566:    /* for(j=1;j<=cptcoveff;j++)  */
                   7567:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
                   7568:    fprintf(ficresprobmorprev,"\n");
                   7569: 
                   7570:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   7571:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7572:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   7573:      for(i=1; i<=nlstate;i++)
                   7574:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   7575:    }  
                   7576:    fprintf(ficresprobmorprev,"\n");
                   7577:   
                   7578:    fprintf(ficgp,"\n# Routine varevsij");
                   7579:    fprintf(ficgp,"\nunset title \n");
                   7580:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   7581:    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");
                   7582:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   7583: 
                   7584:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7585:    pstamp(ficresvij);
                   7586:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   7587:    if(popbased==1)
                   7588:      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);
                   7589:    else
                   7590:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   7591:    fprintf(ficresvij,"# Age");
                   7592:    for(i=1; i<=nlstate;i++)
                   7593:      for(j=1; j<=nlstate;j++)
                   7594:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   7595:    fprintf(ficresvij,"\n");
                   7596: 
                   7597:    xp=vector(1,npar);
                   7598:    dnewm=matrix(1,nlstate,1,npar);
                   7599:    doldm=matrix(1,nlstate,1,nlstate);
                   7600:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   7601:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7602: 
                   7603:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   7604:    gpp=vector(nlstate+1,nlstate+ndeath);
                   7605:    gmp=vector(nlstate+1,nlstate+ndeath);
                   7606:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   7607:   
                   7608:    if(estepm < stepm){
                   7609:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   7610:    }
                   7611:    else  hstepm=estepm;   
                   7612:    /* For example we decided to compute the life expectancy with the smallest unit */
                   7613:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   7614:       nhstepm is the number of hstepm from age to agelim 
                   7615:       nstepm is the number of stepm from age to agelim. 
                   7616:       Look at function hpijx to understand why because of memory size limitations, 
                   7617:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   7618:       survival function given by stepm (the optimization length). Unfortunately it
                   7619:       means that if the survival funtion is printed every two years of age and if
                   7620:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   7621:       results. So we changed our mind and took the option of the best precision.
                   7622:    */
                   7623:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   7624:    agelim = AGESUP;
                   7625:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7626:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7627:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   7628:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7629:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   7630:      gp=matrix(0,nhstepm,1,nlstate);
                   7631:      gm=matrix(0,nhstepm,1,nlstate);
                   7632:                
                   7633:                
                   7634:      for(theta=1; theta <=npar; theta++){
                   7635:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   7636:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7637:        }
                   7638:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   7639:        * returns into prlim .
                   7640:        */
                   7641:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
                   7642: 
                   7643:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
                   7644:        if (popbased==1) {
                   7645:         if(mobilav ==0){
                   7646:           for(i=1; i<=nlstate;i++)
                   7647:             prlim[i][i]=probs[(int)age][i][ij];
                   7648:         }else{ /* mobilav */ 
                   7649:           for(i=1; i<=nlstate;i++)
                   7650:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   7651:         }
                   7652:        }
                   7653:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
                   7654:        */                      
                   7655:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  /* Returns p3mat[i][j][h] for h=0 to nhstepm */
                   7656:        /**< And for each alive state j, sums over i \f$ w^i_x {}{h}_p^{ij}x\f$, which are the probability
                   7657:        * at horizon h in state j including mortality.
                   7658:        */
                   7659:        for(j=1; j<= nlstate; j++){
                   7660:         for(h=0; h<=nhstepm; h++){
                   7661:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   7662:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   7663:         }
                   7664:        }
                   7665:        /* Next for computing shifted+ probability of death (h=1 means
                   7666:          computed over hstepm matrices product = hstepm*stepm months) 
                   7667:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
                   7668:        */
                   7669:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7670:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   7671:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   7672:        }
                   7673:        
                   7674:        /* Again with minus shift */
                   7675:                        
                   7676:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   7677:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7678: 
                   7679:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
                   7680:                        
                   7681:        if (popbased==1) {
                   7682:         if(mobilav ==0){
                   7683:           for(i=1; i<=nlstate;i++)
                   7684:             prlim[i][i]=probs[(int)age][i][ij];
                   7685:         }else{ /* mobilav */ 
                   7686:           for(i=1; i<=nlstate;i++)
                   7687:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   7688:         }
                   7689:        }
                   7690:                        
                   7691:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
                   7692:                        
                   7693:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   7694:         for(h=0; h<=nhstepm; h++){
                   7695:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   7696:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   7697:         }
                   7698:        }
                   7699:        /* This for computing probability of death (h=1 means
                   7700:          computed over hstepm matrices product = hstepm*stepm months) 
                   7701:          as a weighted average of prlim.
                   7702:        */
                   7703:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7704:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   7705:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   7706:        }    
                   7707:        /* end shifting computations */
                   7708: 
                   7709:        /**< Computing gradient matrix at horizon h 
                   7710:        */
                   7711:        for(j=1; j<= nlstate; j++) /* vareij */
                   7712:         for(h=0; h<=nhstepm; h++){
                   7713:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   7714:         }
                   7715:        /**< Gradient of overall mortality p.3 (or p.j) 
                   7716:        */
                   7717:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
                   7718:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   7719:        }
                   7720:                        
                   7721:      } /* End theta */
                   7722:      
                   7723:      /* We got the gradient matrix for each theta and state j */               
                   7724:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   7725:                
                   7726:      for(h=0; h<=nhstepm; h++) /* veij */
                   7727:        for(j=1; j<=nlstate;j++)
                   7728:         for(theta=1; theta <=npar; theta++)
                   7729:           trgradg[h][j][theta]=gradg[h][theta][j];
                   7730:                
                   7731:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   7732:        for(theta=1; theta <=npar; theta++)
                   7733:         trgradgp[j][theta]=gradgp[theta][j];
                   7734:      /**< as well as its transposed matrix 
                   7735:       */               
                   7736:                
                   7737:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   7738:      for(i=1;i<=nlstate;i++)
                   7739:        for(j=1;j<=nlstate;j++)
                   7740:         vareij[i][j][(int)age] =0.;
                   7741: 
                   7742:      /* Computing trgradg by matcov by gradg at age and summing over h
                   7743:       * and k (nhstepm) formula 15 of article
                   7744:       * Lievre-Brouard-Heathcote
                   7745:       */
                   7746:      
                   7747:      for(h=0;h<=nhstepm;h++){
                   7748:        for(k=0;k<=nhstepm;k++){
                   7749:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   7750:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   7751:         for(i=1;i<=nlstate;i++)
                   7752:           for(j=1;j<=nlstate;j++)
                   7753:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   7754:        }
                   7755:      }
                   7756:                
                   7757:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   7758:       * p.j overall mortality formula 49 but computed directly because
                   7759:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   7760:       * wix is independent of theta.
                   7761:       */
                   7762:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   7763:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   7764:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   7765:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   7766:         varppt[j][i]=doldmp[j][i];
                   7767:      /* end ppptj */
                   7768:      /*  x centered again */
                   7769:                
                   7770:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
                   7771:                
                   7772:      if (popbased==1) {
                   7773:        if(mobilav ==0){
                   7774:         for(i=1; i<=nlstate;i++)
                   7775:           prlim[i][i]=probs[(int)age][i][ij];
                   7776:        }else{ /* mobilav */ 
                   7777:         for(i=1; i<=nlstate;i++)
                   7778:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   7779:        }
                   7780:      }
                   7781:                
                   7782:      /* This for computing probability of death (h=1 means
                   7783:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   7784:        as a weighted average of prlim.
                   7785:      */
                   7786:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
                   7787:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   7788:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   7789:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   7790:      }    
                   7791:      /* end probability of death */
                   7792:                
                   7793:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   7794:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   7795:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   7796:        for(i=1; i<=nlstate;i++){
                   7797:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   7798:        }
                   7799:      } 
                   7800:      fprintf(ficresprobmorprev,"\n");
                   7801:                
                   7802:      fprintf(ficresvij,"%.0f ",age );
                   7803:      for(i=1; i<=nlstate;i++)
                   7804:        for(j=1; j<=nlstate;j++){
                   7805:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   7806:        }
                   7807:      fprintf(ficresvij,"\n");
                   7808:      free_matrix(gp,0,nhstepm,1,nlstate);
                   7809:      free_matrix(gm,0,nhstepm,1,nlstate);
                   7810:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   7811:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   7812:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7813:    } /* End age */
                   7814:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   7815:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   7816:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   7817:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   7818:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   7819:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   7820:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   7821:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   7822:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   7823:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   7824:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7825:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   7826:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   7827:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   7828:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   7829:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   7830:    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);
                   7831:    /*  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);
                   7832:     */
                   7833:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   7834:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   7835: 
                   7836:    free_vector(xp,1,npar);
                   7837:    free_matrix(doldm,1,nlstate,1,nlstate);
                   7838:    free_matrix(dnewm,1,nlstate,1,npar);
                   7839:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7840:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   7841:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   7842:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7843:    fclose(ficresprobmorprev);
                   7844:    fflush(ficgp);
                   7845:    fflush(fichtm); 
                   7846:  }  /* end varevsij */
                   7847: 
                   7848: /************ Variance of prevlim ******************/
                   7849:  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)
                   7850: {
                   7851:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   7852:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   7853: 
                   7854:   double **dnewmpar,**doldm;
                   7855:   int i, j, nhstepm, hstepm;
                   7856:   double *xp;
                   7857:   double *gp, *gm;
                   7858:   double **gradg, **trgradg;
                   7859:   double **mgm, **mgp;
                   7860:   double age,agelim;
                   7861:   int theta;
                   7862:   
                   7863:   pstamp(ficresvpl);
                   7864:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
                   7865:   fprintf(ficresvpl,"# Age ");
                   7866:   if(nresult >=1)
                   7867:     fprintf(ficresvpl," Result# ");
                   7868:   for(i=1; i<=nlstate;i++)
                   7869:       fprintf(ficresvpl," %1d-%1d",i,i);
                   7870:   fprintf(ficresvpl,"\n");
                   7871: 
                   7872:   xp=vector(1,npar);
                   7873:   dnewmpar=matrix(1,nlstate,1,npar);
                   7874:   doldm=matrix(1,nlstate,1,nlstate);
                   7875:   
                   7876:   hstepm=1*YEARM; /* Every year of age */
                   7877:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7878:   agelim = AGESUP;
                   7879:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   7880:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7881:     if (stepm >= YEARM) hstepm=1;
                   7882:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7883:     gradg=matrix(1,npar,1,nlstate);
                   7884:     mgp=matrix(1,npar,1,nlstate);
                   7885:     mgm=matrix(1,npar,1,nlstate);
                   7886:     gp=vector(1,nlstate);
                   7887:     gm=vector(1,nlstate);
                   7888: 
                   7889:     for(theta=1; theta <=npar; theta++){
                   7890:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7891:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7892:       }
                   7893:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7894:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7895:       /* else */
                   7896:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
                   7897:       for(i=1;i<=nlstate;i++){
                   7898:        gp[i] = prlim[i][i];
                   7899:        mgp[theta][i] = prlim[i][i];
                   7900:       }
                   7901:       for(i=1; i<=npar; i++) /* Computes gradient */
                   7902:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7903:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   7904:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   7905:       /* else */
                   7906:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
                   7907:       for(i=1;i<=nlstate;i++){
                   7908:        gm[i] = prlim[i][i];
                   7909:        mgm[theta][i] = prlim[i][i];
                   7910:       }
                   7911:       for(i=1;i<=nlstate;i++)
                   7912:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   7913:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   7914:     } /* End theta */
                   7915: 
                   7916:     trgradg =matrix(1,nlstate,1,npar);
                   7917: 
                   7918:     for(j=1; j<=nlstate;j++)
                   7919:       for(theta=1; theta <=npar; theta++)
                   7920:        trgradg[j][theta]=gradg[theta][j];
                   7921:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7922:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7923:     /*   for(j=1; j<=nlstate;j++){ */
                   7924:     /*         printf(" %d ",j); */
                   7925:     /*         for(theta=1; theta <=npar; theta++) */
                   7926:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7927:     /*         printf("\n "); */
                   7928:     /*   } */
                   7929:     /* } */
                   7930:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7931:     /*   printf("\n gradg %d ",(int)age); */
                   7932:     /*   for(j=1; j<=nlstate;j++){ */
                   7933:     /*         printf("%d ",j); */
                   7934:     /*         for(theta=1; theta <=npar; theta++) */
                   7935:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7936:     /*         printf("\n "); */
                   7937:     /*   } */
                   7938:     /* } */
                   7939: 
                   7940:     for(i=1;i<=nlstate;i++)
                   7941:       varpl[i][(int)age] =0.;
                   7942:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7943:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7944:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7945:     }else{
                   7946:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7947:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7948:     }
                   7949:     for(i=1;i<=nlstate;i++)
                   7950:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7951: 
                   7952:     fprintf(ficresvpl,"%.0f ",age );
                   7953:     if(nresult >=1)
                   7954:       fprintf(ficresvpl,"%d ",nres );
                   7955:     for(i=1; i<=nlstate;i++){
                   7956:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   7957:       /* for(j=1;j<=nlstate;j++) */
                   7958:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   7959:     }
                   7960:     fprintf(ficresvpl,"\n");
                   7961:     free_vector(gp,1,nlstate);
                   7962:     free_vector(gm,1,nlstate);
                   7963:     free_matrix(mgm,1,npar,1,nlstate);
                   7964:     free_matrix(mgp,1,npar,1,nlstate);
                   7965:     free_matrix(gradg,1,npar,1,nlstate);
                   7966:     free_matrix(trgradg,1,nlstate,1,npar);
                   7967:   } /* End age */
                   7968: 
                   7969:   free_vector(xp,1,npar);
                   7970:   free_matrix(doldm,1,nlstate,1,npar);
                   7971:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   7972: 
                   7973: }
                   7974: 
                   7975: 
                   7976: /************ Variance of backprevalence limit ******************/
                   7977:  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)
                   7978: {
                   7979:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   7980:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   7981: 
                   7982:   double **dnewmpar,**doldm;
                   7983:   int i, j, nhstepm, hstepm;
                   7984:   double *xp;
                   7985:   double *gp, *gm;
                   7986:   double **gradg, **trgradg;
                   7987:   double **mgm, **mgp;
                   7988:   double age,agelim;
                   7989:   int theta;
                   7990:   
                   7991:   pstamp(ficresvbl);
                   7992:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   7993:   fprintf(ficresvbl,"# Age ");
                   7994:   if(nresult >=1)
                   7995:     fprintf(ficresvbl," Result# ");
                   7996:   for(i=1; i<=nlstate;i++)
                   7997:       fprintf(ficresvbl," %1d-%1d",i,i);
                   7998:   fprintf(ficresvbl,"\n");
                   7999: 
                   8000:   xp=vector(1,npar);
                   8001:   dnewmpar=matrix(1,nlstate,1,npar);
                   8002:   doldm=matrix(1,nlstate,1,nlstate);
                   8003:   
                   8004:   hstepm=1*YEARM; /* Every year of age */
                   8005:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   8006:   agelim = AGEINF;
                   8007:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   8008:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   8009:     if (stepm >= YEARM) hstepm=1;
                   8010:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   8011:     gradg=matrix(1,npar,1,nlstate);
                   8012:     mgp=matrix(1,npar,1,nlstate);
                   8013:     mgm=matrix(1,npar,1,nlstate);
                   8014:     gp=vector(1,nlstate);
                   8015:     gm=vector(1,nlstate);
                   8016: 
                   8017:     for(theta=1; theta <=npar; theta++){
                   8018:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   8019:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   8020:       }
                   8021:       if(mobilavproj > 0 )
                   8022:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   8023:       else
                   8024:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   8025:       for(i=1;i<=nlstate;i++){
                   8026:        gp[i] = bprlim[i][i];
                   8027:        mgp[theta][i] = bprlim[i][i];
                   8028:       }
                   8029:      for(i=1; i<=npar; i++) /* Computes gradient */
                   8030:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   8031:        if(mobilavproj > 0 )
                   8032:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   8033:        else
                   8034:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   8035:       for(i=1;i<=nlstate;i++){
                   8036:        gm[i] = bprlim[i][i];
                   8037:        mgm[theta][i] = bprlim[i][i];
                   8038:       }
                   8039:       for(i=1;i<=nlstate;i++)
                   8040:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   8041:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   8042:     } /* End theta */
                   8043: 
                   8044:     trgradg =matrix(1,nlstate,1,npar);
                   8045: 
                   8046:     for(j=1; j<=nlstate;j++)
                   8047:       for(theta=1; theta <=npar; theta++)
                   8048:        trgradg[j][theta]=gradg[theta][j];
                   8049:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   8050:     /*   printf("\nmgm mgp %d ",(int)age); */
                   8051:     /*   for(j=1; j<=nlstate;j++){ */
                   8052:     /*         printf(" %d ",j); */
                   8053:     /*         for(theta=1; theta <=npar; theta++) */
                   8054:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   8055:     /*         printf("\n "); */
                   8056:     /*   } */
                   8057:     /* } */
                   8058:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   8059:     /*   printf("\n gradg %d ",(int)age); */
                   8060:     /*   for(j=1; j<=nlstate;j++){ */
                   8061:     /*         printf("%d ",j); */
                   8062:     /*         for(theta=1; theta <=npar; theta++) */
                   8063:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   8064:     /*         printf("\n "); */
                   8065:     /*   } */
                   8066:     /* } */
                   8067: 
                   8068:     for(i=1;i<=nlstate;i++)
                   8069:       varbpl[i][(int)age] =0.;
                   8070:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   8071:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   8072:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   8073:     }else{
                   8074:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   8075:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   8076:     }
                   8077:     for(i=1;i<=nlstate;i++)
                   8078:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   8079: 
                   8080:     fprintf(ficresvbl,"%.0f ",age );
                   8081:     if(nresult >=1)
                   8082:       fprintf(ficresvbl,"%d ",nres );
                   8083:     for(i=1; i<=nlstate;i++)
                   8084:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   8085:     fprintf(ficresvbl,"\n");
                   8086:     free_vector(gp,1,nlstate);
                   8087:     free_vector(gm,1,nlstate);
                   8088:     free_matrix(mgm,1,npar,1,nlstate);
                   8089:     free_matrix(mgp,1,npar,1,nlstate);
                   8090:     free_matrix(gradg,1,npar,1,nlstate);
                   8091:     free_matrix(trgradg,1,nlstate,1,npar);
                   8092:   } /* End age */
                   8093: 
                   8094:   free_vector(xp,1,npar);
                   8095:   free_matrix(doldm,1,nlstate,1,npar);
                   8096:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   8097: 
                   8098: }
                   8099: 
                   8100: /************ Variance of one-step probabilities  ******************/
                   8101: 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[])
                   8102:  {
                   8103:    int i, j=0,  k1, l1, tj;
                   8104:    int k2, l2, j1,  z1;
                   8105:    int k=0, l;
                   8106:    int first=1, first1, first2;
                   8107:    int nres=0; /* New */
                   8108:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   8109:    double **dnewm,**doldm;
                   8110:    double *xp;
                   8111:    double *gp, *gm;
                   8112:    double **gradg, **trgradg;
                   8113:    double **mu;
                   8114:    double age, cov[NCOVMAX+1];
                   8115:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   8116:    int theta;
                   8117:    char fileresprob[FILENAMELENGTH];
                   8118:    char fileresprobcov[FILENAMELENGTH];
                   8119:    char fileresprobcor[FILENAMELENGTH];
                   8120:    double ***varpij;
                   8121: 
                   8122:    strcpy(fileresprob,"PROB_"); 
1.2       brouard  8123:    strcat(fileresprob,fileresu);
1.1       brouard  8124:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   8125:      printf("Problem with resultfile: %s\n", fileresprob);
                   8126:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   8127:    }
                   8128:    strcpy(fileresprobcov,"PROBCOV_"); 
                   8129:    strcat(fileresprobcov,fileresu);
                   8130:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   8131:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   8132:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   8133:    }
                   8134:    strcpy(fileresprobcor,"PROBCOR_"); 
                   8135:    strcat(fileresprobcor,fileresu);
                   8136:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   8137:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   8138:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   8139:    }
                   8140:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   8141:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   8142:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   8143:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   8144:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   8145:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   8146:    pstamp(ficresprob);
                   8147:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   8148:    fprintf(ficresprob,"# Age");
                   8149:    pstamp(ficresprobcov);
                   8150:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   8151:    fprintf(ficresprobcov,"# Age");
                   8152:    pstamp(ficresprobcor);
                   8153:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   8154:    fprintf(ficresprobcor,"# Age");
                   8155: 
                   8156: 
                   8157:    for(i=1; i<=nlstate;i++)
                   8158:      for(j=1; j<=(nlstate+ndeath);j++){
                   8159:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   8160:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   8161:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   8162:      }  
                   8163:    /* fprintf(ficresprob,"\n");
                   8164:       fprintf(ficresprobcov,"\n");
                   8165:       fprintf(ficresprobcor,"\n");
                   8166:    */
                   8167:    xp=vector(1,npar);
                   8168:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   8169:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   8170:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   8171:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   8172:    first=1;
                   8173:    fprintf(ficgp,"\n# Routine varprob");
                   8174:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   8175:    fprintf(fichtm,"\n");
                   8176: 
                   8177:    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);
                   8178:    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);
                   8179:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
                   8180: and drawn. It helps understanding how is the covariance between two incidences.\
                   8181:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   8182:    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. \
                   8183: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   8184: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   8185: standard deviations wide on each axis. <br>\
                   8186:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   8187:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   8188: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   8189: 
                   8190:    cov[1]=1;
                   8191:    /* tj=cptcoveff; */
                   8192:    tj = (int) pow(2,cptcoveff);
                   8193:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   8194:    j1=0;
                   8195: 
                   8196:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   8197:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
                   8198:      /* 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); */
                   8199:      if(tj != 1 && TKresult[nres]!= j1)
                   8200:        continue;
                   8201: 
                   8202:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   8203:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   8204:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
                   8205:      if  (cptcovn>0) {
                   8206:        fprintf(ficresprob, "\n#********** Variable ");
                   8207:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   8208:        fprintf(ficgp, "\n#********** Variable ");
                   8209:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   8210:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   8211: 
                   8212:        /* Including quantitative variables of the resultline to be done */
                   8213:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
                   8214:         /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
                   8215:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   8216:         /* fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s resultline[%d]=%s \n",nres, z1, modelresult[nres][z1], model, nres, resultline[nres]); */
                   8217:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   8218:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   8219:             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  */
                   8220:             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  */
                   8221:             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  */
                   8222:             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  */
                   8223:             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  */
                   8224:             fprintf(ficresprob,"fixed ");
                   8225:             fprintf(ficresprobcov,"fixed ");
                   8226:             fprintf(ficgp,"fixed ");
                   8227:             fprintf(fichtmcov,"fixed ");
                   8228:             fprintf(ficresprobcor,"fixed ");
                   8229:           }else{
                   8230:             fprintf(ficresprob,"varyi ");
                   8231:             fprintf(ficresprobcov,"varyi ");
                   8232:             fprintf(ficgp,"varyi ");
                   8233:             fprintf(fichtmcov,"varyi ");
                   8234:             fprintf(ficresprobcor,"varyi ");
                   8235:           }
                   8236:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   8237:           /* For each selected (single) quantitative value */
                   8238:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
                   8239:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   8240:             fprintf(ficresprob,"fixed ");
                   8241:             fprintf(ficresprobcov,"fixed ");
                   8242:             fprintf(ficgp,"fixed ");
                   8243:             fprintf(fichtmcov,"fixed ");
                   8244:             fprintf(ficresprobcor,"fixed ");
                   8245:           }else{
                   8246:             fprintf(ficresprob,"varyi ");
                   8247:             fprintf(ficresprobcov,"varyi ");
                   8248:             fprintf(ficgp,"varyi ");
                   8249:             fprintf(fichtmcov,"varyi ");
                   8250:             fprintf(ficresprobcor,"varyi ");
                   8251:           }
                   8252:         }else{
                   8253:           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 */
                   8254:           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 */
                   8255:           exit(1);
                   8256:         }
                   8257:        } /* End loop on variable of this resultline */
                   8258:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
                   8259:        fprintf(ficresprob, "**********\n#\n");
                   8260:        fprintf(ficresprobcov, "**********\n#\n");
                   8261:        fprintf(ficgp, "**********\n#\n");
                   8262:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   8263:        fprintf(ficresprobcor, "**********\n#");    
                   8264:        if(invalidvarcomb[j1]){
                   8265:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   8266:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   8267:         continue;
                   8268:        }
                   8269:      }
                   8270:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   8271:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   8272:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   8273:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   8274:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
                   8275:        cov[2]=age;
                   8276:        if(nagesqr==1)
                   8277:         cov[3]= age*age;
                   8278:        /* New code end of combination but for each resultline */
                   8279:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   8280:         if(Typevar[k1]==1 || Typevar[k1] ==3){ /* A product with age */
                   8281:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   8282:         }else{
                   8283:           cov[2+nagesqr+k1]=precov[nres][k1];
                   8284:         }
                   8285:        }/* End of loop on model equation */
                   8286: /* Old code */
                   8287:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   8288:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   8289:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   8290:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   8291:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   8292:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   8293:        /*                                                                  * 1  1 1 1 1 */
                   8294:        /*                                                                  * 2  2 1 1 1 */
                   8295:        /*                                                                  * 3  1 2 1 1 */
                   8296:        /*                                                                  *\/ */
                   8297:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   8298:        /* } */
                   8299:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   8300:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   8301:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   8302:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   8303:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   8304:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   8305:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   8306:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   8307:        /*         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]); */
                   8308:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   8309:        /*         /\* exit(1); *\/ */
                   8310:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   8311:        /*       } */
                   8312:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   8313:        /* } */
                   8314:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   8315:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   8316:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   8317:        /*           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]])]; */
                   8318:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   8319:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   8320:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   8321:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   8322:        /*         } */
                   8323:        /*       }else{ */
                   8324:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   8325:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   8326:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   8327:        /*         }else{ */
                   8328:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   8329:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   8330:        /*         } */
                   8331:        /*       } */
                   8332:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   8333:        /* } */                 
                   8334: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
                   8335:        for(theta=1; theta <=npar; theta++){
                   8336:         for(i=1; i<=npar; i++)
                   8337:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   8338:                                
                   8339:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   8340:                                
                   8341:         k=0;
                   8342:         for(i=1; i<= (nlstate); i++){
                   8343:           for(j=1; j<=(nlstate+ndeath);j++){
                   8344:             k=k+1;
                   8345:             gp[k]=pmmij[i][j];
                   8346:           }
                   8347:         }
                   8348:                                
                   8349:         for(i=1; i<=npar; i++)
                   8350:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   8351:                                
                   8352:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   8353:         k=0;
                   8354:         for(i=1; i<=(nlstate); i++){
                   8355:           for(j=1; j<=(nlstate+ndeath);j++){
                   8356:             k=k+1;
                   8357:             gm[k]=pmmij[i][j];
                   8358:           }
                   8359:         }
                   8360:                                
                   8361:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   8362:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   8363:        }
                   8364: 
                   8365:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   8366:         for(theta=1; theta <=npar; theta++)
                   8367:           trgradg[j][theta]=gradg[theta][j];
                   8368:                        
                   8369:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   8370:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   8371:                        
                   8372:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   8373:                        
                   8374:        k=0;
                   8375:        for(i=1; i<=(nlstate); i++){
                   8376:         for(j=1; j<=(nlstate+ndeath);j++){
                   8377:           k=k+1;
                   8378:           mu[k][(int) age]=pmmij[i][j];
                   8379:         }
                   8380:        }
                   8381:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   8382:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   8383:           varpij[i][j][(int)age] = doldm[i][j];
                   8384:                        
                   8385:        /*printf("\n%d ",(int)age);
                   8386:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   8387:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   8388:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   8389:         }*/
                   8390:                        
                   8391:        fprintf(ficresprob,"\n%d ",(int)age);
                   8392:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   8393:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   8394:                        
                   8395:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   8396:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   8397:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   8398:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   8399:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   8400:        }
                   8401:        i=0;
                   8402:        for (k=1; k<=(nlstate);k++){
                   8403:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   8404:           i++;
                   8405:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   8406:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   8407:           for (j=1; j<=i;j++){
                   8408:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   8409:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   8410:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   8411:           }
                   8412:         }
                   8413:        }/* end of loop for state */
                   8414:      } /* end of loop for age */
                   8415:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   8416:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   8417:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   8418:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   8419:     
                   8420:      /* Confidence intervalle of pij  */
                   8421:      /*
                   8422:        fprintf(ficgp,"\nunset parametric;unset label");
                   8423:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   8424:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   8425:        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);
                   8426:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   8427:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   8428:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   8429:      */
                   8430:                
                   8431:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   8432:      first1=1;first2=2;
                   8433:      for (k2=1; k2<=(nlstate);k2++){
                   8434:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   8435:         if(l2==k2) continue;
                   8436:         j=(k2-1)*(nlstate+ndeath)+l2;
                   8437:         for (k1=1; k1<=(nlstate);k1++){
                   8438:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   8439:             if(l1==k1) continue;
                   8440:             i=(k1-1)*(nlstate+ndeath)+l1;
                   8441:             if(i<=j) continue;
                   8442:             for (age=bage; age<=fage; age ++){ 
                   8443:               if ((int)age %5==0){
                   8444:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   8445:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   8446:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   8447:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   8448:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   8449:                 c12=cv12/sqrt(v1*v2);
                   8450:                 /* Computing eigen value of matrix of covariance */
                   8451:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   8452:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   8453:                 if ((lc2 <0) || (lc1 <0) ){
                   8454:                   if(first2==1){
                   8455:                     first1=0;
                   8456:                     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);
                   8457:                   }
                   8458:                   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);
                   8459:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   8460:                   /* lc2=fabs(lc2); */
                   8461:                 }
                   8462:                                                                
                   8463:                 /* Eigen vectors */
                   8464:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   8465:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   8466:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   8467:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   8468:                 }else
                   8469:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   8470:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   8471:                 v21=(lc1-v1)/cv12*v11;
                   8472:                 v12=-v21;
                   8473:                 v22=v11;
                   8474:                 tnalp=v21/v11;
                   8475:                 if(first1==1){
                   8476:                   first1=0;
                   8477:                   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);
                   8478:                 }
                   8479:                 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);
                   8480:                 /*printf(fignu*/
                   8481:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   8482:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   8483:                 if(first==1){
                   8484:                   first=0;
                   8485:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   8486:                   fprintf(ficgp,"\nset parametric;unset label");
                   8487:                   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);
                   8488:                   fprintf(ficgp,"\nset ter svg size 640, 480");
                   8489:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
                   8490:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
                   8491: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
                   8492:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   8493:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   8494:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   8495:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   8496:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   8497:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   8498:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   8499:                   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",      \
                   8500:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   8501:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
                   8502:                 }else{
                   8503:                   first=0;
                   8504:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   8505:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   8506:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   8507:                   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", \
                   8508:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   8509:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
                   8510:                 }/* if first */
                   8511:               } /* age mod 5 */
                   8512:             } /* end loop age */
                   8513:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   8514:             first=1;
                   8515:           } /*l12 */
                   8516:         } /* k12 */
                   8517:        } /*l1 */
                   8518:      }/* k1 */
                   8519:    }  /* loop on combination of covariates j1 */
                   8520:    } /* loop on nres */
                   8521:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   8522:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   8523:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   8524:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   8525:    free_vector(xp,1,npar);
                   8526:    fclose(ficresprob);
                   8527:    fclose(ficresprobcov);
                   8528:    fclose(ficresprobcor);
                   8529:    fflush(ficgp);
                   8530:    fflush(fichtmcov);
                   8531:  }
                   8532: 
                   8533: 
                   8534: /******************* Printing html file ***********/
                   8535: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
                   8536:                  int lastpass, int stepm, int weightopt, char model[],\
                   8537:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   8538:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   8539:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   8540:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
                   8541:   int jj1, k1, i1, cpt, k4, nres;
                   8542:   /* In fact some results are already printed in fichtm which is open */
                   8543:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   8544:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   8545: </ul>");
                   8546: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   8547: /* </ul>", model); */
                   8548:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   8549:    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",
                   8550:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   8551:    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) ",
                   8552:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   8553:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
                   8554:    fprintf(fichtm,"\
                   8555:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   8556:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
                   8557:    fprintf(fichtm,"\
                   8558:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   8559:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   8560:    fprintf(fichtm,"\
                   8561:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   8562:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
                   8563:    fprintf(fichtm,"\
                   8564:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   8565:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   8566:    fprintf(fichtm,"\
                   8567:  - (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): \
                   8568:    <a href=\"%s\">%s</a> <br>\n",
                   8569:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
                   8570:    if(prevfcast==1){
                   8571:      fprintf(fichtm,"\
                   8572:  - Prevalence projections by age and states:                           \
                   8573:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
                   8574:    }
                   8575: 
                   8576: 
                   8577:    m=pow(2,cptcoveff);
                   8578:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   8579: 
                   8580:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
                   8581: 
                   8582:    jj1=0;
                   8583: 
                   8584:    fprintf(fichtm," \n<ul>");
                   8585:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8586:      /* k1=nres; */
                   8587:      k1=TKresult[nres];
                   8588:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
                   8589:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8590:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   8591:    /*     continue; */
                   8592:      jj1++;
                   8593:      if (cptcovn > 0) {
                   8594:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
                   8595:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   8596:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8597:        }
                   8598:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   8599:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   8600:        /* } */
                   8601:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8602:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8603:        /* } */
                   8604:        fprintf(fichtm,"\">");
                   8605:        
                   8606:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8607:        fprintf(fichtm,"************ Results for covariates");
                   8608:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8609:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8610:        }
                   8611:        /* fprintf(fichtm,"************ Results for covariates"); */
                   8612:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   8613:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   8614:        /* } */
                   8615:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8616:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8617:        /* } */
                   8618:        if(invalidvarcomb[k1]){
                   8619:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8620:         continue;
                   8621:        }
                   8622:        fprintf(fichtm,"</a></li>");
                   8623:      } /* cptcovn >0 */
                   8624:    }
                   8625:    fprintf(fichtm," \n</ul>");
                   8626: 
                   8627:    jj1=0;
                   8628: 
                   8629:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8630:      /* k1=nres; */
                   8631:      k1=TKresult[nres];
                   8632:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
                   8633:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8634:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   8635:    /*     continue; */
                   8636: 
                   8637:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8638:      jj1++;
                   8639:      if (cptcovn > 0) {
                   8640:        fprintf(fichtm,"\n<p><a name=\"rescov");
                   8641:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8642:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8643:        }
                   8644:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8645:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8646:        /* } */
                   8647:        fprintf(fichtm,"\"</a>");
                   8648:  
                   8649:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   8650:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8651:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8652:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8653:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   8654:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
                   8655:        }
                   8656:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8657:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
                   8658:        if(invalidvarcomb[k1]){
                   8659:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   8660:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   8661:         continue;
                   8662:        }
                   8663:      }
                   8664:      /* aij, bij */
                   8665:      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> \
                   8666: <img src=\"%s_%d-1-%d.svg\">",model,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres);
                   8667:      /* Pij */
                   8668:      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> \
                   8669: <img src=\"%s_%d-2-%d.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres);     
                   8670:      /* Quasi-incidences */
                   8671:      fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
                   8672:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
                   8673:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
                   8674: 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> \
                   8675: <img src=\"%s_%d-3-%d.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres); 
                   8676:      /* Survival functions (period) in state j */
                   8677:      for(cpt=1; cpt<=nlstate;cpt++){
1.5     ! brouard  8678:        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. Mean times spent in state (or Life Expectancy or Health Expectancy etc.) are the areas under each curve. <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);
1.1       brouard  8679:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   8680:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
                   8681:      }
                   8682:      /* State specific survival functions (period) */
                   8683:      for(cpt=1; cpt<=nlstate;cpt++){
                   8684:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
1.5     ! brouard  8685:  And probability to be observed in various states (up to %d) being in state %d at different ages.  Mean times spent in state (or Life Expectancy or Health Expectancy etc.) are the areas under each curve. \
1.1       brouard  8686:  <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);
                   8687:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   8688:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
                   8689:      }
                   8690:      /* Period (forward stable) prevalence in each health state */
                   8691:      for(cpt=1; cpt<=nlstate;cpt++){
1.5     ! brouard  8692:        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 alive 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);
1.1       brouard  8693:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   8694:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
                   8695:      }
                   8696:      if(prevbcast==1){
                   8697:        /* Backward prevalence in each health state */
                   8698:        for(cpt=1; cpt<=nlstate;cpt++){
                   8699:         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);
                   8700:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   8701:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
                   8702:        }
                   8703:      }
                   8704:      if(prevfcast==1){
                   8705:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
                   8706:        for(cpt=1; cpt<=nlstate;cpt++){
                   8707:         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);
                   8708:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   8709:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   8710:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
                   8711:        }
                   8712:      }
                   8713:      if(prevbcast==1){
                   8714:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   8715:        for(cpt=1; cpt<=nlstate;cpt++){
                   8716:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
1.5     ! brouard  8717:  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 \
        !          8718:  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) \
1.1       brouard  8719: 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);
                   8720:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   8721:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   8722:        }
                   8723:      }
                   8724:         
                   8725:      for(cpt=1; cpt<=nlstate;cpt++) {
                   8726:        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);
                   8727:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   8728:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
                   8729:      }
                   8730:      /* } /\* end i1 *\/ */
                   8731:    }/* End k1=nres */
                   8732:    fprintf(fichtm,"</ul>");
                   8733: 
                   8734:    fprintf(fichtm,"\
                   8735: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
                   8736:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
                   8737:  - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
                   8738: But because parameters are usually highly correlated (a higher incidence of disability \
                   8739: and a higher incidence of recovery can give very close observed transition) it might \
                   8740: be very useful to look not only at linear confidence intervals estimated from the \
                   8741: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   8742: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   8743: covariance matrix of the one-step probabilities. \
                   8744: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
                   8745: 
                   8746:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   8747:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   8748:    fprintf(fichtm,"\
                   8749:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   8750:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
                   8751: 
                   8752:    fprintf(fichtm,"\
                   8753:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   8754:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   8755:    fprintf(fichtm,"\
                   8756:  - 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): \
                   8757:    <a href=\"%s\">%s</a> <br>\n</li>",
                   8758:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
                   8759:    fprintf(fichtm,"\
                   8760:  - (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): \
                   8761:    <a href=\"%s\">%s</a> <br>\n</li>",
                   8762:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
                   8763:    fprintf(fichtm,"\
                   8764:  - 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",
                   8765:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   8766:    fprintf(fichtm,"\
                   8767:  - 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",
                   8768:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   8769:    fprintf(fichtm,"\
                   8770:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
                   8771:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   8772: 
                   8773: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   8774: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   8775: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   8776: /*     <br>",fileres,fileres,fileres,fileres); */
                   8777: /*  else  */
                   8778: /*    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); */
                   8779:    fflush(fichtm);
                   8780: 
                   8781:    m=pow(2,cptcoveff);
                   8782:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   8783: 
                   8784:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   8785: 
                   8786:   jj1=0;
                   8787: 
                   8788:    fprintf(fichtm," \n<ul>");
                   8789:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8790:      /* k1=nres; */
                   8791:      k1=TKresult[nres];
                   8792:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   8793:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8794:      /*   continue; */
                   8795:      jj1++;
                   8796:      if (cptcovn > 0) {
                   8797:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
                   8798:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8799:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8800:        }
                   8801:        fprintf(fichtm,"\">");
                   8802:        
                   8803:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   8804:        fprintf(fichtm,"************ Results for covariates");
                   8805:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8806:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8807:        }
                   8808:        if(invalidvarcomb[k1]){
                   8809:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   8810:         continue;
                   8811:        }
                   8812:        fprintf(fichtm,"</a></li>");
                   8813:      } /* cptcovn >0 */
                   8814:    } /* End nres */
                   8815:    fprintf(fichtm," \n</ul>");
                   8816: 
                   8817:    jj1=0;
                   8818: 
                   8819:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   8820:      /* k1=nres; */
                   8821:      k1=TKresult[nres];
                   8822:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
                   8823:      /* for(k1=1; k1<=m;k1++){ */
                   8824:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8825:      /*   continue; */
                   8826:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   8827:      jj1++;
                   8828:      if (cptcovn > 0) {
                   8829:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
                   8830:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   8831:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8832:        }
                   8833:        fprintf(fichtm,"\"</a>");
                   8834:        
                   8835:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   8836:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   8837:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8838:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   8839:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   8840:        }
                   8841: 
                   8842:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
                   8843: 
                   8844:        if(invalidvarcomb[k1]){
                   8845:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   8846:         continue;
                   8847:        }
                   8848:      } /* If cptcovn >0 */
                   8849:      for(cpt=1; cpt<=nlstate;cpt++) {
                   8850:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
                   8851: 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);
                   8852:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   8853:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
                   8854:      }
                   8855:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
                   8856: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
                   8857: true period expectancies (those weighted with period prevalences are also\
                   8858:  drawn in addition to the population based expectancies computed using\
                   8859:  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);
                   8860:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   8861:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
                   8862:      /* } /\* end i1 *\/ */
                   8863:   }/* End nres */
                   8864:    fprintf(fichtm,"</ul>");
                   8865:    fflush(fichtm);
                   8866: }
                   8867: 
                   8868: /******************* Gnuplot file **************/
                   8869: 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){
                   8870: 
                   8871:   char dirfileres[256],optfileres[256];
                   8872:   char gplotcondition[256], gplotlabel[256];
                   8873:   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;
                   8874:   int lv=0, vlv=0, kl=0;
                   8875:   int ng=0;
                   8876:   int vpopbased;
                   8877:   int ioffset; /* variable offset for columns */
                   8878:   int iyearc=1; /* variable column for year of projection  */
                   8879:   int iagec=1; /* variable column for age of projection  */
                   8880:   int nres=0; /* Index of resultline */
                   8881:   int istart=1; /* For starting graphs in projections */
                   8882: 
                   8883: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   8884: /*     printf("Problem with file %s",optionfilegnuplot); */
                   8885: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   8886: /*   } */
                   8887: 
                   8888:   /*#ifdef windows */
                   8889:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   8890:   /*#endif */
                   8891:   m=pow(2,cptcoveff);
                   8892: 
                   8893:   /* diagram of the model */
                   8894:   fprintf(ficgp,"\n#Diagram of the model \n");
                   8895:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   8896:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   8897:   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);
                   8898: 
                   8899:   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);
                   8900:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   8901:   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);
                   8902:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   8903:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   8904:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   8905:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   8906: 
                   8907:   /* Contribution to likelihood */
                   8908:   /* Plot the probability implied in the likelihood */
                   8909:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   8910:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   8911:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   8912:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   8913: /* nice for mle=4 plot by number of matrix products.
                   8914:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   8915: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
                   8916:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   8917:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8918:   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));
                   8919:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8920:   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));
                   8921:   for (i=1; i<= nlstate ; i ++) {
                   8922:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   8923:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   8924:     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);
                   8925:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   8926:       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);
                   8927:     }
                   8928:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8929:   }
                   8930:   /* 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 */               
                   8931:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8932:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8933:   fprintf(ficgp,"\nset out;unset log\n");
                   8934:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   8935: 
                   8936:   /* Plot the probability implied in the likelihood by covariate value */
                   8937:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   8938:   /* if(debugILK==1){ */
                   8939:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
                   8940:     kvar=Tvar[TvarFind[kf]]; /* variable name */
                   8941:     /* k=18+Tvar[TvarFind[kf]];/\*offset because there are 18 columns in the ILK_ file but could be placed else where *\/ */
1.2       brouard  8942:     /* k=18+kf;/\*offset because there are 18 columns in the ILK_ file *\/ */
                   8943:     /* k=19+kf;/\*offset because there are 19 columns in the ILK_ file *\/ */
                   8944:     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  8945:     for (i=1; i<= nlstate ; i ++) {
                   8946:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8947:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   8948:       if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8949:        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);
                   8950:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   8951:          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);
                   8952:        }
                   8953:       }else{
                   8954:        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);
                   8955:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   8956:          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);
                   8957:        }
                   8958:       }
                   8959:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8960:     }
                   8961:   } /* End of each covariate dummy */
                   8962:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
                   8963:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   8964:      *     kmodel       =     1   2     3     4         5        6        7       8        9
                   8965:      *  varying                   1     2                                 3       4        5
                   8966:      *  ncovv                     1     2                                3 4     5 6      7 8
                   8967:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
                   8968:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
                   8969:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
                   8970:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
                   8971:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
                   8972:      */
                   8973:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   8974:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   8975:     /* 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]); */
                   8976:     if(ipos!=iposold){ /* Not a product or first of a product */
                   8977:       /* printf(" %d",ipos); */
                   8978:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   8979:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
                   8980:       kk++; /* Position of the ncovv column in ILK_ */
                   8981:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
                   8982:       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)  */
                   8983:        for (i=1; i<= nlstate ; i ++) {
                   8984:          fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   8985:          fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   8986: 
                   8987:            /* printf("Before DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
                   8988:          if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   8989:            /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
                   8990:            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);
                   8991:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8992:              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);
                   8993:            }
                   8994:          }else{
                   8995:            /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
                   8996:            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);
                   8997:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   8998:              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);
                   8999:            }
                   9000:          }
                   9001:          fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   9002:        }
                   9003:       }/* End if dummy varying */
                   9004:     }else{ /*Product */
                   9005:       /* printf("*"); */
                   9006:       /* fprintf(ficresilk,"*"); */
                   9007:     }
                   9008:     iposold=ipos;
                   9009:   } /* For each time varying covariate */
                   9010:   /* } /\* debugILK==1 *\/ */
                   9011:   /* 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 */               
                   9012:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   9013:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   9014:   fprintf(ficgp,"\nset out;unset log\n");
                   9015:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   9016: 
                   9017: 
                   9018:   
                   9019:   strcpy(dirfileres,optionfilefiname);
                   9020:   strcpy(optfileres,"vpl");
                   9021:   /* 1eme*/
                   9022:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   9023:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
                   9024:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9025:        k1=TKresult[nres];
                   9026:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
                   9027:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   9028:        /* if(m != 1 && TKresult[nres]!= k1) */
                   9029:        /*   continue; */
                   9030:        /* We are interested in selected combination by the resultline */
                   9031:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
                   9032:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
                   9033:        strcpy(gplotlabel,"(");
                   9034:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9035:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9036:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9037: 
                   9038:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   9039:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   9040:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9041:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9042:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9043:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9044:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   9045:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   9046:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   9047:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9048:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9049:        /* } */
                   9050:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9051:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   9052:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9053:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9054:        }
                   9055:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   9056:        /* printf("\n#\n"); */
                   9057:        fprintf(ficgp,"\n#\n");
                   9058:        if(invalidvarcomb[k1]){
                   9059:           /*k1=k1-1;*/ /* To be checked */
                   9060:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9061:          continue;
                   9062:        }
                   9063:       
                   9064:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   9065:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
                   9066:        /* fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel); */
                   9067:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
                   9068:        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);
                   9069:        /* 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); */
                   9070:       /* k1-1 error should be nres-1*/
                   9071:        for (i=1; i<= nlstate ; i ++) {
                   9072:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   9073:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   9074:        }
                   9075:        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);
                   9076:        for (i=1; i<= nlstate ; i ++) {
                   9077:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   9078:          else fprintf(ficgp," %%*lf (%%*lf)");
                   9079:        } 
                   9080:        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); 
                   9081:        for (i=1; i<= nlstate ; i ++) {
                   9082:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   9083:          else fprintf(ficgp," %%*lf (%%*lf)");
                   9084:        }  
                   9085:        /* 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)); */
                   9086:        
                   9087:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   9088:         if(cptcoveff ==0){
                   9089:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
                   9090:        }else{
                   9091:          kl=0;
                   9092:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   9093:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   9094:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
                   9095:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9096:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9097:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   9098:            vlv= nbcode[Tvaraff[k]][lv];
                   9099:            kl++;
                   9100:            /* 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 *\/ */
                   9101:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9102:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9103:            /* ''  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*/
                   9104:            if(k==cptcoveff){
                   9105:              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], \
                   9106:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   9107:            }else{
                   9108:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   9109:              kl++;
                   9110:            }
                   9111:          } /* end covariate */
                   9112:        } /* end if no covariate */
                   9113: 
                   9114:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
                   9115:          /* 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); */
                   9116:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
                   9117:          if(cptcoveff ==0){
                   9118:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
                   9119:          }else{
                   9120:            kl=0;
                   9121:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   9122:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   9123:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
                   9124:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9125:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9126:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   9127:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   9128:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
                   9129:              kl++;
                   9130:              /* 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 *\/ */
                   9131:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9132:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9133:              /* ''  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*/
                   9134:              if(k==cptcoveff){
                   9135:                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], \
                   9136:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
                   9137:              }else{
                   9138:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
                   9139:                kl++;
                   9140:              }
                   9141:            } /* end covariate */
                   9142:          } /* end if no covariate */
                   9143:          if(prevbcast == 1){
                   9144:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   9145:            /* k1-1 error should be nres-1*/
                   9146:            for (i=1; i<= nlstate ; i ++) {
                   9147:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   9148:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   9149:            }
                   9150:            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);
                   9151:            for (i=1; i<= nlstate ; i ++) {
                   9152:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   9153:              else fprintf(ficgp," %%*lf (%%*lf)");
                   9154:            } 
                   9155:            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); 
                   9156:            for (i=1; i<= nlstate ; i ++) {
                   9157:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   9158:              else fprintf(ficgp," %%*lf (%%*lf)");
                   9159:            } 
                   9160:            fprintf(ficgp,"\" t\"\" w l lt 4");
                   9161:          } /* end if backprojcast */
                   9162:        } /* end if prevbcast */
                   9163:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   9164:        fprintf(ficgp,"\nset out ;unset title;\n");
                   9165:       } /* nres */
                   9166:     /* } /\* k1 *\/ */
                   9167:   } /* cpt */
                   9168: 
                   9169:   
                   9170:   /*2 eme*/
                   9171:   /* for (k1=1; k1<= m ; k1 ++){   */
                   9172:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9173:       k1=TKresult[nres];
                   9174:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
                   9175:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9176:       /*       continue; */
                   9177:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
                   9178:       strcpy(gplotlabel,"(");
                   9179:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9180:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9181:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9182:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   9183:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   9184:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9185:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9186:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9187:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9188:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9189:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9190:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9191:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9192:       /* } */
                   9193:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   9194:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9195:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9196:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9197:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9198:       }
                   9199:       strcpy(gplotlabel+strlen(gplotlabel),")");
                   9200:       fprintf(ficgp,"\n#\n");
                   9201:       if(invalidvarcomb[k1]){
                   9202:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9203:        continue;
                   9204:       }
                   9205:                        
                   9206:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
                   9207:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   9208:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   9209:        if(vpopbased==0){
                   9210:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   9211:        }else
                   9212:          fprintf(ficgp,"\nreplot ");
                   9213:        for (i=1; i<= nlstate+1 ; i ++) {
                   9214:          k=2*i;
                   9215:          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);
                   9216:          for (j=1; j<= nlstate+1 ; j ++) {
                   9217:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   9218:            else fprintf(ficgp," %%*lf (%%*lf)");
                   9219:          }   
                   9220:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   9221:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   9222:          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);
                   9223:          for (j=1; j<= nlstate+1 ; j ++) {
                   9224:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   9225:            else fprintf(ficgp," %%*lf (%%*lf)");
                   9226:          }   
                   9227:          fprintf(ficgp,"\" t\"\" w l lt 0,");
                   9228:          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);
                   9229:          for (j=1; j<= nlstate+1 ; j ++) {
                   9230:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   9231:            else fprintf(ficgp," %%*lf (%%*lf)");
                   9232:          }   
                   9233:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   9234:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   9235:        } /* state */
                   9236:       } /* vpopbased */
                   9237:       fprintf(ficgp,"\nset out;set out \"%s_%d-%d.svg\"; replot; set out; unset label;\n",subdirf2(optionfilefiname,"E_"),k1,nres); /* Buggy gnuplot */
                   9238:     } /* end nres */
                   9239:   /* } /\* k1 end 2 eme*\/ */
                   9240:        
                   9241:        
                   9242:   /*3eme*/
                   9243:   /* for (k1=1; k1<= m ; k1 ++){ */
                   9244:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9245:       k1=TKresult[nres];
                   9246:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
                   9247:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9248:       /*       continue; */
                   9249: 
                   9250:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
                   9251:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
                   9252:        strcpy(gplotlabel,"(");
                   9253:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9254:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9255:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9256:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   9257:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   9258:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9259:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9260:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9261:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9262:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9263:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9264:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9265:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9266:        /* } */
                   9267:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9268:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   9269:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   9270:        }
                   9271:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   9272:        fprintf(ficgp,"\n#\n");
                   9273:        if(invalidvarcomb[k1]){
                   9274:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9275:          continue;
                   9276:        }
                   9277:                        
                   9278:        /*       k=2+nlstate*(2*cpt-2); */
                   9279:        k=2+(nlstate+1)*(cpt-1);
                   9280:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
                   9281:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
                   9282:        fprintf(ficgp,"set ter svg size 640, 480\n\
                   9283: 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);
                   9284:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   9285:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   9286:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   9287:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   9288:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   9289:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   9290:                                
                   9291:        */
                   9292:        for (i=1; i< nlstate ; i ++) {
                   9293:          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);
                   9294:          /*    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);*/
                   9295:                                
                   9296:        } 
                   9297:        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),nres-1,nres-1,k+nlstate,cpt);
                   9298:       }
                   9299:       fprintf(ficgp,"\nunset label;\n");
                   9300:     } /* end nres */
                   9301:   /* } /\* end kl 3eme *\/ */
                   9302:   
                   9303:   /* 4eme */
                   9304:   /* Survival functions (period) from state i in state j by initial state i */
                   9305:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
                   9306:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9307:       k1=TKresult[nres];
                   9308:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
                   9309:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9310:       /*       continue; */
                   9311:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
                   9312:        strcpy(gplotlabel,"(");
                   9313:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   9314:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9315:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9316:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9317:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   9318:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9319:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   9320:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9321:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9322:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9323:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9324:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9325:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9326:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9327:        /* } */
                   9328:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9329:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9330:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9331:        }       
                   9332:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   9333:        fprintf(ficgp,"\n#\n");
                   9334:        if(invalidvarcomb[k1]){
                   9335:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9336:          continue;
                   9337:        }
                   9338:       
                   9339:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
                   9340:        fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   9341:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   9342: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   9343:        k=3;
                   9344:        for (i=1; i<= nlstate ; i ++){
                   9345:          if(i==1){
                   9346:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   9347:          }else{
                   9348:            fprintf(ficgp,", '' ");
                   9349:          }
                   9350:          l=(nlstate+ndeath)*(i-1)+1;
                   9351:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   9352:          for (j=2; j<= nlstate+ndeath ; j ++)
                   9353:            fprintf(ficgp,"+$%d",k+l+j-1);
                   9354:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   9355:        } /* nlstate */
                   9356:        fprintf(ficgp,"\nset out; unset label;\n");
                   9357:       } /* end cpt state*/ 
                   9358:     } /* end nres */
                   9359:   /* } /\* end covariate k1 *\/   */
                   9360: 
                   9361: /* 5eme */
                   9362:   /* Survival functions (period) from state i in state j by final state j */
                   9363:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
                   9364:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9365:       k1=TKresult[nres];
                   9366:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
                   9367:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9368:       /*       continue; */
                   9369:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
                   9370:        strcpy(gplotlabel,"(");
                   9371:        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);
                   9372:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9373:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9374:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9375:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   9376:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9377:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   9378:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9379:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9380:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9381:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9382:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9383:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9384:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9385:        /* } */
                   9386:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9387:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9388:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9389:        }       
                   9390:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   9391:        fprintf(ficgp,"\n#\n");
                   9392:        if(invalidvarcomb[k1]){
                   9393:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9394:          continue;
                   9395:        }
                   9396:       
                   9397:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
                   9398:        fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   9399:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   9400: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   9401:        k=3;
                   9402:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   9403:          if(j==1)
                   9404:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   9405:          else
                   9406:            fprintf(ficgp,", '' ");
                   9407:          l=(nlstate+ndeath)*(cpt-1) +j;
                   9408:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   9409:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   9410:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   9411:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   9412:        } /* nlstate */
                   9413:        fprintf(ficgp,", '' ");
                   9414:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   9415:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   9416:          l=(nlstate+ndeath)*(cpt-1) +j;
                   9417:          if(j < nlstate)
                   9418:            fprintf(ficgp,"$%d +",k+l);
                   9419:          else
                   9420:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   9421:        }
                   9422:        fprintf(ficgp,"\nset out; unset label;\n");
                   9423:       } /* end cpt state*/ 
                   9424:     /* } /\* end covariate *\/   */
                   9425:   } /* end nres */
                   9426:   
                   9427: /* 6eme */
                   9428:   /* CV preval stable (period) for each covariate */
                   9429:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
                   9430:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9431:      k1=TKresult[nres];
                   9432:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
                   9433:      /* if(m != 1 && TKresult[nres]!= k1) */
                   9434:      /*  continue; */
                   9435:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
                   9436:       strcpy(gplotlabel,"(");      
                   9437:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   9438:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9439:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9440:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9441:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   9442:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   9443:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9444:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9445:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9446:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9447:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9448:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9449:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9450:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9451:       /* } */
                   9452:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9453:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9454:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9455:       }        
                   9456:       strcpy(gplotlabel+strlen(gplotlabel),")");
                   9457:       fprintf(ficgp,"\n#\n");
                   9458:       if(invalidvarcomb[k1]){
                   9459:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9460:        continue;
                   9461:       }
                   9462:       
                   9463:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
                   9464:       fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   9465:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
                   9466: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   9467:       k=3; /* Offset */
                   9468:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
                   9469:        if(i==1)
                   9470:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   9471:        else
                   9472:          fprintf(ficgp,", '' ");
                   9473:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
                   9474:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   9475:        for (j=2; j<= nlstate ; j ++)
                   9476:          fprintf(ficgp,"+$%d",k+l+j-1);
                   9477:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   9478:       } /* nlstate */
                   9479:       fprintf(ficgp,"\nset out; unset label;\n");
                   9480:     } /* end cpt state*/ 
                   9481:   } /* end covariate */  
                   9482:   
                   9483:   
                   9484: /* 7eme */
                   9485:   if(prevbcast == 1){
                   9486:     /* CV backward prevalence  for each covariate */
                   9487:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
                   9488:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9489:       k1=TKresult[nres];
                   9490:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
                   9491:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9492:       /*       continue; */
                   9493:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
                   9494:        strcpy(gplotlabel,"(");      
                   9495:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
                   9496:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9497:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9498:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9499:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   9500:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   9501:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9502:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9503:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9504:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9505:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9506:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9507:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9508:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9509:        /* } */
                   9510:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9511:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9512:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9513:        }       
                   9514:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   9515:        fprintf(ficgp,"\n#\n");
                   9516:        if(invalidvarcomb[k1]){
                   9517:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9518:          continue;
                   9519:        }
                   9520:        
                   9521:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
                   9522:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   9523:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
                   9524: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   9525:        k=3; /* Offset */
                   9526:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
                   9527:          if(i==1)
                   9528:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   9529:          else
                   9530:            fprintf(ficgp,", '' ");
                   9531:          /* l=(nlstate+ndeath)*(i-1)+1; */
                   9532:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
                   9533:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   9534:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
                   9535:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
                   9536:          /* for (j=2; j<= nlstate ; j ++) */
                   9537:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   9538:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
                   9539:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
                   9540:        } /* nlstate */
                   9541:        fprintf(ficgp,"\nset out; unset label;\n");
                   9542:       } /* end cpt state*/ 
                   9543:     } /* end covariate */  
                   9544:   } /* End if prevbcast */
                   9545:   
                   9546:   /* 8eme */
                   9547:   if(prevfcast==1){
                   9548:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
                   9549:     
                   9550:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
                   9551:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9552:       k1=TKresult[nres];
                   9553:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
                   9554:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9555:       /*       continue; */
                   9556:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   9557:        strcpy(gplotlabel,"(");      
                   9558:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
                   9559:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9560:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9561:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9562:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9563:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9564:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9565:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9566:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9567:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9568:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9569:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9570:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9571:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9572:        /* } */
                   9573:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9574:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9575:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9576:        }       
                   9577:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   9578:        fprintf(ficgp,"\n#\n");
                   9579:        if(invalidvarcomb[k1]){
                   9580:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9581:          continue;
                   9582:        }
                   9583:        
                   9584:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
                   9585:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
                   9586:        fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   9587:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   9588: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   9589: 
                   9590:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   9591:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9592:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9593:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   9594:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9595:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9596:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9597:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9598:          if(i==istart){
                   9599:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   9600:          }else{
                   9601:            fprintf(ficgp,",\\\n '' ");
                   9602:          }
                   9603:          if(cptcoveff ==0){ /* No covariate */
                   9604:            ioffset=2; /* Age is in 2 */
                   9605:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9606:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9607:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9608:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9609:            fprintf(ficgp," u %d:(", ioffset); 
                   9610:            if(i==nlstate+1){
                   9611:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
                   9612:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9613:              fprintf(ficgp,",\\\n '' ");
                   9614:              fprintf(ficgp," u %d:(",ioffset); 
                   9615:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
                   9616:                     offyear,                           \
                   9617:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
                   9618:            }else
                   9619:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   9620:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   9621:          }else{ /* more than 2 covariates */
                   9622:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9623:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9624:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9625:            iyearc=ioffset-1;
                   9626:            iagec=ioffset;
                   9627:            fprintf(ficgp," u %d:(",ioffset); 
                   9628:            kl=0;
                   9629:            strcpy(gplotcondition,"(");
1.2       brouard  9630:            /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
1.1       brouard  9631:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
1.2       brouard  9632:            for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9633:              /* lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   9634:              lv=Tvresult[nres][k];
                   9635:              vlv=TinvDoQresult[nres][Tvresult[nres][k]];
1.1       brouard  9636:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9637:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9638:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   9639:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
1.2       brouard  9640:              /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
1.1       brouard  9641:              kl++;
1.2       brouard  9642:              /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   9643:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,lv, kl+1, vlv );
1.1       brouard  9644:              kl++;
1.2       brouard  9645:              if(k <cptcovs && cptcovs>1)
1.1       brouard  9646:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9647:            }
                   9648:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9649:            /* 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 *\/ */
                   9650:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9651:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9652:            /* ''  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*/
                   9653:            if(i==nlstate+1){
                   9654:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   9655:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
                   9656:              fprintf(ficgp,",\\\n '' ");
                   9657:              fprintf(ficgp," u %d:(",iagec); 
                   9658:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   9659:                      iyearc, iagec, offyear,                           \
                   9660:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
                   9661: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   9662:            }else{
                   9663:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   9664:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   9665:            }
                   9666:          } /* end if covariate */
                   9667:        } /* nlstate */
                   9668:        fprintf(ficgp,"\nset out; unset label;\n");
                   9669:       } /* end cpt state*/
                   9670:     } /* end covariate */
                   9671:   } /* End if prevfcast */
                   9672:   
                   9673:   if(prevbcast==1){
                   9674:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   9675:     
                   9676:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
                   9677:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9678:      k1=TKresult[nres];
                   9679:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
                   9680:        /* if(m != 1 && TKresult[nres]!= k1) */
                   9681:        /*      continue; */
                   9682:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   9683:        strcpy(gplotlabel,"(");      
                   9684:        fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
                   9685:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   9686:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9687:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9688:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9689:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9690:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9691:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9692:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9693:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9694:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9695:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9696:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9697:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9698:        /* } */
                   9699:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9700:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9701:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9702:        }       
                   9703:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   9704:        fprintf(ficgp,"\n#\n");
                   9705:        if(invalidvarcomb[k1]){
                   9706:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   9707:          continue;
                   9708:        }
                   9709:        
                   9710:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   9711:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   9712:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   9713:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   9714: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   9715: 
                   9716:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   9717:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9718:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   9719:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   9720:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9721:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9722:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9723:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   9724:          if(i==istart){
                   9725:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   9726:          }else{
                   9727:            fprintf(ficgp,",\\\n '' ");
                   9728:          }
1.2       brouard  9729:          /* if(cptcoveff ==0){ /\* No covariate *\/ */
                   9730:          if(cptcovs ==0){ /* No covariate */
1.1       brouard  9731:            ioffset=2; /* Age is in 2 */
                   9732:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9733:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9734:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   9735:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   9736:            fprintf(ficgp," u %d:(", ioffset); 
                   9737:            if(i==nlstate+1){
                   9738:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
                   9739:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   9740:              fprintf(ficgp,",\\\n '' ");
                   9741:              fprintf(ficgp," u %d:(",ioffset); 
                   9742:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
                   9743:                     offbyear,                          \
                   9744:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   9745:            }else
                   9746:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   9747:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   9748:          }else{ /* more than 2 covariates */
                   9749:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   9750:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   9751:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   9752:            iyearc=ioffset-1;
                   9753:            iagec=ioffset;
1.2       brouard  9754:            fprintf(ficgp," u %d:(",ioffset); 
1.1       brouard  9755:            kl=0;
                   9756:            strcpy(gplotcondition,"(");
                   9757:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
                   9758:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
                   9759:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   9760:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9761:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9762:                lv=Tvresult[nres][k];
                   9763:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   9764:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   9765:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   9766:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   9767:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   9768:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9769:                kl++;
                   9770:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   9771:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   9772:                kl++;
                   9773:                if(k <cptcovs && cptcovs>1)
                   9774:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   9775:              }
                   9776:            }
                   9777:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   9778:            /* 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 *\/ */
                   9779:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   9780:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   9781:            /* ''  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*/
                   9782:            if(i==nlstate+1){
                   9783:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   9784:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
                   9785:              fprintf(ficgp,",\\\n '' ");
                   9786:              fprintf(ficgp," u %d:(",iagec); 
                   9787:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
                   9788:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   9789:                      iyearc,iagec,offbyear,                            \
                   9790:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
                   9791: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   9792:            }else{
                   9793:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   9794:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   9795:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   9796:            }
                   9797:          } /* end if covariate */
                   9798:        } /* nlstate */
                   9799:        fprintf(ficgp,"\nset out; unset label;\n");
                   9800:       } /* end cpt state*/
                   9801:     } /* end covariate */
                   9802:   } /* End if prevbcast */
                   9803:   
                   9804:   
                   9805:   /* 9eme writing MLE parameters */
                   9806:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
                   9807:   for(i=1,jk=1; i <=nlstate; i++){
                   9808:     fprintf(ficgp,"# initial state %d\n",i);
                   9809:     for(k=1; k <=(nlstate+ndeath); k++){
                   9810:       if (k != i) {
                   9811:        fprintf(ficgp,"#   current state %d\n",k);
                   9812:        for(j=1; j <=ncovmodel; j++){
                   9813:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   9814:          jk++; 
                   9815:        }
                   9816:        fprintf(ficgp,"\n");
                   9817:       }
                   9818:     }
                   9819:   }
                   9820:   fprintf(ficgp,"##############\n#\n");
                   9821:   
                   9822:   /*goto avoid;*/
                   9823:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   9824:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
                   9825:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   9826:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   9827:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   9828:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   9829:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9830:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9831:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9832:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   9833:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   9834:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   9835:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   9836:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   9837:   fprintf(ficgp,"#\n");
                   9838:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
                   9839:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
                   9840:     fprintf(ficgp,"#model=1+age+%s \n",model);
                   9841:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.2       brouard  9842:     /* fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/\* to be checked *\/ */
                   9843:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcovs,m);/* to be checked */
1.1       brouard  9844:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
                   9845:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9846:      /* k1=nres; */
                   9847:       k1=TKresult[nres];
                   9848:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
                   9849:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
                   9850:       strcpy(gplotlabel,"(");
                   9851:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
                   9852:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   9853:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   9854:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   9855:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9856:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   9857:       }
                   9858:       /* if(m != 1 && TKresult[nres]!= k1) */
                   9859:       /*       continue; */
                   9860:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   9861:       /* strcpy(gplotlabel,"("); */
                   9862:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   9863:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   9864:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   9865:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   9866:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   9867:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   9868:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   9869:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   9870:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   9871:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   9872:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   9873:       /* } */
                   9874:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9875:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9876:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   9877:       /* }      */
                   9878:       strcpy(gplotlabel+strlen(gplotlabel),")");
                   9879:       fprintf(ficgp,"\n#\n");
                   9880:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
                   9881:       fprintf(ficgp,"\nset key outside ");
                   9882:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   9883:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
                   9884:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   9885:       if (ng==1){
                   9886:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   9887:        fprintf(ficgp,"\nunset log y");
                   9888:       }else if (ng==2){
                   9889:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   9890:        fprintf(ficgp,"\nset log y");
                   9891:       }else if (ng==3){
                   9892:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   9893:        fprintf(ficgp,"\nset log y");
                   9894:       }else
                   9895:        fprintf(ficgp,"\nunset title ");
                   9896:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   9897:       i=1;
                   9898:       for(k2=1; k2<=nlstate; k2++) {
                   9899:        k3=i;
                   9900:        for(k=1; k<=(nlstate+ndeath); k++) {
                   9901:          if (k != k2){
                   9902:            switch( ng) {
                   9903:            case 1:
                   9904:              if(nagesqr==0)
                   9905:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   9906:              else /* nagesqr =1 */
                   9907:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9908:              break;
                   9909:            case 2: /* ng=2 */
                   9910:              if(nagesqr==0)
                   9911:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   9912:              else /* nagesqr =1 */
                   9913:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   9914:              break;
                   9915:            case 3:
                   9916:              if(nagesqr==0)
                   9917:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   9918:              else /* nagesqr =1 */
                   9919:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   9920:              break;
                   9921:            }
                   9922:            ij=1;/* To be checked else nbcode[0][0] wrong */
                   9923:            ijp=1; /* product no age */
                   9924:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   9925:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   9926:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
                   9927:              switch(Typevar[j]){
                   9928:              case 1:
                   9929:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9930:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   9931:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   9932:                      if(DummyV[j]==0){/* Bug valgrind */
                   9933:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   9934:                      }else{ /* quantitative */
                   9935:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9936:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9937:                      }
                   9938:                      ij++;
                   9939:                    }
                   9940:                  }
                   9941:                }
                   9942:                break;
                   9943:              case 2:
                   9944:                if(cptcovprod >0){
                   9945:                  if(j==Tprod[ijp]) { /* */ 
                   9946:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9947:                    if(ijp <=cptcovprod) { /* Product */
                   9948:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9949:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9950:                          /* 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)]); */
                   9951:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9952:                        }else{ /* Vn is dummy and Vm is quanti */
                   9953:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9954:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9955:                        }
                   9956:                      }else{ /* Vn*Vm Vn is quanti */
                   9957:                        if(DummyV[Tvard[ijp][2]]==0){
                   9958:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9959:                        }else{ /* Both quanti */
                   9960:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9961:                        }
                   9962:                      }
                   9963:                      ijp++;
                   9964:                    }
                   9965:                  } /* end Tprod */
                   9966:                }
                   9967:                break;
                   9968:              case 3:
                   9969:                if(cptcovdageprod >0){
                   9970:                  /* if(j==Tprod[ijp]) { */ /* not necessary */ 
                   9971:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
1.2       brouard  9972:                    if(ijp <=cptcovprod) { /* Product Vn*Vm and age*VN*Vm*/
                   9973:                      if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   9974:                        if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.1       brouard  9975:                          /* 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)]); */
                   9976:                          fprintf(ficgp,"+p%d*%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9977:                        }else{ /* Vn is dummy and Vm is quanti */
                   9978:                          /* 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  9979:                          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  9980:                        }
1.2       brouard  9981:                      }else{ /* age* Vn*Vm Vn is quanti HERE */
1.1       brouard  9982:                        if(DummyV[Tvard[ijp][2]]==0){
1.2       brouard  9983:                          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  9984:                        }else{ /* Both quanti */
1.2       brouard  9985:                          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  9986:                        }
                   9987:                      }
                   9988:                      ijp++;
                   9989:                    }
                   9990:                    /* } */ /* end Tprod */
                   9991:                }
                   9992:                break;
                   9993:              case 0:
                   9994:                /* simple covariate */
                   9995:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   9996:                if(Dummy[j]==0){
                   9997:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   9998:                }else{ /* quantitative */
                   9999:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
                   10000:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   10001:                }
                   10002:               /* end simple */
                   10003:                break;
                   10004:              default:
                   10005:                break;
                   10006:              } /* end switch */
                   10007:            } /* end j */
                   10008:          }else{ /* k=k2 */
                   10009:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   10010:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   10011:            }else
                   10012:              i=i-ncovmodel;
                   10013:          }
                   10014:          
                   10015:          if(ng != 1){
                   10016:            fprintf(ficgp,")/(1");
                   10017:            
                   10018:            for(cpt=1; cpt <=nlstate; cpt++){ 
                   10019:              if(nagesqr==0)
                   10020:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
                   10021:              else /* nagesqr =1 */
                   10022:                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);
                   10023:               
                   10024:              ij=1;
                   10025:              ijp=1;
                   10026:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   10027:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   10028:                switch(Typevar[j]){
                   10029:                case 1:
                   10030:                  if(cptcovage >0){ 
                   10031:                    if(j==Tage[ij]) { /* Bug valgrind */
                   10032:                      if(ij <=cptcovage) { /* Bug valgrind */
                   10033:                        if(DummyV[j]==0){/* Bug valgrind */
                   10034:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   10035:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   10036:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   10037:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   10038:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   10039:                        }else{ /* quantitative */
                   10040:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   10041:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   10042:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   10043:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   10044:                        }
                   10045:                        ij++;
                   10046:                      }
                   10047:                    }
                   10048:                  }
                   10049:                  break;
                   10050:                case 2:
                   10051:                  if(cptcovprod >0){
                   10052:                    if(j==Tprod[ijp]) { /* */ 
                   10053:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   10054:                      if(ijp <=cptcovprod) { /* Product */
                   10055:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   10056:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   10057:                            /* 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)]); */
                   10058:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   10059:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   10060:                          }else{ /* Vn is dummy and Vm is quanti */
                   10061:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   10062:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   10063:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   10064:                          }
                   10065:                        }else{ /* Vn*Vm Vn is quanti */
                   10066:                          if(DummyV[Tvard[ijp][2]]==0){
                   10067:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   10068:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   10069:                          }else{ /* Both quanti */
                   10070:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   10071:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   10072:                          } 
                   10073:                        }
                   10074:                        ijp++;
                   10075:                      }
                   10076:                    } /* end Tprod */
                   10077:                  } /* end if */
                   10078:                  break;
                   10079:                case 3:
                   10080:                  if(cptcovdageprod >0){
                   10081:                    /* if(j==Tprod[ijp]) { /\* *\/  */
                   10082:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   10083:                      if(ijp <=cptcovprod) { /* Product */
1.2       brouard  10084:                        if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   10085:                          if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.1       brouard  10086:                            /* 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  10087:                            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  10088:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   10089:                          }else{ /* Vn is dummy and Vm is quanti */
                   10090:                            /* 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  10091:                            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  10092:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   10093:                          }
                   10094:                        }else{ /* Vn*Vm Vn is quanti */
1.2       brouard  10095:                          if(DummyV[Tvardk[ijp][2]]==0){
                   10096:                            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  10097:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   10098:                          }else{ /* Both quanti */
1.2       brouard  10099:                            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  10100:                            /* fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   10101:                          } 
                   10102:                        }
                   10103:                        ijp++;
                   10104:                      }
                   10105:                    /* } /\* end Tprod *\/ */
                   10106:                  } /* end if */
                   10107:                  break;
                   10108:                case 0: 
                   10109:                  /* simple covariate */
                   10110:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   10111:                  if(Dummy[j]==0){
                   10112:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   10113:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   10114:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   10115:                  }else{ /* quantitative */
                   10116:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   10117:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   10118:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   10119:                  }
                   10120:                  /* end simple */
                   10121:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   10122:                  break;
                   10123:                default:
                   10124:                  break;
                   10125:                } /* end switch */
                   10126:              }
                   10127:              fprintf(ficgp,")");
                   10128:            }
                   10129:            fprintf(ficgp,")");
                   10130:            if(ng ==2)
                   10131:              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);
                   10132:            else /* ng= 3 */
                   10133:              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);
                   10134:           }else{ /* end ng <> 1 */
                   10135:            if( k !=k2) /* logit p11 is hard to draw */
                   10136:              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);
                   10137:          }
                   10138:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   10139:            fprintf(ficgp,",");
                   10140:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   10141:            fprintf(ficgp,",");
                   10142:          i=i+ncovmodel;
                   10143:        } /* end k */
                   10144:       } /* end k2 */
                   10145:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   10146:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
                   10147:     } /* end resultline */
                   10148:   } /* end ng */
                   10149:   /* avoid: */
                   10150:   fflush(ficgp); 
                   10151: }  /* end gnuplot */
                   10152: 
                   10153: 
                   10154: /*************** Moving average **************/
                   10155: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
                   10156:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
                   10157:    
                   10158:    int i, cpt, cptcod;
                   10159:    int modcovmax =1;
                   10160:    int mobilavrange, mob;
                   10161:    int iage=0;
                   10162:    int firstA1=0, firstA2=0;
                   10163: 
                   10164:    double sum=0., sumr=0.;
                   10165:    double age;
                   10166:    double *sumnewp, *sumnewm, *sumnewmr;
                   10167:    double *agemingood, *agemaxgood; 
                   10168:    double *agemingoodr, *agemaxgoodr; 
                   10169:   
                   10170:   
                   10171:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   10172:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
                   10173: 
                   10174:    sumnewp = vector(1,ncovcombmax);
                   10175:    sumnewm = vector(1,ncovcombmax);
                   10176:    sumnewmr = vector(1,ncovcombmax);
                   10177:    agemingood = vector(1,ncovcombmax); 
                   10178:    agemingoodr = vector(1,ncovcombmax);        
                   10179:    agemaxgood = vector(1,ncovcombmax);
                   10180:    agemaxgoodr = vector(1,ncovcombmax);
                   10181: 
                   10182:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   10183:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
                   10184:      sumnewp[cptcod]=0.;
                   10185:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   10186:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
                   10187:    }
                   10188:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   10189:   
                   10190:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   10191:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
                   10192:      else mobilavrange=mobilav;
                   10193:      for (age=bage; age<=fage; age++)
                   10194:        for (i=1; i<=nlstate;i++)
                   10195:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   10196:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   10197:      /* We keep the original values on the extreme ages bage, fage and for 
                   10198:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   10199:        we use a 5 terms etc. until the borders are no more concerned. 
                   10200:      */ 
                   10201:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   10202:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   10203:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   10204:           sumnewm[cptcod]=0.;
                   10205:           for (i=1; i<=nlstate;i++){
                   10206:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   10207:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   10208:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   10209:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   10210:             }
                   10211:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   10212:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   10213:           } /* end i */
                   10214:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   10215:         } /* end cptcod */
                   10216:        }/* end age */
                   10217:      }/* end mob */
                   10218:    }else{
                   10219:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
                   10220:      return -1;
                   10221:    }
                   10222: 
                   10223:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
                   10224:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   10225:      if(invalidvarcomb[cptcod]){
                   10226:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   10227:        continue;
                   10228:      }
                   10229: 
                   10230:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   10231:        sumnewm[cptcod]=0.;
                   10232:        sumnewmr[cptcod]=0.;
                   10233:        for (i=1; i<=nlstate;i++){
                   10234:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   10235:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   10236:        }
                   10237:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   10238:         agemingoodr[cptcod]=age;
                   10239:        }
                   10240:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   10241:           agemingood[cptcod]=age;
                   10242:        }
                   10243:      } /* age */
                   10244:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
                   10245:        sumnewm[cptcod]=0.;
                   10246:        sumnewmr[cptcod]=0.;
                   10247:        for (i=1; i<=nlstate;i++){
                   10248:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   10249:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   10250:        }
                   10251:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   10252:         agemaxgoodr[cptcod]=age;
                   10253:        }
                   10254:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   10255:         agemaxgood[cptcod]=age;
                   10256:        }
                   10257:      } /* age */
                   10258:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   10259:      /* but they will change */
                   10260:      firstA1=0;firstA2=0;
                   10261:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   10262:        sumnewm[cptcod]=0.;
                   10263:        sumnewmr[cptcod]=0.;
                   10264:        for (i=1; i<=nlstate;i++){
                   10265:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   10266:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   10267:        }
                   10268:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   10269:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   10270:           agemaxgoodr[cptcod]=age;  /* age min */
                   10271:           for (i=1; i<=nlstate;i++)
                   10272:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   10273:         }else{ /* bad we change the value with the values of good ages */
                   10274:           for (i=1; i<=nlstate;i++){
                   10275:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   10276:           } /* i */
                   10277:         } /* end bad */
                   10278:        }else{
                   10279:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   10280:           agemaxgood[cptcod]=age;
                   10281:         }else{ /* bad we change the value with the values of good ages */
                   10282:           for (i=1; i<=nlstate;i++){
                   10283:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   10284:           } /* i */
                   10285:         } /* end bad */
                   10286:        }/* end else */
                   10287:        sum=0.;sumr=0.;
                   10288:        for (i=1; i<=nlstate;i++){
                   10289:         sum+=mobaverage[(int)age][i][cptcod];
                   10290:         sumr+=probs[(int)age][i][cptcod];
                   10291:        }
                   10292:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   10293:         if(!firstA1){
                   10294:           firstA1=1;
                   10295:           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);
                   10296:         }
                   10297:         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);
                   10298:        } /* end bad */
                   10299:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   10300:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
                   10301:         if(!firstA2){
                   10302:           firstA2=1;
                   10303:           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);
                   10304:         }
                   10305:         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);
                   10306:        } /* end bad */
                   10307:      }/* age */
                   10308: 
                   10309:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
                   10310:        sumnewm[cptcod]=0.;
                   10311:        sumnewmr[cptcod]=0.;
                   10312:        for (i=1; i<=nlstate;i++){
                   10313:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   10314:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   10315:        } 
                   10316:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   10317:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   10318:           agemingoodr[cptcod]=age;
                   10319:           for (i=1; i<=nlstate;i++)
                   10320:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   10321:         }else{ /* bad we change the value with the values of good ages */
                   10322:           for (i=1; i<=nlstate;i++){
                   10323:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   10324:           } /* i */
                   10325:         } /* end bad */
                   10326:        }else{
                   10327:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   10328:           agemingood[cptcod]=age;
                   10329:         }else{ /* bad */
                   10330:           for (i=1; i<=nlstate;i++){
                   10331:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   10332:           } /* i */
                   10333:         } /* end bad */
                   10334:        }/* end else */
                   10335:        sum=0.;sumr=0.;
                   10336:        for (i=1; i<=nlstate;i++){
                   10337:         sum+=mobaverage[(int)age][i][cptcod];
                   10338:         sumr+=mobaverage[(int)age][i][cptcod];
                   10339:        }
                   10340:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   10341:         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);
                   10342:        } /* end bad */
                   10343:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   10344:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
                   10345:         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);
                   10346:        } /* end bad */
                   10347:      }/* age */
                   10348: 
                   10349:                
                   10350:      for (age=bage; age<=fage; age++){
                   10351:        /* printf("%d %d ", cptcod, (int)age); */
                   10352:        sumnewp[cptcod]=0.;
                   10353:        sumnewm[cptcod]=0.;
                   10354:        for (i=1; i<=nlstate;i++){
                   10355:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   10356:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   10357:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   10358:        }
                   10359:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   10360:      }
                   10361:      /* printf("\n"); */
                   10362:      /* } */
                   10363: 
                   10364:      /* brutal averaging */
                   10365:      /* for (i=1; i<=nlstate;i++){ */
                   10366:      /*   for (age=1; age<=bage; age++){ */
                   10367:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   10368:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   10369:      /*   }     */
                   10370:      /*   for (age=fage; age<=AGESUP; age++){ */
                   10371:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   10372:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   10373:      /*   } */
                   10374:      /* } /\* end i status *\/ */
                   10375:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   10376:      /*   for (age=1; age<=AGESUP; age++){ */
                   10377:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   10378:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   10379:      /*   } */
                   10380:      /* } */
                   10381:    }/* end cptcod */
                   10382:    free_vector(agemaxgoodr,1, ncovcombmax);
                   10383:    free_vector(agemaxgood,1, ncovcombmax);
                   10384:    free_vector(agemingood,1, ncovcombmax);
                   10385:    free_vector(agemingoodr,1, ncovcombmax);
                   10386:    free_vector(sumnewmr,1, ncovcombmax);
                   10387:    free_vector(sumnewm,1, ncovcombmax);
                   10388:    free_vector(sumnewp,1, ncovcombmax);
                   10389:    return 0;
                   10390:  }/* End movingaverage */
                   10391:  
                   10392: 
                   10393:  
                   10394: /************** Forecasting ******************/
                   10395: /* 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)*/
                   10396: 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){
                   10397:   /* dateintemean, mean date of interviews
                   10398:      dateprojd, year, month, day of starting projection 
                   10399:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
                   10400:      agemin, agemax range of age
                   10401:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   10402:   */
                   10403:   /* double anprojd, mprojd, jprojd; */
                   10404:   /* double anprojf, mprojf, jprojf; */
                   10405:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   10406:   double agec; /* generic age */
                   10407:   double agelim, ppij, yp,yp1,yp2;
                   10408:   double *popeffectif,*popcount;
                   10409:   double ***p3mat;
                   10410:   /* double ***mobaverage; */
                   10411:   char fileresf[FILENAMELENGTH];
                   10412: 
                   10413:   agelim=AGESUP;
                   10414:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   10415:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   10416:      We still use firstpass and lastpass as another selection.
                   10417:   */
                   10418:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   10419:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   10420:  
                   10421:   strcpy(fileresf,"F_"); 
                   10422:   strcat(fileresf,fileresu);
                   10423:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   10424:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   10425:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   10426:   }
                   10427:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   10428:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   10429: 
                   10430:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   10431: 
                   10432: 
                   10433:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10434:   if (stepm<=12) stepsize=1;
                   10435:   if(estepm < stepm){
                   10436:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   10437:   }
                   10438:   else{
                   10439:     hstepm=estepm;   
                   10440:   }
                   10441:   if(estepm > stepm){ /* Yes every two year */
                   10442:     stepsize=2;
                   10443:   }
                   10444:   hstepm=hstepm/stepm;
                   10445: 
                   10446:   
                   10447:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   10448:   /*                              fractional in yp1 *\/ */
                   10449:   /* aintmean=yp; */
                   10450:   /* yp2=modf((yp1*12),&yp); */
                   10451:   /* mintmean=yp; */
                   10452:   /* yp1=modf((yp2*30.5),&yp); */
                   10453:   /* jintmean=yp; */
                   10454:   /* if(jintmean==0) jintmean=1; */
                   10455:   /* if(mintmean==0) mintmean=1; */
                   10456: 
                   10457: 
                   10458:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   10459:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   10460:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.2       brouard  10461:   /* i1=pow(2,cptcoveff); */
                   10462:   /* if (cptcovn < 1){i1=1;} */
1.1       brouard  10463:   
                   10464:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
                   10465:   
                   10466:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   10467:   
                   10468: /*           if (h==(int)(YEARM*yearp)){ */
1.2       brouard  10469:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10470:     k=TKresult[nres];
                   10471:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   10472:     /*  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) *\/ */
                   10473:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   10474:     /*   continue; */
                   10475:     /* if(invalidvarcomb[k]){ */
                   10476:     /*   printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   10477:     /*   continue; */
                   10478:     /* } */
1.1       brouard  10479:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.2       brouard  10480:     for(j=1;j<=cptcovs;j++){
                   10481:       /* for(j=1;j<=cptcoveff;j++) { */
                   10482:     /*   /\* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); *\/ */
                   10483:     /*   fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10484:     /* } */
                   10485:     /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10486:     /*   fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10487:     /* } */
                   10488:       fprintf(ficresf," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.1       brouard  10489:     }
1.2       brouard  10490:  
1.1       brouard  10491:     fprintf(ficresf," yearproj age");
                   10492:     for(j=1; j<=nlstate+ndeath;j++){ 
                   10493:       for(i=1; i<=nlstate;i++)               
                   10494:        fprintf(ficresf," p%d%d",i,j);
                   10495:       fprintf(ficresf," wp.%d",j);
                   10496:     }
                   10497:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
                   10498:       fprintf(ficresf,"\n");
                   10499:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
                   10500:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   10501:       for (agec=fage; agec>=(bage); agec--){ 
                   10502:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   10503:        nhstepm = nhstepm/hstepm; 
                   10504:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10505:        oldm=oldms;savm=savms;
                   10506:        /* We compute pii at age agec over nhstepm);*/
                   10507:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
                   10508:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   10509:        for (h=0; h<=nhstepm; h++){
                   10510:          if (h*hstepm/YEARM*stepm ==yearp) {
                   10511:            break;
                   10512:          }
                   10513:        }
                   10514:        fprintf(ficresf,"\n");
1.2       brouard  10515:        /* for(j=1;j<=cptcoveff;j++)  */
                   10516:        for(j=1;j<=cptcovs;j++) 
                   10517:          fprintf(ficresf,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.1       brouard  10518:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
1.2       brouard  10519:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* TnsdVar[Tvaraff]  correct *\/ */
1.1       brouard  10520:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
                   10521:        
                   10522:        for(j=1; j<=nlstate+ndeath;j++) {
                   10523:          ppij=0.;
                   10524:          for(i=1; i<=nlstate;i++) {
                   10525:            if (mobilav>=1)
                   10526:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   10527:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   10528:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   10529:            }
                   10530:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   10531:          } /* end i */
                   10532:          fprintf(ficresf," %.3f", ppij);
                   10533:        }/* end j */
                   10534:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10535:       } /* end agec */
                   10536:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   10537:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
                   10538:     } /* end yearp */
                   10539:   } /* end  k */
                   10540:        
                   10541:   fclose(ficresf);
                   10542:   printf("End of Computing forecasting \n");
                   10543:   fprintf(ficlog,"End of Computing forecasting\n");
                   10544: 
                   10545: }
                   10546: 
                   10547: /************** Back Forecasting ******************/
                   10548:  /* 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){ */
                   10549:  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){
                   10550:   /* back1, year, month, day of starting backprojection
                   10551:      agemin, agemax range of age
                   10552:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   10553:      anback2 year of end of backprojection (same day and month as back1).
                   10554:      prevacurrent and prev are prevalences.
                   10555:   */
                   10556:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   10557:   double agec; /* generic age */
                   10558:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
                   10559:   double *popeffectif,*popcount;
                   10560:   double ***p3mat;
                   10561:   /* double ***mobaverage; */
                   10562:   char fileresfb[FILENAMELENGTH];
                   10563:  
                   10564:   agelim=AGEINF;
                   10565:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   10566:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   10567:      We still use firstpass and lastpass as another selection.
                   10568:   */
                   10569:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   10570:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   10571: 
                   10572:   /*Do we need to compute prevalence again?*/
                   10573: 
                   10574:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   10575:   
                   10576:   strcpy(fileresfb,"FB_");
                   10577:   strcat(fileresfb,fileresu);
                   10578:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   10579:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   10580:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   10581:   }
                   10582:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   10583:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   10584:   
                   10585:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   10586:   
                   10587:    
                   10588:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   10589:   if (stepm<=12) stepsize=1;
                   10590:   if(estepm < stepm){
                   10591:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   10592:   }
                   10593:   else{
                   10594:     hstepm=estepm;   
                   10595:   }
                   10596:   if(estepm >= stepm){ /* Yes every two year */
                   10597:     stepsize=2;
                   10598:   }
                   10599:   
                   10600:   hstepm=hstepm/stepm;
                   10601:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   10602:   /*                              fractional in yp1 *\/ */
                   10603:   /* aintmean=yp; */
                   10604:   /* yp2=modf((yp1*12),&yp); */
                   10605:   /* mintmean=yp; */
                   10606:   /* yp1=modf((yp2*30.5),&yp); */
                   10607:   /* jintmean=yp; */
                   10608:   /* if(jintmean==0) jintmean=1; */
                   10609:   /* if(mintmean==0) jintmean=1; */
                   10610:   
1.2       brouard  10611:   /* i1=pow(2,cptcoveff); */
                   10612:   /* if (cptcovn < 1){i1=1;} */
1.1       brouard  10613:   
                   10614:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   10615:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   10616:   
                   10617:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   10618:   
1.2       brouard  10619:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10620:     k=TKresult[nres];
                   10621:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   10622:   /* for(k=1; k<=i1;k++){ */
                   10623:   /*   if(i1 != 1 && TKresult[nres]!= k) */
                   10624:   /*     continue; */
                   10625:   /*   if(invalidvarcomb[k]){ */
                   10626:   /*     printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   10627:   /*     continue; */
                   10628:   /*   } */
1.1       brouard  10629:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.2       brouard  10630:     for(j=1;j<=cptcovs;j++){
                   10631:     /* for(j=1;j<=cptcoveff;j++) { */
                   10632:     /*   fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10633:     /* } */
                   10634:       fprintf(ficresfb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.1       brouard  10635:     }
1.2       brouard  10636:    /*  fprintf(ficrespij,"******\n"); */
                   10637:    /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10638:    /*    fprintf(ficresfb," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10639:    /*  } */
1.1       brouard  10640:     fprintf(ficresfb," yearbproj age");
                   10641:     for(j=1; j<=nlstate+ndeath;j++){
                   10642:       for(i=1; i<=nlstate;i++)
                   10643:        fprintf(ficresfb," b%d%d",i,j);
                   10644:       fprintf(ficresfb," b.%d",j);
                   10645:     }
                   10646:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
                   10647:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   10648:       fprintf(ficresfb,"\n");
                   10649:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
                   10650:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
                   10651:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   10652:       for (agec=bage; agec<=fage; agec++){  /* testing */
                   10653:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
                   10654:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
                   10655:        nhstepm = nhstepm/hstepm;
                   10656:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10657:        oldm=oldms;savm=savms;
                   10658:        /* computes hbxij at age agec over 1 to nhstepm */
                   10659:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
                   10660:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
                   10661:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   10662:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   10663:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
                   10664:        for (h=0; h<=nhstepm; h++){
                   10665:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   10666:            break;
                   10667:          }
                   10668:        }
                   10669:        fprintf(ficresfb,"\n");
1.2       brouard  10670:        /* for(j=1;j<=cptcoveff;j++) */
                   10671:        for(j=1;j<=cptcovs;j++)
                   10672:          fprintf(ficresfb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10673:          /* fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.1       brouard  10674:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
                   10675:        for(i=1; i<=nlstate+ndeath;i++) {
                   10676:          ppij=0.;ppi=0.;
                   10677:          for(j=1; j<=nlstate;j++) {
                   10678:            /* if (mobilav==1) */
                   10679:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   10680:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   10681:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   10682:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
                   10683:              /* else { */
                   10684:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   10685:              /* } */
                   10686:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   10687:          } /* end j */
                   10688:          if(ppi <0.99){
                   10689:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   10690:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   10691:          }
                   10692:          fprintf(ficresfb," %.3f", ppij);
                   10693:        }/* end j */
                   10694:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   10695:       } /* end agec */
                   10696:     } /* end yearp */
                   10697:   } /* end k */
                   10698:   
                   10699:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10700:   
                   10701:   fclose(ficresfb);
                   10702:   printf("End of Computing Back forecasting \n");
                   10703:   fprintf(ficlog,"End of Computing Back forecasting\n");
                   10704:        
                   10705: }
                   10706: 
                   10707: /* Variance of prevalence limit: varprlim */
                   10708:  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){
                   10709:     /*------- Variance of forward period (stable) prevalence------*/   
                   10710:  
                   10711:    char fileresvpl[FILENAMELENGTH];  
                   10712:    FILE *ficresvpl;
                   10713:    double **oldm, **savm;
                   10714:    double **varpl; /* Variances of prevalence limits by age */   
                   10715:    int i1, k, nres, j ;
                   10716:    
                   10717:     strcpy(fileresvpl,"VPL_");
                   10718:     strcat(fileresvpl,fileresu);
                   10719:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   10720:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   10721:       exit(0);
                   10722:     }
                   10723:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   10724:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
                   10725:     
                   10726:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   10727:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   10728:     
                   10729:     i1=pow(2,cptcoveff);
                   10730:     if (cptcovn < 1){i1=1;}
                   10731: 
                   10732:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10733:        k=TKresult[nres];
                   10734:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   10735:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
                   10736:       if(i1 != 1 && TKresult[nres]!= k)
                   10737:        continue;
                   10738:       fprintf(ficresvpl,"\n#****** ");
                   10739:       printf("\n#****** ");
                   10740:       fprintf(ficlog,"\n#****** ");
                   10741:       for(j=1;j<=cptcovs;j++) {
                   10742:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10743:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10744:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   10745:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10746:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10747:       }
                   10748:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10749:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10750:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10751:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10752:       /* }      */
                   10753:       fprintf(ficresvpl,"******\n");
                   10754:       printf("******\n");
                   10755:       fprintf(ficlog,"******\n");
                   10756:       
                   10757:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10758:       oldm=oldms;savm=savms;
                   10759:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   10760:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   10761:       /*}*/
                   10762:     }
                   10763:     
                   10764:     fclose(ficresvpl);
                   10765:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   10766:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
                   10767: 
                   10768:  }
                   10769: /* Variance of back prevalence: varbprlim */
                   10770:  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){
                   10771:       /*------- Variance of back (stable) prevalence------*/
                   10772: 
                   10773:    char fileresvbl[FILENAMELENGTH];  
                   10774:    FILE  *ficresvbl;
                   10775: 
                   10776:    double **oldm, **savm;
                   10777:    double **varbpl; /* Variances of back prevalence limits by age */   
                   10778:    int i1, k, nres, j ;
                   10779: 
                   10780:    strcpy(fileresvbl,"VBL_");
                   10781:    strcat(fileresvbl,fileresu);
                   10782:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   10783:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   10784:      exit(0);
                   10785:    }
                   10786:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   10787:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   10788:    
                   10789:    
                   10790:    i1=pow(2,cptcoveff);
                   10791:    if (cptcovn < 1){i1=1;}
                   10792:    
                   10793:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   10794:      k=TKresult[nres];
                   10795:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   10796:     /* for(k=1; k<=i1;k++){ */
                   10797:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   10798:     /*          continue; */
                   10799:        fprintf(ficresvbl,"\n#****** ");
                   10800:        printf("\n#****** ");
                   10801:        fprintf(ficlog,"\n#****** ");
                   10802:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
                   10803:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10804:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10805:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   10806:        /* for(j=1;j<=cptcoveff;j++) { */
                   10807:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10808:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10809:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   10810:        /* } */
                   10811:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   10812:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10813:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10814:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   10815:        }
                   10816:        fprintf(ficresvbl,"******\n");
                   10817:        printf("******\n");
                   10818:        fprintf(ficlog,"******\n");
                   10819:        
                   10820:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10821:        oldm=oldms;savm=savms;
                   10822:        
                   10823:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   10824:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   10825:        /*}*/
                   10826:      }
                   10827:    
                   10828:    fclose(ficresvbl);
                   10829:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   10830:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   10831: 
                   10832:  } /* End of varbprlim */
                   10833: 
                   10834: /************** Forecasting *****not tested NB*************/
                   10835: /* 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){ */
                   10836:   
                   10837: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   10838: /*   int *popage; */
                   10839: /*   double calagedatem, agelim, kk1, kk2; */
                   10840: /*   double *popeffectif,*popcount; */
                   10841: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   10842: /*   /\* double ***mobaverage; *\/ */
                   10843: /*   char filerespop[FILENAMELENGTH]; */
                   10844: 
                   10845: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10846: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10847: /*   agelim=AGESUP; */
                   10848: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
                   10849:   
                   10850: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   10851:   
                   10852:   
                   10853: /*   strcpy(filerespop,"POP_");  */
                   10854: /*   strcat(filerespop,fileresu); */
                   10855: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   10856: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   10857: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   10858: /*   } */
                   10859: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   10860: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
                   10861: 
                   10862: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
                   10863: 
                   10864: /*   /\* if (mobilav!=0) { *\/ */
                   10865: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   10866: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   10867: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10868: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   10869: /*   /\*   } *\/ */
                   10870: /*   /\* } *\/ */
                   10871: 
                   10872: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   10873: /*   if (stepm<=12) stepsize=1; */
                   10874:   
                   10875: /*   agelim=AGESUP; */
                   10876:   
                   10877: /*   hstepm=1; */
                   10878: /*   hstepm=hstepm/stepm;  */
                   10879:        
                   10880: /*   if (popforecast==1) { */
                   10881: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   10882: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   10883: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   10884: /*     }  */
                   10885: /*     popage=ivector(0,AGESUP); */
                   10886: /*     popeffectif=vector(0,AGESUP); */
                   10887: /*     popcount=vector(0,AGESUP); */
                   10888:     
                   10889: /*     i=1;    */
                   10890: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
                   10891:     
                   10892: /*     imx=i; */
                   10893: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   10894: /*   } */
                   10895:   
                   10896: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   10897: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   10898: /*       k=k+1; */
                   10899: /*       fprintf(ficrespop,"\n#******"); */
                   10900: /*       for(j=1;j<=cptcoveff;j++) { */
                   10901: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   10902: /*       } */
                   10903: /*       fprintf(ficrespop,"******\n"); */
                   10904: /*       fprintf(ficrespop,"# Age"); */
                   10905: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   10906: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
                   10907:       
                   10908: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   10909: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   10910:        
                   10911: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10912: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10913: /*       nhstepm = nhstepm/hstepm;  */
                   10914:          
                   10915: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10916: /*       oldm=oldms;savm=savms; */
                   10917: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   10918:          
                   10919: /*       for (h=0; h<=nhstepm; h++){ */
                   10920: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10921: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10922: /*         }  */
                   10923: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10924: /*           kk1=0.;kk2=0; */
                   10925: /*           for(i=1; i<=nlstate;i++) {               */
                   10926: /*             if (mobilav==1)  */
                   10927: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   10928: /*             else { */
                   10929: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   10930: /*             } */
                   10931: /*           } */
                   10932: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   10933: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   10934: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   10935: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   10936: /*           } */
                   10937: /*         } */
                   10938: /*         for(i=1; i<=nlstate;i++){ */
                   10939: /*           kk1=0.; */
                   10940: /*           for(j=1; j<=nlstate;j++){ */
                   10941: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   10942: /*           } */
                   10943: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   10944: /*         } */
                   10945:            
                   10946: /*         if (h==(int)(calagedatem+12*cpt)) */
                   10947: /*           for(j=1; j<=nlstate;j++)  */
                   10948: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   10949: /*       } */
                   10950: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10951: /*     } */
                   10952: /*       } */
                   10953:       
                   10954: /*       /\******\/ */
                   10955:       
                   10956: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   10957: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   10958: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   10959: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   10960: /*       nhstepm = nhstepm/hstepm;  */
                   10961:          
                   10962: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10963: /*       oldm=oldms;savm=savms; */
                   10964: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   10965: /*       for (h=0; h<=nhstepm; h++){ */
                   10966: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   10967: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   10968: /*         }  */
                   10969: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   10970: /*           kk1=0.;kk2=0; */
                   10971: /*           for(i=1; i<=nlstate;i++) {               */
                   10972: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   10973: /*           } */
                   10974: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   10975: /*         } */
                   10976: /*       } */
                   10977: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   10978: /*     } */
                   10979: /*       } */
                   10980: /*     }  */
                   10981: /*   } */
                   10982:   
                   10983: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   10984:   
                   10985: /*   if (popforecast==1) { */
                   10986: /*     free_ivector(popage,0,AGESUP); */
                   10987: /*     free_vector(popeffectif,0,AGESUP); */
                   10988: /*     free_vector(popcount,0,AGESUP); */
                   10989: /*   } */
                   10990: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10991: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   10992: /*   fclose(ficrespop); */
                   10993: /* } /\* End of popforecast *\/ */
                   10994:  
                   10995: int fileappend(FILE *fichier, char *optionfich)
                   10996: {
                   10997:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   10998:     printf("Problem with file: %s\n", optionfich);
                   10999:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   11000:     return (0);
                   11001:   }
                   11002:   fflush(fichier);
                   11003:   return (1);
                   11004: }
                   11005: 
                   11006: 
                   11007: /**************** function prwizard **********************/
                   11008: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   11009: {
                   11010: 
                   11011:   /* Wizard to print covariance matrix template */
                   11012: 
                   11013:   char ca[32], cb[32];
                   11014:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
                   11015:   int numlinepar;
                   11016: 
                   11017:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   11018:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   11019:   for(i=1; i <=nlstate; i++){
                   11020:     jj=0;
                   11021:     for(j=1; j <=nlstate+ndeath; j++){
                   11022:       if(j==i) continue;
                   11023:       jj++;
                   11024:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   11025:       printf("%1d%1d",i,j);
                   11026:       fprintf(ficparo,"%1d%1d",i,j);
                   11027:       for(k=1; k<=ncovmodel;k++){
                   11028:        /*        printf(" %lf",param[i][j][k]); */
                   11029:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   11030:        printf(" 0.");
                   11031:        fprintf(ficparo," 0.");
                   11032:       }
                   11033:       printf("\n");
                   11034:       fprintf(ficparo,"\n");
                   11035:     }
                   11036:   }
                   11037:   printf("# Scales (for hessian or gradient estimation)\n");
                   11038:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   11039:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   11040:   for(i=1; i <=nlstate; i++){
                   11041:     jj=0;
                   11042:     for(j=1; j <=nlstate+ndeath; j++){
                   11043:       if(j==i) continue;
                   11044:       jj++;
                   11045:       fprintf(ficparo,"%1d%1d",i,j);
                   11046:       printf("%1d%1d",i,j);
                   11047:       fflush(stdout);
                   11048:       for(k=1; k<=ncovmodel;k++){
                   11049:        /*      printf(" %le",delti3[i][j][k]); */
                   11050:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   11051:        printf(" 0.");
                   11052:        fprintf(ficparo," 0.");
                   11053:       }
                   11054:       numlinepar++;
                   11055:       printf("\n");
                   11056:       fprintf(ficparo,"\n");
                   11057:     }
                   11058:   }
                   11059:   printf("# Covariance matrix\n");
                   11060: /* # 121 Var(a12)\n\ */
                   11061: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   11062: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   11063: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   11064: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   11065: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   11066: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   11067: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   11068:   fflush(stdout);
                   11069:   fprintf(ficparo,"# Covariance matrix\n");
                   11070:   /* # 121 Var(a12)\n\ */
                   11071:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   11072:   /* #   ...\n\ */
                   11073:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   11074:   
                   11075:   for(itimes=1;itimes<=2;itimes++){
                   11076:     jj=0;
                   11077:     for(i=1; i <=nlstate; i++){
                   11078:       for(j=1; j <=nlstate+ndeath; j++){
                   11079:        if(j==i) continue;
                   11080:        for(k=1; k<=ncovmodel;k++){
                   11081:          jj++;
                   11082:          ca[0]= k+'a'-1;ca[1]='\0';
                   11083:          if(itimes==1){
                   11084:            printf("#%1d%1d%d",i,j,k);
                   11085:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   11086:          }else{
                   11087:            printf("%1d%1d%d",i,j,k);
                   11088:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   11089:            /*  printf(" %.5le",matcov[i][j]); */
                   11090:          }
                   11091:          ll=0;
                   11092:          for(li=1;li <=nlstate; li++){
                   11093:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   11094:              if(lj==li) continue;
                   11095:              for(lk=1;lk<=ncovmodel;lk++){
                   11096:                ll++;
                   11097:                if(ll<=jj){
                   11098:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   11099:                  if(ll<jj){
                   11100:                    if(itimes==1){
                   11101:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   11102:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   11103:                    }else{
                   11104:                      printf(" 0.");
                   11105:                      fprintf(ficparo," 0.");
                   11106:                    }
                   11107:                  }else{
                   11108:                    if(itimes==1){
                   11109:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   11110:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   11111:                    }else{
                   11112:                      printf(" 0.");
                   11113:                      fprintf(ficparo," 0.");
                   11114:                    }
                   11115:                  }
                   11116:                }
                   11117:              } /* end lk */
                   11118:            } /* end lj */
                   11119:          } /* end li */
                   11120:          printf("\n");
                   11121:          fprintf(ficparo,"\n");
                   11122:          numlinepar++;
                   11123:        } /* end k*/
                   11124:       } /*end j */
                   11125:     } /* end i */
                   11126:   } /* end itimes */
                   11127: 
                   11128: } /* end of prwizard */
                   11129: /******************* Gompertz Likelihood ******************************/
                   11130: double gompertz(double x[])
                   11131: { 
                   11132:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
                   11133:   int i,n=0; /* n is the size of the sample */
                   11134: 
                   11135:   for (i=1;i<=imx ; i++) {
                   11136:     sump=sump+weight[i];
                   11137:     /*    sump=sump+1;*/
                   11138:     num=num+1;
                   11139:   }
                   11140:   L=0.0;
                   11141:   /* agegomp=AGEGOMP; */
                   11142:   /* for (i=0; i<=imx; i++) 
                   11143:      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]);*/
                   11144: 
                   11145:   for (i=1;i<=imx ; i++) {
                   11146:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   11147:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   11148:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   11149:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   11150:      * +
                   11151:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   11152:      */
                   11153:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   11154:        if (cens[i] == 1){
                   11155:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   11156:        } else if (cens[i] == 0){
                   11157:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   11158:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   11159:       } else
                   11160:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
                   11161:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   11162:        L=L+A*weight[i];
                   11163:        /*      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]);*/
                   11164:      }
                   11165:   }
                   11166: 
                   11167:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   11168:  
                   11169:   return -2*L*num/sump;
                   11170: }
                   11171: 
                   11172: #ifdef GSL
                   11173: /******************* Gompertz_f Likelihood ******************************/
                   11174: double gompertz_f(const gsl_vector *v, void *params)
                   11175: { 
                   11176:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
                   11177:   double *x= (double *) v->data;
                   11178:   int i,n=0; /* n is the size of the sample */
                   11179: 
                   11180:   for (i=0;i<=imx-1 ; i++) {
                   11181:     sump=sump+weight[i];
                   11182:     /*    sump=sump+1;*/
                   11183:     num=num+1;
                   11184:   }
                   11185:  
                   11186:  
                   11187:   /* for (i=0; i<=imx; i++) 
                   11188:      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]);*/
                   11189:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   11190:   for (i=1;i<=imx ; i++)
                   11191:     {
                   11192:       if (cens[i] == 1 && wav[i]>1)
                   11193:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   11194:       
                   11195:       if (cens[i] == 0 && wav[i]>1)
                   11196:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   11197:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   11198:       
                   11199:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   11200:       if (wav[i] > 1 ) { /* ??? */
                   11201:        LL=LL+A*weight[i];
                   11202:        /*      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]);*/
                   11203:       }
                   11204:     }
                   11205: 
                   11206:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   11207:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   11208:  
                   11209:   return -2*LL*num/sump;
                   11210: }
                   11211: #endif
                   11212: 
                   11213: /******************* Printing html file ***********/
                   11214: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
                   11215:                  int lastpass, int stepm, int weightopt, char model[],\
                   11216:                  int imx,  double p[],double **matcov,double agemortsup){
                   11217:   int i,k;
                   11218: 
                   11219:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   11220:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   11221:   for (i=1;i<=2;i++) 
                   11222:     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]));
                   11223:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
                   11224:   fprintf(fichtm,"</ul>");
                   11225: 
                   11226: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   11227: 
                   11228:  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>");
                   11229: 
                   11230:  for (k=agegomp;k<(agemortsup-2);k++) 
                   11231:    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]);
                   11232: 
                   11233:  
                   11234:   fflush(fichtm);
                   11235: }
                   11236: 
                   11237: /******************* Gnuplot file **************/
                   11238: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   11239: 
                   11240:   char dirfileres[132],optfileres[132];
                   11241: 
                   11242:   int ng;
                   11243: 
                   11244: 
                   11245:   /*#ifdef windows */
                   11246:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   11247:     /*#endif */
                   11248: 
                   11249: 
                   11250:   strcpy(dirfileres,optionfilefiname);
                   11251:   strcpy(optfileres,"vpl");
                   11252:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
                   11253:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
                   11254:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
                   11255:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
                   11256:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   11257: 
                   11258: } 
                   11259: 
                   11260: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   11261: {
                   11262: 
                   11263:   /*-------- data file ----------*/
                   11264:   FILE *fic;
                   11265:   char dummy[]="                         ";
                   11266:   int i=0, j=0, n=0, iv=0, v;
                   11267:   int lstra;
                   11268:   int linei, month, year,iout;
                   11269:   int noffset=0; /* This is the offset if BOM data file */
                   11270:   char line[MAXLINE], linetmp[MAXLINE];
                   11271:   char stra[MAXLINE], strb[MAXLINE];
                   11272:   char *stratrunc;
                   11273: 
                   11274:   /* DummyV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
                   11275:   /* FixedV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
                   11276:   
                   11277:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   11278:   
                   11279:   if((fic=fopen(datafile,"r"))==NULL)    {
                   11280:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   11281:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   11282:   }
                   11283: 
                   11284:     /* Is it a BOM UTF-8 Windows file? */
                   11285:   /* First data line */
                   11286:   linei=0;
                   11287:   while(fgets(line, MAXLINE, fic)) {
                   11288:     noffset=0;
                   11289:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   11290:     {
                   11291:       noffset=noffset+3;
                   11292:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   11293:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   11294:       fflush(ficlog); return 1;
                   11295:     }
                   11296:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   11297:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   11298:     {
                   11299:       noffset=noffset+2;
                   11300:       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);
                   11301:       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);
                   11302:       fflush(ficlog); return 1;
                   11303:     }
                   11304:     else if( line[0] == 0 && line[1] == 0)
                   11305:     {
                   11306:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   11307:        noffset=noffset+4;
                   11308:        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);
                   11309:        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);
                   11310:        fflush(ficlog); return 1;
                   11311:       }
                   11312:     } else{
                   11313:       ;/*printf(" Not a BOM file\n");*/
                   11314:     }
                   11315:         /* If line starts with a # it is a comment */
                   11316:     if (line[noffset] == '#') {
                   11317:       linei=linei+1;
                   11318:       break;
                   11319:     }else{
                   11320:       break;
                   11321:     }
                   11322:   }
                   11323:   fclose(fic);
                   11324:   if((fic=fopen(datafile,"r"))==NULL)    {
                   11325:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   11326:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   11327:   }
                   11328:   /* Not a Bom file */
                   11329:   
                   11330:   i=1;
                   11331:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   11332:     linei=linei+1;
                   11333:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   11334:       if(line[j] == '\t')
                   11335:        line[j] = ' ';
                   11336:     }
                   11337:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   11338:       ;
                   11339:     };
                   11340:     line[j+1]=0;  /* Trims blanks at end of line */
                   11341:     if(line[0]=='#'){
                   11342:       fprintf(ficlog,"Comment line\n%s\n",line);
                   11343:       printf("Comment line\n%s\n",line);
                   11344:       continue;
                   11345:     }
                   11346:     trimbb(linetmp,line); /* Trims multiple blanks in line */
                   11347:     strcpy(line, linetmp);
                   11348:     
                   11349:     /* Loops on waves */
                   11350:     for (j=maxwav;j>=1;j--){
                   11351:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
                   11352:        cutv(stra, strb, line, ' '); 
                   11353:        if(strb[0]=='.') { /* Missing value */
                   11354:          lval=-1;
                   11355:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   11356:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
                   11357:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   11358:            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);
                   11359:            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);
                   11360:            return 1;
                   11361:          }
                   11362:        }else{
                   11363:          errno=0;
                   11364:          /* what_kind_of_number(strb); */
                   11365:          dval=strtod(strb,&endptr); 
                   11366:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   11367:          /* if(strb != endptr && *endptr == '\0') */
                   11368:          /*    dval=dlval; */
                   11369:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   11370:          if( strb[0]=='\0' || (*endptr != '\0')){
                   11371:            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);
                   11372:            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);
                   11373:            return 1;
                   11374:          }
                   11375:          cotqvar[j][iv][i]=dval; 
                   11376:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
                   11377:        }
                   11378:        strcpy(line,stra);
                   11379:       }/* end loop ntqv */
                   11380:       
                   11381:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
                   11382:        cutv(stra, strb, line, ' '); 
                   11383:        if(strb[0]=='.') { /* Missing value */
                   11384:          lval=-1;
                   11385:        }else{
                   11386:          errno=0;
                   11387:          lval=strtol(strb,&endptr,10); 
                   11388:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   11389:          if( strb[0]=='\0' || (*endptr != '\0')){
                   11390:            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);
                   11391:            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);
                   11392:            return 1;
                   11393:          }
                   11394:        }
                   11395:        if(lval <-1 || lval >1){
                   11396:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
                   11397:  Should be a value of %d(nth) covariate of wave %d (0 should be the value for the reference and 1\n \
                   11398:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   11399:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11400:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11401:         V1=1 V2=0 for (2) \n                                           \
                   11402:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   11403:  output of IMaCh is often meaningless.\n                               \
                   11404:  Exiting.\n",lval,linei, i,line,iv,j);
                   11405:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
                   11406:  Should be a value of %d(nth) covariate of wave %d (0 should be the value for the reference and 1\n \
                   11407:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   11408:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11409:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11410:         V1=1 V2=0 for (2) \n                                           \
                   11411:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   11412:  output of IMaCh is often meaningless.\n                               \
                   11413:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
                   11414:          return 1;
                   11415:        }
                   11416:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
                   11417:        strcpy(line,stra);
                   11418:       }/* end loop ntv */
                   11419:       
                   11420:       /* Statuses  at wave */
                   11421:       cutv(stra, strb, line, ' '); 
                   11422:       if(strb[0]=='.') { /* Missing value */
                   11423:        lval=-1;
                   11424:       }else{
                   11425:        errno=0;
                   11426:        lval=strtol(strb,&endptr,10); 
                   11427:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   11428:        if( strb[0]=='\0' || (*endptr != '\0' )){
                   11429:          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);
                   11430:          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);
                   11431:          return 1;
                   11432:        }else if( lval==0 || lval > nlstate+ndeath){
                   11433:          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);
                   11434:          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);
                   11435:          return 1;
                   11436:        }
                   11437:       }
                   11438:       
                   11439:       s[j][i]=lval;
                   11440:       
                   11441:       /* Date of Interview */
                   11442:       strcpy(line,stra);
                   11443:       cutv(stra, strb,line,' ');
                   11444:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
                   11445:       }
                   11446:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
                   11447:        month=99;
                   11448:        year=9999;
                   11449:       }else{
                   11450:        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);
                   11451:        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);
                   11452:        return 1;
                   11453:       }
                   11454:       anint[j][i]= (double) year; 
                   11455:       mint[j][i]= (double)month;
                   11456:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   11457:       /*       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]); */
                   11458:       /*       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]); */
                   11459:       /* } */
                   11460:       strcpy(line,stra);
                   11461:     } /* End loop on waves */
                   11462:     
                   11463:     /* Date of death */
                   11464:     cutv(stra, strb,line,' '); 
                   11465:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
                   11466:     }
                   11467:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
                   11468:       month=99;
                   11469:       year=9999;
                   11470:     }else{
                   11471:       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);
                   11472:       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);
                   11473:       return 1;
                   11474:     }
                   11475:     andc[i]=(double) year; 
                   11476:     moisdc[i]=(double) month; 
                   11477:     strcpy(line,stra);
                   11478:     
                   11479:     /* Date of birth */
                   11480:     cutv(stra, strb,line,' '); 
                   11481:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
                   11482:     }
                   11483:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
                   11484:       month=99;
                   11485:       year=9999;
                   11486:     }else{
                   11487:       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);
                   11488:       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);
                   11489:       return 1;
                   11490:     }
                   11491:     if (year==9999) {
                   11492:       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);
                   11493:       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);
                   11494:       return 1;
                   11495:       
                   11496:     }
                   11497:     annais[i]=(double)(year);
                   11498:     moisnais[i]=(double)(month);
                   11499:     for (j=1;j<=maxwav;j++){
                   11500:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   11501:        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]);
                   11502:        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]);
                   11503:       }
                   11504:     }
                   11505: 
                   11506:     strcpy(line,stra);
                   11507:     
                   11508:     /* Sample weight */
                   11509:     cutv(stra, strb,line,' '); 
                   11510:     errno=0;
                   11511:     dval=strtod(strb,&endptr); 
                   11512:     if( strb[0]=='\0' || (*endptr != '\0')){
                   11513:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   11514:       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);
                   11515:       fflush(ficlog);
                   11516:       return 1;
                   11517:     }
                   11518:     weight[i]=dval; 
                   11519:     strcpy(line,stra);
                   11520:     
                   11521:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   11522:       cutv(stra, strb, line, ' '); 
                   11523:       if(strb[0]=='.') { /* Missing value */
                   11524:        lval=-1;
                   11525:        coqvar[iv][i]=NAN; 
                   11526:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
                   11527:       }else{
                   11528:        errno=0;
                   11529:        /* what_kind_of_number(strb); */
                   11530:        dval=strtod(strb,&endptr);
                   11531:        /* if(strb != endptr && *endptr == '\0') */
                   11532:        /*   dval=dlval; */
                   11533:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   11534:        if( strb[0]=='\0' || (*endptr != '\0')){
                   11535:          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);
                   11536:          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);
                   11537:          return 1;
                   11538:        }
                   11539:        coqvar[iv][i]=dval; 
                   11540:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
                   11541:       }
                   11542:       strcpy(line,stra);
                   11543:     }/* end loop nqv */
                   11544:     
                   11545:     /* Covariate values */
                   11546:     for (j=ncovcol;j>=1;j--){
                   11547:       cutv(stra, strb,line,' '); 
                   11548:       if(strb[0]=='.') { /* Missing covariate value */
                   11549:        lval=-1;
                   11550:       }else{
                   11551:        errno=0;
                   11552:        lval=strtol(strb,&endptr,10); 
                   11553:        if( strb[0]=='\0' || (*endptr != '\0')){
                   11554:          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);
                   11555:          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);
                   11556:          return 1;
                   11557:        }
                   11558:       }
                   11559:       if(lval <-1 || lval >1){
                   11560:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
                   11561:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   11562:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   11563:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11564:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11565:         V1=1 V2=0 for (2) \n                                           \
                   11566:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   11567:  output of IMaCh is often meaningless.\n                               \
                   11568:  Exiting.\n",lval,linei, i,line,j);
                   11569:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
                   11570:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   11571:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   11572:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   11573:  build V1=0 V2=0 for the reference value (1),\n                                \
                   11574:         V1=1 V2=0 for (2) \n                                           \
                   11575:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   11576:  output of IMaCh is often meaningless.\n                               \
                   11577:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   11578:        return 1;
                   11579:       }
                   11580:       covar[j][i]=(double)(lval);
                   11581:       strcpy(line,stra);
                   11582:     }  
                   11583:     lstra=strlen(stra);
                   11584:     
                   11585:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   11586:       stratrunc = &(stra[lstra-9]);
                   11587:       num[i]=atol(stratrunc);
                   11588:     }
                   11589:     else
                   11590:       num[i]=atol(stra);
                   11591:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   11592:       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;}*/
                   11593:     
                   11594:     i=i+1;
                   11595:   } /* End loop reading  data */
                   11596:   
                   11597:   *imax=i-1; /* Number of individuals */
                   11598:   fclose(fic);
                   11599:   
                   11600:   return (0);
                   11601:   /* endread: */
                   11602:   printf("Exiting readdata: ");
                   11603:   fclose(fic);
                   11604:   return (1);
                   11605: }
                   11606: 
                   11607: void removefirstspace(char **stri){/*, char stro[]) {*/
                   11608:   char *p1 = *stri, *p2 = *stri;
                   11609:   while (*p2 == ' ')
                   11610:     p2++; 
                   11611:   /* while ((*p1++ = *p2++) !=0) */
                   11612:   /*   ; */
                   11613:   /* do */
                   11614:   /*   while (*p2 == ' ') */
                   11615:   /*     p2++; */
                   11616:   /* while (*p1++ == *p2++); */
                   11617:   *stri=p2; 
                   11618: }
                   11619: 
                   11620: int decoderesult( char resultline[], int nres)
                   11621: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   11622: {
                   11623:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
                   11624:   char resultsav[MAXLINE];
                   11625:   /* int resultmodel[MAXLINE]; */
                   11626:   /* int modelresult[MAXLINE]; */
                   11627:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   11628: 
                   11629:   removefirstspace(&resultline);
                   11630:   printf("decoderesult:%s\n",resultline);
                   11631: 
                   11632:   strcpy(resultsav,resultline);
                   11633:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
                   11634:   if (strlen(resultsav) >1){
                   11635:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
                   11636:   }
1.2       brouard  11637:   if(j == 0 && cptcovs== 0){ /* Resultline but no =  and no covariate in the model */
1.1       brouard  11638:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   11639:     return (0);
                   11640:   }
                   11641:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.2       brouard  11642:     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);
                   11643:     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);
                   11644:     if(j==0)
                   11645:       return 1;
1.1       brouard  11646:   }
                   11647:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
                   11648:     if(nbocc(resultsav,'=') >1){
                   11649:       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" */
                   11650:       /* If resultsav= "V4= 1 V5=25.1 V3=0" with a blank then strb="V4=" and stra="1 V5=25.1 V3=0" */
                   11651:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
                   11652:       /* If a blank, then strc="V4=" and strd='\0' */
                   11653:       if(strc[0]=='\0'){
                   11654:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   11655:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   11656:        return 1;
                   11657:       }
                   11658:     }else
                   11659:       cutl(strc,strd,resultsav,'=');
                   11660:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
                   11661:     
                   11662:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
                   11663:     Tvarsel[k]=atoi(strc);  /* 4 */ /* Tvarsel is the id of the kth covariate in the result line Tvarsel[1] in "V4=1.." is 4.*/
                   11664:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   11665:     /* cptcovsel++;     */
                   11666:     if (nbocc(stra,'=') >0)
                   11667:       strcpy(resultsav,stra); /* and analyzes it */
                   11668:   }
                   11669:   /* Checking for missing or useless values in comparison of current model needs */
                   11670:   /* Feeds resultmodel[nres][k1]=k2 for k1th product covariate with age in the model equation fed by the index k2 of the resutline*/
                   11671:   for(k1=1; k1<= cptcovt ;k1++){ /* Loop on MODEL LINE V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11672:     if(Typevar[k1]==0){ /* Single covariate in model */
                   11673:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
                   11674:       match=0;
                   11675:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11676:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11677:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
                   11678:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11679:          break;
                   11680:        }
                   11681:       }
                   11682:       if(match == 0){
                   11683:        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]);
                   11684:        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);
                   11685:        return 1;
                   11686:       }
                   11687:     }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*/
                   11688:       /* We feed resultmodel[k1]=k2; */
                   11689:       match=0;
                   11690:       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 */
                   11691:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11692:          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 */
                   11693:          resultmodel[nres][k1]=k2; /* Added here */
                   11694:          /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
                   11695:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11696:          break;
                   11697:        }
                   11698:       }
                   11699:       if(match == 0){
                   11700:        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]);
                   11701:        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]);
                   11702:       return 1;
                   11703:       }
                   11704:     }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*/
                   11705:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   11706:       match=0;
                   11707:       /* 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]); */
                   11708:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11709:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11710:          /* modelresult[k2]=k1; */
                   11711:          /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
                   11712:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11713:        }
                   11714:       }
                   11715:       if(match == 0){
                   11716:        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);
                   11717:        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);
                   11718:        return 1;
                   11719:       }
                   11720:       match=0;
                   11721:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11722:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   11723:          /* modelresult[k2]=k1;*/
                   11724:          /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
                   11725:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   11726:          break;
                   11727:        }
                   11728:       }
                   11729:       if(match == 0){
                   11730:        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);
                   11731:        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);
                   11732:        return 1;
                   11733:       }
                   11734:     }/* End of testing */
                   11735:   }/* End loop cptcovt */
                   11736:   /* Checking for missing or useless values in comparison of current model needs */
                   11737:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
                   11738:   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)
                   11739:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11740:     match=0;
                   11741:     for(k1=1; k1<= cptcovt ;k1++){ /* loop on model: model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11742:       if(Typevar[k1]==0){ /* Single only */
                   11743:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4  What if a product?  */
                   11744:          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 */
                   11745:          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 */
                   11746:          ++match;
                   11747:        }
                   11748:       }
                   11749:     }
                   11750:     if(match == 0){
                   11751:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   11752:       fprintf(ficlog,"Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   11753:       return 1;
                   11754:     }else if(match > 1){
                   11755:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   11756:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   11757:       return 1;
                   11758:     }
                   11759:   }
                   11760:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
                   11761:   /* We need to deduce which combination number is chosen and save quantitative values */
                   11762:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11763:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   11764:   /* 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*/
                   11765:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   11766:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   11767:   /*    1 0 0 0 */
                   11768:   /*    2 1 0 0 */
                   11769:   /*    3 0 1 0 */ 
                   11770:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
                   11771:   /*    5 0 0 1 */
                   11772:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
                   11773:   /*    7 0 1 1 */
                   11774:   /*    8 1 1 1 */
                   11775:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   11776:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   11777:   /* V5*age V5 known which value for nres?  */
                   11778:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
                   11779:   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.
                   11780:                                                   * loop on position k1 in the MODEL LINE */
                   11781:     /* k counting number of combination of single dummies in the equation model */
                   11782:     /* k4 counting single dummies in the equation model */
                   11783:     /* k4q counting single quantitatives in the equation model */
                   11784:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Dummy and Single, fixed or timevarying, k1 is sorting according to MODEL, but k3 to resultline */
                   11785:        /* 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) */
                   11786:       /* modelresult[k3]=k1: k3th position in the result line corresponds to the k1 position in the model line (doesn't work with products)*/
                   11787:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
                   11788:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   11789:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   11790:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   11791:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   11792:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
                   11793:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
                   11794:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
                   11795:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
                   11796:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   11797:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   11798:       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)*/
                   11799:       k+=Tvalsel[k3]*pow(2,k4);  /* nres=1 k1=2 Tvalsel[1]=1 (V4=1); k1=3 k3=2 Tvalsel[2]=0 (V3=0) */
                   11800:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
                   11801:       /* Tinvresult[nres][4]=1 */
                   11802:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   11803:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   11804:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11805:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   11806:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
                   11807:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
                   11808:       /* 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); */
                   11809:       k4++;;
                   11810:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
                   11811:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
                   11812:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
                   11813:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
                   11814:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   11815:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   11816:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
                   11817:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   11818:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   11819:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   11820:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   11821:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   11822:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   11823:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
                   11824:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
                   11825:       precov[nres][k1]=Tvalsel[k3q];
                   11826:       /* 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]); */
                   11827:       k4q++;;
1.2       brouard  11828:     }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"*/
                   11829:       /* Tvar[k1]; */ /* Age variable */ /* 17 age*V6*V2 ?*/
1.1       brouard  11830:       /* Wrong we want the value of variable name Tvar[k1] */
1.2       brouard  11831:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   11832:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   11833:       /* 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]]); */
                   11834:       }else{
                   11835:        k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   11836:        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)*/
                   11837:        TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
                   11838:        precov[nres][k1]=Tvalsel[k3];
                   11839:       }
1.1       brouard  11840:       /* 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]); */
                   11841:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.2       brouard  11842:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   11843:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   11844:       /* 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]]); */
                   11845:       }else{
                   11846:        k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
                   11847:        k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
                   11848:        TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
                   11849:        precov[nres][k1]=Tvalsel[k3q];
                   11850:       }
1.1       brouard  11851:       /* 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]); */
                   11852:     }else if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   11853:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   11854:       /* 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]]); */
                   11855:     }else{
                   11856:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   11857:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   11858:     }
                   11859:   }
                   11860:   
                   11861:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
                   11862:   return (0);
                   11863: }
                   11864: 
                   11865: int decodemodel( char model[], int lastobs)
                   11866:  /**< This routine decodes the model and returns:
                   11867:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   11868:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   11869:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   11870:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   11871:        * - cptcovage number of covariates with age*products =2
                   11872:        * - cptcovs number of simple covariates
                   11873:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
                   11874:        * - 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
                   11875:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
                   11876:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
                   11877:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   11878:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   11879:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   11880:        */
                   11881: /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   11882: {
                   11883:   int i, j, k, ks, v;
                   11884:   int n,m;
                   11885:   int  j1, k1, k11, k12, k2, k3, k4;
                   11886:   char modelsav[300];
                   11887:   char stra[300], strb[300], strc[300], strd[300],stre[300],strf[300];
                   11888:   char *strpt;
                   11889:   int  **existcomb;
                   11890:   
                   11891:   existcomb=imatrix(1,NCOVMAX,1,NCOVMAX);
                   11892:   for(i=1;i<=NCOVMAX;i++)
                   11893:     for(j=1;j<=NCOVMAX;j++)
                   11894:       existcomb[i][j]=0;
                   11895:     
                   11896:   /*removespace(model);*/
                   11897:   if (strlen(model) >1){ /* If there is at least 1 covariate */
                   11898:     j=0, j1=0, k1=0, k12=0, k2=-1, ks=0, cptcovn=0;
                   11899:     if (strstr(model,"AGE") !=0){
                   11900:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   11901:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
                   11902:       return 1;
                   11903:     }
                   11904:     if (strstr(model,"v") !=0){
                   11905:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   11906:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
                   11907:       return 1;
                   11908:     }
                   11909:     strcpy(modelsav,model); 
                   11910:     if ((strpt=strstr(model,"age*age")) !=0){
                   11911:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
                   11912:       if(strpt != model){
                   11913:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
                   11914:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
                   11915:  corresponding column of parameters.\n",model);
                   11916:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
                   11917:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
                   11918:  corresponding column of parameters.\n",model); fflush(ficlog);
                   11919:        return 1;
                   11920:       }
                   11921:       nagesqr=1;
                   11922:       if (strstr(model,"+age*age") !=0)
                   11923:        substrchaine(modelsav, model, "+age*age");
                   11924:       else if (strstr(model,"age*age+") !=0)
                   11925:        substrchaine(modelsav, model, "age*age+");
                   11926:       else 
                   11927:        substrchaine(modelsav, model, "age*age");
                   11928:     }else
                   11929:       nagesqr=0;
                   11930:     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 */
                   11931:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   11932:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.2       brouard  11933:       cptcovs=0; /**<  Number of simple covariates V1 +V1*age +V3 +V3*V4 +age*age => V1 + V3 =4+1-3=2  Wrong */
1.1       brouard  11934:       cptcovt= j+1; /* Number of total covariates in the model, not including
                   11935:                     * cst, age and age*age 
                   11936:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   11937:       /* including age products which are counted in cptcovage.
                   11938:        * but the covariates which are products must be treated 
                   11939:        * separately: ncovn=4- 2=2 (V1+V3). */
1.2       brouard  11940:       cptcovprod=0; /**< Number of products  V1*V2 +v3*age = 2 */
                   11941:       cptcovdageprod=0; /* Number of doouble products with age age*Vn*VM or Vn*age*Vm or Vn*Vm*age */
1.1       brouard  11942:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.2       brouard  11943:       cptcovprodage=0;
1.1       brouard  11944:       /* cptcovprodage=nboccstr(modelsav,"age");*/
                   11945:       
                   11946:       /*   Design
                   11947:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   11948:        *  <          ncovcol=8                >
                   11949:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   11950:        *   k=  1    2      3       4     5       6      7        8
                   11951:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   11952:        *  covar[k,i], are for fixed covariates, value of kth covariate if not including age for individual i:
                   11953:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   11954:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
                   11955:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   11956:        *  Tage[++cptcovage]=k
                   11957:        *       if products, new covar are created after ncovcol + nqv (quanti fixed) with k1
                   11958:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   11959:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   11960:        *  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
                   11961:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   11962:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   11963:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   11964:        *  <          ncovcol=8  8 fixed covariate. Additional starts at 9 (V5*V6) and 10(V7*V8)              >
                   11965:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   11966:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   11967:        *     Tvard[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   11968:        * p Tvar[1]@12={2,   1,     3,      3,   9,     10,     8,       8}
                   11969:        * p Tprod[1]@2={                         6, 5}
                   11970:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   11971:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   11972:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   11973:        *How to reorganize? Tvars(orted)
                   11974:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   11975:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   11976:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   11977:        * Struct []
                   11978:        */
                   11979:       
                   11980:       /* This loop fills the array Tvar from the string 'model'.*/
                   11981:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   11982:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   11983:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   11984:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   11985:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   11986:       /*       k=1 Tvar[1]=2 (from V2) */
                   11987:       /*       k=5 Tvar[5] */
                   11988:       /* for (k=1; k<=cptcovn;k++) { */
                   11989:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   11990:       /*       } */
                   11991:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
                   11992:       /*
                   11993:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   11994:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   11995:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   11996:       }
                   11997:       cptcovage=0;
1.2       brouard  11998: 
                   11999:       /* First loop in order to calculate */
                   12000:       /* for age*VN*Vm
                   12001:        * Provides, Typevar[k], Tage[cptcovage], existcomb[n][m], FixedV[ncovcolt+k12]
                   12002:        * Tprod[k1]=k  Tposprod[k]=k1;    Tvard[k1][1] =m;
                   12003:       */
                   12004:       /* Needs  FixedV[Tvardk[k][1]] */
                   12005:       /* For others:
                   12006:        * Sets  Typevar[k];
                   12007:        * Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   12008:        *       Tposprod[k]=k11;
                   12009:        *       Tprod[k11]=k;
                   12010:        *       Tvardk[k][1] =m;
                   12011:        * Needs FixedV[Tvardk[k][1]] == 0
                   12012:       */
                   12013:       
1.1       brouard  12014:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   12015:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   12016:                                         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" */
                   12017:        if (nbocc(modelsav,'+')==0)
                   12018:          strcpy(strb,modelsav); /* and analyzes it */
                   12019:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   12020:        /*scanf("%d",i);*/
                   12021:        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  12022:          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  */
                   12023:          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  12024:            Typevar[k]=3;  /* 3 for age and double product age*Vn*Vm varying of fixed */
1.2       brouard  12025:             if(strstr(strc,"age")!=0) { /* It means that strc=V2*age or age*V2 and thus that strd=Vn */
                   12026:               cutl(stre,strf,strc,'*') ; /* strf=age or Vm, stre=Vm or age. If strc=V6*V2 then strf=V6 and stre=V2 */
                   12027:              strcpy(strc,strb); /* save strb(=age*Vn*Vm) into strc */
1.1       brouard  12028:              /* We want strb=Vn*Vm */
1.2       brouard  12029:               if(strcmp(strf,"age")==0){ /* strf is "age" so that stre=Vm =V2 . */
                   12030:                 strcpy(strb,strd);
                   12031:                 strcat(strb,"*");
                   12032:                 strcat(strb,stre);
                   12033:               }else{  /* strf=Vm  If strf=V6 then stre=V2 */
1.1       brouard  12034:                 strcpy(strb,strf);
                   12035:                 strcat(strb,"*");
1.2       brouard  12036:                 strcat(strb,stre);
                   12037:                 strcpy(strd,strb); /* in order for strd to not be "age"  for next test (will be Vn*Vm */
1.1       brouard  12038:               }
1.2       brouard  12039:              /* 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]]]); */
                   12040:              /* FixedV[Tvar[Tage[k]]]=0; /\* HERY not sure if V7*V4*age Fixed might not exist  yet*\/ */
                   12041:             }else{  /* strc=Vn*Vm (and strd=age) and should be strb=Vn*Vm but want to keep original strb double product  */
1.1       brouard  12042:              strcpy(stre,strb); /* save full b in stre */
                   12043:              strcpy(strb,strc); /* save short c in new short b for next block strb=Vn*Vm*/
                   12044:              strcpy(strf,strc); /* save short c in new short f */
                   12045:               cutl(strc,strd,strf,'*'); /* We get strd=Vn and strc=Vm for next block (strb=Vn*Vm)*/
                   12046:              /* strcpy(strc,stre);*/ /* save full e in c for future */
                   12047:             }
                   12048:             cptcovdageprod++; /* double product with age  Which product is it? */
                   12049:             /* 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 *\/ */
                   12050:             /* cutl(strc,strd,strb,'*'); /\* strd=  V6    or   V2     or    age and  strc=  V2 or    age or    V2 *\/ */
                   12051:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   12052:            n=atoi(stre);
                   12053:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   12054:            m=atoi(strc);
                   12055:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   12056:            Tage[cptcovage]=k; /* For age*V3*V2 gives the position in model of covariates associated with age Tage[1]=6 HERY too*/
                   12057:            if(existcomb[n][m] == 0){
                   12058:              /*  r /home/brouard/Documents/Recherches/REVES/Zachary/Zach-2022/Feinuo_Sun/Feinuo-threeway/femV12V15_3wayintNBe.imach */
                   12059:              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);
                   12060:              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);
                   12061:              fflush(ficlog);
                   12062:              k1++;  /* The combination Vn*Vm will be in the model so we create it at k1 */
                   12063:              k12++;
                   12064:              existcomb[n][m]=k1;
                   12065:              existcomb[m][n]=k1;
                   12066:              Tvar[k]=ncovcol+nqv+ntv+nqtv+k1;
                   12067:              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*/
                   12068:              Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 Gives the k1 double product  Vn*Vm or age*Vn*Vm at the k position */
                   12069:              Tvard[k1][1] =m; /* m 1 for V1*/
                   12070:              Tvardk[k][1] =m; /* m 1 for V1*/
                   12071:              Tvard[k1][2] =n; /* n 4 for V4*/
                   12072:              Tvardk[k][2] =n; /* n 4 for V4*/
1.2       brouard  12073: /*           Tvar[Tage[cptcovage]]=k1;*/ /* Tvar[6=age*V3*V2]=9 (new fixed covariate) */ /* We don't know about Fixed yet HERE */
1.1       brouard  12074:              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 */
                   12075:                for (i=1; i<=lastobs;i++){/* For fixed product */
                   12076:                  /* Computes the new covariate which is a product of
                   12077:                     covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   12078:                  covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   12079:                }
                   12080:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   12081:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   12082:                k12++;
                   12083:                FixedV[ncovcolt+k12]=0;
                   12084:              }else{ /*End of FixedV */
                   12085:                cptcovprodvage++; /* Counting the number of varying covariate with age */
                   12086:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   12087:                k12++;
                   12088:                FixedV[ncovcolt+k12]=1;
                   12089:              }
                   12090:            }else{  /* k1 Vn*Vm already exists */
                   12091:              k11=existcomb[n][m];
                   12092:              Tposprod[k]=k11; /* OK */
                   12093:              Tvar[k]=Tvar[Tprod[k11]]; /* HERY */
                   12094:              Tvardk[k][1]=m;
                   12095:              Tvardk[k][2]=n;
                   12096:              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 */
                   12097:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   12098:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   12099:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   12100:                Tvar[Tage[cptcovage]]=k1;
                   12101:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   12102:                k12++;
                   12103:                FixedV[ncovcolt+k12]=0;
                   12104:              }else{ /* Already exists but time varying (and age) */
                   12105:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   12106:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   12107:                /* Tvar[Tage[cptcovage]]=k1; */
                   12108:                cptcovprodvage++;
                   12109:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
1.2       brouard  12110:                k12++;
                   12111:                FixedV[ncovcolt+k12]=1;
1.1       brouard  12112:              }
                   12113:            }
                   12114:            /* Tage[cptcovage]=k;  /\*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   12115:            /* Tvar[k]=k11; /\* HERY *\/ */
                   12116:          } 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 */
                   12117:             cptcovprod++;
                   12118:             if (strcmp(strc,"age")==0) { /**< Model includes age: strb= Vn*age c=age d=Vn*/
                   12119:               /* covar is not filled and then is empty */
                   12120:               cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   12121:               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 */
                   12122:               Typevar[k]=1;  /* 1 for age product */
                   12123:               cptcovage++; /* Counts the number of covariates which include age as a product */
                   12124:               Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   12125:              if( FixedV[Tvar[k]] == 0){
                   12126:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   12127:              }else{
                   12128:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
                   12129:              }
                   12130:               /*printf("stre=%s ", stre);*/
                   12131:             } else if (strcmp(strd,"age")==0) { /* strb= age*Vn c=Vn */
                   12132:               cutl(stre,strb,strc,'V');
                   12133:               Tvar[k]=atoi(stre);
                   12134:               Typevar[k]=1;  /* 1 for age product */
                   12135:               cptcovage++;
                   12136:               Tage[cptcovage]=k;
                   12137:              if( FixedV[Tvar[k]] == 0){
                   12138:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   12139:              }else{
                   12140:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
                   12141:              }
                   12142:             }else{ /*  for product Vn*Vm */
                   12143:              Typevar[k]=2;  /* 2 for product Vn*Vm */
                   12144:              cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   12145:              n=atoi(stre);
                   12146:              cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   12147:              m=atoi(strc);
                   12148:              k1++;
                   12149:              cptcovprodnoage++;
                   12150:              if(existcomb[n][m] != 0 || existcomb[m][n] != 0){
                   12151:                printf("Warning in model combination V%d*V%d already exists in the model in position k1=%d!\n",n,m,existcomb[n][m]);
                   12152:                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]);
                   12153:                fflush(ficlog);
                   12154:                k11=existcomb[n][m];
                   12155:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   12156:                Tposprod[k]=k11;
                   12157:                Tprod[k11]=k;
                   12158:                Tvardk[k][1] =m; /* m 1 for V1*/
                   12159:                /* Tvard[k11][1] =m; /\* n 4 for V4*\/ */
                   12160:                Tvardk[k][2] =n; /* n 4 for V4*/                
                   12161:                /* Tvard[k11][2] =n; /\* n 4 for V4*\/ */
                   12162:              }else{ /* combination Vn*Vm doesn't exist we create it (no age)*/
                   12163:                existcomb[n][m]=k1;
                   12164:                existcomb[m][n]=k1;
                   12165:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
                   12166:                                                    because this model-covariate is a construction we invent a new column
                   12167:                                                    which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   12168:                                                    If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
                   12169:                                                    thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   12170:                                                    Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
                   12171:                /* Please remark that the new variables are model dependent */
                   12172:                /* If we have 4 variable but the model uses only 3, like in
                   12173:                 * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   12174:                 *  k=     1     2      3   4     5        6        7       8
                   12175:                 * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   12176:                 * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   12177:                 * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   12178:                 */
                   12179:                /* We need to feed some variables like TvarVV, but later on next loop because of ncovv (k2) is not correct */
                   12180:                Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 +V6*V2*age  */
                   12181:                Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
                   12182:                Tvard[k1][1] =m; /* m 1 for V1*/
                   12183:                Tvardk[k][1] =m; /* m 1 for V1*/
                   12184:                Tvard[k1][2] =n; /* n 4 for V4*/
                   12185:                Tvardk[k][2] =n; /* n 4 for V4*/
                   12186:                k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   12187:                /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   12188:                /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
                   12189:                /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
                   12190:                /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   12191:                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 */
                   12192:                  for (i=1; i<=lastobs;i++){/* For fixed product */
                   12193:                    /* Computes the new covariate which is a product of
                   12194:                       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   12195:                    covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   12196:                  }
                   12197:                  /* TvarVV[k2]=n; */
                   12198:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   12199:                  /* TvarVV[k2+1]=m; */
                   12200:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   12201:                }else{ /* not FixedV */
                   12202:                  /* TvarVV[k2]=n; */
                   12203:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   12204:                  /* TvarVV[k2+1]=m; */
                   12205:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   12206:                }                 
                   12207:              }  /* End of creation of Vn*Vm if not created by age*Vn*Vm earlier  */
                   12208:            } /*  End of product Vn*Vm */
                   12209:           } /* End of age*double product or simple product */
                   12210:        }else { /* not a product */
                   12211:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   12212:          /*  scanf("%d",i);*/
                   12213:          cutl(strd,strc,strb,'V');
                   12214:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   12215:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   12216:          Tvar[k]=atoi(strd);
                   12217:          Typevar[k]=0;  /* 0 for simple covariates */
                   12218:        }
                   12219:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
                   12220:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   12221:                                  scanf("%d",i);*/
                   12222:       } /* end of loop + on total covariates */
1.2       brouard  12223: 
                   12224:       
1.1       brouard  12225:     } /* end if strlen(modelsave == 0) age*age might exist */
                   12226:   } /* end if strlen(model == 0) */
                   12227:   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  */
                   12228: 
                   12229:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   12230:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   12231:   
                   12232:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   12233:      printf("cptcovprod=%d ", cptcovprod);
                   12234:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   12235:      scanf("%d ",i);*/
                   12236: 
                   12237: 
                   12238: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   12239:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
                   12240: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   12241:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   12242:    k =           1    2   3     4       5       6      7      8        9
                   12243:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
                   12244:    Typevar[k]=   0    0   0     2       1       0      2      1        0
                   12245:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   12246:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   12247:          Tmodelind[combination of covar]=k;
                   12248: */  
                   12249: /* Dispatching between quantitative and time varying covariates */
                   12250:   /* If Tvar[k] >ncovcol it is a product */
                   12251:   /* Tvar[k] is the value n of Vn with n varying for 1 to nvcol, or p  Vp=Vn*Vm for product */
                   12252:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
                   12253:   printf("Model=1+age+%s\n\
                   12254: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product, 3 for double product with age \n\
                   12255: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   12256: 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);
                   12257:   fprintf(ficlog,"Model=1+age+%s\n\
                   12258: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product, 3 for double product with age  \n\
                   12259: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   12260: 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);
                   12261:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
                   12262:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
1.2       brouard  12263: 
                   12264: 
                   12265:   /* Second loop for calculating  Fixed[k], Dummy[k]*/
                   12266: 
                   12267:   
1.1       brouard  12268:   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 */
                   12269:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
                   12270:       Fixed[k]= 0;
                   12271:       Dummy[k]= 0;
                   12272:       ncoveff++;
                   12273:       ncovf++;
                   12274:       nsd++;
                   12275:       modell[k].maintype= FTYPE;
                   12276:       TvarsD[nsd]=Tvar[k];
                   12277:       TvarsDind[nsd]=k;
                   12278:       TnsdVar[Tvar[k]]=nsd;
                   12279:       TvarF[ncovf]=Tvar[k];
                   12280:       TvarFind[ncovf]=k;
                   12281:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   12282:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   12283:     /* }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /\* Product of fixed dummy (<=ncovcol) covariates For a fixed product k is higher than ncovcol *\/ */
                   12284:     }else if( Tvar[k] <=ncovcol+nqv && Typevar[k]==0){/* Remind that product Vn*Vm are added in k Only simple fixed quantitative variable */
                   12285:       Fixed[k]= 0;
                   12286:       Dummy[k]= 1;
                   12287:       nqfveff++;
                   12288:       modell[k].maintype= FTYPE;
                   12289:       modell[k].subtype= FQ;
                   12290:       nsq++;
                   12291:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   12292:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
                   12293:       ncovf++;
                   12294:       TvarF[ncovf]=Tvar[k];
                   12295:       TvarFind[ncovf]=k;
                   12296:       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 */
                   12297:       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 */
                   12298:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
                   12299:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   12300:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   12301:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   12302:       ncovvt++;
                   12303:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   12304:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   12305: 
                   12306:       Fixed[k]= 1;
                   12307:       Dummy[k]= 0;
                   12308:       ntveff++; /* Only simple time varying dummy variable */
                   12309:       modell[k].maintype= VTYPE;
                   12310:       modell[k].subtype= VD;
                   12311:       nsd++;
                   12312:       TvarsD[nsd]=Tvar[k];
                   12313:       TvarsDind[nsd]=k;
                   12314:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
                   12315:       ncovv++; /* Only simple time varying variables */
                   12316:       TvarV[ncovv]=Tvar[k];
                   12317:       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 */
                   12318:       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 */
                   12319:       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 */
                   12320:       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);
                   12321:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
                   12322:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
                   12323:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   12324:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   12325:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   12326:       ncovvt++;
                   12327:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   12328:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   12329:       
                   12330:       Fixed[k]= 1;
                   12331:       Dummy[k]= 1;
                   12332:       nqtveff++;
                   12333:       modell[k].maintype= VTYPE;
                   12334:       modell[k].subtype= VQ;
                   12335:       ncovv++; /* Only simple time varying variables */
                   12336:       nsq++;
                   12337:       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) */
                   12338:       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) */
                   12339:       TvarV[ncovv]=Tvar[k];
                   12340:       TvarVind[ncovv]=k; /* TvarVind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Any time varying singele */
                   12341:       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 */
                   12342:       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 */
                   12343:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   12344:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   12345:       /* 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); */
                   12346:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
                   12347:     }else if (Typevar[k] == 1) {  /* product with age */
                   12348:       ncova++;
                   12349:       TvarA[ncova]=Tvar[k];
                   12350:       TvarAind[ncova]=k;
                   12351:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   12352:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   12353:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
                   12354:        Fixed[k]= 2;
                   12355:        Dummy[k]= 2;
                   12356:        modell[k].maintype= ATYPE;
                   12357:        modell[k].subtype= APFD;
                   12358:        ncovta++;
                   12359:        TvarAVVA[ncovta]=Tvar[k]; /*  (2)age*V3 */
                   12360:        TvarAVVAind[ncovta]=k;
                   12361:        /* ncoveff++; */
                   12362:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
                   12363:        Fixed[k]= 2;
                   12364:        Dummy[k]= 3;
                   12365:        modell[k].maintype= ATYPE;
                   12366:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   12367:        ncovta++;
                   12368:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   12369:        TvarAVVAind[ncovta]=k;
                   12370:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
                   12371:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
                   12372:        Fixed[k]= 3;
                   12373:        Dummy[k]= 2;
                   12374:        modell[k].maintype= ATYPE;
                   12375:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   12376:        ncovva++;
                   12377:        TvarVVA[ncovva]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   12378:        TvarVVAind[ncovva]=k;
                   12379:        ncovta++;
                   12380:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   12381:        TvarAVVAind[ncovta]=k;
                   12382:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
                   12383:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
                   12384:        Fixed[k]= 3;
                   12385:        Dummy[k]= 3;
                   12386:        modell[k].maintype= ATYPE;
                   12387:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   12388:        ncovva++;
                   12389:        TvarVVA[ncovva]=Tvar[k]; /*   */
                   12390:        TvarVVAind[ncovva]=k;
                   12391:        ncovta++;
                   12392:        TvarAVVA[ncovta]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   12393:        TvarAVVAind[ncovta]=k;
                   12394:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
                   12395:       }
                   12396:     }else if( Tposprod[k]>0  &&  Typevar[k]==2){  /* Detects if fixed product no age Vm*Vn */
                   12397:       printf("MEMORY ERRORR k=%d  Tposprod[k]=%d, Typevar[k]=%d\n ",k, Tposprod[k], Typevar[k]);
                   12398:       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 */
                   12399:       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]]);
                   12400:        Fixed[k]= 0;
                   12401:        Dummy[k]= 0;
                   12402:        ncoveff++;
                   12403:        ncovf++;
                   12404:        /* ncovv++; */
                   12405:        /* TvarVV[ncovv]=Tvardk[k][1]; */
                   12406:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   12407:        /* ncovv++; */
                   12408:        /* TvarVV[ncovv]=Tvardk[k][2]; */
                   12409:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   12410:        modell[k].maintype= FTYPE;
                   12411:        TvarF[ncovf]=Tvar[k];
                   12412:        /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
                   12413:        TvarFind[ncovf]=k;
                   12414:        TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   12415:        TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   12416:       }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  */
                   12417:        /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   12418:        /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   12419:        /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   12420:        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 */
                   12421:        ncovvt++;
                   12422:        TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   12423:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   12424:        ncovvt++;
                   12425:        TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   12426:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   12427:        
                   12428:        /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   12429:        /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   12430:        
                   12431:        if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   12432:          if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
                   12433:            Fixed[k]= 1;
                   12434:            Dummy[k]= 0;
                   12435:            modell[k].maintype= FTYPE;
                   12436:            modell[k].subtype= FPDD;            /*      Product fixed dummy * fixed dummy */
                   12437:            ncovf++; /* Fixed variables without age */
                   12438:            TvarF[ncovf]=Tvar[k];
                   12439:            TvarFind[ncovf]=k;
                   12440:          }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   12441:            Fixed[k]= 0;  /* Fixed product */
                   12442:            Dummy[k]= 1;
                   12443:            modell[k].maintype= FTYPE;
                   12444:            modell[k].subtype= FPDQ;            /*      Product fixed dummy * fixed quantitative */
                   12445:            ncovf++; /* Varying variables without age */
                   12446:            TvarF[ncovf]=Tvar[k];
                   12447:            TvarFind[ncovf]=k;
                   12448:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
                   12449:            Fixed[k]= 1;
                   12450:            Dummy[k]= 0;
                   12451:            modell[k].maintype= VTYPE;
                   12452:            modell[k].subtype= VPDD;            /*      Product fixed dummy * varying dummy */
                   12453:            ncovv++; /* Varying variables without age */
                   12454:            TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   12455:            TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   12456:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
                   12457:            Fixed[k]= 1;
                   12458:            Dummy[k]= 1;
                   12459:            modell[k].maintype= VTYPE;
                   12460:            modell[k].subtype= VPDQ;            /*      Product fixed dummy * varying quantitative */
                   12461:            ncovv++; /* Varying variables without age */
                   12462:            TvarV[ncovv]=Tvar[k];
                   12463:            TvarVind[ncovv]=k;
                   12464:          }
                   12465:        }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   12466:          if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   12467:            Fixed[k]= 0;  /*  Fixed product */
                   12468:            Dummy[k]= 1;
                   12469:            modell[k].maintype= FTYPE;
                   12470:            modell[k].subtype= FPDQ;            /*      Product fixed quantitative * fixed dummy */
                   12471:            ncovf++; /* Fixed variables without age */
                   12472:            TvarF[ncovf]=Tvar[k];
                   12473:            TvarFind[ncovf]=k;
                   12474:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
                   12475:            Fixed[k]= 1;
                   12476:            Dummy[k]= 1;
                   12477:            modell[k].maintype= VTYPE;
                   12478:            modell[k].subtype= VPDQ;            /*      Product fixed quantitative * varying dummy */
                   12479:            ncovv++; /* Varying variables without age */
                   12480:            TvarV[ncovv]=Tvar[k];
                   12481:            TvarVind[ncovv]=k;
                   12482:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
                   12483:            Fixed[k]= 1;
                   12484:            Dummy[k]= 1;
                   12485:            modell[k].maintype= VTYPE;
                   12486:            modell[k].subtype= VPQQ;            /*      Product fixed quantitative * varying quantitative */
                   12487:            ncovv++; /* Varying variables without age */
                   12488:            TvarV[ncovv]=Tvar[k];
                   12489:            TvarVind[ncovv]=k;
                   12490:            ncovv++; /* Varying variables without age */
                   12491:            TvarV[ncovv]=Tvar[k];
                   12492:            TvarVind[ncovv]=k;
                   12493:          }
                   12494:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
                   12495:          if(Tvard[k1][2] <=ncovcol){
                   12496:            Fixed[k]= 1;
                   12497:            Dummy[k]= 1;
                   12498:            modell[k].maintype= VTYPE;
                   12499:            modell[k].subtype= VPDD;            /*      Product time varying dummy * fixed dummy */
                   12500:            ncovv++; /* Varying variables without age */
                   12501:            TvarV[ncovv]=Tvar[k];
                   12502:            TvarVind[ncovv]=k;
                   12503:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   12504:            Fixed[k]= 1;
                   12505:            Dummy[k]= 1;
                   12506:            modell[k].maintype= VTYPE;
                   12507:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * fixed quantitative */
                   12508:            ncovv++; /* Varying variables without age */
                   12509:            TvarV[ncovv]=Tvar[k];
                   12510:            TvarVind[ncovv]=k;
                   12511:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   12512:            Fixed[k]= 1;
                   12513:            Dummy[k]= 0;
                   12514:            modell[k].maintype= VTYPE;
                   12515:            modell[k].subtype= VPDD;            /*      Product time varying dummy * time varying dummy */
                   12516:            ncovv++; /* Varying variables without age */
                   12517:            TvarV[ncovv]=Tvar[k];
                   12518:            TvarVind[ncovv]=k;
                   12519:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   12520:            Fixed[k]= 1;
                   12521:            Dummy[k]= 1;
                   12522:            modell[k].maintype= VTYPE;
                   12523:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * time varying quantitative */
                   12524:            ncovv++; /* Varying variables without age */
                   12525:            TvarV[ncovv]=Tvar[k];
                   12526:            TvarVind[ncovv]=k;
                   12527:          }
                   12528:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
                   12529:          if(Tvard[k1][2] <=ncovcol){
                   12530:            Fixed[k]= 1;
                   12531:            Dummy[k]= 1;
                   12532:            modell[k].maintype= VTYPE;
                   12533:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * fixed dummy */
                   12534:            ncovv++; /* Varying variables without age */
                   12535:            TvarV[ncovv]=Tvar[k];
                   12536:            TvarVind[ncovv]=k;
                   12537:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   12538:            Fixed[k]= 1;
                   12539:            Dummy[k]= 1;
                   12540:            modell[k].maintype= VTYPE;
                   12541:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * fixed quantitative */
                   12542:            ncovv++; /* Varying variables without age */
                   12543:            TvarV[ncovv]=Tvar[k];
                   12544:            TvarVind[ncovv]=k;
                   12545:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   12546:            Fixed[k]= 1;
                   12547:            Dummy[k]= 1;
                   12548:            modell[k].maintype= VTYPE;
                   12549:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * time varying dummy */
                   12550:            ncovv++; /* Varying variables without age */
                   12551:            TvarV[ncovv]=Tvar[k];
                   12552:            TvarVind[ncovv]=k;
                   12553:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   12554:            Fixed[k]= 1;
                   12555:            Dummy[k]= 1;
                   12556:            modell[k].maintype= VTYPE;
                   12557:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * time varying quantitative */
                   12558:            ncovv++; /* Varying variables without age */
                   12559:            TvarV[ncovv]=Tvar[k];
                   12560:            TvarVind[ncovv]=k;
                   12561:          }
                   12562:        }else{
                   12563:          printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12564:          fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12565:        } /*end k1*/
                   12566:       }
                   12567:     }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  */
                   12568:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   12569:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   12570:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   12571:       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 */
                   12572:       ncova++;
                   12573:       TvarA[ncova]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   12574:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   12575:       ncova++;
                   12576:       TvarA[ncova]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   12577:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   12578: 
                   12579:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   12580:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   12581:       if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){
                   12582:        ncovta++;
                   12583:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12584:        TvarAVVAind[ncovta]=k;
                   12585:        ncovta++;
                   12586:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12587:        TvarAVVAind[ncovta]=k;
                   12588:       }else{
                   12589:        ncovva++;  /* HERY  reached */
                   12590:        TvarVVA[ncovva]=Tvard[k1][1]; /*  age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4  */
                   12591:        TvarVVAind[ncovva]=k;
                   12592:        ncovva++;
                   12593:        TvarVVA[ncovva]=Tvard[k1][2]; /*   */
                   12594:        TvarVVAind[ncovva]=k;
                   12595:        ncovta++;
                   12596:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12597:        TvarAVVAind[ncovta]=k;
                   12598:        ncovta++;
                   12599:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   12600:        TvarAVVAind[ncovta]=k;
                   12601:       }
                   12602:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   12603:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
                   12604:          Fixed[k]= 2;
                   12605:          Dummy[k]= 2;
                   12606:          modell[k].maintype= FTYPE;
                   12607:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   12608:          /* TvarF[ncova]=Tvar[k];   /\* Problem to solve *\/ */
                   12609:          /* TvarFind[ncova]=k; */
                   12610:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   12611:          Fixed[k]= 2;  /* Fixed product */
                   12612:          Dummy[k]= 3;
                   12613:          modell[k].maintype= FTYPE;
                   12614:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   12615:          /* TvarF[ncova]=Tvar[k]; */
                   12616:          /* TvarFind[ncova]=k; */
                   12617:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
                   12618:          Fixed[k]= 3;
                   12619:          Dummy[k]= 2;
                   12620:          modell[k].maintype= VTYPE;
                   12621:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   12622:          TvarV[ncova]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   12623:          TvarVind[ncova]=k;/* TvarVind[1]=5 */ 
                   12624:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
                   12625:          Fixed[k]= 3;
                   12626:          Dummy[k]= 3;
                   12627:          modell[k].maintype= VTYPE;
                   12628:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   12629:          /* ncovv++; /\* Varying variables without age *\/ */
                   12630:          /* TvarV[ncovv]=Tvar[k]; */
                   12631:          /* TvarVind[ncovv]=k; */
                   12632:        }
                   12633:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   12634:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   12635:          Fixed[k]= 2;  /*  Fixed product */
                   12636:          Dummy[k]= 2;
                   12637:          modell[k].maintype= FTYPE;
                   12638:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   12639:          /* ncova++; /\* Fixed variables with age *\/ */
                   12640:          /* TvarF[ncovf]=Tvar[k]; */
                   12641:          /* TvarFind[ncovf]=k; */
                   12642:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
                   12643:          Fixed[k]= 2;
                   12644:          Dummy[k]= 3;
                   12645:          modell[k].maintype= VTYPE;
                   12646:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   12647:          /* ncova++; /\* Varying variables with age *\/ */
                   12648:          /* TvarV[ncova]=Tvar[k]; */
                   12649:          /* TvarVind[ncova]=k; */
                   12650:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
                   12651:          Fixed[k]= 3;
                   12652:          Dummy[k]= 2;
                   12653:          modell[k].maintype= VTYPE;
                   12654:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   12655:          ncova++; /* Varying variables without age */
                   12656:          TvarV[ncova]=Tvar[k];
                   12657:          TvarVind[ncova]=k;
                   12658:          /* ncova++; /\* Varying variables without age *\/ */
                   12659:          /* TvarV[ncova]=Tvar[k]; */
                   12660:          /* TvarVind[ncova]=k; */
                   12661:        }
                   12662:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
                   12663:        if(Tvard[k1][2] <=ncovcol){
                   12664:          Fixed[k]= 2;
                   12665:          Dummy[k]= 2;
                   12666:          modell[k].maintype= VTYPE;
                   12667:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   12668:          /* ncova++; /\* Varying variables with age *\/ */
                   12669:          /* TvarV[ncova]=Tvar[k]; */
                   12670:          /* TvarVind[ncova]=k; */
                   12671:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   12672:          Fixed[k]= 2;
                   12673:          Dummy[k]= 3;
                   12674:          modell[k].maintype= VTYPE;
                   12675:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   12676:          /* ncova++; /\* Varying variables with age *\/ */
                   12677:          /* TvarV[ncova]=Tvar[k]; */
                   12678:          /* TvarVind[ncova]=k; */
                   12679:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   12680:          Fixed[k]= 3;
                   12681:          Dummy[k]= 2;
                   12682:          modell[k].maintype= VTYPE;
                   12683:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   12684:          /* ncova++; /\* Varying variables with age *\/ */
                   12685:          /* TvarV[ncova]=Tvar[k]; */
                   12686:          /* TvarVind[ncova]=k; */
                   12687:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   12688:          Fixed[k]= 3;
                   12689:          Dummy[k]= 3;
                   12690:          modell[k].maintype= VTYPE;
                   12691:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   12692:          /* ncova++; /\* Varying variables with age *\/ */
                   12693:          /* TvarV[ncova]=Tvar[k]; */
                   12694:          /* TvarVind[ncova]=k; */
                   12695:        }
                   12696:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
                   12697:        if(Tvard[k1][2] <=ncovcol){
                   12698:          Fixed[k]= 2;
                   12699:          Dummy[k]= 2;
                   12700:          modell[k].maintype= VTYPE;
                   12701:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   12702:          /* ncova++; /\* Varying variables with age *\/ */
                   12703:          /* TvarV[ncova]=Tvar[k]; */
                   12704:          /* TvarVind[ncova]=k; */
                   12705:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   12706:          Fixed[k]= 2;
                   12707:          Dummy[k]= 3;
                   12708:          modell[k].maintype= VTYPE;
                   12709:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   12710:          /* ncova++; /\* Varying variables with age *\/ */
                   12711:          /* TvarV[ncova]=Tvar[k]; */
                   12712:          /* TvarVind[ncova]=k; */
                   12713:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   12714:          Fixed[k]= 3;
                   12715:          Dummy[k]= 2;
                   12716:          modell[k].maintype= VTYPE;
                   12717:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   12718:          /* ncova++; /\* Varying variables with age *\/ */
                   12719:          /* TvarV[ncova]=Tvar[k]; */
                   12720:          /* TvarVind[ncova]=k; */
                   12721:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   12722:          Fixed[k]= 3;
                   12723:          Dummy[k]= 3;
                   12724:          modell[k].maintype= VTYPE;
                   12725:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   12726:          /* ncova++; /\* Varying variables with age *\/ */
                   12727:          /* TvarV[ncova]=Tvar[k]; */
                   12728:          /* TvarVind[ncova]=k; */
                   12729:        }
                   12730:       }else{
                   12731:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12732:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   12733:       } /*end k1*/
                   12734:     } else{
                   12735:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   12736:       fprintf(ficlog,"Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   12737:     }
                   12738:     /* 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]); */
                   12739:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
                   12740:     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]);
                   12741:   }
                   12742:   ncovvta=ncovva;
                   12743:   /* Searching for doublons in the model */
                   12744:   for(k1=1; k1<= cptcovt;k1++){
                   12745:     for(k2=1; k2 <k1;k2++){
                   12746:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   12747:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
                   12748:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   12749:          if(Tvar[k1]==Tvar[k2]){
                   12750:            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]);
                   12751:            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);
                   12752:            return(1);
                   12753:          }
                   12754:        }else if (Typevar[k1] ==2){
                   12755:          k3=Tposprod[k1];
                   12756:          k4=Tposprod[k2];
                   12757:          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])) ){
                   12758:            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]]);
                   12759:            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);
                   12760:            return(1);
                   12761:          }
                   12762:        }
                   12763:       }
                   12764:     }
                   12765:   }
                   12766:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   12767:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   12768:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   12769:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
                   12770: 
                   12771:   free_imatrix(existcomb,1,NCOVMAX,1,NCOVMAX);
                   12772:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
                   12773:   /*endread:*/
                   12774:   printf("Exiting decodemodel: ");
                   12775:   return (1);
                   12776: }
                   12777: 
                   12778: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
                   12779: {/* Check ages at death */
                   12780:   int i, m;
                   12781:   int firstone=0;
                   12782:   
                   12783:   for (i=1; i<=imx; i++) {
                   12784:     for(m=2; (m<= maxwav); m++) {
                   12785:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   12786:        anint[m][i]=9999;
                   12787:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   12788:          s[m][i]=-1;
                   12789:       }
                   12790:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
                   12791:        *nberr = *nberr + 1;
                   12792:        if(firstone == 0){
                   12793:          firstone=1;
                   12794:        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);
                   12795:        }
                   12796:        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);
                   12797:        s[m][i]=-1;  /* Droping the death status */
                   12798:       }
                   12799:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
                   12800:        (*nberr)++;
                   12801:        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);
                   12802:        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);
                   12803:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   12804:       }
                   12805:     }
                   12806:   }
                   12807: 
                   12808:   for (i=1; i<=imx; i++)  {
                   12809:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   12810:     for(m=firstpass; (m<= lastpass); m++){
                   12811:       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 */
                   12812:        if (s[m][i] >= nlstate+1) {
                   12813:          if(agedc[i]>0){
                   12814:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
                   12815:              agev[m][i]=agedc[i];
                   12816:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
                   12817:            }else {
                   12818:              if ((int)andc[i]!=9999){
                   12819:                nbwarn++;
                   12820:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   12821:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   12822:                agev[m][i]=-1;
                   12823:              }
                   12824:            }
                   12825:          } /* agedc > 0 */
                   12826:        } /* end if */
                   12827:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   12828:                                 years but with the precision of a month */
                   12829:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   12830:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   12831:            agev[m][i]=1;
                   12832:          else if(agev[m][i] < *agemin){ 
                   12833:            *agemin=agev[m][i];
                   12834:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   12835:          }
                   12836:          else if(agev[m][i] >*agemax){
                   12837:            *agemax=agev[m][i];
                   12838:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
                   12839:          }
                   12840:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   12841:          /*     agev[m][i] = age[i]+2*m;*/
                   12842:        } /* en if 9*/
                   12843:        else { /* =9 */
                   12844:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
                   12845:          agev[m][i]=1;
                   12846:          s[m][i]=-1;
                   12847:        }
                   12848:       }
                   12849:       else if(s[m][i]==0) /*= 0 Unknown */
                   12850:        agev[m][i]=1;
                   12851:       else{
                   12852:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   12853:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   12854:        agev[m][i]=0;
                   12855:       }
                   12856:     } /* End for lastpass */
                   12857:   }
                   12858:     
                   12859:   for (i=1; i<=imx; i++)  {
                   12860:     for(m=firstpass; (m<=lastpass); m++){
                   12861:       if (s[m][i] > (nlstate+ndeath)) {
                   12862:        (*nberr)++;
                   12863:        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);     
                   12864:        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);     
                   12865:        return 1;
                   12866:       }
                   12867:     }
                   12868:   }
                   12869: 
                   12870:   /*for (i=1; i<=imx; i++){
                   12871:   for (m=firstpass; (m<lastpass); m++){
                   12872:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   12873: }
                   12874: 
                   12875: }*/
                   12876: 
                   12877: 
                   12878:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   12879:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
                   12880: 
                   12881:   return (0);
                   12882:  /* endread:*/
                   12883:     printf("Exiting calandcheckages: ");
                   12884:     return (1);
                   12885: }
                   12886: 
                   12887: #if defined(_MSC_VER)
                   12888: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   12889: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   12890: //#include "stdafx.h"
                   12891: //#include <stdio.h>
                   12892: //#include <tchar.h>
                   12893: //#include <windows.h>
                   12894: //#include <iostream>
                   12895: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   12896: 
                   12897: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   12898: 
                   12899: BOOL IsWow64()
                   12900: {
                   12901:        BOOL bIsWow64 = FALSE;
                   12902: 
                   12903:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   12904:        //  (HANDLE, PBOOL);
                   12905: 
                   12906:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   12907: 
                   12908:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   12909:        const char funcName[] = "IsWow64Process";
                   12910:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   12911:                GetProcAddress(module, funcName);
                   12912: 
                   12913:        if (NULL != fnIsWow64Process)
                   12914:        {
                   12915:                if (!fnIsWow64Process(GetCurrentProcess(),
                   12916:                        &bIsWow64))
                   12917:                        //throw std::exception("Unknown error");
                   12918:                        printf("Unknown error\n");
                   12919:        }
                   12920:        return bIsWow64 != FALSE;
                   12921: }
                   12922: #endif
                   12923: 
                   12924: void syscompilerinfo(int logged)
                   12925: {
                   12926: #include <stdint.h>
                   12927: 
                   12928:   /* #include "syscompilerinfo.h"*/
                   12929:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   12930:    /* /GS /W3 /Gy
                   12931:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   12932:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   12933:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
                   12934:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   12935:    */ 
                   12936:    /* 64 bits */
                   12937:    /*
                   12938:      /GS /W3 /Gy
                   12939:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   12940:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   12941:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   12942:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   12943:    /* Optimization are useless and O3 is slower than O2 */
                   12944:    /*
                   12945:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   12946:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   12947:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   12948:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   12949:    */
                   12950:    /* Link is */ /* /OUT:"visual studio
                   12951:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   12952:       /PDB:"visual studio
                   12953:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   12954:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   12955:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   12956:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   12957:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   12958:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   12959:       uiAccess='false'"
                   12960:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   12961:       /NOLOGO /TLBID:1
                   12962:    */
                   12963: 
                   12964: 
                   12965: #if defined __INTEL_COMPILER
                   12966: #if defined(__GNUC__)
                   12967:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   12968: #endif
                   12969: #elif defined(__GNUC__) 
                   12970: #ifndef  __APPLE__
                   12971: #include <gnu/libc-version.h>  /* Only on gnu */
                   12972: #endif
                   12973:    struct utsname sysInfo;
                   12974:    int cross = CROSS;
                   12975:    if (cross){
                   12976:           printf("Cross-");
                   12977:           if(logged) fprintf(ficlog, "Cross-");
                   12978:    }
                   12979: #endif
                   12980: 
                   12981:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
                   12982: #if defined(__clang__)
                   12983:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
                   12984: #endif
                   12985: #if defined(__ICC) || defined(__INTEL_COMPILER)
                   12986:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
                   12987: #endif
                   12988: #if defined(__GNUC__) || defined(__GNUG__)
                   12989:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
                   12990: #endif
                   12991: #if defined(__HP_cc) || defined(__HP_aCC)
                   12992:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
                   12993: #endif
                   12994: #if defined(__IBMC__) || defined(__IBMCPP__)
                   12995:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
                   12996: #endif
                   12997: #if defined(_MSC_VER)
                   12998:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
                   12999: #endif
                   13000: #if defined(__PGI)
                   13001:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
                   13002: #endif
                   13003: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
                   13004:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
                   13005: #endif
                   13006:    printf(" for "); if (logged) fprintf(ficlog, " for ");
                   13007:    
                   13008: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   13009: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   13010:     // Windows (x64 and x86)
                   13011:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
                   13012: #elif __unix__ // all unices, not all compilers
                   13013:     // Unix
                   13014:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
                   13015: #elif __linux__
                   13016:     // linux
                   13017:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
                   13018: #elif __APPLE__
                   13019:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
                   13020:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
                   13021: #endif
                   13022: 
                   13023: /*  __MINGW32__          */
                   13024: /*  __CYGWIN__  */
                   13025: /* __MINGW64__  */
                   13026: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   13027: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   13028: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   13029: /* _WIN64  // Defined for applications for Win64. */
                   13030: /* _M_X64 // Defined for compilations that target x64 processors. */
                   13031: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
                   13032: 
                   13033: #if UINTPTR_MAX == 0xffffffff
                   13034:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
                   13035: #elif UINTPTR_MAX == 0xffffffffffffffff
                   13036:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
                   13037: #else
                   13038:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
                   13039: #endif
                   13040: 
                   13041: #if defined(__GNUC__)
                   13042: # if defined(__GNUC_PATCHLEVEL__)
                   13043: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   13044:                             + __GNUC_MINOR__ * 100 \
                   13045:                             + __GNUC_PATCHLEVEL__)
                   13046: # else
                   13047: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   13048:                             + __GNUC_MINOR__ * 100)
                   13049: # endif
                   13050:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
                   13051:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
                   13052: 
                   13053:    if (uname(&sysInfo) != -1) {
                   13054:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
                   13055:         if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
                   13056:    }
                   13057:    else
                   13058:       perror("uname() error");
                   13059:    //#ifndef __INTEL_COMPILER 
                   13060: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
                   13061:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
                   13062:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
                   13063: #endif
                   13064: #endif
                   13065: 
                   13066:    //   void main ()
                   13067:    //   {
                   13068: #if defined(_MSC_VER)
                   13069:    if (IsWow64()){
                   13070:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   13071:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   13072:    }
                   13073:    else{
                   13074:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   13075:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   13076:    }
                   13077:    //     printf("\nPress Enter to continue...");
                   13078:    //     getchar();
                   13079:    //   }
                   13080: 
                   13081: #endif
                   13082:    
                   13083: 
                   13084: }
                   13085: 
                   13086: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
                   13087:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
                   13088:   /* Computes the prevalence limit for each combination of the dummy covariates */
                   13089:   int i, j, k, i1, k4=0, nres=0 ;
                   13090:   /* double ftolpl = 1.e-10; */
                   13091:   double age, agebase, agelim;
                   13092:   double tot;
                   13093: 
                   13094:   strcpy(filerespl,"PL_");
                   13095:   strcat(filerespl,fileresu);
                   13096:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   13097:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   13098:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   13099:   }
                   13100:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   13101:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   13102:   pstamp(ficrespl);
                   13103:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
                   13104:   fprintf(ficrespl,"#Age ");
                   13105:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   13106:   fprintf(ficrespl,"\n");
                   13107:   
                   13108:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   13109: 
                   13110:   agebase=ageminpar;
                   13111:   agelim=agemaxpar;
                   13112: 
                   13113:   /* i1=pow(2,ncoveff); */
                   13114:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   13115:   if (cptcovn < 1){i1=1;}
                   13116: 
                   13117:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
                   13118:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   13119:       k=TKresult[nres];
                   13120:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   13121:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   13122:       /*       continue; */
                   13123: 
                   13124:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   13125:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   13126:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   13127:       /* k=k+1; */
                   13128:       /* to clean */
                   13129:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
                   13130:       fprintf(ficrespl,"#******");
                   13131:       printf("#******");
                   13132:       fprintf(ficlog,"#******");
                   13133:       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) */
                   13134:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
                   13135:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   13136:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   13137:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   13138:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   13139:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   13140:       }
                   13141:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   13142:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   13143:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   13144:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   13145:       /* } */
                   13146:       fprintf(ficrespl,"******\n");
                   13147:       printf("******\n");
                   13148:       fprintf(ficlog,"******\n");
                   13149:       if(invalidvarcomb[k]){
                   13150:        printf("\nCombination (%d) ignored because no case \n",k); 
                   13151:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   13152:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   13153:        continue;
                   13154:       }
                   13155: 
                   13156:       fprintf(ficrespl,"#Age ");
                   13157:       /* for(j=1;j<=cptcoveff;j++) { */
                   13158:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   13159:       /* } */
                   13160:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   13161:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   13162:       }
                   13163:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   13164:       fprintf(ficrespl,"Total Years_to_converge\n");
                   13165:     
                   13166:       for (age=agebase; age<=agelim; age++){
                   13167:        /* for (age=agebase; age<=agebase; age++){ */
                   13168:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   13169:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
                   13170:        fprintf(ficrespl,"%.0f ",age );
                   13171:        /* for(j=1;j<=cptcoveff;j++) */
                   13172:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   13173:        for(j=1;j<=cptcovs;j++)
                   13174:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   13175:        tot=0.;
                   13176:        for(i=1; i<=nlstate;i++){
                   13177:          tot +=  prlim[i][i];
                   13178:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   13179:        }
                   13180:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   13181:       } /* Age */
                   13182:       /* was end of cptcod */
                   13183:     } /* nres */
                   13184:   /* } /\* for each combination *\/ */
                   13185:   return 0;
                   13186: }
                   13187: 
                   13188: 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){
                   13189:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
                   13190:        
                   13191:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   13192:    * at any age between ageminpar and agemaxpar
                   13193:         */
                   13194:   int i, j, k, i1, nres=0 ;
                   13195:   /* double ftolpl = 1.e-10; */
                   13196:   double age, agebase, agelim;
                   13197:   double tot;
                   13198:   /* double ***mobaverage; */
                   13199:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
                   13200: 
                   13201:   strcpy(fileresplb,"PLB_");
                   13202:   strcat(fileresplb,fileresu);
                   13203:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
                   13204:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   13205:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   13206:   }
                   13207:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   13208:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
                   13209:   pstamp(ficresplb);
                   13210:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
                   13211:   fprintf(ficresplb,"#Age ");
                   13212:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   13213:   fprintf(ficresplb,"\n");
                   13214:   
                   13215:   
                   13216:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   13217:   
                   13218:   agebase=ageminpar;
                   13219:   agelim=agemaxpar;
                   13220:   
                   13221:   
                   13222:   i1=pow(2,cptcoveff);
                   13223:   if (cptcovn < 1){i1=1;}
                   13224:   
                   13225:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   13226:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   13227:       k=TKresult[nres];
                   13228:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   13229:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   13230:      /*        continue; */
                   13231:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
                   13232:       fprintf(ficresplb,"#******");
                   13233:       printf("#******");
                   13234:       fprintf(ficlog,"#******");
                   13235:       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) */
                   13236:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   13237:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   13238:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   13239:       }
                   13240:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   13241:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   13242:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   13243:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   13244:       /* } */
                   13245:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   13246:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   13247:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   13248:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   13249:       /* } */
                   13250:       fprintf(ficresplb,"******\n");
                   13251:       printf("******\n");
                   13252:       fprintf(ficlog,"******\n");
                   13253:       if(invalidvarcomb[k]){
                   13254:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   13255:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   13256:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   13257:        continue;
                   13258:       }
                   13259:     
                   13260:       fprintf(ficresplb,"#Age ");
                   13261:       for(j=1;j<=cptcovs;j++) {
                   13262:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   13263:       }
                   13264:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   13265:       fprintf(ficresplb,"Total Years_to_converge\n");
                   13266:     
                   13267:     
                   13268:       for (age=agebase; age<=agelim; age++){
                   13269:        /* for (age=agebase; age<=agebase; age++){ */
                   13270:        if(mobilavproj > 0){
                   13271:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   13272:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   13273:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
                   13274:        }else if (mobilavproj == 0){
                   13275:          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);
                   13276:          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);
                   13277:          exit(1);
                   13278:        }else{
                   13279:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   13280:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
                   13281:          /* printf("TOTOT\n"); */
                   13282:           /* exit(1); */
                   13283:        }
                   13284:        fprintf(ficresplb,"%.0f ",age );
                   13285:        for(j=1;j<=cptcovs;j++)
                   13286:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   13287:        tot=0.;
                   13288:        for(i=1; i<=nlstate;i++){
                   13289:          tot +=  bprlim[i][i];
                   13290:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   13291:        }
                   13292:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   13293:       } /* Age */
                   13294:       /* was end of cptcod */
                   13295:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
                   13296:     /* } /\* end of any combination *\/ */
                   13297:   } /* end of nres */  
                   13298:   /* hBijx(p, bage, fage); */
                   13299:   /* fclose(ficrespijb); */
                   13300:   
                   13301:   return 0;
                   13302: }
                   13303:  
                   13304: int hPijx(double *p, int bage, int fage){
                   13305:     /*------------- h Pij x at various ages ------------*/
                   13306:   /* to be optimized with precov */
                   13307:   int stepsize;
                   13308:   int agelim;
                   13309:   int hstepm;
                   13310:   int nhstepm;
                   13311:   int h, i, i1, j, k, k4, nres=0;
                   13312: 
                   13313:   double agedeb;
                   13314:   double ***p3mat;
                   13315: 
                   13316:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   13317:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   13318:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   13319:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   13320:   }
                   13321:   printf("Computing pij: result on file '%s' \n", filerespij);
                   13322:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   13323:   
                   13324:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   13325:   /*if (stepm<=24) stepsize=2;*/
                   13326:   
                   13327:   agelim=AGESUP;
                   13328:   hstepm=stepsize*YEARM; /* Every year of age */
                   13329:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   13330:   
                   13331:   /* hstepm=1;   aff par mois*/
                   13332:   pstamp(ficrespij);
                   13333:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   13334:   i1= pow(2,cptcoveff);
                   13335:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   13336:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   13337:   /*   k=k+1;  */
                   13338:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   13339:     k=TKresult[nres];
                   13340:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   13341:     /* for(k=1; k<=i1;k++){ */
                   13342:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   13343:     /*         continue; */
                   13344:     fprintf(ficrespij,"\n#****** ");
                   13345:     for(j=1;j<=cptcovs;j++){
                   13346:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   13347:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   13348:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   13349:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   13350:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   13351:     }
                   13352:     fprintf(ficrespij,"******\n");
                   13353:     
                   13354:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   13355:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   13356:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   13357:       
                   13358:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   13359:       
                   13360:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   13361:       oldm=oldms;savm=savms;
                   13362:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   13363:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   13364:       for(i=1; i<=nlstate;i++)
                   13365:        for(j=1; j<=nlstate+ndeath;j++)
                   13366:          fprintf(ficrespij," %1d-%1d",i,j);
                   13367:       fprintf(ficrespij,"\n");
                   13368:       for (h=0; h<=nhstepm; h++){
                   13369:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   13370:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
                   13371:        for(i=1; i<=nlstate;i++)
                   13372:          for(j=1; j<=nlstate+ndeath;j++)
                   13373:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
                   13374:        fprintf(ficrespij,"\n");
                   13375:       }
                   13376:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   13377:       fprintf(ficrespij,"\n");
                   13378:     }
                   13379:   }
                   13380:   /*}*/
                   13381:   return 0;
                   13382: }
                   13383:  
                   13384:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
                   13385:     /*------------- h Bij x at various ages ------------*/
                   13386:     /* To be optimized with precov */
                   13387:   int stepsize;
                   13388:   /* int agelim; */
                   13389:        int ageminl;
                   13390:   int hstepm;
                   13391:   int nhstepm;
                   13392:   int h, i, i1, j, k, nres;
                   13393:        
                   13394:   double agedeb;
                   13395:   double ***p3mat;
                   13396:        
                   13397:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   13398:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   13399:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   13400:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   13401:   }
                   13402:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   13403:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   13404:   
                   13405:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   13406:   /*if (stepm<=24) stepsize=2;*/
                   13407:   
                   13408:   /* agelim=AGESUP; */
                   13409:   ageminl=AGEINF; /* was 30 */
                   13410:   hstepm=stepsize*YEARM; /* Every year of age */
                   13411:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   13412:   
                   13413:   /* hstepm=1;   aff par mois*/
                   13414:   pstamp(ficrespijb);
                   13415:   fprintf(ficrespijb,"#****** h Bij x Back probability to be in state i at age x-h being in j at x: B1j+B2j+...=1 ");
                   13416:   i1= pow(2,cptcoveff);
                   13417:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   13418:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   13419:   /*   k=k+1;  */
                   13420:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   13421:     k=TKresult[nres];
                   13422:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   13423:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   13424:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   13425:     /*         continue; */
                   13426:     fprintf(ficrespijb,"\n#****** ");
                   13427:     for(j=1;j<=cptcovs;j++){
                   13428:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   13429:       /* for(j=1;j<=cptcoveff;j++) */
                   13430:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   13431:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   13432:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   13433:     }
                   13434:     fprintf(ficrespijb,"******\n");
                   13435:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   13436:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   13437:       continue;
                   13438:     }
                   13439:     
                   13440:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   13441:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   13442:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   13443:       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 */
                   13444:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   13445:       
                   13446:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   13447:       
                   13448:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   13449:       /* and memory limitations if stepm is small */
                   13450:       
                   13451:       /* oldm=oldms;savm=savms; */
                   13452:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   13453:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   13454:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   13455:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   13456:       for(i=1; i<=nlstate;i++)
                   13457:        for(j=1; j<=nlstate+ndeath;j++)
                   13458:          fprintf(ficrespijb," %1d-%1d",i,j);
                   13459:       fprintf(ficrespijb,"\n");
                   13460:       for (h=0; h<=nhstepm; h++){
                   13461:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   13462:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   13463:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   13464:        for(i=1; i<=nlstate;i++)
                   13465:          for(j=1; j<=nlstate+ndeath;j++)
                   13466:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
                   13467:        fprintf(ficrespijb,"\n");
                   13468:       }
                   13469:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   13470:       fprintf(ficrespijb,"\n");
                   13471:     } /* end age deb */
                   13472:     /* } /\* end combination *\/ */
                   13473:   } /* end nres */
                   13474:   return 0;
                   13475:  } /*  hBijx */
                   13476: 
                   13477: 
                   13478: /***********************************************/
                   13479: /**************** Main Program *****************/
                   13480: /***********************************************/
                   13481: 
                   13482: int main(int argc, char *argv[])
                   13483: {
                   13484: #ifdef GSL
                   13485:   const gsl_multimin_fminimizer_type *T;
                   13486:   size_t iteri = 0, it;
                   13487:   int rval = GSL_CONTINUE;
                   13488:   int status = GSL_SUCCESS;
                   13489:   double ssval;
                   13490: #endif
                   13491:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
                   13492:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   13493:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
                   13494:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
                   13495:   int jj, ll, li, lj, lk;
                   13496:   int numlinepar=0; /* Current linenumber of parameter file */
                   13497:   int num_filled;
                   13498:   int itimes;
                   13499:   int NDIM=2;
                   13500:   int vpopbased=0;
                   13501:   int nres=0;
                   13502:   int endishere=0;
                   13503:   int noffset=0;
                   13504:   int ncurrv=0; /* Temporary variable */
                   13505:   
                   13506:   char ca[32], cb[32];
                   13507:   /*  FILE *fichtm; *//* Html File */
                   13508:   /* FILE *ficgp;*/ /*Gnuplot File */
                   13509:   struct stat info;
                   13510:   double agedeb=0.;
                   13511: 
                   13512:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
                   13513:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
                   13514: 
                   13515:   double fret;
                   13516:   double dum=0.; /* Dummy variable */
                   13517:   double ***p3mat;
                   13518:   /* double ***mobaverage; */
                   13519:   double wald;
                   13520: 
1.2       brouard  13521:   char line[MAXLINE], linetmp[MAXLINE];
1.1       brouard  13522:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   13523: 
                   13524:   char  modeltemp[MAXLINE];
                   13525:   char resultline[MAXLINE], resultlineori[MAXLINE];
                   13526:   
                   13527:   char pathr[MAXLINE], pathimach[MAXLINE]; 
                   13528:   char *tok, *val; /* pathtot */
                   13529:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
                   13530:   int c,  h , cpt, c2;
                   13531:   int jl=0;
                   13532:   int i1, j1, jk, stepsize=0;
                   13533:   int count=0;
                   13534: 
                   13535:   int *tab; 
                   13536:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   13537:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   13538:   /* double anprojf, mprojf, jprojf; */
                   13539:   /* double jintmean,mintmean,aintmean;   */
                   13540:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   13541:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   13542:   double yrfproj= 10.0; /* Number of years of forward projections */
                   13543:   double yrbproj= 10.0; /* Number of years of backward projections */
                   13544:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
                   13545:   int mobilav=0,popforecast=0;
                   13546:   int hstepm=0, nhstepm=0;
                   13547:   int agemortsup;
                   13548:   float  sumlpop=0.;
                   13549:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   13550:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   13551: 
                   13552:   double bage=0, fage=110., age, agelim=0., agebase=0.;
                   13553:   double ftolpl=FTOL;
                   13554:   double **prlim;
                   13555:   double **bprlim;
                   13556:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   13557:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
                   13558:   double ***paramstart; /* Matrix of starting parameter values */
                   13559:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
                   13560:   double **matcov; /* Matrix of covariance */
                   13561:   double **hess; /* Hessian matrix */
                   13562:   double ***delti3; /* Scale */
                   13563:   double *delti; /* Scale */
                   13564:   double ***eij, ***vareij;
                   13565:   double **varpl; /* Variances of prevalence limits by age */
                   13566: 
                   13567:   double *epj, vepp;
                   13568: 
                   13569:   double dateprev1, dateprev2;
                   13570:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   13571:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   13572: 
                   13573: 
                   13574:   double **ximort;
                   13575:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
                   13576:   int *dcwave;
                   13577: 
                   13578:   char z[1]="c";
                   13579: 
                   13580:   /*char  *strt;*/
                   13581:   char strtend[80];
                   13582: 
                   13583: 
                   13584: /*   setlocale (LC_ALL, ""); */
                   13585: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   13586: /*   textdomain (PACKAGE); */
                   13587: /*   setlocale (LC_CTYPE, ""); */
                   13588: /*   setlocale (LC_MESSAGES, ""); */
                   13589: 
                   13590:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
                   13591:   rstart_time = time(NULL);  
                   13592:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   13593:   start_time = *localtime(&rstart_time);
                   13594:   curr_time=start_time;
                   13595:   /*tml = *localtime(&start_time.tm_sec);*/
                   13596:   /* strcpy(strstart,asctime(&tml)); */
                   13597:   strcpy(strstart,asctime(&start_time));
                   13598: 
                   13599: /*  printf("Localtime (at start)=%s",strstart); */
                   13600: /*  tp.tm_sec = tp.tm_sec +86400; */
                   13601: /*  tm = *localtime(&start_time.tm_sec); */
                   13602: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   13603: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   13604: /*   tmg.tm_hour=tmg.tm_hour + 1; */
                   13605: /*   tp.tm_sec = mktime(&tmg); */
                   13606: /*   strt=asctime(&tmg); */
                   13607: /*   printf("Time(after) =%s",strstart);  */
                   13608: /*  (void) time (&time_value);
                   13609: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   13610: *  tm = *localtime(&time_value);
                   13611: *  strstart=asctime(&tm);
                   13612: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   13613: */
                   13614: 
                   13615:   nberr=0; /* Number of errors and warnings */
                   13616:   nbwarn=0;
                   13617: #ifdef WIN32
                   13618:   _getcwd(pathcd, size);
                   13619: #else
                   13620:   getcwd(pathcd, size);
                   13621: #endif
                   13622:   syscompilerinfo(0);
1.5     ! brouard  13623:   printf("\nIMaCh prax version minfit %s, %s\n%s",version, copyright, fullversion);
1.1       brouard  13624:   if(argc <=1){
                   13625:     printf("\nEnter the parameter file name: ");
                   13626:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   13627:       printf("ERROR Empty parameter file name\n");
                   13628:       goto end;
                   13629:     }
                   13630:     i=strlen(pathr);
                   13631:     if(pathr[i-1]=='\n')
                   13632:       pathr[i-1]='\0';
                   13633:     i=strlen(pathr);
                   13634:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
                   13635:       pathr[i-1]='\0';
                   13636:     }
                   13637:     i=strlen(pathr);
                   13638:     if( i==0 ){
                   13639:       printf("ERROR Empty parameter file name\n");
                   13640:       goto end;
                   13641:     }
                   13642:     for (tok = pathr; tok != NULL; ){
                   13643:       printf("Pathr |%s|\n",pathr);
                   13644:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   13645:       printf("val= |%s| pathr=%s\n",val,pathr);
                   13646:       strcpy (pathtot, val);
                   13647:       if(pathr[0] == '\0') break; /* Dirty */
                   13648:     }
                   13649:   }
                   13650:   else if (argc<=2){
                   13651:     strcpy(pathtot,argv[1]);
                   13652:   }
                   13653:   else{
                   13654:     strcpy(pathtot,argv[1]);
                   13655:     strcpy(z,argv[2]);
                   13656:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
                   13657:   }
                   13658:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   13659:   /*cygwin_split_path(pathtot,path,optionfile);
                   13660:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   13661:   /* cutv(path,optionfile,pathtot,'\\');*/
                   13662: 
                   13663:   /* Split argv[0], imach program to get pathimach */
                   13664:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   13665:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   13666:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   13667:  /*   strcpy(pathimach,argv[0]); */
                   13668:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   13669:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   13670:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
                   13671: #ifdef WIN32
                   13672:   _chdir(path); /* Can be a relative path */
                   13673:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   13674: #else
                   13675:   chdir(path); /* Can be a relative path */
                   13676:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   13677: #endif
                   13678:   printf("Current directory %s!\n",pathcd);
                   13679:   strcpy(command,"mkdir ");
                   13680:   strcat(command,optionfilefiname);
                   13681:   if((outcmd=system(command)) != 0){
                   13682:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
                   13683:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   13684:     /* fclose(ficlog); */
                   13685: /*     exit(1); */
                   13686:   }
                   13687: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   13688: /*     perror("mkdir"); */
                   13689: /*   } */
                   13690: 
                   13691:   /*-------- arguments in the command line --------*/
                   13692: 
                   13693:   /* Main Log file */
                   13694:   strcat(filelog, optionfilefiname);
                   13695:   strcat(filelog,".log");    /* */
                   13696:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   13697:     printf("Problem with logfile %s\n",filelog);
                   13698:     goto end;
                   13699:   }
                   13700:   fprintf(ficlog,"Log filename:%s\n",filelog);
                   13701:   fprintf(ficlog,"Version %s %s",version,fullversion);
                   13702:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   13703:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   13704:  path=%s \n\
                   13705:  optionfile=%s\n\
                   13706:  optionfilext=%s\n\
                   13707:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
                   13708: 
                   13709:   syscompilerinfo(1);
                   13710: 
                   13711:   printf("Local time (at start):%s",strstart);
                   13712:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   13713:   fflush(ficlog);
                   13714: /*   (void) gettimeofday(&curr_time,&tzp); */
                   13715: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
                   13716: 
                   13717:   /* */
                   13718:   strcpy(fileres,"r");
                   13719:   strcat(fileres, optionfilefiname);
                   13720:   strcat(fileresu, optionfilefiname); /* Without r in front */
                   13721:   strcat(fileres,".txt");    /* Other files have txt extension */
                   13722:   strcat(fileresu,".txt");    /* Other files have txt extension */
                   13723: 
                   13724:   /* Main ---------arguments file --------*/
                   13725: 
                   13726:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
                   13727:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   13728:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   13729:     fflush(ficlog);
                   13730:     /* goto end; */
                   13731:     exit(70); 
                   13732:   }
                   13733: 
                   13734:   strcpy(filereso,"o");
                   13735:   strcat(filereso,fileresu);
                   13736:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   13737:     printf("Problem with Output resultfile: %s\n", filereso);
                   13738:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   13739:     fflush(ficlog);
                   13740:     goto end;
                   13741:   }
                   13742:       /*-------- Rewriting parameter file ----------*/
                   13743:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   13744:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   13745:   strcat(rfileres,".");    /* */
                   13746:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   13747:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   13748:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   13749:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   13750:     fflush(ficlog);
                   13751:     goto end;
                   13752:   }
                   13753:   fprintf(ficres,"#IMaCh %s\n",version);
                   13754: 
                   13755:                                      
                   13756:   /* Reads comments: lines beginning with '#' */
                   13757:   numlinepar=0;
                   13758:   /* Is it a BOM UTF-8 Windows file? */
                   13759:   /* First parameter line */
                   13760:   while(fgets(line, MAXLINE, ficpar)) {
                   13761:     noffset=0;
                   13762:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   13763:     {
                   13764:       noffset=noffset+3;
                   13765:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   13766:     }
                   13767: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   13768:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   13769:     {
                   13770:       noffset=noffset+2;
                   13771:       printf("# File is an UTF16BE BOM file\n");
                   13772:     }
                   13773:     else if( line[0] == 0 && line[1] == 0)
                   13774:     {
                   13775:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   13776:        noffset=noffset+4;
                   13777:        printf("# File is an UTF16BE BOM file\n");
                   13778:       }
                   13779:     } else{
                   13780:       ;/*printf(" Not a BOM file\n");*/
                   13781:     }
                   13782:   
                   13783:     /* If line starts with a # it is a comment */
                   13784:     if (line[noffset] == '#') {
                   13785:       numlinepar++;
                   13786:       fputs(line,stdout);
                   13787:       fputs(line,ficparo);
                   13788:       fputs(line,ficres);
                   13789:       fputs(line,ficlog);
                   13790:       continue;
                   13791:     }else
                   13792:       break;
                   13793:   }
                   13794:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   13795:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   13796:     if (num_filled != 5) {
                   13797:       printf("Should be 5 parameters\n");
                   13798:       fprintf(ficlog,"Should be 5 parameters\n");
                   13799:     }
                   13800:     numlinepar++;
                   13801:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13802:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13803:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13804:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   13805:   }
                   13806:   /* Second parameter line */
                   13807:   while(fgets(line, MAXLINE, ficpar)) {
                   13808:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   13809:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
                   13810:     if (line[0] == '#') {
                   13811:       numlinepar++;
                   13812:       printf("%s",line);
                   13813:       fprintf(ficres,"%s",line);
                   13814:       fprintf(ficparo,"%s",line);
                   13815:       fprintf(ficlog,"%s",line);
                   13816:       continue;
                   13817:     }else
                   13818:       break;
                   13819:   }
                   13820:   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", \
                   13821:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   13822:     if (num_filled != 11) {
                   13823:       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");
                   13824:       printf("but line=%s\n",line);
                   13825:       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");
                   13826:       fprintf(ficlog,"but line=%s\n",line);
                   13827:     }
                   13828:     if( lastpass > maxwav){
                   13829:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   13830:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   13831:       fflush(ficlog);
                   13832:       goto end;
                   13833:     }
                   13834:       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);
                   13835:     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);
                   13836:     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);
                   13837:     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);
                   13838:   }
                   13839:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   13840:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   13841:   /* Third parameter line */
                   13842:   while(fgets(line, MAXLINE, ficpar)) {
                   13843:     /* If line starts with a # it is a comment */
                   13844:     if (line[0] == '#') {
                   13845:       numlinepar++;
                   13846:       printf("%s",line);
                   13847:       fprintf(ficres,"%s",line);
                   13848:       fprintf(ficparo,"%s",line);
                   13849:       fprintf(ficlog,"%s",line);
                   13850:       continue;
                   13851:     }else
                   13852:       break;
                   13853:   }
1.2       brouard  13854:   if((num_filled=sscanf(line,"model=%[^.\n]", model)) !=EOF){ /* Every character after model but dot and  return */
                   13855:     if (num_filled != 1){
                   13856:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13857:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13858:       model[0]='\0';
                   13859:       goto end;
                   13860:     }else{
                   13861:       trimbtab(linetmp,line); /* Trims multiple blanks in line */
                   13862:       strcpy(line, linetmp);
                   13863:     }
                   13864:   }
                   13865:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){ /* Every character after 1+age but dot and  return */
1.1       brouard  13866:     if (num_filled != 1){
                   13867:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13868:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   13869:       model[0]='\0';
                   13870:       goto end;
                   13871:     }
                   13872:     else{
                   13873:       if (model[0]=='+'){
                   13874:        for(i=1; i<=strlen(model);i++)
                   13875:          modeltemp[i-1]=model[i];
                   13876:        strcpy(model,modeltemp); 
                   13877:       }
                   13878:     }
                   13879:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
                   13880:     printf("model=1+age+%s\n",model);fflush(stdout);
                   13881:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   13882:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   13883:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
                   13884:   }
                   13885:   /* 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); */
                   13886:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   13887:   /* 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); */
                   13888:   /* 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); */
                   13889:   /* 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); */
                   13890:   fflush(ficlog);
                   13891:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   13892:   if(model[0]=='#'){
                   13893:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   13894:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   13895:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
                   13896:     if(mle != -1){
                   13897:       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");
                   13898:       exit(1);
                   13899:     }
                   13900:   }
                   13901:   while((c=getc(ficpar))=='#' && c!= EOF){
                   13902:     ungetc(c,ficpar);
                   13903:     fgets(line, MAXLINE, ficpar);
                   13904:     numlinepar++;
                   13905:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   13906:       z[0]=line[1];
                   13907:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
                   13908:       debugILK=1;printf("DebugILK\n");
                   13909:     }
                   13910:     /* printf("****line [1] = %c \n",line[1]); */
                   13911:     fputs(line, stdout);
                   13912:     //puts(line);
                   13913:     fputs(line,ficparo);
                   13914:     fputs(line,ficlog);
                   13915:   }
                   13916:   ungetc(c,ficpar);
                   13917: 
                   13918:    
                   13919:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   13920:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   13921:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
                   13922:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
                   13923:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
                   13924:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   13925:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   13926:      v1+v2*age+v2*v3 makes cptcovn = 3
                   13927:   */
                   13928:   if (strlen(model)>1) 
                   13929:     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*/
                   13930:   else
                   13931:     ncovmodel=2; /* Constant and age */
                   13932:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   13933:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
                   13934:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   13935:     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);
                   13936:     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);
                   13937:     fflush(stdout);
                   13938:     fclose (ficlog);
                   13939:     goto end;
                   13940:   }
                   13941:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13942:   delti=delti3[1][1];
                   13943:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   13944:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   13945: /* We could also provide initial parameters values giving by simple logistic regression 
                   13946:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   13947:       /* for(i=1;i<nlstate;i++){ */
                   13948:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13949:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13950:       /* } */
                   13951:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   13952:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   13953:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   13954:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   13955:     fclose (ficparo);
                   13956:     fclose (ficlog);
                   13957:     goto end;
                   13958:     exit(0);
                   13959:   }  else if(mle==-5) { /* Main Wizard */
                   13960:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   13961:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   13962:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   13963:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13964:     matcov=matrix(1,npar,1,npar);
                   13965:     hess=matrix(1,npar,1,npar);
                   13966:   }  else{ /* Begin of mle != -1 or -5 */
                   13967:     /* Read guessed parameters */
                   13968:     /* Reads comments: lines beginning with '#' */
                   13969:     while((c=getc(ficpar))=='#' && c!= EOF){
                   13970:       ungetc(c,ficpar);
                   13971:       fgets(line, MAXLINE, ficpar);
                   13972:       numlinepar++;
                   13973:       fputs(line,stdout);
                   13974:       fputs(line,ficparo);
                   13975:       fputs(line,ficlog);
                   13976:     }
                   13977:     ungetc(c,ficpar);
                   13978:     
                   13979:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13980:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   13981:     for(i=1; i <=nlstate; i++){
                   13982:       j=0;
                   13983:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   13984:        if(jj==i) continue;
                   13985:        j++;
                   13986:        while((c=getc(ficpar))=='#' && c!= EOF){
                   13987:          ungetc(c,ficpar);
                   13988:          fgets(line, MAXLINE, ficpar);
                   13989:          numlinepar++;
                   13990:          fputs(line,stdout);
                   13991:          fputs(line,ficparo);
                   13992:          fputs(line,ficlog);
                   13993:        }
                   13994:        ungetc(c,ficpar);
                   13995:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   13996:        if ((i1 != i) || (j1 != jj)){
                   13997:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   13998: It might be a problem of design; if ncovcol and the model are correct\n \
                   13999: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   14000:          exit(1);
                   14001:        }
                   14002:        fprintf(ficparo,"%1d%1d",i1,j1);
                   14003:        if(mle==1)
                   14004:          printf("%1d%1d",i,jj);
                   14005:        fprintf(ficlog,"%1d%1d",i,jj);
                   14006:        for(k=1; k<=ncovmodel;k++){
                   14007:          fscanf(ficpar," %lf",&param[i][j][k]);
                   14008:          if(mle==1){
                   14009:            printf(" %lf",param[i][j][k]);
                   14010:            fprintf(ficlog," %lf",param[i][j][k]);
                   14011:          }
                   14012:          else
                   14013:            fprintf(ficlog," %lf",param[i][j][k]);
                   14014:          fprintf(ficparo," %lf",param[i][j][k]);
                   14015:        }
                   14016:        fscanf(ficpar,"\n");
                   14017:        numlinepar++;
                   14018:        if(mle==1)
                   14019:          printf("\n");
                   14020:        fprintf(ficlog,"\n");
                   14021:        fprintf(ficparo,"\n");
                   14022:       }
                   14023:     }  
                   14024:     fflush(ficlog);
                   14025:     
                   14026:     /* Reads parameters values */
                   14027:     p=param[1][1];
                   14028:     pstart=paramstart[1][1];
                   14029:     
                   14030:     /* Reads comments: lines beginning with '#' */
                   14031:     while((c=getc(ficpar))=='#' && c!= EOF){
                   14032:       ungetc(c,ficpar);
                   14033:       fgets(line, MAXLINE, ficpar);
                   14034:       numlinepar++;
                   14035:       fputs(line,stdout);
                   14036:       fputs(line,ficparo);
                   14037:       fputs(line,ficlog);
                   14038:     }
                   14039:     ungetc(c,ficpar);
                   14040: 
                   14041:     for(i=1; i <=nlstate; i++){
                   14042:       for(j=1; j <=nlstate+ndeath-1; j++){
                   14043:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   14044:        if ( (i1-i) * (j1-j) != 0){
                   14045:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   14046:          exit(1);
                   14047:        }
                   14048:        printf("%1d%1d",i,j);
                   14049:        fprintf(ficparo,"%1d%1d",i1,j1);
                   14050:        fprintf(ficlog,"%1d%1d",i1,j1);
                   14051:        for(k=1; k<=ncovmodel;k++){
                   14052:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   14053:          printf(" %le",delti3[i][j][k]);
                   14054:          fprintf(ficparo," %le",delti3[i][j][k]);
                   14055:          fprintf(ficlog," %le",delti3[i][j][k]);
                   14056:        }
                   14057:        fscanf(ficpar,"\n");
                   14058:        numlinepar++;
                   14059:        printf("\n");
                   14060:        fprintf(ficparo,"\n");
                   14061:        fprintf(ficlog,"\n");
                   14062:       }
                   14063:     }
                   14064:     fflush(ficlog);
                   14065:     
                   14066:     /* Reads covariance matrix */
                   14067:     delti=delti3[1][1];
                   14068:                
                   14069:                
                   14070:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   14071:                
                   14072:     /* Reads comments: lines beginning with '#' */
                   14073:     while((c=getc(ficpar))=='#' && c!= EOF){
                   14074:       ungetc(c,ficpar);
                   14075:       fgets(line, MAXLINE, ficpar);
                   14076:       numlinepar++;
                   14077:       fputs(line,stdout);
                   14078:       fputs(line,ficparo);
                   14079:       fputs(line,ficlog);
                   14080:     }
                   14081:     ungetc(c,ficpar);
                   14082:                
                   14083:     matcov=matrix(1,npar,1,npar);
                   14084:     hess=matrix(1,npar,1,npar);
                   14085:     for(i=1; i <=npar; i++)
                   14086:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   14087:                
                   14088:     /* Scans npar lines */
                   14089:     for(i=1; i <=npar; i++){
                   14090:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
                   14091:       if(count != 3){
                   14092:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   14093: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   14094: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   14095:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   14096: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   14097: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   14098:        exit(1);
                   14099:       }else{
                   14100:        if(mle==1)
                   14101:          printf("%1d%1d%d",i1,j1,jk);
                   14102:       }
                   14103:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   14104:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
                   14105:       for(j=1; j <=i; j++){
                   14106:        fscanf(ficpar," %le",&matcov[i][j]);
                   14107:        if(mle==1){
                   14108:          printf(" %.5le",matcov[i][j]);
                   14109:        }
                   14110:        fprintf(ficlog," %.5le",matcov[i][j]);
                   14111:        fprintf(ficparo," %.5le",matcov[i][j]);
                   14112:       }
                   14113:       fscanf(ficpar,"\n");
                   14114:       numlinepar++;
                   14115:       if(mle==1)
                   14116:                                printf("\n");
                   14117:       fprintf(ficlog,"\n");
                   14118:       fprintf(ficparo,"\n");
                   14119:     }
                   14120:     /* End of read covariance matrix npar lines */
                   14121:     for(i=1; i <=npar; i++)
                   14122:       for(j=i+1;j<=npar;j++)
                   14123:        matcov[i][j]=matcov[j][i];
                   14124:     
                   14125:     if(mle==1)
                   14126:       printf("\n");
                   14127:     fprintf(ficlog,"\n");
                   14128:     
                   14129:     fflush(ficlog);
                   14130:     
                   14131:   }    /* End of mle != -3 */
                   14132:   
                   14133:   /*  Main data
                   14134:    */
                   14135:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   14136:   /* num=lvector(1,n); */
                   14137:   /* moisnais=vector(1,n); */
                   14138:   /* annais=vector(1,n); */
                   14139:   /* moisdc=vector(1,n); */
                   14140:   /* andc=vector(1,n); */
                   14141:   /* weight=vector(1,n); */
                   14142:   /* agedc=vector(1,n); */
                   14143:   /* cod=ivector(1,n); */
                   14144:   /* for(i=1;i<=n;i++){ */
                   14145:   num=lvector(firstobs,lastobs);
                   14146:   moisnais=vector(firstobs,lastobs);
                   14147:   annais=vector(firstobs,lastobs);
                   14148:   moisdc=vector(firstobs,lastobs);
                   14149:   andc=vector(firstobs,lastobs);
                   14150:   weight=vector(firstobs,lastobs);
                   14151:   agedc=vector(firstobs,lastobs);
                   14152:   cod=ivector(firstobs,lastobs);
                   14153:   for(i=firstobs;i<=lastobs;i++){
                   14154:     num[i]=0;
                   14155:     moisnais[i]=0;
                   14156:     annais[i]=0;
                   14157:     moisdc[i]=0;
                   14158:     andc[i]=0;
                   14159:     agedc[i]=0;
                   14160:     cod[i]=0;
                   14161:     weight[i]=1.0; /* Equal weights, 1 by default */
                   14162:   }
                   14163:   mint=matrix(1,maxwav,firstobs,lastobs);
                   14164:   anint=matrix(1,maxwav,firstobs,lastobs);
                   14165:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
                   14166:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
                   14167:   tab=ivector(1,NCOVMAX);
                   14168:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
                   14169:   ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
                   14170: 
                   14171:   /* Reads data from file datafile */
                   14172:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   14173:     goto end;
                   14174: 
                   14175:   /* Calculation of the number of parameters from char model */
                   14176:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   14177:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   14178:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   14179:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   14180:        k=1 Tvar[1]=2 (from V2)
                   14181:   */
                   14182:   
                   14183:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   14184:   TvarsDind=ivector(1,NCOVMAX); /*  */
                   14185:   TnsdVar=ivector(1,NCOVMAX); /*  */
                   14186:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
                   14187:   TvarsD=ivector(1,NCOVMAX); /*  */
                   14188:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   14189:   TvarsQ=ivector(1,NCOVMAX); /*  */
                   14190:   TvarF=ivector(1,NCOVMAX); /*  */
                   14191:   TvarFind=ivector(1,NCOVMAX); /*  */
                   14192:   TvarV=ivector(1,NCOVMAX); /*  */
                   14193:   TvarVind=ivector(1,NCOVMAX); /*  */
                   14194:   TvarA=ivector(1,NCOVMAX); /*  */
                   14195:   TvarAind=ivector(1,NCOVMAX); /*  */
                   14196:   TvarFD=ivector(1,NCOVMAX); /*  */
                   14197:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   14198:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   14199:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   14200:   TvarVD=ivector(1,NCOVMAX); /*  */
                   14201:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   14202:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   14203:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   14204:   TvarVV=ivector(1,NCOVMAX); /*  */
                   14205:   TvarVVind=ivector(1,NCOVMAX); /*  */
                   14206:   TvarVVA=ivector(1,NCOVMAX); /*  */
                   14207:   TvarVVAind=ivector(1,NCOVMAX); /*  */
                   14208:   TvarAVVA=ivector(1,NCOVMAX); /*  */
                   14209:   TvarAVVAind=ivector(1,NCOVMAX); /*  */
                   14210: 
                   14211:   Tvalsel=vector(1,NCOVMAX); /*  */
                   14212:   Tvarsel=ivector(1,NCOVMAX); /*  */
                   14213:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   14214:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   14215:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
                   14216:   DummyV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   14217:   FixedV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   14218: 
                   14219:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   14220:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   14221:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   14222:   */
                   14223:   /* For model-covariate k tells which data-covariate to use but
                   14224:     because this model-covariate is a construction we invent a new column
                   14225:     ncovcol + k1
                   14226:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   14227:     Tvar[3=V1*V4]=4+1 etc */
                   14228:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   14229:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
                   14230:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   14231:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   14232:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
                   14233:   */
                   14234:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   14235:   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
                   14236:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   14237:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.2       brouard  14238:   Tvardk=imatrix(0,NCOVMAX,1,2);
1.1       brouard  14239:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
                   14240:                         4 covariates (3 plus signs)
                   14241:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   14242:                           */  
                   14243:   for(i=1;i<NCOVMAX;i++)
                   14244:     Tage[i]=0;
                   14245:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
                   14246:                                * individual dummy, fixed or varying:
                   14247:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   14248:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   14249:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   14250:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   14251:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   14252:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   14253:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
                   14254:                                * individual quantitative, fixed or varying:
                   14255:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   14256:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   14257:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
                   14258: 
                   14259: /* Probably useless zeroes */
                   14260:   for(i=1;i<NCOVMAX;i++){
                   14261:     DummyV[i]=0;
                   14262:     FixedV[i]=0;
                   14263:   }
                   14264: 
                   14265:   for(i=1; i <=ncovcol;i++){
                   14266:     DummyV[i]=0;
                   14267:     FixedV[i]=0;
                   14268:   }
                   14269:   for(i=ncovcol+1; i <=ncovcol+nqv;i++){
                   14270:     DummyV[i]=1;
                   14271:     FixedV[i]=0;
                   14272:   }
                   14273:   for(i=ncovcol+nqv+1; i <=ncovcol+nqv+ntv;i++){
                   14274:     DummyV[i]=0;
                   14275:     FixedV[i]=1;
                   14276:   }
                   14277:   for(i=ncovcol+nqv+ntv+1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   14278:     DummyV[i]=1;
                   14279:     FixedV[i]=1;
                   14280:   }
                   14281:   for(i=1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   14282:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",i,i,DummyV[i],i,FixedV[i]);
                   14283:     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]);
                   14284:   }
                   14285: 
                   14286: 
                   14287: 
                   14288: /* Main decodemodel */
                   14289: 
                   14290: 
                   14291:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
                   14292:     goto end;
                   14293: 
                   14294:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   14295:     nbwarn++;
                   14296:     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); 
                   14297:     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); 
                   14298:   }
                   14299:     /*  if(mle==1){*/
                   14300:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   14301:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
                   14302:   }
                   14303: 
                   14304:     /*-calculation of age at interview from date of interview and age at death -*/
                   14305:   agev=matrix(1,maxwav,1,imx);
                   14306: 
                   14307:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   14308:     goto end;
                   14309: 
                   14310: 
                   14311:   agegomp=(int)agemin;
                   14312:   free_vector(moisnais,firstobs,lastobs);
                   14313:   free_vector(annais,firstobs,lastobs);
                   14314:   /* free_matrix(mint,1,maxwav,1,n);
                   14315:      free_matrix(anint,1,maxwav,1,n);*/
                   14316:   /* free_vector(moisdc,1,n); */
                   14317:   /* free_vector(andc,1,n); */
                   14318:   /* */
                   14319:   
                   14320:   wav=ivector(1,imx);
                   14321:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   14322:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   14323:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   14324:   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.*/
                   14325:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   14326:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
                   14327:    
                   14328:   /* Concatenates waves */
                   14329:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   14330:      Death is a valid wave (if date is known).
                   14331:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   14332:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   14333:      and mw[mi+1][i]. dh depends on stepm.
                   14334:   */
                   14335: 
                   14336:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
                   14337:   /* Concatenates waves */
                   14338:  
                   14339:   free_vector(moisdc,firstobs,lastobs);
                   14340:   free_vector(andc,firstobs,lastobs);
                   14341: 
                   14342:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   14343:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   14344:   ncodemax[1]=1;
                   14345:   Ndum =ivector(-1,NCOVMAX);  
                   14346:   cptcoveff=0;
                   14347:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   14348:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; as well as calculate cptcoveff or number of total effective dummy covariates*/
                   14349:   }
                   14350:   
                   14351:   ncovcombmax=pow(2,cptcoveff);
                   14352:   invalidvarcomb=ivector(0, ncovcombmax); 
                   14353:   for(i=0;i<ncovcombmax;i++)
                   14354:     invalidvarcomb[i]=0;
                   14355:   
                   14356:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
                   14357:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
                   14358:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
                   14359:   
                   14360:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
                   14361:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
                   14362:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
                   14363:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   14364:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   14365:    * (currently 0 or 1) in the data.
                   14366:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   14367:    * corresponding modality (h,j).
                   14368:    */
                   14369: 
                   14370:   h=0;
                   14371:   /*if (cptcovn > 0) */
                   14372:   m=pow(2,cptcoveff);
                   14373:  
                   14374:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
                   14375:           * For k=4 covariates, h goes from 1 to m=2**k
                   14376:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   14377:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   14378:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   14379:           *______________________________   *______________________
                   14380:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   14381:           *     2     2     1     1     1   *     1     0  0  0  1 
                   14382:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   14383:           *     4     2     2     1     1   *     3     0  0  1  1 
                   14384:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   14385:           *     6     2     1     2     1   *     5     0  1  0  1 
                   14386:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   14387:           *     8     2     2     2     1   *     7     0  1  1  1 
                   14388:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   14389:           *    10     2     1     1     2   *     9     1  0  0  1 
                   14390:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   14391:           *    12     2     2     1     2   *    11     1  0  1  1 
                   14392:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   14393:           *    14     2     1     2     2   *    13     1  1  0  1 
                   14394:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   14395:           *    16     2     2     2     2   *    15     1  1  1  1          
                   14396:           */                                     
                   14397:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
                   14398:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   14399:      * and the value of each covariate?
                   14400:      * V1=1, V2=1, V3=2, V4=1 ?
                   14401:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   14402:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   14403:      * In order to get the real value in the data, we use nbcode
                   14404:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   14405:      * We are keeping this crazy system in order to be able (in the future?) 
                   14406:      * to have more than 2 values (0 or 1) for a covariate.
                   14407:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   14408:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   14409:      *              bbbbbbbb
                   14410:      *              76543210     
                   14411:      *   h-1        00000101 (6-1=5)
                   14412:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
                   14413:      *           &
                   14414:      *     1        00000001 (1)
                   14415:      *              00000000        = 1 & ((h-1) >> (k-1))
                   14416:      *          +1= 00000001 =1 
                   14417:      *
                   14418:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   14419:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   14420:      *    >>k'            11
                   14421:      *          &   00000001
                   14422:      *            = 00000001
                   14423:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   14424:      * Reverse h=6 and m=16?
                   14425:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   14426:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   14427:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   14428:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   14429:      * V3=decodtabm(14,3,2**4)=2
                   14430:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   14431:      *(h-1) >> (j-1)    0011 =13 >> 2
                   14432:      *          &1 000000001
                   14433:      *           = 000000001
                   14434:      *         +1= 000000010 =2
                   14435:      *                  2211
                   14436:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   14437:      *                  V3=2
                   14438:                 * codtabm and decodtabm are identical
                   14439:      */
                   14440: 
                   14441: 
                   14442:  free_ivector(Ndum,-1,NCOVMAX);
                   14443: 
                   14444: 
                   14445:     
                   14446:   /* Initialisation of ----------- gnuplot -------------*/
                   14447:   strcpy(optionfilegnuplot,optionfilefiname);
                   14448:   if(mle==-3)
                   14449:     strcat(optionfilegnuplot,"-MORT_");
                   14450:   strcat(optionfilegnuplot,".gp");
                   14451: 
                   14452:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   14453:     printf("Problem with file %s",optionfilegnuplot);
                   14454:   }
                   14455:   else{
                   14456:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
                   14457:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
                   14458:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   14459:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
                   14460:   }
                   14461:   /*  fclose(ficgp);*/
                   14462: 
                   14463: 
                   14464:   /* Initialisation of --------- index.htm --------*/
                   14465: 
                   14466:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   14467:   if(mle==-3)
                   14468:     strcat(optionfilehtm,"-MORT_");
                   14469:   strcat(optionfilehtm,".htm");
                   14470:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
                   14471:     printf("Problem with %s \n",optionfilehtm);
                   14472:     exit(0);
                   14473:   }
                   14474: 
                   14475:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   14476:   strcat(optionfilehtmcov,"-cov.htm");
                   14477:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   14478:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   14479:   }
                   14480:   else{
                   14481:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   14482: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   14483: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
                   14484:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   14485:   }
                   14486: 
                   14487:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   14488: <title>IMaCh %s</title></head>\n\
                   14489:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   14490: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   14491: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   14492: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   14493: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   14494:   
                   14495:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
                   14496: <font size=\"2\">IMaCh-%s <br> %s</font> \
                   14497: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   14498: 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\
                   14499: \n\
                   14500: <hr  size=\"2\" color=\"#EC5E5E\">\
                   14501:  <ul><li><h4>Parameter files</h4>\n\
                   14502:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   14503:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   14504:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   14505:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   14506:  - Date and time at start: %s</ul>\n",\
                   14507:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
                   14508:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   14509:          fileres,fileres,\
                   14510:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   14511:   fflush(fichtm);
                   14512: 
                   14513:   strcpy(pathr,path);
                   14514:   strcat(pathr,optionfilefiname);
                   14515: #ifdef WIN32
                   14516:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   14517: #else
                   14518:   chdir(optionfilefiname); /* Move to directory named optionfile */
                   14519: #endif
                   14520:          
                   14521:   
                   14522:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   14523:                 and for any valid combination of covariates
                   14524:      and prints on file fileres'p'. */
                   14525:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
                   14526:              firstpass, lastpass,  stepm,  weightopt, model);
                   14527: 
                   14528:   fprintf(fichtm,"\n");
                   14529:   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",\
                   14530:          ftol, stepm);
                   14531:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   14532:   ncurrv=1;
                   14533:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   14534:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   14535:   ncurrv=i;
                   14536:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
                   14537:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
                   14538:   ncurrv=i;
                   14539:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
                   14540:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
                   14541:   ncurrv=i;
                   14542:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   14543:   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", \
                   14544:           nlstate, ndeath, maxwav, mle, weightopt);
                   14545: 
                   14546:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   14547: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   14548: 
                   14549:   
                   14550:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
                   14551: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   14552: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   14553:   imx,agemin,agemax,jmin,jmax,jmean);
                   14554:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14555:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14556:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14557:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   14558:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   14559: 
                   14560:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   14561:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   14562:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   14563: 
                   14564:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
                   14565:   /* For mortality only */
                   14566:   if (mle==-3){
                   14567:     ximort=matrix(1,NDIM,1,NDIM); 
                   14568:     for(i=1;i<=NDIM;i++)
                   14569:       for(j=1;j<=NDIM;j++)
                   14570:        ximort[i][j]=0.;
                   14571:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
                   14572:     cens=ivector(firstobs,lastobs);
                   14573:     ageexmed=vector(firstobs,lastobs);
                   14574:     agecens=vector(firstobs,lastobs);
                   14575:     dcwave=ivector(firstobs,lastobs);
                   14576:                
                   14577:     for (i=1; i<=imx; i++){
                   14578:       dcwave[i]=-1;
                   14579:       for (m=firstpass; m<=lastpass; m++)
                   14580:        if (s[m][i]>nlstate) {
                   14581:          dcwave[i]=m;
                   14582:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   14583:          break;
                   14584:        }
                   14585:     }
                   14586:     
                   14587:     for (i=1; i<=imx; i++) {
                   14588:       if (wav[i]>0){
                   14589:        ageexmed[i]=agev[mw[1][i]][i];
                   14590:        j=wav[i];
                   14591:        agecens[i]=1.; 
                   14592:        
                   14593:        if (ageexmed[i]> 1 && wav[i] > 0){
                   14594:          agecens[i]=agev[mw[j][i]][i];
                   14595:          cens[i]= 1;
                   14596:        }else if (ageexmed[i]< 1) 
                   14597:          cens[i]= -1;
                   14598:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   14599:          cens[i]=0 ;
                   14600:       }
                   14601:       else cens[i]=-1;
                   14602:     }
                   14603:     
                   14604:     for (i=1;i<=NDIM;i++) {
                   14605:       for (j=1;j<=NDIM;j++)
                   14606:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   14607:     }
                   14608:     
                   14609:     p[1]=0.0268; p[NDIM]=0.083;
                   14610:     /* printf("%lf %lf", p[1], p[2]); */
                   14611:     
                   14612:     
                   14613: #ifdef GSL
                   14614:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
                   14615: #else
1.5     ! brouard  14616:     printf("Powell-mort\n");  fprintf(ficlog,"Powell-mort\n");
1.1       brouard  14617: #endif
                   14618:     strcpy(filerespow,"POW-MORT_"); 
                   14619:     strcat(filerespow,fileresu);
                   14620:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   14621:       printf("Problem with resultfile: %s\n", filerespow);
                   14622:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   14623:     }
                   14624: #ifdef GSL
                   14625:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
                   14626: #else
                   14627:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   14628: #endif
                   14629:     /*  for (i=1;i<=nlstate;i++)
                   14630:        for(j=1;j<=nlstate+ndeath;j++)
                   14631:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   14632:     */
                   14633:     fprintf(ficrespow,"\n");
                   14634: #ifdef GSL
                   14635:     /* gsl starts here */ 
                   14636:     T = gsl_multimin_fminimizer_nmsimplex;
                   14637:     gsl_multimin_fminimizer *sfm = NULL;
                   14638:     gsl_vector *ss, *x;
                   14639:     gsl_multimin_function minex_func;
                   14640: 
                   14641:     /* Initial vertex size vector */
                   14642:     ss = gsl_vector_alloc (NDIM);
                   14643:     
                   14644:     if (ss == NULL){
                   14645:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   14646:     }
                   14647:     /* Set all step sizes to 1 */
                   14648:     gsl_vector_set_all (ss, 0.001);
                   14649: 
                   14650:     /* Starting point */
                   14651:     
                   14652:     x = gsl_vector_alloc (NDIM);
                   14653:     
                   14654:     if (x == NULL){
                   14655:       gsl_vector_free(ss);
                   14656:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   14657:     }
                   14658:   
                   14659:     /* Initialize method and iterate */
                   14660:     /*     p[1]=0.0268; p[NDIM]=0.083; */
                   14661:     /*     gsl_vector_set(x, 0, 0.0268); */
                   14662:     /*     gsl_vector_set(x, 1, 0.083); */
                   14663:     gsl_vector_set(x, 0, p[1]);
                   14664:     gsl_vector_set(x, 1, p[2]);
                   14665: 
                   14666:     minex_func.f = &gompertz_f;
                   14667:     minex_func.n = NDIM;
                   14668:     minex_func.params = (void *)&p; /* ??? */
                   14669:     
                   14670:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   14671:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   14672:     
                   14673:     printf("Iterations beginning .....\n\n");
                   14674:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   14675: 
                   14676:     iteri=0;
                   14677:     while (rval == GSL_CONTINUE){
                   14678:       iteri++;
                   14679:       status = gsl_multimin_fminimizer_iterate(sfm);
                   14680:       
                   14681:       if (status) printf("error: %s\n", gsl_strerror (status));
                   14682:       fflush(0);
                   14683:       
                   14684:       if (status) 
                   14685:         break;
                   14686:       
                   14687:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   14688:       ssval = gsl_multimin_fminimizer_size (sfm);
                   14689:       
                   14690:       if (rval == GSL_SUCCESS)
                   14691:         printf ("converged to a local maximum at\n");
                   14692:       
                   14693:       printf("%5d ", iteri);
                   14694:       for (it = 0; it < NDIM; it++){
                   14695:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   14696:       }
                   14697:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   14698:     }
                   14699:     
                   14700:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   14701:     
                   14702:     gsl_vector_free(x); /* initial values */
                   14703:     gsl_vector_free(ss); /* inital step size */
                   14704:     for (it=0; it<NDIM; it++){
                   14705:       p[it+1]=gsl_vector_get(sfm->x,it);
                   14706:       fprintf(ficrespow," %.12lf", p[it]);
                   14707:     }
                   14708:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   14709: #endif
                   14710: #ifdef POWELL
                   14711:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   14712: #endif  
                   14713:     fclose(ficrespow);
                   14714:     
                   14715:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
                   14716: 
                   14717:     for(i=1; i <=NDIM; i++)
                   14718:       for(j=i+1;j<=NDIM;j++)
1.5     ! brouard  14719:        matcov[i][j]=matcov[j][i];
1.1       brouard  14720:     
                   14721:     printf("\nCovariance matrix\n ");
                   14722:     fprintf(ficlog,"\nCovariance matrix\n ");
                   14723:     for(i=1; i <=NDIM; i++) {
                   14724:       for(j=1;j<=NDIM;j++){ 
                   14725:                                printf("%f ",matcov[i][j]);
                   14726:                                fprintf(ficlog,"%f ",matcov[i][j]);
                   14727:       }
                   14728:       printf("\n ");  fprintf(ficlog,"\n ");
                   14729:     }
                   14730:     
                   14731:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
                   14732:     for (i=1;i<=NDIM;i++) {
                   14733:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   14734:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   14735:     }
                   14736:     lsurv=vector(agegomp,AGESUP);
                   14737:     lpop=vector(agegomp,AGESUP);
                   14738:     tpop=vector(agegomp,AGESUP);
                   14739:     lsurv[agegomp]=100000;
                   14740:     
                   14741:     for (k=agegomp;k<=AGESUP;k++) {
                   14742:       agemortsup=k;
                   14743:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   14744:     }
                   14745:     
                   14746:     for (k=agegomp;k<agemortsup;k++)
                   14747:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   14748:     
                   14749:     for (k=agegomp;k<agemortsup;k++){
                   14750:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   14751:       sumlpop=sumlpop+lpop[k];
                   14752:     }
                   14753:     
                   14754:     tpop[agegomp]=sumlpop;
                   14755:     for (k=agegomp;k<(agemortsup-3);k++){
                   14756:       /*  tpop[k+1]=2;*/
                   14757:       tpop[k+1]=tpop[k]-lpop[k];
                   14758:     }
                   14759:     
                   14760:     
                   14761:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   14762:     for (k=agegomp;k<(agemortsup-2);k++) 
                   14763:       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]);
                   14764:     
                   14765:     
                   14766:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   14767:                ageminpar=50;
                   14768:                agemaxpar=100;
                   14769:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   14770:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   14771: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14772: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   14773:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   14774: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   14775: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   14776:     }else{
                   14777:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   14778:                        fprintf(ficlog,"Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   14779:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   14780:                }
                   14781:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
                   14782:                     stepm, weightopt,\
                   14783:                     model,imx,p,matcov,agemortsup);
                   14784:     
                   14785:     free_vector(lsurv,agegomp,AGESUP);
                   14786:     free_vector(lpop,agegomp,AGESUP);
                   14787:     free_vector(tpop,agegomp,AGESUP);
                   14788:     free_matrix(ximort,1,NDIM,1,NDIM);
                   14789:     free_ivector(dcwave,firstobs,lastobs);
                   14790:     free_vector(agecens,firstobs,lastobs);
                   14791:     free_vector(ageexmed,firstobs,lastobs);
                   14792:     free_ivector(cens,firstobs,lastobs);
                   14793: #ifdef GSL
                   14794: #endif
                   14795:   } /* Endof if mle==-3 mortality only */
                   14796:   /* Standard  */
                   14797:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   14798:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   14799:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   14800:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   14801:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   14802:     for (k=1; k<=npar;k++)
                   14803:       printf(" %d %8.5f",k,p[k]);
                   14804:     printf("\n");
                   14805:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   14806:       /* mlikeli uses func not funcone */
                   14807:       /* for(i=1;i<nlstate;i++){ */
                   14808:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   14809:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   14810:       /* } */
                   14811:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   14812:     }
                   14813:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   14814:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   14815:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   14816:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   14817:     }
                   14818:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
                   14819:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   14820:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   14821:           /* exit(0); */
                   14822:     for (k=1; k<=npar;k++)
                   14823:       printf(" %d %8.5f",k,p[k]);
                   14824:     printf("\n");
                   14825:     
                   14826:     /*--------- results files --------------*/
                   14827:     /* 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); */
                   14828:     
                   14829:     
                   14830:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   14831:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
                   14832:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   14833: 
                   14834:     printf("#model=  1      +     age ");
                   14835:     fprintf(ficres,"#model=  1      +     age ");
                   14836:     fprintf(ficlog,"#model=  1      +     age ");
                   14837:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   14838: </ul>", model);
                   14839: 
                   14840:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   14841:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   14842:     if(nagesqr==1){
                   14843:       printf("  + age*age  ");
                   14844:       fprintf(ficres,"  + age*age  ");
                   14845:       fprintf(ficlog,"  + age*age  ");
                   14846:       fprintf(fichtm, "<th>+ age*age</th>");
                   14847:     }
                   14848:     for(j=1;j <=ncovmodel-2;j++){
                   14849:       if(Typevar[j]==0) {
                   14850:        printf("  +      V%d  ",Tvar[j]);
                   14851:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   14852:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   14853:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   14854:       }else if(Typevar[j]==1) {
                   14855:        printf("  +    V%d*age ",Tvar[j]);
                   14856:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   14857:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   14858:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   14859:       }else if(Typevar[j]==2) {
                   14860:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14861:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14862:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14863:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14864:       }else if(Typevar[j]==3) { /* TO VERIFY */
                   14865:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14866:        fprintf(ficres,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14867:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14868:        fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14869:       }
                   14870:     }
                   14871:     printf("\n");
                   14872:     fprintf(ficres,"\n");
                   14873:     fprintf(ficlog,"\n");
                   14874:     fprintf(fichtm, "</tr>");
                   14875:     fprintf(fichtm, "\n");
                   14876:     
                   14877:     
                   14878:     for(i=1,jk=1; i <=nlstate; i++){
                   14879:       for(k=1; k <=(nlstate+ndeath); k++){
                   14880:        if (k != i) {
                   14881:          fprintf(fichtm, "<tr>");
                   14882:          printf("%d%d ",i,k);
                   14883:          fprintf(ficlog,"%d%d ",i,k);
                   14884:          fprintf(ficres,"%1d%1d ",i,k);
                   14885:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
                   14886:          for(j=1; j <=ncovmodel; j++){
                   14887:            printf("%12.7f ",p[jk]);
                   14888:            fprintf(ficlog,"%12.7f ",p[jk]);
                   14889:            fprintf(ficres,"%12.7f ",p[jk]);
                   14890:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
                   14891:            jk++; 
                   14892:          }
                   14893:          printf("\n");
                   14894:          fprintf(ficlog,"\n");
                   14895:          fprintf(ficres,"\n");
                   14896:          fprintf(fichtm, "</tr>\n");
                   14897:        }
                   14898:       }
                   14899:     }
                   14900:     /* fprintf(fichtm,"</tr>\n"); */
                   14901:     fprintf(fichtm,"</table>\n");
                   14902:     fprintf(fichtm, "\n");
                   14903: 
                   14904:     if(mle != 0){
                   14905:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
                   14906:       ftolhess=ftol; /* Usually correct */
                   14907:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   14908:       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");
                   14909:       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");
                   14910:       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);
                   14911:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   14912:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   14913:       if(nagesqr==1){
                   14914:        printf("  + age*age  ");
                   14915:        fprintf(ficres,"  + age*age  ");
                   14916:        fprintf(ficlog,"  + age*age  ");
                   14917:        fprintf(fichtm, "<th>+ age*age</th>");
                   14918:       }
                   14919:       for(j=1;j <=ncovmodel-2;j++){
                   14920:        if(Typevar[j]==0) {
                   14921:          printf("  +      V%d  ",Tvar[j]);
                   14922:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   14923:        }else if(Typevar[j]==1) {
                   14924:          printf("  +    V%d*age ",Tvar[j]);
                   14925:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   14926:        }else if(Typevar[j]==2) {
                   14927:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14928:        }else if(Typevar[j]==3) { /* TO VERIFY */
                   14929:          fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   14930:        }
                   14931:       }
                   14932:       fprintf(fichtm, "</tr>\n");
                   14933:  
                   14934:       for(i=1,jk=1; i <=nlstate; i++){
                   14935:        for(k=1; k <=(nlstate+ndeath); k++){
                   14936:          if (k != i) {
                   14937:            fprintf(fichtm, "<tr valign=top>");
                   14938:            printf("%d%d ",i,k);
                   14939:            fprintf(ficlog,"%d%d ",i,k);
                   14940:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
                   14941:            for(j=1; j <=ncovmodel; j++){
                   14942:              wald=p[jk]/sqrt(matcov[jk][jk]);
                   14943:              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]));
                   14944:              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]));
                   14945:              if(fabs(wald) > 1.96){
                   14946:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   14947:              }else{
                   14948:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   14949:              }
                   14950:              fprintf(fichtm,"W=%8.3f</br>",wald);
                   14951:              fprintf(fichtm,"[%12.7f;%12.7f]</br></td>", p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
                   14952:              jk++; 
                   14953:            }
                   14954:            printf("\n");
                   14955:            fprintf(ficlog,"\n");
                   14956:            fprintf(fichtm, "</tr>\n");
                   14957:          }
                   14958:        }
                   14959:       }
                   14960:     } /* end of hesscov and Wald tests */
                   14961:     fprintf(fichtm,"</table>\n");
                   14962:     
                   14963:     /*  */
                   14964:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   14965:     printf("# Scales (for hessian or gradient estimation)\n");
                   14966:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   14967:     for(i=1,jk=1; i <=nlstate; i++){
                   14968:       for(j=1; j <=nlstate+ndeath; j++){
                   14969:        if (j!=i) {
                   14970:          fprintf(ficres,"%1d%1d",i,j);
                   14971:          printf("%1d%1d",i,j);
                   14972:          fprintf(ficlog,"%1d%1d",i,j);
                   14973:          for(k=1; k<=ncovmodel;k++){
                   14974:            printf(" %.5e",delti[jk]);
                   14975:            fprintf(ficlog," %.5e",delti[jk]);
                   14976:            fprintf(ficres," %.5e",delti[jk]);
                   14977:            jk++;
                   14978:          }
                   14979:          printf("\n");
                   14980:          fprintf(ficlog,"\n");
                   14981:          fprintf(ficres,"\n");
                   14982:        }
                   14983:       }
                   14984:     }
                   14985:     
                   14986:     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");
                   14987:     if(mle >= 1) /* Too big for the screen */
                   14988:       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");
                   14989:     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");
                   14990:     /* # 121 Var(a12)\n\ */
                   14991:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   14992:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   14993:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   14994:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   14995:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   14996:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   14997:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   14998:     
                   14999:     
                   15000:     /* Just to have a covariance matrix which will be more understandable
                   15001:        even is we still don't want to manage dictionary of variables
                   15002:     */
                   15003:     for(itimes=1;itimes<=2;itimes++){
                   15004:       jj=0;
                   15005:       for(i=1; i <=nlstate; i++){
                   15006:        for(j=1; j <=nlstate+ndeath; j++){
                   15007:          if(j==i) continue;
                   15008:          for(k=1; k<=ncovmodel;k++){
                   15009:            jj++;
                   15010:            ca[0]= k+'a'-1;ca[1]='\0';
                   15011:            if(itimes==1){
                   15012:              if(mle>=1)
                   15013:                printf("#%1d%1d%d",i,j,k);
                   15014:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   15015:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   15016:            }else{
                   15017:              if(mle>=1)
                   15018:                printf("%1d%1d%d",i,j,k);
                   15019:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   15020:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   15021:            }
                   15022:            ll=0;
                   15023:            for(li=1;li <=nlstate; li++){
                   15024:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   15025:                if(lj==li) continue;
                   15026:                for(lk=1;lk<=ncovmodel;lk++){
                   15027:                  ll++;
                   15028:                  if(ll<=jj){
                   15029:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   15030:                    if(ll<jj){
                   15031:                      if(itimes==1){
                   15032:                        if(mle>=1)
                   15033:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   15034:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   15035:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   15036:                      }else{
                   15037:                        if(mle>=1)
                   15038:                          printf(" %.5e",matcov[jj][ll]); 
                   15039:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   15040:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   15041:                      }
                   15042:                    }else{
                   15043:                      if(itimes==1){
                   15044:                        if(mle>=1)
                   15045:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   15046:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   15047:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   15048:                      }else{
                   15049:                        if(mle>=1)
                   15050:                          printf(" %.7e",matcov[jj][ll]); 
                   15051:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   15052:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   15053:                      }
                   15054:                    }
                   15055:                  }
                   15056:                } /* end lk */
                   15057:              } /* end lj */
                   15058:            } /* end li */
                   15059:            if(mle>=1)
                   15060:              printf("\n");
                   15061:            fprintf(ficlog,"\n");
                   15062:            fprintf(ficres,"\n");
                   15063:            numlinepar++;
                   15064:          } /* end k*/
                   15065:        } /*end j */
                   15066:       } /* end i */
                   15067:     } /* end itimes */
                   15068:     
                   15069:     fflush(ficlog);
                   15070:     fflush(ficres);
                   15071:     while(fgets(line, MAXLINE, ficpar)) {
                   15072:       /* If line starts with a # it is a comment */
                   15073:       if (line[0] == '#') {
                   15074:        numlinepar++;
                   15075:        fputs(line,stdout);
                   15076:        fputs(line,ficparo);
                   15077:        fputs(line,ficlog);
                   15078:        fputs(line,ficres);
                   15079:        continue;
                   15080:       }else
                   15081:        break;
                   15082:     }
                   15083:     
                   15084:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   15085:     /*   ungetc(c,ficpar); */
                   15086:     /*   fgets(line, MAXLINE, ficpar); */
                   15087:     /*   fputs(line,stdout); */
                   15088:     /*   fputs(line,ficparo); */
                   15089:     /* } */
                   15090:     /* ungetc(c,ficpar); */
                   15091:     
                   15092:     estepm=0;
                   15093:     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){
                   15094:       
                   15095:       if (num_filled != 6) {
                   15096:        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);
                   15097:        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);
                   15098:        goto end;
                   15099:       }
                   15100:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   15101:     }
                   15102:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   15103:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   15104:     
                   15105:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
                   15106:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   15107:     if (fage <= 2) {
                   15108:       bage = ageminpar;
                   15109:       fage = agemaxpar;
                   15110:     }
                   15111:     
                   15112:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   15113:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   15114:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   15115:                
                   15116:     /* Other stuffs, more or less useful */    
                   15117:     while(fgets(line, MAXLINE, ficpar)) {
                   15118:       /* If line starts with a # it is a comment */
                   15119:       if (line[0] == '#') {
                   15120:        numlinepar++;
                   15121:        fputs(line,stdout);
                   15122:        fputs(line,ficparo);
                   15123:        fputs(line,ficlog);
                   15124:        fputs(line,ficres);
                   15125:        continue;
                   15126:       }else
                   15127:        break;
                   15128:     }
                   15129: 
                   15130:     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){
                   15131:       
                   15132:       if (num_filled != 7) {
                   15133:        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);
                   15134:        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);
                   15135:        goto end;
                   15136:       }
                   15137:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   15138:       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);
                   15139:       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);
                   15140:       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);
                   15141:     }
                   15142: 
                   15143:     while(fgets(line, MAXLINE, ficpar)) {
                   15144:       /* If line starts with a # it is a comment */
                   15145:       if (line[0] == '#') {
                   15146:        numlinepar++;
                   15147:        fputs(line,stdout);
                   15148:        fputs(line,ficparo);
                   15149:        fputs(line,ficlog);
                   15150:        fputs(line,ficres);
                   15151:        continue;
                   15152:       }else
                   15153:        break;
                   15154:     }
                   15155:     
                   15156:     
                   15157:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   15158:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   15159:     
                   15160:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   15161:       if (num_filled != 1) {
                   15162:        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);
                   15163:        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);
                   15164:        goto end;
                   15165:       }
                   15166:       printf("pop_based=%d\n",popbased);
                   15167:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   15168:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   15169:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   15170:     }
                   15171:      
                   15172:     /* Results */
1.5     ! brouard  15173:     /* Value of covariate in each resultine will be computed (if product) and sorted according to model rank */
1.1       brouard  15174:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   15175:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
                   15176:     endishere=0;
                   15177:     nresult=0;
                   15178:     parameterline=0;
                   15179:     do{
                   15180:       if(!fgets(line, MAXLINE, ficpar)){
                   15181:        endishere=1;
                   15182:        parameterline=15;
                   15183:       }else if (line[0] == '#') {
                   15184:        /* If line starts with a # it is a comment */
                   15185:        numlinepar++;
                   15186:        fputs(line,stdout);
                   15187:        fputs(line,ficparo);
                   15188:        fputs(line,ficlog);
                   15189:        fputs(line,ficres);
                   15190:        continue;
                   15191:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   15192:        parameterline=11;
                   15193:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
                   15194:        parameterline=12;
                   15195:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
                   15196:        parameterline=13;
                   15197:       }
                   15198:       else{
                   15199:        parameterline=14;
                   15200:       }
                   15201:       switch (parameterline){ /* =0 only if only comments */
                   15202:       case 11:
                   15203:        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)){
                   15204:                  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);
                   15205:          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);
                   15206:          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);
                   15207:          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);
                   15208:          /* day and month of proj2 are not used but only year anproj2.*/
                   15209:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   15210:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
                   15211:           prvforecast = 1;
                   15212:        } 
                   15213:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
                   15214:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   15215:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   15216:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   15217:           prvforecast = 2;
                   15218:        }
                   15219:        else {
                   15220:          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);
                   15221:          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);
                   15222:          goto end;
                   15223:        }
                   15224:        break;
                   15225:       case 12:
                   15226:        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)){
                   15227:           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);
                   15228:          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);
                   15229:          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);
                   15230:          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);
                   15231:          /* day and month of back2 are not used but only year anback2.*/
                   15232:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   15233:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
                   15234:           prvbackcast = 1;
                   15235:        } 
                   15236:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
                   15237:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   15238:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   15239:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   15240:           prvbackcast = 2;
                   15241:        }
                   15242:        else {
                   15243:          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);
                   15244:          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);
                   15245:          goto end;
                   15246:        }
                   15247:        break;
                   15248:       case 13:
                   15249:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
                   15250:        nresult++; /* Sum of resultlines */
                   15251:        /* printf("Result %d: result:%s\n",nresult, resultlineori); */
                   15252:        /* removefirstspace(&resultlineori); */
                   15253:        
                   15254:        if(strstr(resultlineori,"v") !=0){
                   15255:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   15256:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   15257:          return 1;
                   15258:        }
                   15259:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
                   15260:        /* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
                   15261:        if(nresult > MAXRESULTLINESPONE-1){
                   15262:          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);
                   15263:          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);
                   15264:          goto end;
                   15265:        }
                   15266:        
                   15267:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
                   15268:          fprintf(ficparo,"result: %s\n",resultline);
                   15269:          fprintf(ficres,"result: %s\n",resultline);
                   15270:          fprintf(ficlog,"result: %s\n",resultline);
                   15271:        } else
                   15272:          goto end;
                   15273:        break;
                   15274:       case 14:
                   15275:        printf("Error: Unknown command '%s'\n",line);
                   15276:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
                   15277:        if(line[0] == ' ' || line[0] == '\n'){
                   15278:          printf("It should not be an empty line '%s'\n",line);
                   15279:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   15280:        }         
                   15281:        if(ncovmodel >=2 && nresult==0 ){
                   15282:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   15283:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   15284:        }
                   15285:        /* goto end; */
                   15286:        break;
                   15287:       case 15:
                   15288:        printf("End of resultlines.\n");
                   15289:        fprintf(ficlog,"End of resultlines.\n");
                   15290:        break;
                   15291:       default: /* parameterline =0 */
                   15292:        nresult=1;
                   15293:        decoderesult(".",nresult ); /* No covariate */
                   15294:       } /* End switch parameterline */
                   15295:     }while(endishere==0); /* End do */
                   15296:     
                   15297:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   15298:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
                   15299:     
                   15300:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   15301:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
                   15302:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   15303: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   15304: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   15305:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   15306: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   15307: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   15308:     }else{
                   15309:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
                   15310:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   15311:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   15312:       if(prvforecast==1){
                   15313:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   15314:         jprojd=jproj1;
                   15315:         mprojd=mproj1;
                   15316:         anprojd=anproj1;
                   15317:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   15318:         jprojf=jproj2;
                   15319:         mprojf=mproj2;
                   15320:         anprojf=anproj2;
                   15321:       } else if(prvforecast == 2){
                   15322:         dateprojd=dateintmean;
                   15323:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   15324:         dateprojf=dateintmean+yrfproj;
                   15325:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   15326:       }
                   15327:       if(prvbackcast==1){
                   15328:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   15329:         jbackd=jback1;
                   15330:         mbackd=mback1;
                   15331:         anbackd=anback1;
                   15332:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   15333:         jbackf=jback2;
                   15334:         mbackf=mback2;
                   15335:         anbackf=anback2;
                   15336:       } else if(prvbackcast == 2){
                   15337:         datebackd=dateintmean;
                   15338:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   15339:         datebackf=dateintmean-yrbproj;
                   15340:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   15341:       }
                   15342:       
1.2       brouard  15343:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);/* HERE valgrind Tvard*/
1.1       brouard  15344:     }
                   15345:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
                   15346:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   15347:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
                   15348:                
                   15349:     /*------------ free_vector  -------------*/
                   15350:     /*  chdir(path); */
                   15351:                
                   15352:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   15353:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   15354:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   15355:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
                   15356:     free_lvector(num,firstobs,lastobs);
                   15357:     free_vector(agedc,firstobs,lastobs);
                   15358:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   15359:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   15360:     fclose(ficparo);
                   15361:     fclose(ficres);
                   15362:                
                   15363:                
                   15364:     /* Other results (useful)*/
                   15365:                
                   15366:                
                   15367:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   15368:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   15369:     prlim=matrix(1,nlstate,1,nlstate);
                   15370:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
                   15371:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
                   15372:     fclose(ficrespl);
                   15373: 
                   15374:     /*------------- h Pij x at various ages ------------*/
                   15375:     /*#include "hpijx.h"*/
                   15376:     /** 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?*/
                   15377:     /* calls hpxij with combination k */
                   15378:     hPijx(p, bage, fage);
                   15379:     fclose(ficrespij);
                   15380:     
                   15381:     /* ncovcombmax=  pow(2,cptcoveff); */
                   15382:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
                   15383:     k=1;
                   15384:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   15385:     
                   15386:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   15387:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   15388:     for(i=AGEINF;i<=AGESUP;i++)
                   15389:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
                   15390:        for(k=1;k<=ncovcombmax;k++)
                   15391:          probs[i][j][k]=0.;
                   15392:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   15393:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   15394:     if (mobilav!=0 ||mobilavproj !=0 ) {
                   15395:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   15396:       for(i=AGEINF;i<=AGESUP;i++)
                   15397:        for(j=1;j<=nlstate+ndeath;j++)
                   15398:          for(k=1;k<=ncovcombmax;k++)
                   15399:            mobaverages[i][j][k]=0.;
                   15400:       mobaverage=mobaverages;
                   15401:       if (mobilav!=0) {
                   15402:        printf("Movingaveraging observed prevalence\n");
                   15403:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
                   15404:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   15405:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   15406:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   15407:        }
                   15408:       } else if (mobilavproj !=0) {
                   15409:        printf("Movingaveraging projected observed prevalence\n");
                   15410:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
                   15411:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   15412:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   15413:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   15414:        }
                   15415:       }else{
                   15416:        printf("Internal error moving average\n");
                   15417:        fflush(stdout);
                   15418:        exit(1);
                   15419:       }
                   15420:     }/* end if moving average */
                   15421:     
                   15422:     /*---------- Forecasting ------------------*/
                   15423:     if(prevfcast==1){ 
                   15424:       /*   /\*    if(stepm ==1){*\/ */
                   15425:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   15426:       /*This done previously after freqsummary.*/
                   15427:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   15428:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   15429:       
                   15430:       /* } else if (prvforecast==2){ */
                   15431:       /*   /\*    if(stepm ==1){*\/ */
                   15432:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   15433:       /* } */
                   15434:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   15435:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
                   15436:     }
                   15437: 
                   15438:     /* Prevbcasting */
                   15439:     if(prevbcast==1){
                   15440:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   15441:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   15442:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   15443: 
                   15444:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   15445: 
                   15446:       bprlim=matrix(1,nlstate,1,nlstate);
                   15447: 
                   15448:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   15449:       fclose(ficresplb);
                   15450: 
                   15451:       hBijx(p, bage, fage, mobaverage);
                   15452:       fclose(ficrespijb);
                   15453: 
                   15454:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   15455:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   15456:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   15457:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   15458:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   15459:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   15460: 
                   15461:       
                   15462:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
                   15463: 
                   15464:       
                   15465:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   15466:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   15467:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   15468:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   15469:     }    /* end  Prevbcasting */
                   15470:  
                   15471:  
                   15472:     /* ------ Other prevalence ratios------------ */
                   15473: 
                   15474:     free_ivector(wav,1,imx);
                   15475:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   15476:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   15477:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
                   15478:                
                   15479:                
                   15480:     /*---------- Health expectancies, no variances ------------*/
                   15481:                
                   15482:     strcpy(filerese,"E_");
                   15483:     strcat(filerese,fileresu);
                   15484:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   15485:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   15486:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   15487:     }
                   15488:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   15489:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
                   15490: 
                   15491:     pstamp(ficreseij);
                   15492:                
1.2       brouard  15493:     /* i1=pow(2,cptcoveff); /\* Number of combination of dummy covariates *\/ */
                   15494:     /* if (cptcovn < 1){i1=1;} */
1.1       brouard  15495:     
1.2       brouard  15496:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   15497:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   15498:       /* if(i1 != 1 && TKresult[nres]!= k) */
                   15499:       /*       continue; */
1.1       brouard  15500:       fprintf(ficreseij,"\n#****** ");
                   15501:       printf("\n#****** ");
1.2       brouard  15502:       for(j=1;j<=cptcovs;j++){
                   15503:       /* for(j=1;j<=cptcoveff;j++) { */
                   15504:        /* fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15505:        fprintf(ficreseij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   15506:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   15507:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.1       brouard  15508:       }
                   15509:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   15510:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   15511:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
                   15512:       }
                   15513:       fprintf(ficreseij,"******\n");
                   15514:       printf("******\n");
                   15515:       
                   15516:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15517:       oldm=oldms;savm=savms;
                   15518:       /* printf("HELLO Entering evsij bage=%d fage=%d k=%d estepm=%d nres=%d\n",(int) bage, (int)fage, k, estepm, nres); */
                   15519:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
                   15520:       
                   15521:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   15522:     }
                   15523:     fclose(ficreseij);
                   15524:     printf("done evsij\n");fflush(stdout);
                   15525:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
                   15526: 
                   15527:                
                   15528:     /*---------- State-specific expectancies and variances ------------*/
                   15529:     /* Should be moved in a function */                
                   15530:     strcpy(filerest,"T_");
                   15531:     strcat(filerest,fileresu);
                   15532:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   15533:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   15534:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   15535:     }
                   15536:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   15537:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
                   15538:     strcpy(fileresstde,"STDE_");
                   15539:     strcat(fileresstde,fileresu);
                   15540:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   15541:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   15542:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   15543:     }
                   15544:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   15545:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   15546: 
                   15547:     strcpy(filerescve,"CVE_");
                   15548:     strcat(filerescve,fileresu);
                   15549:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   15550:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   15551:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   15552:     }
                   15553:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   15554:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   15555: 
                   15556:     strcpy(fileresv,"V_");
                   15557:     strcat(fileresv,fileresu);
                   15558:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   15559:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   15560:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   15561:     }
                   15562:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   15563:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
                   15564: 
                   15565:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   15566:     if (cptcovn < 1){i1=1;}
                   15567:     
                   15568:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   15569:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   15570:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   15571:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   15572:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   15573:       /* */
                   15574:       if(i1 != 1 && TKresult[nres]!= k) /* TKresult[nres] is the combination of this nres resultline. All the i1 combinations are not output */
                   15575:        continue;
1.5     ! brouard  15576:       printf("\n# model=1+age+%s \n#****** Result for:", model);  /* HERE model is empty */
        !          15577:       fprintf(ficrest,"\n# model=1+age+%s \n#****** Result for:", model);
        !          15578:       fprintf(ficlog,"\n# model=1+age+%s \n#****** Result for:", model);
1.1       brouard  15579:       /* It might not be a good idea to mix dummies and quantitative */
                   15580:       /* 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 *\/ */
                   15581:       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 */
                   15582:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   15583:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   15584:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   15585:         * (V5 is quanti) V4 and V3 are dummies
                   15586:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   15587:         *                                                              l=1 l=2
                   15588:         *                                                           k=1  1   1   0   0
                   15589:         *                                                           k=2  2   1   1   0
                   15590:         *                                                           k=3 [1] [2]  0   1
                   15591:         *                                                           k=4  2   2   1   1
                   15592:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   15593:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   15594:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   15595:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   15596:         */
                   15597:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   15598:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   15599: /* We give up with the combinations!! */
                   15600:        /* if(debugILK) */
                   15601:        /*   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 *\/ */
                   15602: 
                   15603:        if(Dummy[modelresult[nres][j]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to j in resultline  */
                   15604:          /* 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] */
                   15605:          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  */
                   15606:          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  */
                   15607:          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  */
                   15608:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   15609:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   15610:          }else{
                   15611:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   15612:          }
                   15613:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15614:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15615:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   15616:          /* For each selected (single) quantitative value */
                   15617:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   15618:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   15619:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   15620:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   15621:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   15622:          }else{
                   15623:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   15624:          }
                   15625:        }else{
                   15626:          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 */
                   15627:          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 */
                   15628:          exit(1);
                   15629:        }
                   15630:       } /* End loop for each variable in the resultline */
                   15631:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   15632:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   15633:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   15634:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   15635:       /* }      */
                   15636:       fprintf(ficrest,"******\n");
                   15637:       fprintf(ficlog,"******\n");
                   15638:       printf("******\n");
                   15639:       
                   15640:       fprintf(ficresstdeij,"\n#****** ");
                   15641:       fprintf(ficrescveij,"\n#****** ");
                   15642:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   15643:       /* But it won't be sorted and depends on how the resultline is ordered */
                   15644:       for(j=1;j<=cptcoveff;j++) {
                   15645:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   15646:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15647:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   15648:       }
                   15649:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value, TvarsQind gives the position of a quantitative in model equation  */
                   15650:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   15651:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   15652:       }        
                   15653:       fprintf(ficresstdeij,"******\n");
                   15654:       fprintf(ficrescveij,"******\n");
                   15655:       
                   15656:       fprintf(ficresvij,"\n#****** ");
                   15657:       /* pstamp(ficresvij); */
                   15658:       for(j=1;j<=cptcoveff;j++) 
                   15659:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   15660:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
                   15661:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   15662:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
                   15663:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
                   15664:       }        
                   15665:       fprintf(ficresvij,"******\n");
                   15666:       
                   15667:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15668:       oldm=oldms;savm=savms;
                   15669:       printf(" cvevsij ");
                   15670:       fprintf(ficlog, " cvevsij ");
                   15671:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
                   15672:       printf(" end cvevsij \n ");
                   15673:       fprintf(ficlog, " end cvevsij \n ");
                   15674:       
                   15675:       /*
                   15676:        */
                   15677:       /* goto endfree; */
                   15678:       
                   15679:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   15680:       pstamp(ficrest);
                   15681:       
                   15682:       epj=vector(1,nlstate+1);
                   15683:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   15684:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   15685:        cptcod= 0; /* To be deleted */
                   15686:        printf("varevsij vpopbased=%d \n",vpopbased);
                   15687:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
                   15688:        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 */
                   15689:        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 ");
                   15690:        if(vpopbased==1)
                   15691:          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);
                   15692:        else
                   15693:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
                   15694:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
                   15695:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   15696:        fprintf(ficrest,"\n");
                   15697:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   15698:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   15699:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
                   15700:        for(age=bage; age <=fage ;age++){
                   15701:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
                   15702:          if (vpopbased==1) {
                   15703:            if(mobilav ==0){
                   15704:              for(i=1; i<=nlstate;i++)
                   15705:                prlim[i][i]=probs[(int)age][i][k];
                   15706:            }else{ /* mobilav */ 
                   15707:              for(i=1; i<=nlstate;i++)
                   15708:                prlim[i][i]=mobaverage[(int)age][i][k];
                   15709:            }
                   15710:          }
                   15711:          
                   15712:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   15713:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   15714:          /* printf(" age %4.0f ",age); */
                   15715:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   15716:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   15717:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   15718:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   15719:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   15720:            }
                   15721:            epj[nlstate+1] +=epj[j];
                   15722:          }
                   15723:          /* printf(" age %4.0f \n",age); */
                   15724:          
                   15725:          for(i=1, vepp=0.;i <=nlstate;i++)
                   15726:            for(j=1;j <=nlstate;j++)
                   15727:              vepp += vareij[i][j][(int)age];
                   15728:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   15729:          for(j=1;j <=nlstate;j++){
                   15730:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   15731:          }
                   15732:          fprintf(ficrest,"\n");
                   15733:        }
                   15734:       } /* End vpopbased */
                   15735:       free_vector(epj,1,nlstate+1);
                   15736:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   15737:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   15738:       printf("done selection\n");fflush(stdout);
                   15739:       fprintf(ficlog,"done selection\n");fflush(ficlog);
                   15740:       
                   15741:     } /* End k selection or end covariate selection for nres */
                   15742: 
                   15743:     printf("done State-specific expectancies\n");fflush(stdout);
                   15744:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   15745: 
                   15746:     /* variance-covariance of forward period prevalence */
                   15747:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
                   15748: 
                   15749:     
                   15750:     free_vector(weight,firstobs,lastobs);
1.2       brouard  15751:     free_imatrix(Tvardk,0,NCOVMAX,1,2);
1.1       brouard  15752:     free_imatrix(Tvard,1,NCOVMAX,1,2);
                   15753:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   15754:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   15755:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   15756:     free_ivector(cod,firstobs,lastobs);
                   15757:     free_ivector(tab,1,NCOVMAX);
                   15758:     fclose(ficresstdeij);
                   15759:     fclose(ficrescveij);
                   15760:     fclose(ficresvij);
                   15761:     fclose(ficrest);
                   15762:     fclose(ficpar);
                   15763:     
                   15764:     
                   15765:     /*---------- End : free ----------------*/
                   15766:     if (mobilav!=0 ||mobilavproj !=0)
                   15767:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   15768:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   15769:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   15770:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   15771:   }  /* mle==-3 arrives here for freeing */
                   15772:   /* endfree:*/
1.5     ! brouard  15773:   if(mle!=-3) free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
1.1       brouard  15774:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   15775:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   15776:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   15777:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
                   15778:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
                   15779:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   15780:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   15781:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
                   15782:   free_matrix(matcov,1,npar,1,npar);
                   15783:   free_matrix(hess,1,npar,1,npar);
                   15784:   /*free_vector(delti,1,npar);*/
                   15785:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   15786:   free_matrix(agev,1,maxwav,1,imx);
                   15787:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   15788:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   15789:   
                   15790:   free_ivector(ncodemax,1,NCOVMAX);
                   15791:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   15792:   free_ivector(Dummy,-1,NCOVMAX);
                   15793:   free_ivector(Fixed,-1,NCOVMAX);
                   15794:   free_ivector(DummyV,-1,NCOVMAX);
                   15795:   free_ivector(FixedV,-1,NCOVMAX);
                   15796:   free_ivector(Typevar,-1,NCOVMAX);
                   15797:   free_ivector(Tvar,1,NCOVMAX);
                   15798:   free_ivector(TvarsQ,1,NCOVMAX);
                   15799:   free_ivector(TvarsQind,1,NCOVMAX);
                   15800:   free_ivector(TvarsD,1,NCOVMAX);
                   15801:   free_ivector(TnsdVar,1,NCOVMAX);
                   15802:   free_ivector(TvarsDind,1,NCOVMAX);
                   15803:   free_ivector(TvarFD,1,NCOVMAX);
                   15804:   free_ivector(TvarFDind,1,NCOVMAX);
                   15805:   free_ivector(TvarF,1,NCOVMAX);
                   15806:   free_ivector(TvarFind,1,NCOVMAX);
                   15807:   free_ivector(TvarV,1,NCOVMAX);
                   15808:   free_ivector(TvarVind,1,NCOVMAX);
                   15809:   free_ivector(TvarA,1,NCOVMAX);
                   15810:   free_ivector(TvarAind,1,NCOVMAX);
                   15811:   free_ivector(TvarFQ,1,NCOVMAX);
                   15812:   free_ivector(TvarFQind,1,NCOVMAX);
                   15813:   free_ivector(TvarVD,1,NCOVMAX);
                   15814:   free_ivector(TvarVDind,1,NCOVMAX);
                   15815:   free_ivector(TvarVQ,1,NCOVMAX);
                   15816:   free_ivector(TvarVQind,1,NCOVMAX);
                   15817:   free_ivector(TvarAVVA,1,NCOVMAX);
                   15818:   free_ivector(TvarAVVAind,1,NCOVMAX);
                   15819:   free_ivector(TvarVVA,1,NCOVMAX);
                   15820:   free_ivector(TvarVVAind,1,NCOVMAX);
                   15821:   free_ivector(TvarVV,1,NCOVMAX);
                   15822:   free_ivector(TvarVVind,1,NCOVMAX);
                   15823:   
                   15824:   free_ivector(Tvarsel,1,NCOVMAX);
                   15825:   free_vector(Tvalsel,1,NCOVMAX);
                   15826:   free_ivector(Tposprod,1,NCOVMAX);
                   15827:   free_ivector(Tprod,1,NCOVMAX);
                   15828:   free_ivector(Tvaraff,1,NCOVMAX);
                   15829:   free_ivector(invalidvarcomb,0,ncovcombmax);
                   15830:   free_ivector(Tage,1,NCOVMAX);
                   15831:   free_ivector(Tmodelind,1,NCOVMAX);
                   15832:   free_ivector(TmodelInvind,1,NCOVMAX);
                   15833:   free_ivector(TmodelInvQind,1,NCOVMAX);
                   15834: 
                   15835:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   15836: 
                   15837:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   15838:   /* free_imatrix(codtab,1,100,1,10); */
                   15839:   fflush(fichtm);
                   15840:   fflush(ficgp);
                   15841:   
                   15842:   
                   15843:   if((nberr >0) || (nbwarn>0)){
                   15844:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   15845:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d. Please look at the log file for details.\n",nberr,nbwarn);
                   15846:   }else{
                   15847:     printf("End of Imach\n");
                   15848:     fprintf(ficlog,"End of Imach\n");
                   15849:   }
                   15850:   printf("See log file on %s\n",filelog);
                   15851:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
                   15852:   /*(void) gettimeofday(&end_time,&tzp);*/
                   15853:   rend_time = time(NULL);  
                   15854:   end_time = *localtime(&rend_time);
                   15855:   /* tml = *localtime(&end_time.tm_sec); */
                   15856:   strcpy(strtend,asctime(&end_time));
                   15857:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   15858:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
                   15859:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   15860:   
                   15861:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   15862:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   15863:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   15864:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   15865: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   15866:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   15867:   fclose(fichtm);
                   15868:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   15869:   fclose(fichtmcov);
                   15870:   fclose(ficgp);
                   15871:   fclose(ficlog);
                   15872:   /*------ End -----------*/
                   15873:   
                   15874: 
                   15875: /* Executes gnuplot */
                   15876:   
                   15877:   printf("Before Current directory %s!\n",pathcd);
                   15878: #ifdef WIN32
                   15879:   if (_chdir(pathcd) != 0)
                   15880:     printf("Can't move to directory %s!\n",path);
                   15881:   if(_getcwd(pathcd,MAXLINE) > 0)
                   15882: #else
                   15883:     if(chdir(pathcd) != 0)
                   15884:       printf("Can't move to directory %s!\n", path);
                   15885:   if (getcwd(pathcd, MAXLINE) > 0)
                   15886: #endif 
                   15887:     printf("Current directory %s!\n",pathcd);
                   15888:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   15889:   sprintf(plotcmd,"gnuplot");
                   15890: #ifdef _WIN32
                   15891:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   15892: #endif
                   15893:   if(!stat(plotcmd,&info)){
                   15894:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
                   15895:     if(!stat(getenv("GNUPLOTBIN"),&info)){
                   15896:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
                   15897:     }else
                   15898:       strcpy(pplotcmd,plotcmd);
                   15899: #ifdef __unix
                   15900:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   15901:     if(!stat(plotcmd,&info)){
                   15902:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
                   15903:     }else
                   15904:       strcpy(pplotcmd,plotcmd);
                   15905: #endif
                   15906:   }else
                   15907:     strcpy(pplotcmd,plotcmd);
                   15908:   
                   15909:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
                   15910:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
                   15911:   strcpy(pplotcmd,plotcmd);
                   15912:   
                   15913:   if((outcmd=system(plotcmd)) != 0){
                   15914:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
                   15915:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
                   15916:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
                   15917:     if((outcmd=system(plotcmd)) != 0){
                   15918:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
                   15919:       strcpy(plotcmd,pplotcmd);
                   15920:     }
                   15921:   }
                   15922:   printf(" Successful, please wait...");
                   15923:   while (z[0] != 'q') {
                   15924:     /* chdir(path); */
                   15925:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
                   15926:     scanf("%s",z);
                   15927: /*     if (z[0] == 'c') system("./imach"); */
                   15928:     if (z[0] == 'e') {
                   15929: #ifdef __APPLE__
                   15930:       sprintf(pplotcmd, "open %s", optionfilehtm);
                   15931: #elif __linux
                   15932:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
                   15933: #else
                   15934:       sprintf(pplotcmd, "%s", optionfilehtm);
                   15935: #endif
                   15936:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   15937:       system(pplotcmd);
                   15938:     }
                   15939:     else if (z[0] == 'g') system(plotcmd);
                   15940:     else if (z[0] == 'q') exit(0);
                   15941:   }
                   15942: end:
                   15943:   while (z[0] != 'q') {
                   15944:     printf("\nType  q for exiting: "); fflush(stdout);
                   15945:     scanf("%s",z);
                   15946:   }
                   15947:   printf("End\n");
                   15948:   exit(0);
                   15949: }

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