Annotation of imach/src/imach-0.98r.c, revision 1.2

1.2     ! brouard     1: /* $Id: imach-0.98r.c,v 1.1 2016/02/19 09:46:04 brouard Exp $
1.1       brouard     2:   $State: Exp $
1.2     ! brouard     3:   $Log: imach-0.98r.c,v $
        !             4:   Revision 1.1  2016/02/19 09:46:04  brouard
        !             5:   Summary: Kind of 0.98r? series, starting with r7
        !             6: 
1.1       brouard     7:   Revision 1.222  2016/02/17 08:14:50  brouard
                      8:   Summary: Probably last 0.98 stable version 0.98r6
                      9: 
                     10:   Revision 1.221  2016/02/15 23:35:36  brouard
                     11:   Summary: minor bug
                     12: 
                     13:   Revision 1.219  2016/02/15 00:48:12  brouard
                     14:   *** empty log message ***
                     15: 
                     16:   Revision 1.218  2016/02/12 11:29:23  brouard
                     17:   Summary: 0.99 Back projections
                     18: 
                     19:   Revision 1.217  2015/12/23 17:18:31  brouard
                     20:   Summary: Experimental backcast
                     21: 
                     22:   Revision 1.216  2015/12/18 17:32:11  brouard
                     23:   Summary: 0.98r4 Warning and status=-2
                     24: 
                     25:   Version 0.98r4 is now:
                     26:    - displaying an error when status is -1, date of interview unknown and date of death known;
                     27:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                     28:   Older changes concerning s=-2, dating from 2005 have been supersed.
                     29: 
                     30:   Revision 1.215  2015/12/16 08:52:24  brouard
                     31:   Summary: 0.98r4 working
                     32: 
                     33:   Revision 1.214  2015/12/16 06:57:54  brouard
                     34:   Summary: temporary not working
                     35: 
                     36:   Revision 1.213  2015/12/11 18:22:17  brouard
                     37:   Summary: 0.98r4
                     38: 
                     39:   Revision 1.212  2015/11/21 12:47:24  brouard
                     40:   Summary: minor typo
                     41: 
                     42:   Revision 1.211  2015/11/21 12:41:11  brouard
                     43:   Summary: 0.98r3 with some graph of projected cross-sectional
                     44: 
                     45:   Author: Nicolas Brouard
                     46: 
                     47:   Revision 1.210  2015/11/18 17:41:20  brouard
                     48:   Summary: Start working on projected prevalences
                     49: 
                     50:   Revision 1.209  2015/11/17 22:12:03  brouard
                     51:   Summary: Adding ftolpl parameter
                     52:   Author: N Brouard
                     53: 
                     54:   We had difficulties to get smoothed confidence intervals. It was due
                     55:   to the period prevalence which wasn't computed accurately. The inner
                     56:   parameter ftolpl is now an outer parameter of the .imach parameter
                     57:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                     58:   computation are long.
                     59: 
                     60:   Revision 1.208  2015/11/17 14:31:57  brouard
                     61:   Summary: temporary
                     62: 
                     63:   Revision 1.207  2015/10/27 17:36:57  brouard
                     64:   *** empty log message ***
                     65: 
                     66:   Revision 1.206  2015/10/24 07:14:11  brouard
                     67:   *** empty log message ***
                     68: 
                     69:   Revision 1.205  2015/10/23 15:50:53  brouard
                     70:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                     71: 
                     72:   Revision 1.204  2015/10/01 16:20:26  brouard
                     73:   Summary: Some new graphs of contribution to likelihood
                     74: 
                     75:   Revision 1.203  2015/09/30 17:45:14  brouard
                     76:   Summary: looking at better estimation of the hessian
                     77: 
                     78:   Also a better criteria for convergence to the period prevalence And
                     79:   therefore adding the number of years needed to converge. (The
                     80:   prevalence in any alive state shold sum to one
                     81: 
                     82:   Revision 1.202  2015/09/22 19:45:16  brouard
                     83:   Summary: Adding some overall graph on contribution to likelihood. Might change
                     84: 
                     85:   Revision 1.201  2015/09/15 17:34:58  brouard
                     86:   Summary: 0.98r0
                     87: 
                     88:   - Some new graphs like suvival functions
                     89:   - Some bugs fixed like model=1+age+V2.
                     90: 
                     91:   Revision 1.200  2015/09/09 16:53:55  brouard
                     92:   Summary: Big bug thanks to Flavia
                     93: 
                     94:   Even model=1+age+V2. did not work anymore
                     95: 
                     96:   Revision 1.199  2015/09/07 14:09:23  brouard
                     97:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                     98: 
                     99:   Revision 1.198  2015/09/03 07:14:39  brouard
                    100:   Summary: 0.98q5 Flavia
                    101: 
                    102:   Revision 1.197  2015/09/01 18:24:39  brouard
                    103:   *** empty log message ***
                    104: 
                    105:   Revision 1.196  2015/08/18 23:17:52  brouard
                    106:   Summary: 0.98q5
                    107: 
                    108:   Revision 1.195  2015/08/18 16:28:39  brouard
                    109:   Summary: Adding a hack for testing purpose
                    110: 
                    111:   After reading the title, ftol and model lines, if the comment line has
                    112:   a q, starting with #q, the answer at the end of the run is quit. It
                    113:   permits to run test files in batch with ctest. The former workaround was
                    114:   $ echo q | imach foo.imach
                    115: 
                    116:   Revision 1.194  2015/08/18 13:32:00  brouard
                    117:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    118: 
                    119:   Revision 1.193  2015/08/04 07:17:42  brouard
                    120:   Summary: 0.98q4
                    121: 
                    122:   Revision 1.192  2015/07/16 16:49:02  brouard
                    123:   Summary: Fixing some outputs
                    124: 
                    125:   Revision 1.191  2015/07/14 10:00:33  brouard
                    126:   Summary: Some fixes
                    127: 
                    128:   Revision 1.190  2015/05/05 08:51:13  brouard
                    129:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    130: 
                    131:   Fix 1+age+.
                    132: 
                    133:   Revision 1.189  2015/04/30 14:45:16  brouard
                    134:   Summary: 0.98q2
                    135: 
                    136:   Revision 1.188  2015/04/30 08:27:53  brouard
                    137:   *** empty log message ***
                    138: 
                    139:   Revision 1.187  2015/04/29 09:11:15  brouard
                    140:   *** empty log message ***
                    141: 
                    142:   Revision 1.186  2015/04/23 12:01:52  brouard
                    143:   Summary: V1*age is working now, version 0.98q1
                    144: 
                    145:   Some codes had been disabled in order to simplify and Vn*age was
                    146:   working in the optimization phase, ie, giving correct MLE parameters,
                    147:   but, as usual, outputs were not correct and program core dumped.
                    148: 
                    149:   Revision 1.185  2015/03/11 13:26:42  brouard
                    150:   Summary: Inclusion of compile and links command line for Intel Compiler
                    151: 
                    152:   Revision 1.184  2015/03/11 11:52:39  brouard
                    153:   Summary: Back from Windows 8. Intel Compiler
                    154: 
                    155:   Revision 1.183  2015/03/10 20:34:32  brouard
                    156:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    157: 
                    158:   We use directest instead of original Powell test; probably no
                    159:   incidence on the results, but better justifications;
                    160:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    161:   wrong results.
                    162: 
                    163:   Revision 1.182  2015/02/12 08:19:57  brouard
                    164:   Summary: Trying to keep directest which seems simpler and more general
                    165:   Author: Nicolas Brouard
                    166: 
                    167:   Revision 1.181  2015/02/11 23:22:24  brouard
                    168:   Summary: Comments on Powell added
                    169: 
                    170:   Author:
                    171: 
                    172:   Revision 1.180  2015/02/11 17:33:45  brouard
                    173:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    174: 
                    175:   Revision 1.179  2015/01/04 09:57:06  brouard
                    176:   Summary: back to OS/X
                    177: 
                    178:   Revision 1.178  2015/01/04 09:35:48  brouard
                    179:   *** empty log message ***
                    180: 
                    181:   Revision 1.177  2015/01/03 18:40:56  brouard
                    182:   Summary: Still testing ilc32 on OSX
                    183: 
                    184:   Revision 1.176  2015/01/03 16:45:04  brouard
                    185:   *** empty log message ***
                    186: 
                    187:   Revision 1.175  2015/01/03 16:33:42  brouard
                    188:   *** empty log message ***
                    189: 
                    190:   Revision 1.174  2015/01/03 16:15:49  brouard
                    191:   Summary: Still in cross-compilation
                    192: 
                    193:   Revision 1.173  2015/01/03 12:06:26  brouard
                    194:   Summary: trying to detect cross-compilation
                    195: 
                    196:   Revision 1.172  2014/12/27 12:07:47  brouard
                    197:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    198: 
                    199:   Revision 1.171  2014/12/23 13:26:59  brouard
                    200:   Summary: Back from Visual C
                    201: 
                    202:   Still problem with utsname.h on Windows
                    203: 
                    204:   Revision 1.170  2014/12/23 11:17:12  brouard
                    205:   Summary: Cleaning some \%% back to %%
                    206: 
                    207:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    208: 
                    209:   Revision 1.169  2014/12/22 23:08:31  brouard
                    210:   Summary: 0.98p
                    211: 
                    212:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    213: 
                    214:   Revision 1.168  2014/12/22 15:17:42  brouard
                    215:   Summary: update
                    216: 
                    217:   Revision 1.167  2014/12/22 13:50:56  brouard
                    218:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    219: 
                    220:   Testing on Linux 64
                    221: 
                    222:   Revision 1.166  2014/12/22 11:40:47  brouard
                    223:   *** empty log message ***
                    224: 
                    225:   Revision 1.165  2014/12/16 11:20:36  brouard
                    226:   Summary: After compiling on Visual C
                    227: 
                    228:   * imach.c (Module): Merging 1.61 to 1.162
                    229: 
                    230:   Revision 1.164  2014/12/16 10:52:11  brouard
                    231:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    232: 
                    233:   * imach.c (Module): Merging 1.61 to 1.162
                    234: 
                    235:   Revision 1.163  2014/12/16 10:30:11  brouard
                    236:   * imach.c (Module): Merging 1.61 to 1.162
                    237: 
                    238:   Revision 1.162  2014/09/25 11:43:39  brouard
                    239:   Summary: temporary backup 0.99!
                    240: 
                    241:   Revision 1.1  2014/09/16 11:06:58  brouard
                    242:   Summary: With some code (wrong) for nlopt
                    243: 
                    244:   Author:
                    245: 
                    246:   Revision 1.161  2014/09/15 20:41:41  brouard
                    247:   Summary: Problem with macro SQR on Intel compiler
                    248: 
                    249:   Revision 1.160  2014/09/02 09:24:05  brouard
                    250:   *** empty log message ***
                    251: 
                    252:   Revision 1.159  2014/09/01 10:34:10  brouard
                    253:   Summary: WIN32
                    254:   Author: Brouard
                    255: 
                    256:   Revision 1.158  2014/08/27 17:11:51  brouard
                    257:   *** empty log message ***
                    258: 
                    259:   Revision 1.157  2014/08/27 16:26:55  brouard
                    260:   Summary: Preparing windows Visual studio version
                    261:   Author: Brouard
                    262: 
                    263:   In order to compile on Visual studio, time.h is now correct and time_t
                    264:   and tm struct should be used. difftime should be used but sometimes I
                    265:   just make the differences in raw time format (time(&now).
                    266:   Trying to suppress #ifdef LINUX
                    267:   Add xdg-open for __linux in order to open default browser.
                    268: 
                    269:   Revision 1.156  2014/08/25 20:10:10  brouard
                    270:   *** empty log message ***
                    271: 
                    272:   Revision 1.155  2014/08/25 18:32:34  brouard
                    273:   Summary: New compile, minor changes
                    274:   Author: Brouard
                    275: 
                    276:   Revision 1.154  2014/06/20 17:32:08  brouard
                    277:   Summary: Outputs now all graphs of convergence to period prevalence
                    278: 
                    279:   Revision 1.153  2014/06/20 16:45:46  brouard
                    280:   Summary: If 3 live state, convergence to period prevalence on same graph
                    281:   Author: Brouard
                    282: 
                    283:   Revision 1.152  2014/06/18 17:54:09  brouard
                    284:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    285: 
                    286:   Revision 1.151  2014/06/18 16:43:30  brouard
                    287:   *** empty log message ***
                    288: 
                    289:   Revision 1.150  2014/06/18 16:42:35  brouard
                    290:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    291:   Author: brouard
                    292: 
                    293:   Revision 1.149  2014/06/18 15:51:14  brouard
                    294:   Summary: Some fixes in parameter files errors
                    295:   Author: Nicolas Brouard
                    296: 
                    297:   Revision 1.148  2014/06/17 17:38:48  brouard
                    298:   Summary: Nothing new
                    299:   Author: Brouard
                    300: 
                    301:   Just a new packaging for OS/X version 0.98nS
                    302: 
                    303:   Revision 1.147  2014/06/16 10:33:11  brouard
                    304:   *** empty log message ***
                    305: 
                    306:   Revision 1.146  2014/06/16 10:20:28  brouard
                    307:   Summary: Merge
                    308:   Author: Brouard
                    309: 
                    310:   Merge, before building revised version.
                    311: 
                    312:   Revision 1.145  2014/06/10 21:23:15  brouard
                    313:   Summary: Debugging with valgrind
                    314:   Author: Nicolas Brouard
                    315: 
                    316:   Lot of changes in order to output the results with some covariates
                    317:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    318:   improve the code.
                    319:   No more memory valgrind error but a lot has to be done in order to
                    320:   continue the work of splitting the code into subroutines.
                    321:   Also, decodemodel has been improved. Tricode is still not
                    322:   optimal. nbcode should be improved. Documentation has been added in
                    323:   the source code.
                    324: 
                    325:   Revision 1.143  2014/01/26 09:45:38  brouard
                    326:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    327: 
                    328:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    329:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    330: 
                    331:   Revision 1.142  2014/01/26 03:57:36  brouard
                    332:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    333: 
                    334:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    335: 
                    336:   Revision 1.141  2014/01/26 02:42:01  brouard
                    337:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    338: 
                    339:   Revision 1.140  2011/09/02 10:37:54  brouard
                    340:   Summary: times.h is ok with mingw32 now.
                    341: 
                    342:   Revision 1.139  2010/06/14 07:50:17  brouard
                    343:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    344:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    345: 
                    346:   Revision 1.138  2010/04/30 18:19:40  brouard
                    347:   *** empty log message ***
                    348: 
                    349:   Revision 1.137  2010/04/29 18:11:38  brouard
                    350:   (Module): Checking covariates for more complex models
                    351:   than V1+V2. A lot of change to be done. Unstable.
                    352: 
                    353:   Revision 1.136  2010/04/26 20:30:53  brouard
                    354:   (Module): merging some libgsl code. Fixing computation
                    355:   of likelione (using inter/intrapolation if mle = 0) in order to
                    356:   get same likelihood as if mle=1.
                    357:   Some cleaning of code and comments added.
                    358: 
                    359:   Revision 1.135  2009/10/29 15:33:14  brouard
                    360:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    361: 
                    362:   Revision 1.134  2009/10/29 13:18:53  brouard
                    363:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    364: 
                    365:   Revision 1.133  2009/07/06 10:21:25  brouard
                    366:   just nforces
                    367: 
                    368:   Revision 1.132  2009/07/06 08:22:05  brouard
                    369:   Many tings
                    370: 
                    371:   Revision 1.131  2009/06/20 16:22:47  brouard
                    372:   Some dimensions resccaled
                    373: 
                    374:   Revision 1.130  2009/05/26 06:44:34  brouard
                    375:   (Module): Max Covariate is now set to 20 instead of 8. A
                    376:   lot of cleaning with variables initialized to 0. Trying to make
                    377:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    378: 
                    379:   Revision 1.129  2007/08/31 13:49:27  lievre
                    380:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    381: 
                    382:   Revision 1.128  2006/06/30 13:02:05  brouard
                    383:   (Module): Clarifications on computing e.j
                    384: 
                    385:   Revision 1.127  2006/04/28 18:11:50  brouard
                    386:   (Module): Yes the sum of survivors was wrong since
                    387:   imach-114 because nhstepm was no more computed in the age
                    388:   loop. Now we define nhstepma in the age loop.
                    389:   (Module): In order to speed up (in case of numerous covariates) we
                    390:   compute health expectancies (without variances) in a first step
                    391:   and then all the health expectancies with variances or standard
                    392:   deviation (needs data from the Hessian matrices) which slows the
                    393:   computation.
                    394:   In the future we should be able to stop the program is only health
                    395:   expectancies and graph are needed without standard deviations.
                    396: 
                    397:   Revision 1.126  2006/04/28 17:23:28  brouard
                    398:   (Module): Yes the sum of survivors was wrong since
                    399:   imach-114 because nhstepm was no more computed in the age
                    400:   loop. Now we define nhstepma in the age loop.
                    401:   Version 0.98h
                    402: 
                    403:   Revision 1.125  2006/04/04 15:20:31  lievre
                    404:   Errors in calculation of health expectancies. Age was not initialized.
                    405:   Forecasting file added.
                    406: 
                    407:   Revision 1.124  2006/03/22 17:13:53  lievre
                    408:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    409:   The log-likelihood is printed in the log file
                    410: 
                    411:   Revision 1.123  2006/03/20 10:52:43  brouard
                    412:   * imach.c (Module): <title> changed, corresponds to .htm file
                    413:   name. <head> headers where missing.
                    414: 
                    415:   * imach.c (Module): Weights can have a decimal point as for
                    416:   English (a comma might work with a correct LC_NUMERIC environment,
                    417:   otherwise the weight is truncated).
                    418:   Modification of warning when the covariates values are not 0 or
                    419:   1.
                    420:   Version 0.98g
                    421: 
                    422:   Revision 1.122  2006/03/20 09:45:41  brouard
                    423:   (Module): Weights can have a decimal point as for
                    424:   English (a comma might work with a correct LC_NUMERIC environment,
                    425:   otherwise the weight is truncated).
                    426:   Modification of warning when the covariates values are not 0 or
                    427:   1.
                    428:   Version 0.98g
                    429: 
                    430:   Revision 1.121  2006/03/16 17:45:01  lievre
                    431:   * imach.c (Module): Comments concerning covariates added
                    432: 
                    433:   * imach.c (Module): refinements in the computation of lli if
                    434:   status=-2 in order to have more reliable computation if stepm is
                    435:   not 1 month. Version 0.98f
                    436: 
                    437:   Revision 1.120  2006/03/16 15:10:38  lievre
                    438:   (Module): refinements in the computation of lli if
                    439:   status=-2 in order to have more reliable computation if stepm is
                    440:   not 1 month. Version 0.98f
                    441: 
                    442:   Revision 1.119  2006/03/15 17:42:26  brouard
                    443:   (Module): Bug if status = -2, the loglikelihood was
                    444:   computed as likelihood omitting the logarithm. Version O.98e
                    445: 
                    446:   Revision 1.118  2006/03/14 18:20:07  brouard
                    447:   (Module): varevsij Comments added explaining the second
                    448:   table of variances if popbased=1 .
                    449:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    450:   (Module): Function pstamp added
                    451:   (Module): Version 0.98d
                    452: 
                    453:   Revision 1.117  2006/03/14 17:16:22  brouard
                    454:   (Module): varevsij Comments added explaining the second
                    455:   table of variances if popbased=1 .
                    456:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    457:   (Module): Function pstamp added
                    458:   (Module): Version 0.98d
                    459: 
                    460:   Revision 1.116  2006/03/06 10:29:27  brouard
                    461:   (Module): Variance-covariance wrong links and
                    462:   varian-covariance of ej. is needed (Saito).
                    463: 
                    464:   Revision 1.115  2006/02/27 12:17:45  brouard
                    465:   (Module): One freematrix added in mlikeli! 0.98c
                    466: 
                    467:   Revision 1.114  2006/02/26 12:57:58  brouard
                    468:   (Module): Some improvements in processing parameter
                    469:   filename with strsep.
                    470: 
                    471:   Revision 1.113  2006/02/24 14:20:24  brouard
                    472:   (Module): Memory leaks checks with valgrind and:
                    473:   datafile was not closed, some imatrix were not freed and on matrix
                    474:   allocation too.
                    475: 
                    476:   Revision 1.112  2006/01/30 09:55:26  brouard
                    477:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    478: 
                    479:   Revision 1.111  2006/01/25 20:38:18  brouard
                    480:   (Module): Lots of cleaning and bugs added (Gompertz)
                    481:   (Module): Comments can be added in data file. Missing date values
                    482:   can be a simple dot '.'.
                    483: 
                    484:   Revision 1.110  2006/01/25 00:51:50  brouard
                    485:   (Module): Lots of cleaning and bugs added (Gompertz)
                    486: 
                    487:   Revision 1.109  2006/01/24 19:37:15  brouard
                    488:   (Module): Comments (lines starting with a #) are allowed in data.
                    489: 
                    490:   Revision 1.108  2006/01/19 18:05:42  lievre
                    491:   Gnuplot problem appeared...
                    492:   To be fixed
                    493: 
                    494:   Revision 1.107  2006/01/19 16:20:37  brouard
                    495:   Test existence of gnuplot in imach path
                    496: 
                    497:   Revision 1.106  2006/01/19 13:24:36  brouard
                    498:   Some cleaning and links added in html output
                    499: 
                    500:   Revision 1.105  2006/01/05 20:23:19  lievre
                    501:   *** empty log message ***
                    502: 
                    503:   Revision 1.104  2005/09/30 16:11:43  lievre
                    504:   (Module): sump fixed, loop imx fixed, and simplifications.
                    505:   (Module): If the status is missing at the last wave but we know
                    506:   that the person is alive, then we can code his/her status as -2
                    507:   (instead of missing=-1 in earlier versions) and his/her
                    508:   contributions to the likelihood is 1 - Prob of dying from last
                    509:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    510:   the healthy state at last known wave). Version is 0.98
                    511: 
                    512:   Revision 1.103  2005/09/30 15:54:49  lievre
                    513:   (Module): sump fixed, loop imx fixed, and simplifications.
                    514: 
                    515:   Revision 1.102  2004/09/15 17:31:30  brouard
                    516:   Add the possibility to read data file including tab characters.
                    517: 
                    518:   Revision 1.101  2004/09/15 10:38:38  brouard
                    519:   Fix on curr_time
                    520: 
                    521:   Revision 1.100  2004/07/12 18:29:06  brouard
                    522:   Add version for Mac OS X. Just define UNIX in Makefile
                    523: 
                    524:   Revision 1.99  2004/06/05 08:57:40  brouard
                    525:   *** empty log message ***
                    526: 
                    527:   Revision 1.98  2004/05/16 15:05:56  brouard
                    528:   New version 0.97 . First attempt to estimate force of mortality
                    529:   directly from the data i.e. without the need of knowing the health
                    530:   state at each age, but using a Gompertz model: log u =a + b*age .
                    531:   This is the basic analysis of mortality and should be done before any
                    532:   other analysis, in order to test if the mortality estimated from the
                    533:   cross-longitudinal survey is different from the mortality estimated
                    534:   from other sources like vital statistic data.
                    535: 
                    536:   The same imach parameter file can be used but the option for mle should be -3.
                    537: 
                    538:   Agnès, who wrote this part of the code, tried to keep most of the
                    539:   former routines in order to include the new code within the former code.
                    540: 
                    541:   The output is very simple: only an estimate of the intercept and of
                    542:   the slope with 95% confident intervals.
                    543: 
                    544:   Current limitations:
                    545:   A) Even if you enter covariates, i.e. with the
                    546:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    547:   B) There is no computation of Life Expectancy nor Life Table.
                    548: 
                    549:   Revision 1.97  2004/02/20 13:25:42  lievre
                    550:   Version 0.96d. Population forecasting command line is (temporarily)
                    551:   suppressed.
                    552: 
                    553:   Revision 1.96  2003/07/15 15:38:55  brouard
                    554:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    555:   rewritten within the same printf. Workaround: many printfs.
                    556: 
                    557:   Revision 1.95  2003/07/08 07:54:34  brouard
                    558:   * imach.c (Repository):
                    559:   (Repository): Using imachwizard code to output a more meaningful covariance
                    560:   matrix (cov(a12,c31) instead of numbers.
                    561: 
                    562:   Revision 1.94  2003/06/27 13:00:02  brouard
                    563:   Just cleaning
                    564: 
                    565:   Revision 1.93  2003/06/25 16:33:55  brouard
                    566:   (Module): On windows (cygwin) function asctime_r doesn't
                    567:   exist so I changed back to asctime which exists.
                    568:   (Module): Version 0.96b
                    569: 
                    570:   Revision 1.92  2003/06/25 16:30:45  brouard
                    571:   (Module): On windows (cygwin) function asctime_r doesn't
                    572:   exist so I changed back to asctime which exists.
                    573: 
                    574:   Revision 1.91  2003/06/25 15:30:29  brouard
                    575:   * imach.c (Repository): Duplicated warning errors corrected.
                    576:   (Repository): Elapsed time after each iteration is now output. It
                    577:   helps to forecast when convergence will be reached. Elapsed time
                    578:   is stamped in powell.  We created a new html file for the graphs
                    579:   concerning matrix of covariance. It has extension -cov.htm.
                    580: 
                    581:   Revision 1.90  2003/06/24 12:34:15  brouard
                    582:   (Module): Some bugs corrected for windows. Also, when
                    583:   mle=-1 a template is output in file "or"mypar.txt with the design
                    584:   of the covariance matrix to be input.
                    585: 
                    586:   Revision 1.89  2003/06/24 12:30:52  brouard
                    587:   (Module): Some bugs corrected for windows. Also, when
                    588:   mle=-1 a template is output in file "or"mypar.txt with the design
                    589:   of the covariance matrix to be input.
                    590: 
                    591:   Revision 1.88  2003/06/23 17:54:56  brouard
                    592:   * 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.
                    593: 
                    594:   Revision 1.87  2003/06/18 12:26:01  brouard
                    595:   Version 0.96
                    596: 
                    597:   Revision 1.86  2003/06/17 20:04:08  brouard
                    598:   (Module): Change position of html and gnuplot routines and added
                    599:   routine fileappend.
                    600: 
                    601:   Revision 1.85  2003/06/17 13:12:43  brouard
                    602:   * imach.c (Repository): Check when date of death was earlier that
                    603:   current date of interview. It may happen when the death was just
                    604:   prior to the death. In this case, dh was negative and likelihood
                    605:   was wrong (infinity). We still send an "Error" but patch by
                    606:   assuming that the date of death was just one stepm after the
                    607:   interview.
                    608:   (Repository): Because some people have very long ID (first column)
                    609:   we changed int to long in num[] and we added a new lvector for
                    610:   memory allocation. But we also truncated to 8 characters (left
                    611:   truncation)
                    612:   (Repository): No more line truncation errors.
                    613: 
                    614:   Revision 1.84  2003/06/13 21:44:43  brouard
                    615:   * imach.c (Repository): Replace "freqsummary" at a correct
                    616:   place. It differs from routine "prevalence" which may be called
                    617:   many times. Probs is memory consuming and must be used with
                    618:   parcimony.
                    619:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    620: 
                    621:   Revision 1.83  2003/06/10 13:39:11  lievre
                    622:   *** empty log message ***
                    623: 
                    624:   Revision 1.82  2003/06/05 15:57:20  brouard
                    625:   Add log in  imach.c and  fullversion number is now printed.
                    626: 
                    627: */
                    628: /*
                    629:    Interpolated Markov Chain
                    630: 
                    631:   Short summary of the programme:
                    632:   
                    633:   This program computes Healthy Life Expectancies from
                    634:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    635:   first survey ("cross") where individuals from different ages are
                    636:   interviewed on their health status or degree of disability (in the
                    637:   case of a health survey which is our main interest) -2- at least a
                    638:   second wave of interviews ("longitudinal") which measure each change
                    639:   (if any) in individual health status.  Health expectancies are
                    640:   computed from the time spent in each health state according to a
                    641:   model. More health states you consider, more time is necessary to reach the
                    642:   Maximum Likelihood of the parameters involved in the model.  The
                    643:   simplest model is the multinomial logistic model where pij is the
                    644:   probability to be observed in state j at the second wave
                    645:   conditional to be observed in state i at the first wave. Therefore
                    646:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    647:   'age' is age and 'sex' is a covariate. If you want to have a more
                    648:   complex model than "constant and age", you should modify the program
                    649:   where the markup *Covariates have to be included here again* invites
                    650:   you to do it.  More covariates you add, slower the
                    651:   convergence.
                    652: 
                    653:   The advantage of this computer programme, compared to a simple
                    654:   multinomial logistic model, is clear when the delay between waves is not
                    655:   identical for each individual. Also, if a individual missed an
                    656:   intermediate interview, the information is lost, but taken into
                    657:   account using an interpolation or extrapolation.  
                    658: 
                    659:   hPijx is the probability to be observed in state i at age x+h
                    660:   conditional to the observed state i at age x. The delay 'h' can be
                    661:   split into an exact number (nh*stepm) of unobserved intermediate
                    662:   states. This elementary transition (by month, quarter,
                    663:   semester or year) is modelled as a multinomial logistic.  The hPx
                    664:   matrix is simply the matrix product of nh*stepm elementary matrices
                    665:   and the contribution of each individual to the likelihood is simply
                    666:   hPijx.
                    667: 
                    668:   Also this programme outputs the covariance matrix of the parameters but also
                    669:   of the life expectancies. It also computes the period (stable) prevalence.
                    670: 
                    671: Back prevalence and projections:
                    672:  - 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)
                    673:     Computes the back prevalence limit  for any combination    of covariate values k
                    674:     at any age between ageminpar and agemaxpar and returns it in **bprlim. In the loops,
                    675:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm, **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    676:  - hBijx Back Probability to be in state i at age x-h being in j at x
                    677:    Computes for any combination of covariates k and any age between bage and fage 
                    678:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    679:                        oldm=oldms;savm=savms;
                    680:         - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
                    681:      Computes the transition matrix starting at age 'age' over
                    682:      'nhstepm*hstepm*stepm' months (i.e. until
                    683:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                    684:      nhstepm*hstepm matrices. Returns p3mat[i][j][h] after calling 
                    685:      p3mat[i][j][h]=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\
                    686:                                                                         1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
                    687: 
                    688:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    689:            Institut national d'études démographiques, Paris.
                    690:   This software have been partly granted by Euro-REVES, a concerted action
                    691:   from the European Union.
                    692:   It is copyrighted identically to a GNU software product, ie programme and
                    693:   software can be distributed freely for non commercial use. Latest version
                    694:   can be accessed at http://euroreves.ined.fr/imach .
                    695: 
                    696:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    697:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    698:   
                    699:   **********************************************************************/
                    700: /*
                    701:   main
                    702:   read parameterfile
                    703:   read datafile
                    704:   concatwav
                    705:   freqsummary
                    706:   if (mle >= 1)
                    707:     mlikeli
                    708:   print results files
                    709:   if mle==1 
                    710:      computes hessian
                    711:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    712:       begin-prev-date,...
                    713:   open gnuplot file
                    714:   open html file
                    715:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    716:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    717:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    718:     freexexit2 possible for memory heap.
                    719: 
                    720:   h Pij x                         | pij_nom  ficrestpij
                    721:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    722:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    723:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    724: 
                    725:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    726:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    727:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    728:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    729:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    730: 
                    731:   forecasting if prevfcast==1 prevforecast call prevalence()
                    732:   health expectancies
                    733:   Variance-covariance of DFLE
                    734:   prevalence()
                    735:    movingaverage()
                    736:   varevsij() 
                    737:   if popbased==1 varevsij(,popbased)
                    738:   total life expectancies
                    739:   Variance of period (stable) prevalence
                    740:  end
                    741: */
                    742: 
                    743: /* #define DEBUG */
                    744: /* #define DEBUGBRENT */
                    745: /* #define DEBUGLINMIN */
                    746: /* #define DEBUGHESS */
                    747: #define DEBUGHESSIJ
                    748: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan)*\/ */
                    749: #define POWELL /* Instead of NLOPT */
1.2     ! brouard   750: /* #ifndef POWELLNOF3INFF1TEST  */
        !           751: /* #define POWELLNOF3INFF1TEST /\* Skip test *\/ */
        !           752: /* #endif */
1.1       brouard   753: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    754: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
                    755: 
                    756: #include <math.h>
                    757: #include <stdio.h>
                    758: #include <stdlib.h>
                    759: #include <string.h>
                    760: 
                    761: #ifdef _WIN32
                    762: #include <io.h>
                    763: #include <windows.h>
                    764: #include <tchar.h>
                    765: #else
                    766: #include <unistd.h>
                    767: #endif
                    768: 
                    769: #include <limits.h>
                    770: #include <sys/types.h>
                    771: 
                    772: #if defined(__GNUC__)
                    773: #include <sys/utsname.h> /* Doesn't work on Windows */
                    774: #endif
                    775: 
                    776: #include <sys/stat.h>
                    777: #include <errno.h>
                    778: /* extern int errno; */
                    779: 
                    780: /* #ifdef LINUX */
                    781: /* #include <time.h> */
                    782: /* #include "timeval.h" */
                    783: /* #else */
                    784: /* #include <sys/time.h> */
                    785: /* #endif */
                    786: 
                    787: #include <time.h>
                    788: 
                    789: #ifdef GSL
                    790: #include <gsl/gsl_errno.h>
                    791: #include <gsl/gsl_multimin.h>
                    792: #endif
                    793: 
                    794: 
                    795: #ifdef NLOPT
                    796: #include <nlopt.h>
                    797: typedef struct {
                    798:   double (* function)(double [] );
                    799: } myfunc_data ;
                    800: #endif
                    801: 
                    802: /* #include <libintl.h> */
                    803: /* #define _(String) gettext (String) */
                    804: 
                    805: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
                    806: 
                    807: #define GNUPLOTPROGRAM "gnuplot"
                    808: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    809: #define FILENAMELENGTH 132
                    810: 
                    811: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    812: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    813: 
                    814: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    815: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
                    816: 
                    817: #define NINTERVMAX 8
                    818: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    819: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    820: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
                    821: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                    822: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                    823: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
                    824: #define MAXN 20000
                    825: #define YEARM 12. /**< Number of months per year */
                    826: /* #define AGESUP 130 */
                    827: #define AGESUP 150
                    828: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
                    829: #define AGEBASE 40
                    830: #define AGEOVERFLOW 1.e20
                    831: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
                    832: #ifdef _WIN32
                    833: #define DIRSEPARATOR '\\'
                    834: #define CHARSEPARATOR "\\"
                    835: #define ODIRSEPARATOR '/'
                    836: #else
                    837: #define DIRSEPARATOR '/'
                    838: #define CHARSEPARATOR "/"
                    839: #define ODIRSEPARATOR '\\'
                    840: #endif
                    841: 
1.2     ! brouard   842: /* $Id: imach-0.98r.c,v 1.1 2016/02/19 09:46:04 brouard Exp $ */
1.1       brouard   843: /* $State: Exp $ */
                    844: #include "version.h"
1.2     ! brouard   845: char version[]=__IMACH_VERSION_98R__;
        !           846: char copyright[]="February 2016,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015-2018";
        !           847: char fullversion[]="$Revision: 1.1 $ $Date: 2016/02/19 09:46:04 $"; 
1.1       brouard   848: char strstart[80];
                    849: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
                    850: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
                    851: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
                    852: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    853: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    854: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    855: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    856: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    857: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    858: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    859: int cptcov=0; /* Working variable */
                    860: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
                    861: int npar=NPARMAX;
                    862: int nlstate=2; /* Number of live states */
                    863: int ndeath=1; /* Number of dead states */
                    864: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
                    865: int popbased=0;
                    866: 
                    867: int *wav; /* Number of waves for this individuual 0 is possible */
                    868: int maxwav=0; /* Maxim number of waves */
                    869: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    870: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    871: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
                    872:                   to the likelihood and the sum of weights (done by funcone)*/
                    873: int mle=1, weightopt=0;
                    874: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    875: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    876: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    877:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
                    878: int countcallfunc=0;  /* Count the number of calls to func */
                    879: double jmean=1; /* Mean space between 2 waves */
                    880: double **matprod2(); /* test */
                    881: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    882: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
                    883: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                    884: 
                    885: /*FILE *fic ; */ /* Used in readdata only */
                    886: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
                    887: FILE *ficlog, *ficrespow;
                    888: int globpr=0; /* Global variable for printing or not */
                    889: double fretone; /* Only one call to likelihood */
                    890: long ipmx=0; /* Number of contributions */
                    891: double sw; /* Sum of weights */
                    892: char filerespow[FILENAMELENGTH];
                    893: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    894: FILE *ficresilk;
                    895: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    896: FILE *ficresprobmorprev;
                    897: FILE *fichtm, *fichtmcov; /* Html File */
                    898: FILE *ficreseij;
                    899: char filerese[FILENAMELENGTH];
                    900: FILE *ficresstdeij;
                    901: char fileresstde[FILENAMELENGTH];
                    902: FILE *ficrescveij;
                    903: char filerescve[FILENAMELENGTH];
                    904: FILE  *ficresvij;
                    905: char fileresv[FILENAMELENGTH];
                    906: FILE  *ficresvpl;
                    907: char fileresvpl[FILENAMELENGTH];
                    908: char title[MAXLINE];
                    909: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
                    910: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    911: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    912: char command[FILENAMELENGTH];
                    913: int  outcmd=0;
                    914: 
                    915: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
                    916: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
                    917: char filelog[FILENAMELENGTH]; /* Log file */
                    918: char filerest[FILENAMELENGTH];
                    919: char fileregp[FILENAMELENGTH];
                    920: char popfile[FILENAMELENGTH];
                    921: 
                    922: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    923: 
                    924: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    925: /* struct timezone tzp; */
                    926: /* extern int gettimeofday(); */
                    927: struct tm tml, *gmtime(), *localtime();
                    928: 
                    929: extern time_t time();
                    930: 
                    931: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    932: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    933: struct tm tm;
                    934: 
                    935: char strcurr[80], strfor[80];
                    936: 
                    937: char *endptr;
                    938: long lval;
                    939: double dval;
                    940: 
                    941: #define NR_END 1
                    942: #define FREE_ARG char*
                    943: #define FTOL 1.0e-10
                    944: 
                    945: #define NRANSI 
                    946: #define ITMAX 200 
                    947: 
                    948: #define TOL 2.0e-4 
                    949: 
                    950: #define CGOLD 0.3819660 
                    951: #define ZEPS 1.0e-10 
                    952: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    953: 
                    954: #define GOLD 1.618034 
                    955: #define GLIMIT 100.0 
                    956: #define TINY 1.0e-20 
                    957: 
                    958: static double maxarg1,maxarg2;
                    959: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    960: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    961:   
                    962: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    963: #define rint(a) floor(a+0.5)
                    964: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
                    965: #define mytinydouble 1.0e-16
                    966: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    967: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    968: /* static double dsqrarg; */
                    969: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
                    970: static double sqrarg;
                    971: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    972: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    973: int agegomp= AGEGOMP;
                    974: 
                    975: int imx; 
                    976: int stepm=1;
                    977: /* Stepm, step in month: minimum step interpolation*/
                    978: 
                    979: int estepm;
                    980: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    981: 
                    982: int m,nb;
                    983: long *num;
                    984: int firstpass=0, lastpass=4,*cod, *cens;
                    985: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                    986:                   covariate for which somebody answered excluding 
                    987:                   undefined. Usually 2: 0 and 1. */
                    988: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                    989:                             covariate for which somebody answered including 
                    990:                             undefined. Usually 3: -1, 0 and 1. */
                    991: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    992: double **pmmij, ***probs; /* Global pointer */
                    993: double ***mobaverage, ***mobaverages; /* New global variable */
                    994: double *ageexmed,*agecens;
                    995: double dateintmean=0;
                    996: 
                    997: double *weight;
                    998: int **s; /* Status */
                    999: double *agedc;
                   1000: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
                   1001:                  * covar=matrix(0,NCOVMAX,1,n); 
                   1002:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
                   1003: double  idx; 
                   1004: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
                   1005: int *Tage;
                   1006: int *Ndum; /** Freq of modality (tricode */
                   1007: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
                   1008: int **Tvard, *Tprod, cptcovprod, *Tvaraff, *invalidvarcomb;
                   1009: double *lsurv, *lpop, *tpop;
                   1010: 
                   1011: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1012: double ftolhess; /**< Tolerance for computing hessian */
                   1013: 
                   1014: /**************** split *************************/
                   1015: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1016: {
                   1017:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1018:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1019:   */ 
                   1020:   char *ss;                            /* pointer */
                   1021:   int  l1=0, l2=0;                             /* length counters */
                   1022: 
                   1023:   l1 = strlen(path );                  /* length of path */
                   1024:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1025:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1026:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1027:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1028:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1029:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1030:     /* get current working directory */
                   1031:     /*    extern  char* getcwd ( char *buf , int len);*/
                   1032: #ifdef WIN32
                   1033:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1034: #else
                   1035:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1036: #endif
                   1037:       return( GLOCK_ERROR_GETCWD );
                   1038:     }
                   1039:     /* got dirc from getcwd*/
                   1040:     printf(" DIRC = %s \n",dirc);
                   1041:   } else {                             /* strip directory from path */
                   1042:     ss++;                              /* after this, the filename */
                   1043:     l2 = strlen( ss );                 /* length of filename */
                   1044:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1045:     strcpy( name, ss );                /* save file name */
                   1046:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
                   1047:     dirc[l1-l2] = '\0';                        /* add zero */
                   1048:     printf(" DIRC2 = %s \n",dirc);
                   1049:   }
                   1050:   /* We add a separator at the end of dirc if not exists */
                   1051:   l1 = strlen( dirc );                 /* length of directory */
                   1052:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1053:     dirc[l1] =  DIRSEPARATOR;
                   1054:     dirc[l1+1] = 0; 
                   1055:     printf(" DIRC3 = %s \n",dirc);
                   1056:   }
                   1057:   ss = strrchr( name, '.' );           /* find last / */
                   1058:   if (ss >0){
                   1059:     ss++;
                   1060:     strcpy(ext,ss);                    /* save extension */
                   1061:     l1= strlen( name);
                   1062:     l2= strlen(ss)+1;
                   1063:     strncpy( finame, name, l1-l2);
                   1064:     finame[l1-l2]= 0;
                   1065:   }
                   1066: 
                   1067:   return( 0 );                         /* we're done */
                   1068: }
                   1069: 
                   1070: 
                   1071: /******************************************/
                   1072: 
                   1073: void replace_back_to_slash(char *s, char*t)
                   1074: {
                   1075:   int i;
                   1076:   int lg=0;
                   1077:   i=0;
                   1078:   lg=strlen(t);
                   1079:   for(i=0; i<= lg; i++) {
                   1080:     (s[i] = t[i]);
                   1081:     if (t[i]== '\\') s[i]='/';
                   1082:   }
                   1083: }
                   1084: 
                   1085: char *trimbb(char *out, char *in)
                   1086: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
                   1087:   char *s;
                   1088:   s=out;
                   1089:   while (*in != '\0'){
                   1090:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
                   1091:       in++;
                   1092:     }
                   1093:     *out++ = *in++;
                   1094:   }
                   1095:   *out='\0';
                   1096:   return s;
                   1097: }
                   1098: 
                   1099: /* char *substrchaine(char *out, char *in, char *chain) */
                   1100: /* { */
                   1101: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1102: /*   char *s, *t; */
                   1103: /*   t=in;s=out; */
                   1104: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1105: /*     *out++ = *in++; */
                   1106: /*   } */
                   1107: 
                   1108: /*   /\* *in matches *chain *\/ */
                   1109: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1110: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1111: /*   } */
                   1112: /*   in--; chain--; */
                   1113: /*   while ( (*in != '\0')){ */
                   1114: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1115: /*     *out++ = *in++; */
                   1116: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1117: /*   } */
                   1118: /*   *out='\0'; */
                   1119: /*   out=s; */
                   1120: /*   return out; */
                   1121: /* } */
                   1122: char *substrchaine(char *out, char *in, char *chain)
                   1123: {
                   1124:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1125:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1126: 
                   1127:   char *strloc;
                   1128: 
                   1129:   strcpy (out, in); 
                   1130:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1131:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1132:   if(strloc != NULL){ 
                   1133:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1134:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1135:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1136:   }
                   1137:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1138:   return out;
                   1139: }
                   1140: 
                   1141: 
                   1142: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1143: {
                   1144:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
                   1145:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1146:      gives blocc="abcdef" and alocc="ghi2j".
                   1147:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1148:   */
                   1149:   char *s, *t;
                   1150:   t=in;s=in;
                   1151:   while ((*in != occ) && (*in != '\0')){
                   1152:     *alocc++ = *in++;
                   1153:   }
                   1154:   if( *in == occ){
                   1155:     *(alocc)='\0';
                   1156:     s=++in;
                   1157:   }
                   1158:  
                   1159:   if (s == t) {/* occ not found */
                   1160:     *(alocc-(in-s))='\0';
                   1161:     in=s;
                   1162:   }
                   1163:   while ( *in != '\0'){
                   1164:     *blocc++ = *in++;
                   1165:   }
                   1166: 
                   1167:   *blocc='\0';
                   1168:   return t;
                   1169: }
                   1170: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1171: {
                   1172:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
                   1173:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1174:      gives blocc="abcdef2ghi" and alocc="j".
                   1175:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1176:   */
                   1177:   char *s, *t;
                   1178:   t=in;s=in;
                   1179:   while (*in != '\0'){
                   1180:     while( *in == occ){
                   1181:       *blocc++ = *in++;
                   1182:       s=in;
                   1183:     }
                   1184:     *blocc++ = *in++;
                   1185:   }
                   1186:   if (s == t) /* occ not found */
                   1187:     *(blocc-(in-s))='\0';
                   1188:   else
                   1189:     *(blocc-(in-s)-1)='\0';
                   1190:   in=s;
                   1191:   while ( *in != '\0'){
                   1192:     *alocc++ = *in++;
                   1193:   }
                   1194: 
                   1195:   *alocc='\0';
                   1196:   return s;
                   1197: }
                   1198: 
                   1199: int nbocc(char *s, char occ)
                   1200: {
                   1201:   int i,j=0;
                   1202:   int lg=20;
                   1203:   i=0;
                   1204:   lg=strlen(s);
                   1205:   for(i=0; i<= lg; i++) {
                   1206:   if  (s[i] == occ ) j++;
                   1207:   }
                   1208:   return j;
                   1209: }
                   1210: 
                   1211: /* void cutv(char *u,char *v, char*t, char occ) */
                   1212: /* { */
                   1213: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1214: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1215: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1216: /*   int i,lg,j,p=0; */
                   1217: /*   i=0; */
                   1218: /*   lg=strlen(t); */
                   1219: /*   for(j=0; j<=lg-1; j++) { */
                   1220: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1221: /*   } */
                   1222: 
                   1223: /*   for(j=0; j<p; j++) { */
                   1224: /*     (u[j] = t[j]); */
                   1225: /*   } */
                   1226: /*      u[p]='\0'; */
                   1227: 
                   1228: /*    for(j=0; j<= lg; j++) { */
                   1229: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1230: /*   } */
                   1231: /* } */
                   1232: 
                   1233: #ifdef _WIN32
                   1234: char * strsep(char **pp, const char *delim)
                   1235: {
                   1236:   char *p, *q;
                   1237:          
                   1238:   if ((p = *pp) == NULL)
                   1239:     return 0;
                   1240:   if ((q = strpbrk (p, delim)) != NULL)
                   1241:   {
                   1242:     *pp = q + 1;
                   1243:     *q = '\0';
                   1244:   }
                   1245:   else
                   1246:     *pp = 0;
                   1247:   return p;
                   1248: }
                   1249: #endif
                   1250: 
                   1251: /********************** nrerror ********************/
                   1252: 
                   1253: void nrerror(char error_text[])
                   1254: {
                   1255:   fprintf(stderr,"ERREUR ...\n");
                   1256:   fprintf(stderr,"%s\n",error_text);
                   1257:   exit(EXIT_FAILURE);
                   1258: }
                   1259: /*********************** vector *******************/
                   1260: double *vector(int nl, int nh)
                   1261: {
                   1262:   double *v;
                   1263:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1264:   if (!v) nrerror("allocation failure in vector");
                   1265:   return v-nl+NR_END;
                   1266: }
                   1267: 
                   1268: /************************ free vector ******************/
                   1269: void free_vector(double*v, int nl, int nh)
                   1270: {
                   1271:   free((FREE_ARG)(v+nl-NR_END));
                   1272: }
                   1273: 
                   1274: /************************ivector *******************************/
                   1275: int *ivector(long nl,long nh)
                   1276: {
                   1277:   int *v;
                   1278:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1279:   if (!v) nrerror("allocation failure in ivector");
                   1280:   return v-nl+NR_END;
                   1281: }
                   1282: 
                   1283: /******************free ivector **************************/
                   1284: void free_ivector(int *v, long nl, long nh)
                   1285: {
                   1286:   free((FREE_ARG)(v+nl-NR_END));
                   1287: }
                   1288: 
                   1289: /************************lvector *******************************/
                   1290: long *lvector(long nl,long nh)
                   1291: {
                   1292:   long *v;
                   1293:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1294:   if (!v) nrerror("allocation failure in ivector");
                   1295:   return v-nl+NR_END;
                   1296: }
                   1297: 
                   1298: /******************free lvector **************************/
                   1299: void free_lvector(long *v, long nl, long nh)
                   1300: {
                   1301:   free((FREE_ARG)(v+nl-NR_END));
                   1302: }
                   1303: 
                   1304: /******************* imatrix *******************************/
                   1305: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1306:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1307: { 
                   1308:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1309:   int **m; 
                   1310:   
                   1311:   /* allocate pointers to rows */ 
                   1312:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1313:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1314:   m += NR_END; 
                   1315:   m -= nrl; 
                   1316:   
                   1317:   
                   1318:   /* allocate rows and set pointers to them */ 
                   1319:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1320:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1321:   m[nrl] += NR_END; 
                   1322:   m[nrl] -= ncl; 
                   1323:   
                   1324:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1325:   
                   1326:   /* return pointer to array of pointers to rows */ 
                   1327:   return m; 
                   1328: } 
                   1329: 
                   1330: /****************** free_imatrix *************************/
                   1331: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1332:       int **m;
                   1333:       long nch,ncl,nrh,nrl; 
                   1334:      /* free an int matrix allocated by imatrix() */ 
                   1335: { 
                   1336:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1337:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1338: } 
                   1339: 
                   1340: /******************* matrix *******************************/
                   1341: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1342: {
                   1343:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1344:   double **m;
                   1345: 
                   1346:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1347:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1348:   m += NR_END;
                   1349:   m -= nrl;
                   1350: 
                   1351:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1352:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1353:   m[nrl] += NR_END;
                   1354:   m[nrl] -= ncl;
                   1355: 
                   1356:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1357:   return m;
                   1358:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1359: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1360: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
                   1361:    */
                   1362: }
                   1363: 
                   1364: /*************************free matrix ************************/
                   1365: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1366: {
                   1367:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1368:   free((FREE_ARG)(m+nrl-NR_END));
                   1369: }
                   1370: 
                   1371: /******************* ma3x *******************************/
                   1372: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1373: {
                   1374:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1375:   double ***m;
                   1376: 
                   1377:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1378:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1379:   m += NR_END;
                   1380:   m -= nrl;
                   1381: 
                   1382:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1383:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1384:   m[nrl] += NR_END;
                   1385:   m[nrl] -= ncl;
                   1386: 
                   1387:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1388: 
                   1389:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1390:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1391:   m[nrl][ncl] += NR_END;
                   1392:   m[nrl][ncl] -= nll;
                   1393:   for (j=ncl+1; j<=nch; j++) 
                   1394:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1395:   
                   1396:   for (i=nrl+1; i<=nrh; i++) {
                   1397:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1398:     for (j=ncl+1; j<=nch; j++) 
                   1399:       m[i][j]=m[i][j-1]+nlay;
                   1400:   }
                   1401:   return m; 
                   1402:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1403:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1404:   */
                   1405: }
                   1406: 
                   1407: /*************************free ma3x ************************/
                   1408: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1409: {
                   1410:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1411:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1412:   free((FREE_ARG)(m+nrl-NR_END));
                   1413: }
                   1414: 
                   1415: /*************** function subdirf ***********/
                   1416: char *subdirf(char fileres[])
                   1417: {
                   1418:   /* Caution optionfilefiname is hidden */
                   1419:   strcpy(tmpout,optionfilefiname);
                   1420:   strcat(tmpout,"/"); /* Add to the right */
                   1421:   strcat(tmpout,fileres);
                   1422:   return tmpout;
                   1423: }
                   1424: 
                   1425: /*************** function subdirf2 ***********/
                   1426: char *subdirf2(char fileres[], char *preop)
                   1427: {
                   1428:   
                   1429:   /* Caution optionfilefiname is hidden */
                   1430:   strcpy(tmpout,optionfilefiname);
                   1431:   strcat(tmpout,"/");
                   1432:   strcat(tmpout,preop);
                   1433:   strcat(tmpout,fileres);
                   1434:   return tmpout;
                   1435: }
                   1436: 
                   1437: /*************** function subdirf3 ***********/
                   1438: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1439: {
                   1440:   
                   1441:   /* Caution optionfilefiname is hidden */
                   1442:   strcpy(tmpout,optionfilefiname);
                   1443:   strcat(tmpout,"/");
                   1444:   strcat(tmpout,preop);
                   1445:   strcat(tmpout,preop2);
                   1446:   strcat(tmpout,fileres);
                   1447:   return tmpout;
                   1448: }
                   1449:  
                   1450: /*************** function subdirfext ***********/
                   1451: char *subdirfext(char fileres[], char *preop, char *postop)
                   1452: {
                   1453:   
                   1454:   strcpy(tmpout,preop);
                   1455:   strcat(tmpout,fileres);
                   1456:   strcat(tmpout,postop);
                   1457:   return tmpout;
                   1458: }
                   1459: 
                   1460: /*************** function subdirfext3 ***********/
                   1461: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1462: {
                   1463:   
                   1464:   /* Caution optionfilefiname is hidden */
                   1465:   strcpy(tmpout,optionfilefiname);
                   1466:   strcat(tmpout,"/");
                   1467:   strcat(tmpout,preop);
                   1468:   strcat(tmpout,fileres);
                   1469:   strcat(tmpout,postop);
                   1470:   return tmpout;
                   1471: }
                   1472:  
                   1473: char *asc_diff_time(long time_sec, char ascdiff[])
                   1474: {
                   1475:   long sec_left, days, hours, minutes;
                   1476:   days = (time_sec) / (60*60*24);
                   1477:   sec_left = (time_sec) % (60*60*24);
                   1478:   hours = (sec_left) / (60*60) ;
                   1479:   sec_left = (sec_left) %(60*60);
                   1480:   minutes = (sec_left) /60;
                   1481:   sec_left = (sec_left) % (60);
                   1482:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1483:   return ascdiff;
                   1484: }
                   1485: 
                   1486: /***************** f1dim *************************/
                   1487: extern int ncom; 
                   1488: extern double *pcom,*xicom;
                   1489: extern double (*nrfunc)(double []); 
                   1490:  
                   1491: double f1dim(double x) 
                   1492: { 
                   1493:   int j; 
                   1494:   double f;
                   1495:   double *xt; 
                   1496:  
                   1497:   xt=vector(1,ncom); 
                   1498:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1499:   f=(*nrfunc)(xt); 
                   1500:   free_vector(xt,1,ncom); 
                   1501:   return f; 
                   1502: } 
                   1503: 
                   1504: /*****************brent *************************/
                   1505: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
                   1506: {
                   1507:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1508:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1509:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1510:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1511:    * returned function value. 
                   1512:   */
                   1513:   int iter; 
                   1514:   double a,b,d,etemp;
                   1515:   double fu=0,fv,fw,fx;
                   1516:   double ftemp=0.;
                   1517:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1518:   double e=0.0; 
                   1519:  
                   1520:   a=(ax < cx ? ax : cx); 
                   1521:   b=(ax > cx ? ax : cx); 
                   1522:   x=w=v=bx; 
                   1523:   fw=fv=fx=(*f)(x); 
                   1524:   for (iter=1;iter<=ITMAX;iter++) { 
                   1525:     xm=0.5*(a+b); 
                   1526:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1527:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1528:     printf(".");fflush(stdout);
                   1529:     fprintf(ficlog,".");fflush(ficlog);
                   1530: #ifdef DEBUGBRENT
                   1531:     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);
                   1532:     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);
                   1533:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1534: #endif
                   1535:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1536:       *xmin=x; 
                   1537:       return fx; 
                   1538:     } 
                   1539:     ftemp=fu;
                   1540:     if (fabs(e) > tol1) { 
                   1541:       r=(x-w)*(fx-fv); 
                   1542:       q=(x-v)*(fx-fw); 
                   1543:       p=(x-v)*q-(x-w)*r; 
                   1544:       q=2.0*(q-r); 
                   1545:       if (q > 0.0) p = -p; 
                   1546:       q=fabs(q); 
                   1547:       etemp=e; 
                   1548:       e=d; 
                   1549:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.2     ! brouard  1550:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.1       brouard  1551:       else { 
1.2     ! brouard  1552:                                d=p/q; 
        !          1553:                                u=x+d; 
        !          1554:                                if (u-a < tol2 || b-u < tol2) 
        !          1555:                                        d=SIGN(tol1,xm-x); 
1.1       brouard  1556:       } 
                   1557:     } else { 
                   1558:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1559:     } 
                   1560:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1561:     fu=(*f)(u); 
                   1562:     if (fu <= fx) { 
                   1563:       if (u >= x) a=x; else b=x; 
                   1564:       SHFT(v,w,x,u) 
                   1565:       SHFT(fv,fw,fx,fu) 
                   1566:     } else { 
                   1567:       if (u < x) a=u; else b=u; 
                   1568:       if (fu <= fw || w == x) { 
1.2     ! brouard  1569:                                v=w; 
        !          1570:                                w=u; 
        !          1571:                                fv=fw; 
        !          1572:                                fw=fu; 
1.1       brouard  1573:       } else if (fu <= fv || v == x || v == w) { 
1.2     ! brouard  1574:                                v=u; 
        !          1575:                                fv=fu; 
1.1       brouard  1576:       } 
                   1577:     } 
                   1578:   } 
                   1579:   nrerror("Too many iterations in brent"); 
                   1580:   *xmin=x; 
                   1581:   return fx; 
                   1582: } 
                   1583: 
                   1584: /****************** mnbrak ***********************/
                   1585: 
                   1586: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1587:            double (*func)(double)) 
                   1588: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1589: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1590: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1591: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1592:    */
                   1593:   double ulim,u,r,q, dum;
                   1594:   double fu; 
                   1595: 
                   1596:   double scale=10.;
                   1597:   int iterscale=0;
                   1598: 
                   1599:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1600:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1601: 
                   1602: 
                   1603:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1604:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1605:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1606:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1607:   /* } */
                   1608: 
                   1609:   if (*fb > *fa) { 
                   1610:     SHFT(dum,*ax,*bx,dum) 
                   1611:     SHFT(dum,*fb,*fa,dum) 
                   1612:   } 
                   1613:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1614:   *fc=(*func)(*cx); 
                   1615: #ifdef DEBUG
1.2     ! brouard  1616:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
        !          1617:   fprintf(ficlog,"mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
1.1       brouard  1618: #endif
1.2     ! brouard  1619:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc. If fc=inf it exits*/
1.1       brouard  1620:     r=(*bx-*ax)*(*fb-*fc); 
1.2     ! brouard  1621:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.1       brouard  1622:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
                   1623:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1624:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
1.2     ! brouard  1625:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c  */
1.1       brouard  1626:       fu=(*func)(u); 
                   1627: #ifdef DEBUG
                   1628:       /* f(x)=A(x-u)**2+f(u) */
                   1629:       double A, fparabu; 
                   1630:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1631:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.2     ! brouard  1632:       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);
        !          1633:       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);
1.1       brouard  1634:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1635:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1636:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1637:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
                   1638: #endif 
                   1639: #ifdef MNBRAKORIGINAL
                   1640: #else
                   1641: /*       if (fu > *fc) { */
                   1642: /* #ifdef DEBUG */
                   1643: /*       printf("mnbrak4  fu > fc \n"); */
                   1644: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1645: /* #endif */
                   1646: /*     /\* 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 *\\/  *\/ */
                   1647: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1648: /*     dum=u; /\* Shifting c and u *\/ */
                   1649: /*     u = *cx; */
                   1650: /*     *cx = dum; */
                   1651: /*     dum = fu; */
                   1652: /*     fu = *fc; */
                   1653: /*     *fc =dum; */
                   1654: /*       } else { /\* end *\/ */
                   1655: /* #ifdef DEBUG */
                   1656: /*       printf("mnbrak3  fu < fc \n"); */
                   1657: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1658: /* #endif */
                   1659: /*     dum=u; /\* Shifting c and u *\/ */
                   1660: /*     u = *cx; */
                   1661: /*     *cx = dum; */
                   1662: /*     dum = fu; */
                   1663: /*     fu = *fc; */
                   1664: /*     *fc =dum; */
                   1665: /*       } */
1.2     ! brouard  1666: #ifdef DEBUGMNBRAK
        !          1667:                 double A, fparabu; 
        !          1668:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
        !          1669:      fparabu= *fa - A*(*ax-u)*(*ax-u);
        !          1670:      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);
        !          1671:      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);
1.1       brouard  1672: #endif
                   1673:       dum=u; /* Shifting c and u */
                   1674:       u = *cx;
                   1675:       *cx = dum;
                   1676:       dum = fu;
                   1677:       fu = *fc;
                   1678:       *fc =dum;
                   1679: #endif
                   1680:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
                   1681: #ifdef DEBUG
1.2     ! brouard  1682:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
        !          1683:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.1       brouard  1684: #endif
                   1685:       fu=(*func)(u); 
                   1686:       if (fu < *fc) { 
                   1687: #ifdef DEBUG
1.2     ! brouard  1688:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
        !          1689:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
        !          1690: #endif
        !          1691:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
        !          1692:                                SHFT(*fb,*fc,fu,(*func)(u)) 
        !          1693: #ifdef DEBUG
        !          1694:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.1       brouard  1695: #endif
                   1696:       } 
                   1697:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
                   1698: #ifdef DEBUG
1.2     ! brouard  1699:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
        !          1700:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.1       brouard  1701: #endif
                   1702:       u=ulim; 
                   1703:       fu=(*func)(u); 
                   1704:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1705: #ifdef DEBUG
1.2     ! brouard  1706:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
        !          1707:       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);
1.1       brouard  1708: #endif
                   1709:       u=(*cx)+GOLD*(*cx-*bx); 
                   1710:       fu=(*func)(u); 
1.2     ! brouard  1711: #ifdef DEBUG
        !          1712:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
        !          1713:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
        !          1714: #endif
1.1       brouard  1715:     } /* end tests */
                   1716:     SHFT(*ax,*bx,*cx,u) 
                   1717:     SHFT(*fa,*fb,*fc,fu) 
                   1718: #ifdef DEBUG
1.2     ! brouard  1719:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
        !          1720:       fprintf(ficlog, "\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
1.1       brouard  1721: #endif
                   1722:   } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
                   1723: } 
                   1724: 
                   1725: /*************** linmin ************************/
                   1726: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1727: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1728: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1729: the value of func at the returned location p . This is actually all accomplished by calling the
                   1730: routines mnbrak and brent .*/
                   1731: int ncom; 
                   1732: double *pcom,*xicom;
                   1733: double (*nrfunc)(double []); 
                   1734:  
1.2     ! brouard  1735: #ifdef LINMINORIGINAL
1.1       brouard  1736: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.2     ! brouard  1737: #else
        !          1738: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
        !          1739: #endif
1.1       brouard  1740: { 
                   1741:   double brent(double ax, double bx, double cx, 
                   1742:               double (*f)(double), double tol, double *xmin); 
                   1743:   double f1dim(double x); 
                   1744:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1745:              double *fc, double (*func)(double)); 
                   1746:   int j; 
                   1747:   double xx,xmin,bx,ax; 
                   1748:   double fx,fb,fa;
                   1749: 
                   1750: #ifdef LINMINORIGINAL
                   1751: #else
                   1752:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1753: #endif
                   1754:   
                   1755:   ncom=n; 
                   1756:   pcom=vector(1,n); 
                   1757:   xicom=vector(1,n); 
                   1758:   nrfunc=func; 
                   1759:   for (j=1;j<=n;j++) { 
                   1760:     pcom[j]=p[j]; 
                   1761:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
                   1762:   } 
                   1763: 
                   1764: #ifdef LINMINORIGINAL
                   1765:   xx=1.;
                   1766: #else
                   1767:   axs=0.0;
                   1768:   xxs=1.;
                   1769:   do{
                   1770:     xx= xxs;
                   1771: #endif
                   1772:     ax=0.;
                   1773:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1774:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1775:     /* 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))   */
                   1776:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1777:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1778:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1779:     /* 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]]*/
                   1780: #ifdef LINMINORIGINAL
                   1781: #else
                   1782:     if (fx != fx){
1.2     ! brouard  1783:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
        !          1784:                        printf("|");
        !          1785:                        fprintf(ficlog,"|");
1.1       brouard  1786: #ifdef DEBUGLINMIN
1.2     ! brouard  1787:                        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);
1.1       brouard  1788: #endif
                   1789:     }
1.2     ! brouard  1790:   }while(fx != fx && xxs > 1.e-5);
1.1       brouard  1791: #endif
                   1792:   
                   1793: #ifdef DEBUGLINMIN
                   1794:   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);
                   1795:   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);
                   1796: #endif
1.2     ! brouard  1797: #ifdef LINMINORIGINAL
        !          1798: #else
        !          1799:        if(fb == fx){ /* Flat function in the direction */
        !          1800:                xmin=xx;
        !          1801:     *flat=1;
        !          1802:        }else{
        !          1803:     *flat=0;
        !          1804: #endif
1.1       brouard  1805:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1806:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1807:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1808:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1809:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
                   1810: #ifdef DEBUG
1.2     ! brouard  1811:   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);
        !          1812:   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);
        !          1813: #endif
        !          1814: #ifdef LINMINORIGINAL
        !          1815: #else
        !          1816:                        }
1.1       brouard  1817: #endif
                   1818: #ifdef DEBUGLINMIN
                   1819:   printf("linmin end ");
                   1820:   fprintf(ficlog,"linmin end ");
                   1821: #endif
                   1822:   for (j=1;j<=n;j++) { 
                   1823: #ifdef LINMINORIGINAL
                   1824:     xi[j] *= xmin; 
                   1825: #else
                   1826: #ifdef DEBUGLINMIN
                   1827:     if(xxs <1.0)
                   1828:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   1829: #endif
                   1830:     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) */
                   1831: #ifdef DEBUGLINMIN
                   1832:     if(xxs <1.0)
                   1833:       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 );
                   1834: #endif
                   1835: #endif
                   1836:     p[j] += xi[j]; /* Parameters values are updated accordingly */
                   1837:   } 
                   1838: #ifdef DEBUGLINMIN
                   1839:   printf("\n");
                   1840:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
                   1841:   fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
                   1842:   for (j=1;j<=n;j++) { 
                   1843:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1844:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1845:     if(j % ncovmodel == 0){
                   1846:       printf("\n");
                   1847:       fprintf(ficlog,"\n");
                   1848:     }
                   1849:   }
                   1850: #else
                   1851: #endif
                   1852:   free_vector(xicom,1,n); 
                   1853:   free_vector(pcom,1,n); 
                   1854: } 
                   1855: 
                   1856: 
                   1857: /*************** powell ************************/
                   1858: /*
                   1859: Minimization of a function func of n variables. Input consists of an initial starting point
                   1860: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1861: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1862: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1863: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1864: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1865:  */
1.2     ! brouard  1866: #ifdef LINMINORIGINAL
        !          1867: #else
        !          1868:        int *flatdir; /* Function is vanishing in that direction */
        !          1869:        int flat=0; /* Function is vanishing in that direction */
        !          1870: #endif
1.1       brouard  1871: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1872:            double (*func)(double [])) 
                   1873: { 
1.2     ! brouard  1874: #ifdef LINMINORIGINAL
        !          1875:  void linmin(double p[], double xi[], int n, double *fret, 
1.1       brouard  1876:              double (*func)(double [])); 
1.2     ! brouard  1877: #else 
        !          1878:  void linmin(double p[], double xi[], int n, double *fret, 
        !          1879:                                                 double (*func)(double []),int *flat); 
        !          1880: #endif
1.1       brouard  1881:   int i,ibig,j; 
                   1882:   double del,t,*pt,*ptt,*xit;
                   1883:   double directest;
                   1884:   double fp,fptt;
                   1885:   double *xits;
                   1886:   int niterf, itmp;
1.2     ! brouard  1887: #ifdef LINMINORIGINAL
        !          1888: #else
        !          1889: 
        !          1890:   flatdir=ivector(1,n); 
        !          1891:   for (j=1;j<=n;j++) flatdir[j]=0; 
        !          1892: #endif
1.1       brouard  1893: 
                   1894:   pt=vector(1,n); 
                   1895:   ptt=vector(1,n); 
                   1896:   xit=vector(1,n); 
                   1897:   xits=vector(1,n); 
                   1898:   *fret=(*func)(p); 
                   1899:   for (j=1;j<=n;j++) pt[j]=p[j]; 
                   1900:   rcurr_time = time(NULL);  
                   1901:   for (*iter=1;;++(*iter)) { 
                   1902:     fp=(*fret); /* From former iteration or initial value */
                   1903:     ibig=0; 
                   1904:     del=0.0; 
                   1905:     rlast_time=rcurr_time;
                   1906:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1907:     rcurr_time = time(NULL);  
                   1908:     curr_time = *localtime(&rcurr_time);
                   1909:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1910:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1911: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
                   1912:     for (i=1;i<=n;i++) {
                   1913:       printf(" %d %.12f",i, p[i]);
                   1914:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1915:       fprintf(ficrespow," %.12lf", p[i]);
                   1916:     }
                   1917:     printf("\n");
                   1918:     fprintf(ficlog,"\n");
                   1919:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1920:     if(*iter <=3){
                   1921:       tml = *localtime(&rcurr_time);
                   1922:       strcpy(strcurr,asctime(&tml));
                   1923:       rforecast_time=rcurr_time; 
                   1924:       itmp = strlen(strcurr);
                   1925:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.2     ! brouard  1926:                                strcurr[itmp-1]='\0';
1.1       brouard  1927:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
                   1928:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
                   1929:       for(niterf=10;niterf<=30;niterf+=10){
1.2     ! brouard  1930:                                rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
        !          1931:                                forecast_time = *localtime(&rforecast_time);
        !          1932:                                strcpy(strfor,asctime(&forecast_time));
        !          1933:                                itmp = strlen(strfor);
        !          1934:                                if(strfor[itmp-1]=='\n')
        !          1935:                                        strfor[itmp-1]='\0';
        !          1936:                                printf("   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
        !          1937:                                fprintf(ficlog,"   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
1.1       brouard  1938:       }
                   1939:     }
                   1940:     for (i=1;i<=n;i++) { /* For each direction i */
                   1941:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
                   1942:       fptt=(*fret); 
                   1943: #ifdef DEBUG
                   1944:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1945:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1946: #endif
                   1947:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
                   1948:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.2     ! brouard  1949: #ifdef LINMINORIGINAL
1.1       brouard  1950:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.2     ! brouard  1951: #else
        !          1952:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
        !          1953:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
        !          1954: #endif
        !          1955:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.1       brouard  1956:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.2     ! brouard  1957:                                /* because that direction will be replaced unless the gain del is small */
        !          1958:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
        !          1959:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
        !          1960:                                /* with the new direction. */
        !          1961:                                del=fabs(fptt-(*fret)); 
        !          1962:                                ibig=i; 
1.1       brouard  1963:       } 
                   1964: #ifdef DEBUG
                   1965:       printf("%d %.12e",i,(*fret));
                   1966:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1967:       for (j=1;j<=n;j++) {
1.2     ! brouard  1968:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
        !          1969:                                printf(" x(%d)=%.12e",j,xit[j]);
        !          1970:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.1       brouard  1971:       }
                   1972:       for(j=1;j<=n;j++) {
1.2     ! brouard  1973:                        printf(" p(%d)=%lf ",j,p[j]);
        !          1974:                        fprintf(ficlog," p(%d)=%lf ",j,p[j]);
1.1       brouard  1975:       }
                   1976:       printf("\n");
                   1977:       fprintf(ficlog,"\n");
                   1978: #endif
                   1979:     } /* end loop on each direction i */
                   1980:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
                   1981:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
                   1982:     /* New value of last point Pn is not computed, P(n-1) */
1.2     ! brouard  1983:       for(j=1;j<=n;j++) {
        !          1984:                          printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
        !          1985:                          fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
        !          1986:       }
        !          1987:       printf("\n");
        !          1988:       fprintf(ficlog,"\n");
        !          1989: 
1.1       brouard  1990:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
                   1991:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   1992:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   1993:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   1994:       /* decreased of more than 3.84  */
                   1995:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   1996:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   1997:       /* By adding 10 parameters more the gain should be 18.31 */
1.2     ! brouard  1998:                        
1.1       brouard  1999:       /* Starting the program with initial values given by a former maximization will simply change */
                   2000:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2001:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2002:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
                   2003: #ifdef DEBUG
                   2004:       int k[2],l;
                   2005:       k[0]=1;
                   2006:       k[1]=-1;
                   2007:       printf("Max: %.12e",(*func)(p));
                   2008:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2009:       for (j=1;j<=n;j++) {
                   2010:        printf(" %.12e",p[j]);
                   2011:        fprintf(ficlog," %.12e",p[j]);
                   2012:       }
                   2013:       printf("\n");
                   2014:       fprintf(ficlog,"\n");
                   2015:       for(l=0;l<=1;l++) {
                   2016:        for (j=1;j<=n;j++) {
                   2017:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2018:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2019:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2020:        }
                   2021:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2022:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2023:       }
                   2024: #endif
                   2025: 
1.2     ! brouard  2026: #ifdef LINMINORIGINAL
        !          2027: #else
        !          2028:       free_ivector(flatdir,1,n); 
        !          2029: #endif
1.1       brouard  2030:       free_vector(xit,1,n); 
                   2031:       free_vector(xits,1,n); 
                   2032:       free_vector(ptt,1,n); 
                   2033:       free_vector(pt,1,n); 
                   2034:       return; 
                   2035:     } /* enough precision */ 
                   2036:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
                   2037:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
                   2038:       ptt[j]=2.0*p[j]-pt[j]; 
                   2039:       xit[j]=p[j]-pt[j]; 
                   2040:       pt[j]=p[j]; 
                   2041:     } 
                   2042:     fptt=(*func)(ptt); /* f_3 */
1.2     ! brouard  2043: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.1       brouard  2044: #else
                   2045:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
                   2046: #endif
                   2047:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
                   2048:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
                   2049:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2050:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2051:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.2     ! brouard  2052:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
        !          2053:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
        !          2054:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.1       brouard  2055:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.2     ! brouard  2056:       /*  Even if f3 <f1, directest can be negative and t >0 */
        !          2057:       /* mu² and del² are equal when f3=f1 */
        !          2058:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
        !          2059:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
        !          2060:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
        !          2061:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.1       brouard  2062: #ifdef NRCORIGINAL
                   2063:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2064: #else
                   2065:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
                   2066:       t= t- del*SQR(fp-fptt);
                   2067: #endif
                   2068:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
                   2069: #ifdef DEBUG
                   2070:       printf("t1= %.12lf, t2= %.12lf, t=%.12lf  directest=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t,directest);
                   2071:       fprintf(ficlog,"t1= %.12lf, t2= %.12lf, t=%.12lf directest=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t,directest);
                   2072:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2073:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2074:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2075:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2076:       printf("tt= %.12lf, t=%.12lf\n",2.0*(fp-2.0*(*fret)+fptt)*(fp-(*fret)-del)*(fp-(*fret)-del)-del*(fp-fptt)*(fp-fptt),t);
                   2077:       fprintf(ficlog, "tt= %.12lf, t=%.12lf\n",2.0*(fp-2.0*(*fret)+fptt)*(fp-(*fret)-del)*(fp-(*fret)-del)-del*(fp-fptt)*(fp-fptt),t);
                   2078: #endif
                   2079: #ifdef POWELLORIGINAL
                   2080:       if (t < 0.0) { /* Then we use it for new direction */
                   2081: #else
                   2082:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.2     ! brouard  2083:                                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  2084:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1.2     ! brouard  2085:         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);
1.1       brouard  2086:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2087:       } 
                   2088:       if (directest < 0.0) { /* Then we use it for new direction */
                   2089: #endif
                   2090: #ifdef DEBUGLINMIN
1.2     ! brouard  2091:                                printf("Before linmin in direction P%d-P0\n",n);
        !          2092:                                for (j=1;j<=n;j++) {
        !          2093:                                        printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
        !          2094:                                        fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
        !          2095:                                        if(j % ncovmodel == 0){
        !          2096:                                                printf("\n");
        !          2097:                                                fprintf(ficlog,"\n");
        !          2098:                                        }
        !          2099:                                }
        !          2100: #endif
        !          2101: #ifdef LINMINORIGINAL
        !          2102:                                linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
        !          2103: #else
        !          2104:                                linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
        !          2105:                                flatdir[i]=flat; /* Function is vanishing in that direction i */
1.1       brouard  2106: #endif
1.2     ! brouard  2107: 
1.1       brouard  2108: #ifdef DEBUGLINMIN
1.2     ! brouard  2109:                                for (j=1;j<=n;j++) { 
        !          2110:                                        printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
        !          2111:                                        fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
        !          2112:                                        if(j % ncovmodel == 0){
        !          2113:                                                printf("\n");
        !          2114:                                                fprintf(ficlog,"\n");
        !          2115:                                        }
        !          2116:                                }
        !          2117: #endif
        !          2118:                                for (j=1;j<=n;j++) { 
        !          2119:                                        xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
        !          2120:                                        xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
        !          2121:                                }
        !          2122: #ifdef LINMINORIGINAL
        !          2123: #else
        !          2124:                                printf("Flat directions\n");
        !          2125:                                fprintf(ficlog,"Flat directions\n");
        !          2126:                                for (j=1;j<=n;j++) { 
        !          2127:                                        printf("flatdir[%d]=%d ",j,flatdir[j]);
        !          2128:                                        fprintf(ficlog,"flatdir[%d]=%d ",j,flatdir[j]);
        !          2129:         }
        !          2130:                                printf("\n");
        !          2131:                                fprintf(ficlog,"\n");
1.1       brouard  2132: #endif
1.2     ! brouard  2133:                                printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
        !          2134:                                fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
        !          2135:                                
1.1       brouard  2136: #ifdef DEBUG
1.2     ! brouard  2137:                                printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
        !          2138:                                fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
        !          2139:                                for(j=1;j<=n;j++){
        !          2140:                                        printf(" %lf",xit[j]);
        !          2141:                                        fprintf(ficlog," %lf",xit[j]);
        !          2142:                                }
        !          2143:                                printf("\n");
        !          2144:                                fprintf(ficlog,"\n");
1.1       brouard  2145: #endif
                   2146:       } /* end of t or directest negative */
1.2     ! brouard  2147: #ifdef POWELLNOF3INFF1TEST
1.1       brouard  2148: #else
                   2149:     } /* end if (fptt < fp)  */
                   2150: #endif
                   2151:   } /* loop iteration */ 
                   2152: } 
                   2153: 
                   2154: /**** Prevalence limit (stable or period prevalence)  ****************/
                   2155: 
                   2156: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
                   2157: {
                   2158:   /* Computes the prevalence limit in each live state at age x and for covariate ij by left multiplying the unit
                   2159:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2160:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2161:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2162:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2163:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2164:   /* Initial matrix pimij */
                   2165:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2166:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2167:   /*  0,                   0                  , 1} */
                   2168:   /*
                   2169:    * and after some iteration: */
                   2170:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2171:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2172:   /*  0,                   0                  , 1} */
                   2173:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2174:   /* {0.51571254859325999, 0.4842874514067399, */
                   2175:   /*  0.51326036147820708, 0.48673963852179264} */
                   2176:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2177: 
                   2178:   int i, ii,j,k;
                   2179:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2180:   /* double **matprod2(); */ /* test */
                   2181:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
                   2182:   double **newm;
                   2183:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2184:   int ncvloop=0;
                   2185:   
                   2186:   min=vector(1,nlstate);
                   2187:   max=vector(1,nlstate);
                   2188:   meandiff=vector(1,nlstate);
                   2189: 
                   2190:        /* Starting with matrix unity */
                   2191:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2192:     for (j=1;j<=nlstate+ndeath;j++){
                   2193:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2194:     }
                   2195:   
                   2196:   cov[1]=1.;
                   2197:   
                   2198:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2199:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
                   2200:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
                   2201:     ncvloop++;
                   2202:     newm=savm;
                   2203:     /* Covariates have to be included here again */
                   2204:     cov[2]=agefin;
                   2205:     if(nagesqr==1)
                   2206:       cov[3]= agefin*agefin;;
                   2207:     for (k=1; k<=cptcovn;k++) {
                   2208:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   2209:                        /* Here comes the value of the covariate 'ij' */
                   2210:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2211:       /* 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])]); */
                   2212:     }
                   2213:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   2214:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   2215:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
                   2216:     for (k=1; k<=cptcovprod;k++) /* Useless */
                   2217:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2218:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2219:     
                   2220:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2221:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2222:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2223:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2224:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
                   2225:                /* age and covariate values of ij are in 'cov' */
                   2226:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
                   2227:     
                   2228:     savm=oldm;
                   2229:     oldm=newm;
                   2230: 
                   2231:     for(j=1; j<=nlstate; j++){
                   2232:       max[j]=0.;
                   2233:       min[j]=1.;
                   2234:     }
                   2235:     for(i=1;i<=nlstate;i++){
                   2236:       sumnew=0;
                   2237:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2238:       for(j=1; j<=nlstate; j++){ 
                   2239:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2240:        max[j]=FMAX(max[j],prlim[i][j]);
                   2241:        min[j]=FMIN(min[j],prlim[i][j]);
                   2242:       }
                   2243:     }
                   2244: 
                   2245:     maxmax=0.;
                   2246:     for(j=1; j<=nlstate; j++){
                   2247:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2248:       maxmax=FMAX(maxmax,meandiff[j]);
                   2249:       /* 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); */
                   2250:     } /* j loop */
                   2251:     *ncvyear= (int)age- (int)agefin;
                   2252:     /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2253:     if(maxmax < ftolpl){
                   2254:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2255:       free_vector(min,1,nlstate);
                   2256:       free_vector(max,1,nlstate);
                   2257:       free_vector(meandiff,1,nlstate);
                   2258:       return prlim;
                   2259:     }
                   2260:   } /* age loop */
                   2261:     /* After some age loop it doesn't converge */
                   2262:   printf("Warning: the stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.0f years. Try to lower 'ftolpl'. \n\
                   2263: Earliest age to start was %d-%d=%d, ncvloop=%d, ncvyear=%d\n", (int)age, maxmax, ftolpl, delaymax, (int)age, (int)delaymax, (int)agefin, ncvloop, *ncvyear);
                   2264:   /* 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); */
                   2265:   free_vector(min,1,nlstate);
                   2266:   free_vector(max,1,nlstate);
                   2267:   free_vector(meandiff,1,nlstate);
                   2268:   
                   2269:   return prlim; /* should not reach here */
                   2270: }
                   2271: 
                   2272: 
                   2273:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2274: 
                   2275:  /* 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) */
                   2276:  /* 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) */
                   2277:  double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij)
                   2278: {
                   2279:   /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
                   2280:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2281:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2282:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2283:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2284:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2285:   /* Initial matrix pimij */
                   2286:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2287:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2288:   /*  0,                   0                  , 1} */
                   2289:   /*
                   2290:    * and after some iteration: */
                   2291:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2292:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2293:   /*  0,                   0                  , 1} */
                   2294:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2295:   /* {0.51571254859325999, 0.4842874514067399, */
                   2296:   /*  0.51326036147820708, 0.48673963852179264} */
                   2297:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2298: 
                   2299:   int i, ii,j,k;
                   2300:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2301:   /* double **matprod2(); */ /* test */
                   2302:   double **out, cov[NCOVMAX+1], **bmij();
                   2303:   double **newm;
                   2304:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2305:   double        **oldm, **savm;  /* for use */
                   2306: 
                   2307:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2308:   int ncvloop=0;
                   2309:   
                   2310:   min=vector(1,nlstate);
                   2311:   max=vector(1,nlstate);
                   2312:   meandiff=vector(1,nlstate);
                   2313: 
                   2314:        dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2315:        oldm=oldms; savm=savms;
                   2316: 
                   2317:        /* Starting with matrix unity */
                   2318:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2319:                for (j=1;j<=nlstate+ndeath;j++){
                   2320:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2321:     }
                   2322:   
                   2323:   cov[1]=1.;
                   2324:   
                   2325:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2326:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
                   2327:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2328:   for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
                   2329:     ncvloop++;
                   2330:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2331:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
                   2332:     /* Covariates have to be included here again */
                   2333:     cov[2]=agefin;
                   2334:     if(nagesqr==1)
                   2335:       cov[3]= agefin*agefin;;
                   2336:     for (k=1; k<=cptcovn;k++) {
                   2337:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   2338:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2339:       /* 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])]); */
                   2340:     }
                   2341:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   2342:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   2343:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
                   2344:     for (k=1; k<=cptcovprod;k++) /* Useless */
                   2345:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2346:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2347:     
                   2348:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2349:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2350:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2351:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2352:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
                   2353:                /* ij should be linked to the correct index of cov */
                   2354:                /* age and covariate values ij are in 'cov', but we need to pass
                   2355:                 * ij for the observed prevalence at age and status and covariate
                   2356:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2357:                 */
                   2358:     /* 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 *\/ */
                   2359:     /* 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 *\/ */
                   2360:     out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij)); /* Bug Valgrind */
                   2361:     savm=oldm;
                   2362:     oldm=newm;
                   2363:     for(j=1; j<=nlstate; j++){
                   2364:       max[j]=0.;
                   2365:       min[j]=1.;
                   2366:     }
                   2367:     for(j=1; j<=nlstate; j++){ 
                   2368:       for(i=1;i<=nlstate;i++){
                   2369:                                /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2370:                                bprlim[i][j]= newm[i][j];
                   2371:                                max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2372:                                min[i]=FMIN(min[i],bprlim[i][j]);
                   2373:       }
                   2374:     }
                   2375:                
                   2376:     maxmax=0.;
                   2377:     for(i=1; i<=nlstate; i++){
                   2378:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2379:       maxmax=FMAX(maxmax,meandiff[i]);
                   2380:       /* 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); */
                   2381:     } /* j loop */
                   2382:     *ncvyear= -( (int)age- (int)agefin);
                   2383:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
                   2384:     if(maxmax < ftolpl){
                   2385:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2386:       free_vector(min,1,nlstate);
                   2387:       free_vector(max,1,nlstate);
                   2388:       free_vector(meandiff,1,nlstate);
                   2389:       return bprlim;
                   2390:     }
                   2391:   } /* age loop */
                   2392:     /* After some age loop it doesn't converge */
                   2393:   printf("Warning: the back stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.0f years. Try to lower 'ftolpl'. \n\
                   2394: 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);
                   2395:   /* 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); */
                   2396:   free_vector(min,1,nlstate);
                   2397:   free_vector(max,1,nlstate);
                   2398:   free_vector(meandiff,1,nlstate);
                   2399:   
                   2400:   return bprlim; /* should not reach here */
                   2401: }
                   2402: 
                   2403: /*************** transition probabilities ***************/ 
                   2404: 
                   2405: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2406: {
                   2407:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2408:      computes the probability to be observed in state j being in state i by appying the
                   2409:      model to the ncovmodel covariates (including constant and age).
                   2410:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2411:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2412:      ncth covariate in the global vector x is given by the formula:
                   2413:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2414:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2415:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2416:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2417:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2418:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2419:   */
                   2420:   double s1, lnpijopii;
                   2421:   /*double t34;*/
                   2422:   int i,j, nc, ii, jj;
                   2423: 
1.2     ! brouard  2424:   for(i=1; i<= nlstate; i++){
        !          2425:     for(j=1; j<i;j++){
        !          2426:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
        !          2427:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
        !          2428:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
        !          2429:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
        !          2430:       }
        !          2431:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
        !          2432:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
        !          2433:     }
        !          2434:     for(j=i+1; j<=nlstate+ndeath;j++){
        !          2435:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
        !          2436:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
        !          2437:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
        !          2438:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
        !          2439:       }
        !          2440:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
        !          2441:     }
        !          2442:   }
1.1       brouard  2443:   
1.2     ! brouard  2444:   for(i=1; i<= nlstate; i++){
        !          2445:     s1=0;
        !          2446:     for(j=1; j<i; j++){
        !          2447:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
        !          2448:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
        !          2449:     }
        !          2450:     for(j=i+1; j<=nlstate+ndeath; j++){
        !          2451:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
        !          2452:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
        !          2453:     }
        !          2454:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
        !          2455:     ps[i][i]=1./(s1+1.);
        !          2456:     /* Computing other pijs */
        !          2457:     for(j=1; j<i; j++)
        !          2458:       ps[i][j]= exp(ps[i][j])*ps[i][i];
        !          2459:     for(j=i+1; j<=nlstate+ndeath; j++)
        !          2460:       ps[i][j]= exp(ps[i][j])*ps[i][i];
        !          2461:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
        !          2462:   } /* end i */
1.1       brouard  2463:   
1.2     ! brouard  2464:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
        !          2465:     for(jj=1; jj<= nlstate+ndeath; jj++){
        !          2466:       ps[ii][jj]=0;
        !          2467:       ps[ii][ii]=1;
        !          2468:     }
        !          2469:   }
1.1       brouard  2470:   
                   2471:   
1.2     ! brouard  2472:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
        !          2473:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
        !          2474:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
        !          2475:   /*   } */
        !          2476:   /*   printf("\n "); */
        !          2477:   /* } */
        !          2478:   /* printf("\n ");printf("%lf ",cov[2]);*/
        !          2479:   /*
        !          2480:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.1       brouard  2481:                goto end;*/
1.2     ! brouard  2482:   return ps;
1.1       brouard  2483: }
                   2484: 
                   2485: /*************** backward transition probabilities ***************/ 
                   2486: 
                   2487:  /* 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 ) */
                   2488: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   2489:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   2490: {
                   2491:   /* Computes the backward probability at age agefin and covariate ij
                   2492:    * and returns in **ps as well as **bmij.
                   2493:    */
                   2494:   int i, ii, j,k;
                   2495:   
                   2496:   double **out, **pmij();
                   2497:   double sumnew=0.;
                   2498:   double agefin;
                   2499:   
                   2500:   double **dnewm, **dsavm, **doldm;
                   2501:   double **bbmij;
                   2502:   
                   2503:   doldm=ddoldms; /* global pointers */
                   2504:   dnewm=ddnewms;
                   2505:   dsavm=ddsavms;
                   2506:   
                   2507:   agefin=cov[2];
                   2508:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
                   2509:      the observed prevalence (with this covariate ij) */
                   2510:   dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
                   2511:   /* We do have the matrix Px in savm  and we need pij */
                   2512:   for (j=1;j<=nlstate+ndeath;j++){
                   2513:     sumnew=0.; /* w1 p11 + w2 p21 only on live states */
                   2514:     for (ii=1;ii<=nlstate;ii++){
                   2515:       sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
                   2516:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
                   2517:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2518:       if(sumnew >= 1.e-10){
                   2519:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
                   2520:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2521:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
                   2522:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2523:        /* }else */
                   2524:        doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   2525:       }else{
                   2526:        printf("ii=%d, i=%d, doldm=%lf dsavm=%lf, probs=%lf, sumnew=%lf,agefin=%d\n",ii,j,doldm[ii][j],dsavm[ii][j],prevacurrent[(int)agefin][ii][ij],sumnew, (int)agefin);
                   2527:       }
                   2528:     } /*End ii */
                   2529:   } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2530:   /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
                   2531:   bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
                   2532:   /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
                   2533:   /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2534:   /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2535:   /* left Product of this matrix by diag matrix of prevalences (savm) */
                   2536:   for (j=1;j<=nlstate+ndeath;j++){
                   2537:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2538:       dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
                   2539:     }
                   2540:   } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2541:   ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
                   2542:   /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
                   2543:   /* end bmij */
                   2544:   return ps; 
                   2545: }
                   2546: /*************** transition probabilities ***************/ 
                   2547: 
                   2548: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2549: {
                   2550:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2551:      computes the probability to be observed in state j being in state i by appying the
                   2552:      model to the ncovmodel covariates (including constant and age).
                   2553:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2554:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2555:      ncth covariate in the global vector x is given by the formula:
                   2556:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2557:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2558:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2559:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2560:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2561:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2562:   */
                   2563:   double s1, lnpijopii;
                   2564:   /*double t34;*/
                   2565:   int i,j, nc, ii, jj;
                   2566: 
                   2567:        for(i=1; i<= nlstate; i++){
                   2568:                for(j=1; j<i;j++){
                   2569:                        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2570:                                /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2571:                                lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2572:                                /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2573:                        }
                   2574:                        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2575:                        /*      printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2576:                }
                   2577:                for(j=i+1; j<=nlstate+ndeath;j++){
                   2578:                        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2579:                                /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2580:                                lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2581:                                /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2582:                        }
                   2583:                        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2584:                }
                   2585:        }
                   2586:        
                   2587:        for(i=1; i<= nlstate; i++){
                   2588:                s1=0;
                   2589:                for(j=1; j<i; j++){
                   2590:                        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2591:                        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2592:                }
                   2593:                for(j=i+1; j<=nlstate+ndeath; j++){
                   2594:                        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2595:                        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2596:                }
                   2597:                /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2598:                ps[i][i]=1./(s1+1.);
                   2599:                /* Computing other pijs */
                   2600:                for(j=1; j<i; j++)
                   2601:                        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2602:                for(j=i+1; j<=nlstate+ndeath; j++)
                   2603:                        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2604:                /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2605:        } /* end i */
                   2606:        
                   2607:        for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2608:                for(jj=1; jj<= nlstate+ndeath; jj++){
                   2609:                        ps[ii][jj]=0;
                   2610:                        ps[ii][ii]=1;
                   2611:                }
                   2612:        }
                   2613:        /* Added for backcast */ /* Transposed matrix too */
                   2614:        for(jj=1; jj<= nlstate+ndeath; jj++){
                   2615:                s1=0.;
                   2616:                for(ii=1; ii<= nlstate+ndeath; ii++){
                   2617:                        s1+=ps[ii][jj];
                   2618:                }
                   2619:                for(ii=1; ii<= nlstate; ii++){
                   2620:                        ps[ii][jj]=ps[ii][jj]/s1;
                   2621:                }
                   2622:        }
                   2623:        /* Transposition */
                   2624:        for(jj=1; jj<= nlstate+ndeath; jj++){
                   2625:                for(ii=jj; ii<= nlstate+ndeath; ii++){
                   2626:                        s1=ps[ii][jj];
                   2627:                        ps[ii][jj]=ps[jj][ii];
                   2628:                        ps[jj][ii]=s1;
                   2629:                }
                   2630:        }
                   2631:        /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2632:        /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2633:        /*      printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2634:        /*   } */
                   2635:        /*   printf("\n "); */
                   2636:        /* } */
                   2637:        /* printf("\n ");printf("%lf ",cov[2]);*/
                   2638:        /*
                   2639:                for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2640:                goto end;*/
                   2641:        return ps;
                   2642: }
                   2643: 
                   2644: 
                   2645: /**************** Product of 2 matrices ******************/
                   2646: 
                   2647: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
                   2648: {
                   2649:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2650:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2651:   /* in, b, out are matrice of pointers which should have been initialized 
                   2652:      before: only the contents of out is modified. The function returns
                   2653:      a pointer to pointers identical to out */
                   2654:   int i, j, k;
                   2655:   for(i=nrl; i<= nrh; i++)
                   2656:     for(k=ncolol; k<=ncoloh; k++){
                   2657:       out[i][k]=0.;
                   2658:       for(j=ncl; j<=nch; j++)
                   2659:        out[i][k] +=in[i][j]*b[j][k];
                   2660:     }
                   2661:   return out;
                   2662: }
                   2663: 
                   2664: 
                   2665: /************* Higher Matrix Product ***************/
                   2666: 
                   2667: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   2668: {
                   2669:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
                   2670:      'nhstepm*hstepm*stepm' months (i.e. until
                   2671:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2672:      nhstepm*hstepm matrices. 
                   2673:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2674:      (typically every 2 years instead of every month which is too big 
                   2675:      for the memory).
                   2676:      Model is determined by parameters x and covariates have to be 
                   2677:      included manually here. 
                   2678: 
                   2679:      */
                   2680: 
                   2681:   int i, j, d, h, k;
                   2682:   double **out, cov[NCOVMAX+1];
                   2683:   double **newm;
                   2684:   double agexact;
                   2685:   double agebegin, ageend;
                   2686: 
                   2687:   /* Hstepm could be zero and should return the unit matrix */
                   2688:   for (i=1;i<=nlstate+ndeath;i++)
                   2689:     for (j=1;j<=nlstate+ndeath;j++){
                   2690:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2691:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2692:     }
                   2693:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2694:   for(h=1; h <=nhstepm; h++){
                   2695:     for(d=1; d <=hstepm; d++){
                   2696:       newm=savm;
                   2697:       /* Covariates have to be included here again */
                   2698:       cov[1]=1.;
                   2699:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
                   2700:       cov[2]=agexact;
                   2701:       if(nagesqr==1)
                   2702:                                cov[3]= agexact*agexact;
                   2703:       for (k=1; k<=cptcovn;k++) 
                   2704:                                cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2705:                        /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   2706:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
                   2707:                                /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   2708:                                cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2709:                        /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   2710:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
                   2711:                                cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2712:                        /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2713: 
                   2714: 
                   2715:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2716:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   2717:                        /* right multiplication of oldm by the current matrix */
                   2718:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2719:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2720:       /* if((int)age == 70){ */
                   2721:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   2722:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   2723:       /*         printf("%d pmmij ",i); */
                   2724:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2725:       /*           printf("%f ",pmmij[i][j]); */
                   2726:       /*         } */
                   2727:       /*         printf(" oldm "); */
                   2728:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2729:       /*           printf("%f ",oldm[i][j]); */
                   2730:       /*         } */
                   2731:       /*         printf("\n"); */
                   2732:       /*       } */
                   2733:       /* } */
                   2734:       savm=oldm;
                   2735:       oldm=newm;
                   2736:     }
                   2737:     for(i=1; i<=nlstate+ndeath; i++)
                   2738:       for(j=1;j<=nlstate+ndeath;j++) {
                   2739:                                po[i][j][h]=newm[i][j];
                   2740:                                /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
                   2741:       }
                   2742:     /*printf("h=%d ",h);*/
                   2743:   } /* end h */
                   2744:        /*     printf("\n H=%d \n",h); */
                   2745:   return po;
                   2746: }
                   2747: 
                   2748: /************* Higher Back Matrix Product ***************/
                   2749: /* 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 ) */
                   2750: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
                   2751: {
                   2752:   /* Computes the transition matrix starting at age 'age' over
                   2753:      'nhstepm*hstepm*stepm' months (i.e. until
                   2754:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   2755:      nhstepm*hstepm matrices.
                   2756:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   2757:      (typically every 2 years instead of every month which is too big
                   2758:      for the memory).
                   2759:      Model is determined by parameters x and covariates have to be
                   2760:      included manually here.
                   2761: 
                   2762:   */
                   2763: 
                   2764:   int i, j, d, h, k;
                   2765:   double **out, cov[NCOVMAX+1];
                   2766:   double **newm;
                   2767:   double agexact;
                   2768:   double agebegin, ageend;
                   2769:   double **oldm, **savm;
                   2770: 
                   2771:   oldm=oldms;savm=savms;
                   2772:   /* Hstepm could be zero and should return the unit matrix */
                   2773:   for (i=1;i<=nlstate+ndeath;i++)
                   2774:     for (j=1;j<=nlstate+ndeath;j++){
                   2775:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2776:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2777:     }
                   2778:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2779:   for(h=1; h <=nhstepm; h++){
                   2780:     for(d=1; d <=hstepm; d++){
                   2781:       newm=savm;
                   2782:       /* Covariates have to be included here again */
                   2783:       cov[1]=1.;
                   2784:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
                   2785:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   2786:       cov[2]=agexact;
                   2787:       if(nagesqr==1)
                   2788:        cov[3]= agexact*agexact;
                   2789:       for (k=1; k<=cptcovn;k++)
                   2790:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2791:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   2792:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
                   2793:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   2794:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2795:       /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   2796:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
                   2797:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2798:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2799:                        
                   2800:                        
                   2801:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2802:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   2803:       /* Careful transposed matrix */
                   2804:       /* age is in cov[2] */
                   2805:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
                   2806:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
                   2807:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
                   2808:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
                   2809:       /* if((int)age == 70){ */
                   2810:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   2811:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   2812:       /*         printf("%d pmmij ",i); */
                   2813:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2814:       /*           printf("%f ",pmmij[i][j]); */
                   2815:       /*         } */
                   2816:       /*         printf(" oldm "); */
                   2817:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2818:       /*           printf("%f ",oldm[i][j]); */
                   2819:       /*         } */
                   2820:       /*         printf("\n"); */
                   2821:       /*       } */
                   2822:       /* } */
                   2823:       savm=oldm;
                   2824:       oldm=newm;
                   2825:     }
                   2826:     for(i=1; i<=nlstate+ndeath; i++)
                   2827:       for(j=1;j<=nlstate+ndeath;j++) {
                   2828:        po[i][j][h]=newm[i][j];
                   2829:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
                   2830:       }
                   2831:     /*printf("h=%d ",h);*/
                   2832:   } /* end h */
                   2833:   /*     printf("\n H=%d \n",h); */
                   2834:   return po;
                   2835: }
                   2836: 
                   2837: 
                   2838: #ifdef NLOPT
                   2839:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2840:   double fret;
                   2841:   double *xt;
                   2842:   int j;
                   2843:   myfunc_data *d2 = (myfunc_data *) pd;
                   2844: /* xt = (p1-1); */
                   2845:   xt=vector(1,n); 
                   2846:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2847: 
                   2848:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2849:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2850:   printf("Function = %.12lf ",fret);
                   2851:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2852:   printf("\n");
                   2853:  free_vector(xt,1,n);
                   2854:   return fret;
                   2855: }
                   2856: #endif
                   2857: 
                   2858: /*************** log-likelihood *************/
                   2859: double func( double *x)
                   2860: {
                   2861:   int i, ii, j, k, mi, d, kk;
                   2862:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   2863:   double **out;
                   2864:   double sw; /* Sum of weights */
                   2865:   double lli; /* Individual log likelihood */
                   2866:   int s1, s2;
                   2867:   double bbh, survp;
                   2868:   long ipmx;
                   2869:   double agexact;
                   2870:   /*extern weight */
                   2871:   /* We are differentiating ll according to initial status */
                   2872:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2873:   /*for(i=1;i<imx;i++) 
                   2874:     printf(" %d\n",s[4][i]);
                   2875:   */
                   2876: 
1.2     ! brouard  2877:        ++countcallfunc;
1.1       brouard  2878: 
1.2     ! brouard  2879:        cov[1]=1.;
1.1       brouard  2880: 
                   2881:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2882: 
                   2883:   if(mle==1){
                   2884:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   2885:       /* Computes the values of the ncovmodel covariates of the model
                   2886:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   2887:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   2888:         to be observed in j being in i according to the model.
                   2889:        */
                   2890:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
                   2891:          cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   2892:       }
                   2893:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   2894:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
                   2895:         has been calculated etc */
                   2896:       for(mi=1; mi<= wav[i]-1; mi++){
                   2897:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2898:          for (j=1;j<=nlstate+ndeath;j++){
                   2899:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2900:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2901:          }
                   2902:        for(d=0; d<dh[mi][i]; d++){
                   2903:          newm=savm;
                   2904:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2905:          cov[2]=agexact;
                   2906:          if(nagesqr==1)
                   2907:            cov[3]= agexact*agexact;
                   2908:          for (kk=1; kk<=cptcovage;kk++) {
                   2909:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   2910:          }
                   2911:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2912:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2913:          savm=oldm;
                   2914:          oldm=newm;
                   2915:        } /* end mult */
                   2916:       
                   2917:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   2918:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   2919:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   2920:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   2921:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   2922:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   2923:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   2924:         * probability in order to take into account the bias as a fraction of the way
                   2925:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   2926:         * -stepm/2 to stepm/2 .
                   2927:         * For stepm=1 the results are the same as for previous versions of Imach.
                   2928:         * For stepm > 1 the results are less biased than in previous versions. 
                   2929:         */
                   2930:        s1=s[mw[mi][i]][i];
                   2931:        s2=s[mw[mi+1][i]][i];
                   2932:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2933:        /* bias bh is positive if real duration
                   2934:         * is higher than the multiple of stepm and negative otherwise.
                   2935:         */
                   2936:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2937:        if( s2 > nlstate){ 
                   2938:          /* i.e. if s2 is a death state and if the date of death is known 
                   2939:             then the contribution to the likelihood is the probability to 
                   2940:             die between last step unit time and current  step unit time, 
                   2941:             which is also equal to probability to die before dh 
                   2942:             minus probability to die before dh-stepm . 
                   2943:             In version up to 0.92 likelihood was computed
                   2944:        as if date of death was unknown. Death was treated as any other
                   2945:        health state: the date of the interview describes the actual state
                   2946:        and not the date of a change in health state. The former idea was
                   2947:        to consider that at each interview the state was recorded
                   2948:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2949:        introduced the exact date of death then we should have modified
                   2950:        the contribution of an exact death to the likelihood. This new
                   2951:        contribution is smaller and very dependent of the step unit
                   2952:        stepm. It is no more the probability to die between last interview
                   2953:        and month of death but the probability to survive from last
                   2954:        interview up to one month before death multiplied by the
                   2955:        probability to die within a month. Thanks to Chris
                   2956:        Jackson for correcting this bug.  Former versions increased
                   2957:        mortality artificially. The bad side is that we add another loop
                   2958:        which slows down the processing. The difference can be up to 10%
                   2959:        lower mortality.
                   2960:          */
                   2961:        /* If, at the beginning of the maximization mostly, the
                   2962:           cumulative probability or probability to be dead is
                   2963:           constant (ie = 1) over time d, the difference is equal to
                   2964:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2965:           s1 at precedent wave, to be dead a month before current
                   2966:           wave is equal to probability, being at state s1 at
                   2967:           precedent wave, to be dead at mont of the current
                   2968:           wave. Then the observed probability (that this person died)
                   2969:           is null according to current estimated parameter. In fact,
                   2970:           it should be very low but not zero otherwise the log go to
                   2971:           infinity.
                   2972:        */
                   2973: /* #ifdef INFINITYORIGINAL */
                   2974: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2975: /* #else */
                   2976: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2977: /*         lli=log(mytinydouble); */
                   2978: /*       else */
                   2979: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2980: /* #endif */
1.2     ! brouard  2981:                                        lli=log(out[s1][s2] - savm[s1][s2]);
1.1       brouard  2982:          
1.2     ! brouard  2983:                                } else if  ( s2==-1 ) { /* alive */
        !          2984:                                        for (j=1,survp=0. ; j<=nlstate; j++) 
        !          2985:                                                survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
        !          2986:                                        /*survp += out[s1][j]; */
        !          2987:                                        lli= log(survp);
        !          2988:                                }
        !          2989:                                else if  (s2==-4) { 
        !          2990:                                        for (j=3,survp=0. ; j<=nlstate; j++)  
        !          2991:                                                survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
        !          2992:                                        lli= log(survp); 
        !          2993:                                } 
        !          2994:                                else if  (s2==-5) { 
        !          2995:                                        for (j=1,survp=0. ; j<=2; j++)  
        !          2996:                                                survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
        !          2997:                                        lli= log(survp); 
        !          2998:                                } 
        !          2999:                                else{
        !          3000:                                        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
        !          3001:                                        /*  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 */
        !          3002:                                } 
        !          3003:                                /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
        !          3004:                                /*if(lli ==000.0)*/
        !          3005:                                /*printf("bbh= %f lli=%f savm=%f out=%f %d\n",bbh,lli,savm[s1][s2], out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]],i); */
        !          3006:                                ipmx +=1;
        !          3007:                                sw += weight[i];
        !          3008:                                ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
        !          3009:                                /* if (lli < log(mytinydouble)){ */
        !          3010:                                /*   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); */
        !          3011:                                /*   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]); */
        !          3012:                                /* } */
        !          3013:                        } /* end of wave */
        !          3014:                } /* end of individual */
        !          3015:        }  else if(mle==2){
        !          3016:                for (i=1,ipmx=0, sw=0.; i<=imx; i++){
        !          3017:                        for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
        !          3018:                        for(mi=1; mi<= wav[i]-1; mi++){
        !          3019:                                for (ii=1;ii<=nlstate+ndeath;ii++)
        !          3020:                                        for (j=1;j<=nlstate+ndeath;j++){
        !          3021:                                                oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          3022:                                                savm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          3023:                                        }
        !          3024:                                for(d=0; d<=dh[mi][i]; d++){
        !          3025:                                        newm=savm;
        !          3026:                                        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          3027:                                        cov[2]=agexact;
        !          3028:                                        if(nagesqr==1)
        !          3029:                                                cov[3]= agexact*agexact;
        !          3030:                                        for (kk=1; kk<=cptcovage;kk++) {
        !          3031:                                                cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
        !          3032:                                        }
        !          3033:                                        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
        !          3034:                                                                                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
        !          3035:                                        savm=oldm;
        !          3036:                                        oldm=newm;
        !          3037:                                } /* end mult */
        !          3038:       
        !          3039:                                s1=s[mw[mi][i]][i];
        !          3040:                                s2=s[mw[mi+1][i]][i];
        !          3041:                                bbh=(double)bh[mi][i]/(double)stepm; 
        !          3042:                                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 */
        !          3043:                                ipmx +=1;
        !          3044:                                sw += weight[i];
        !          3045:                                ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
        !          3046:                        } /* end of wave */
        !          3047:                } /* end of individual */
        !          3048:        }  else if(mle==3){  /* exponential inter-extrapolation */
        !          3049:                for (i=1,ipmx=0, sw=0.; i<=imx; i++){
        !          3050:                        for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
        !          3051:                        for(mi=1; mi<= wav[i]-1; mi++){
        !          3052:                                for (ii=1;ii<=nlstate+ndeath;ii++)
        !          3053:                                        for (j=1;j<=nlstate+ndeath;j++){
        !          3054:                                                oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          3055:                                                savm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          3056:                                        }
        !          3057:                                for(d=0; d<dh[mi][i]; d++){
        !          3058:                                        newm=savm;
        !          3059:                                        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          3060:                                        cov[2]=agexact;
        !          3061:                                        if(nagesqr==1)
        !          3062:                                                cov[3]= agexact*agexact;
        !          3063:                                        for (kk=1; kk<=cptcovage;kk++) {
        !          3064:                                                cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
        !          3065:                                        }
        !          3066:                                        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
        !          3067:                                                                                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
        !          3068:                                        savm=oldm;
        !          3069:                                        oldm=newm;
        !          3070:                                } /* end mult */
        !          3071:       
        !          3072:                                s1=s[mw[mi][i]][i];
        !          3073:                                s2=s[mw[mi+1][i]][i];
        !          3074:                                bbh=(double)bh[mi][i]/(double)stepm; 
        !          3075:                                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 */
        !          3076:                                ipmx +=1;
        !          3077:                                sw += weight[i];
        !          3078:                                ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
        !          3079:                        } /* end of wave */
        !          3080:                } /* end of individual */
        !          3081:        }else if (mle==4){  /* ml=4 no inter-extrapolation */
        !          3082:                for (i=1,ipmx=0, sw=0.; i<=imx; i++){
        !          3083:                        for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
        !          3084:                        for(mi=1; mi<= wav[i]-1; mi++){
        !          3085:                                for (ii=1;ii<=nlstate+ndeath;ii++)
        !          3086:                                        for (j=1;j<=nlstate+ndeath;j++){
        !          3087:                                                oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          3088:                                                savm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          3089:                                        }
        !          3090:                                for(d=0; d<dh[mi][i]; d++){
        !          3091:                                        newm=savm;
        !          3092:                                        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          3093:                                        cov[2]=agexact;
        !          3094:                                        if(nagesqr==1)
        !          3095:                                                cov[3]= agexact*agexact;
        !          3096:                                        for (kk=1; kk<=cptcovage;kk++) {
        !          3097:                                                cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
        !          3098:                                        }
1.1       brouard  3099:        
1.2     ! brouard  3100:                                        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
        !          3101:                                                                                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
        !          3102:                                        savm=oldm;
        !          3103:                                        oldm=newm;
        !          3104:                                } /* end mult */
        !          3105:       
        !          3106:                                s1=s[mw[mi][i]][i];
        !          3107:                                s2=s[mw[mi+1][i]][i];
        !          3108:                                if( s2 > nlstate){ 
        !          3109:                                        lli=log(out[s1][s2] - savm[s1][s2]);
        !          3110:                                } else if  ( s2==-1 ) { /* alive */
        !          3111:                                        for (j=1,survp=0. ; j<=nlstate; j++) 
        !          3112:                                                survp += out[s1][j];
        !          3113:                                        lli= log(survp);
        !          3114:                                }else{
        !          3115:                                        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
        !          3116:                                }
        !          3117:                                ipmx +=1;
        !          3118:                                sw += weight[i];
        !          3119:                                ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.1       brouard  3120: /*     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]); */
1.2     ! brouard  3121:                        } /* end of wave */
        !          3122:                } /* end of individual */
        !          3123:        }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
        !          3124:                for (i=1,ipmx=0, sw=0.; i<=imx; i++){
        !          3125:                        for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
        !          3126:                        for(mi=1; mi<= wav[i]-1; mi++){
        !          3127:                                for (ii=1;ii<=nlstate+ndeath;ii++)
        !          3128:                                        for (j=1;j<=nlstate+ndeath;j++){
        !          3129:                                                oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          3130:                                                savm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          3131:                                        }
        !          3132:                                for(d=0; d<dh[mi][i]; d++){
        !          3133:                                        newm=savm;
        !          3134:                                        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          3135:                                        cov[2]=agexact;
        !          3136:                                        if(nagesqr==1)
        !          3137:                                                cov[3]= agexact*agexact;
        !          3138:                                        for (kk=1; kk<=cptcovage;kk++) {
        !          3139:                                                cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
        !          3140:                                        }
1.1       brouard  3141:        
1.2     ! brouard  3142:                                        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
        !          3143:                                                                                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
        !          3144:                                        savm=oldm;
        !          3145:                                        oldm=newm;
        !          3146:                                } /* end mult */
        !          3147:       
        !          3148:                                s1=s[mw[mi][i]][i];
        !          3149:                                s2=s[mw[mi+1][i]][i];
        !          3150:                                lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
        !          3151:                                ipmx +=1;
        !          3152:                                sw += weight[i];
        !          3153:                                ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
        !          3154:                                /*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]);*/
        !          3155:                        } /* end of wave */
        !          3156:                } /* end of individual */
        !          3157:        } /* End of if */
        !          3158:        for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
        !          3159:        /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
        !          3160:        l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
        !          3161:        return -l;
1.1       brouard  3162: }
                   3163: 
                   3164: /*************** log-likelihood *************/
                   3165: double funcone( double *x)
                   3166: {
                   3167:   /* Same as likeli but slower because of a lot of printf and if */
                   3168:   int i, ii, j, k, mi, d, kk;
                   3169:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3170:   double **out;
                   3171:   double lli; /* Individual log likelihood */
                   3172:   double llt;
                   3173:   int s1, s2;
                   3174:   double bbh, survp;
                   3175:   double agexact;
                   3176:   double agebegin, ageend;
                   3177:   /*extern weight */
                   3178:   /* We are differentiating ll according to initial status */
                   3179:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3180:   /*for(i=1;i<imx;i++) 
                   3181:     printf(" %d\n",s[4][i]);
                   3182:   */
                   3183:   cov[1]=1.;
                   3184: 
                   3185:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   3186: 
                   3187:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3188:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3189:     for(mi=1; mi<= wav[i]-1; mi++){
                   3190:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   3191:        for (j=1;j<=nlstate+ndeath;j++){
                   3192:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3193:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3194:        }
                   3195:       
                   3196:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3197:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3198:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.2     ! brouard  3199:                                /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
        !          3200:                                        and mw[mi+1][i]. dh depends on stepm.*/
        !          3201:                                newm=savm;
        !          3202:                                agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          3203:                                cov[2]=agexact;
        !          3204:                                if(nagesqr==1)
        !          3205:                                        cov[3]= agexact*agexact;
        !          3206:                                for (kk=1; kk<=cptcovage;kk++) {
        !          3207:                                        cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
        !          3208:                                }
        !          3209:                                
        !          3210:                                /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
        !          3211:                                out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
        !          3212:                                                                                 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
        !          3213:                                /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
        !          3214:                                /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
        !          3215:                                savm=oldm;
        !          3216:                                oldm=newm;
1.1       brouard  3217:       } /* end mult */
                   3218:       
                   3219:       s1=s[mw[mi][i]][i];
                   3220:       s2=s[mw[mi+1][i]][i];
                   3221:       /* if(s2==-1){ */
                   3222:       /*       printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
                   3223:       /*       /\* exit(1); *\/ */
                   3224:       /* } */
                   3225:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3226:       /* bias is positive if real duration
                   3227:        * is higher than the multiple of stepm and negative otherwise.
                   3228:        */
                   3229:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.2     ! brouard  3230:                                lli=log(out[s1][s2] - savm[s1][s2]);
1.1       brouard  3231:       } else if  ( s2==-1 ) { /* alive */
1.2     ! brouard  3232:                                for (j=1,survp=0. ; j<=nlstate; j++) 
        !          3233:                                        survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
        !          3234:                                lli= log(survp);
1.1       brouard  3235:       }else if (mle==1){
1.2     ! brouard  3236:                                lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.1       brouard  3237:       } else if(mle==2){
1.2     ! brouard  3238:                                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 */
1.1       brouard  3239:       } else if(mle==3){  /* exponential inter-extrapolation */
1.2     ! brouard  3240:                                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 */
1.1       brouard  3241:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.2     ! brouard  3242:                                lli=log(out[s1][s2]); /* Original formula */
1.1       brouard  3243:       } else{  /* mle=0 back to 1 */
1.2     ! brouard  3244:                                lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
        !          3245:                                /*lli=log(out[s1][s2]); */ /* Original formula */
1.1       brouard  3246:       } /* End of if */
                   3247:       ipmx +=1;
                   3248:       sw += weight[i];
                   3249:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3250:       /*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]); */
                   3251:       if(globpr){
1.2     ! brouard  3252:                                fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
1.1       brouard  3253:  %11.6f %11.6f %11.6f ", \
1.2     ! brouard  3254:                                                                num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
        !          3255:                                                                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
        !          3256:                                for(k=1,llt=0.,l=0.; k<=nlstate; k++){
        !          3257:                                        llt +=ll[k]*gipmx/gsw;
        !          3258:                                        fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
        !          3259:                                }
        !          3260:                                fprintf(ficresilk," %10.6f\n", -llt);
1.1       brouard  3261:       }
                   3262:     } /* end of wave */
                   3263:   } /* end of individual */
                   3264:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3265:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3266:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3267:   if(globpr==0){ /* First time we count the contributions and weights */
                   3268:     gipmx=ipmx;
                   3269:     gsw=sw;
                   3270:   }
                   3271:   return -l;
                   3272: }
                   3273: 
                   3274: 
                   3275: /*************** function likelione ***********/
                   3276: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   3277: {
                   3278:   /* This routine should help understanding what is done with 
                   3279:      the selection of individuals/waves and
                   3280:      to check the exact contribution to the likelihood.
                   3281:      Plotting could be done.
                   3282:    */
                   3283:   int k;
                   3284: 
                   3285:   if(*globpri !=0){ /* Just counts and sums, no printings */
                   3286:     strcpy(fileresilk,"ILK_"); 
                   3287:     strcat(fileresilk,fileresu);
                   3288:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3289:       printf("Problem with resultfile: %s\n", fileresilk);
                   3290:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3291:     }
                   3292:     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");
                   3293:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
                   3294:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3295:     for(k=1; k<=nlstate; k++) 
                   3296:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3297:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3298:   }
                   3299: 
                   3300:   *fretone=(*funcone)(p);
                   3301:   if(*globpri !=0){
                   3302:     fclose(ficresilk);
                   3303:     if (mle ==0)
                   3304:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   3305:     else if(mle >=1)
                   3306:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   3307:     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));
                   3308:     
                   3309:       
                   3310:     for (k=1; k<= nlstate ; k++) {
                   3311:       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> \
                   3312: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   3313:     }
                   3314:     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> \
                   3315: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   3316:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
                   3317: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   3318:     fflush(fichtm);
                   3319:   }
                   3320:   return;
                   3321: }
                   3322: 
                   3323: 
                   3324: /*********** Maximum Likelihood Estimation ***************/
                   3325: 
                   3326: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   3327: {
                   3328:   int i,j, iter=0;
                   3329:   double **xi;
                   3330:   double fret;
                   3331:   double fretone; /* Only one call to likelihood */
                   3332:   /*  char filerespow[FILENAMELENGTH];*/
                   3333: 
                   3334: #ifdef NLOPT
                   3335:   int creturn;
                   3336:   nlopt_opt opt;
                   3337:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   3338:   double *lb;
                   3339:   double minf; /* the minimum objective value, upon return */
                   3340:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   3341:   myfunc_data dinst, *d = &dinst;
                   3342: #endif
                   3343: 
                   3344: 
                   3345:   xi=matrix(1,npar,1,npar);
                   3346:   for (i=1;i<=npar;i++)
                   3347:     for (j=1;j<=npar;j++)
                   3348:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   3349:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
                   3350:   strcpy(filerespow,"POW_"); 
                   3351:   strcat(filerespow,fileres);
                   3352:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   3353:     printf("Problem with resultfile: %s\n", filerespow);
                   3354:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   3355:   }
                   3356:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   3357:   for (i=1;i<=nlstate;i++)
                   3358:     for(j=1;j<=nlstate+ndeath;j++)
                   3359:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   3360:   fprintf(ficrespow,"\n");
                   3361: #ifdef POWELL
                   3362:   powell(p,xi,npar,ftol,&iter,&fret,func);
                   3363: #endif
                   3364: 
                   3365: #ifdef NLOPT
                   3366: #ifdef NEWUOA
                   3367:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   3368: #else
                   3369:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   3370: #endif
                   3371:   lb=vector(0,npar-1);
                   3372:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   3373:   nlopt_set_lower_bounds(opt, lb);
                   3374:   nlopt_set_initial_step1(opt, 0.1);
                   3375:   
                   3376:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   3377:   d->function = func;
                   3378:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   3379:   nlopt_set_min_objective(opt, myfunc, d);
                   3380:   nlopt_set_xtol_rel(opt, ftol);
                   3381:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   3382:     printf("nlopt failed! %d\n",creturn); 
                   3383:   }
                   3384:   else {
                   3385:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   3386:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   3387:     iter=1; /* not equal */
                   3388:   }
                   3389:   nlopt_destroy(opt);
                   3390: #endif
                   3391:   free_matrix(xi,1,npar,1,npar);
                   3392:   fclose(ficrespow);
                   3393:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   3394:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   3395:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   3396: 
                   3397: }
                   3398: 
                   3399: /**** Computes Hessian and covariance matrix ***/
                   3400: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
                   3401: {
                   3402:   double  **a,**y,*x,pd;
                   3403:   /* double **hess; */
                   3404:   int i, j;
                   3405:   int *indx;
                   3406: 
                   3407:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
                   3408:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
                   3409:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   3410:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   3411:   double gompertz(double p[]);
                   3412:   /* hess=matrix(1,npar,1,npar); */
                   3413: 
                   3414:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   3415:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   3416:   for (i=1;i<=npar;i++){
                   3417:     printf("%d-",i);fflush(stdout);
                   3418:     fprintf(ficlog,"%d-",i);fflush(ficlog);
                   3419:    
                   3420:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   3421:     
                   3422:     /*  printf(" %f ",p[i]);
                   3423:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   3424:   }
                   3425:   
                   3426:   for (i=1;i<=npar;i++) {
                   3427:     for (j=1;j<=npar;j++)  {
                   3428:       if (j>i) { 
                   3429:        printf(".%d-%d",i,j);fflush(stdout);
                   3430:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   3431:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
                   3432:        
                   3433:        hess[j][i]=hess[i][j];    
                   3434:        /*printf(" %lf ",hess[i][j]);*/
                   3435:       }
                   3436:     }
                   3437:   }
                   3438:   printf("\n");
                   3439:   fprintf(ficlog,"\n");
                   3440: 
                   3441:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3442:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3443:   
                   3444:   a=matrix(1,npar,1,npar);
                   3445:   y=matrix(1,npar,1,npar);
                   3446:   x=vector(1,npar);
                   3447:   indx=ivector(1,npar);
                   3448:   for (i=1;i<=npar;i++)
                   3449:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   3450:   ludcmp(a,npar,indx,&pd);
                   3451: 
                   3452:   for (j=1;j<=npar;j++) {
                   3453:     for (i=1;i<=npar;i++) x[i]=0;
                   3454:     x[j]=1;
                   3455:     lubksb(a,npar,indx,x);
                   3456:     for (i=1;i<=npar;i++){ 
                   3457:       matcov[i][j]=x[i];
                   3458:     }
                   3459:   }
                   3460: 
                   3461:   printf("\n#Hessian matrix#\n");
                   3462:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   3463:   for (i=1;i<=npar;i++) { 
                   3464:     for (j=1;j<=npar;j++) { 
                   3465:       printf("%.6e ",hess[i][j]);
                   3466:       fprintf(ficlog,"%.6e ",hess[i][j]);
                   3467:     }
                   3468:     printf("\n");
                   3469:     fprintf(ficlog,"\n");
                   3470:   }
                   3471: 
                   3472:   /* printf("\n#Covariance matrix#\n"); */
                   3473:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   3474:   /* for (i=1;i<=npar;i++) {  */
                   3475:   /*   for (j=1;j<=npar;j++) {  */
                   3476:   /*     printf("%.6e ",matcov[i][j]); */
                   3477:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   3478:   /*   } */
                   3479:   /*   printf("\n"); */
                   3480:   /*   fprintf(ficlog,"\n"); */
                   3481:   /* } */
                   3482: 
                   3483:   /* Recompute Inverse */
                   3484:   /* for (i=1;i<=npar;i++) */
                   3485:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   3486:   /* ludcmp(a,npar,indx,&pd); */
                   3487: 
                   3488:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   3489: 
                   3490:   /* for (j=1;j<=npar;j++) { */
                   3491:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   3492:   /*   x[j]=1; */
                   3493:   /*   lubksb(a,npar,indx,x); */
                   3494:   /*   for (i=1;i<=npar;i++){  */
                   3495:   /*     y[i][j]=x[i]; */
                   3496:   /*     printf("%.3e ",y[i][j]); */
                   3497:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   3498:   /*   } */
                   3499:   /*   printf("\n"); */
                   3500:   /*   fprintf(ficlog,"\n"); */
                   3501:   /* } */
                   3502: 
                   3503:   /* Verifying the inverse matrix */
                   3504: #ifdef DEBUGHESS
                   3505:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
                   3506: 
                   3507:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   3508:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
                   3509: 
                   3510:   for (j=1;j<=npar;j++) {
                   3511:     for (i=1;i<=npar;i++){ 
                   3512:       printf("%.2f ",y[i][j]);
                   3513:       fprintf(ficlog,"%.2f ",y[i][j]);
                   3514:     }
                   3515:     printf("\n");
                   3516:     fprintf(ficlog,"\n");
                   3517:   }
                   3518: #endif
                   3519: 
                   3520:   free_matrix(a,1,npar,1,npar);
                   3521:   free_matrix(y,1,npar,1,npar);
                   3522:   free_vector(x,1,npar);
                   3523:   free_ivector(indx,1,npar);
                   3524:   /* free_matrix(hess,1,npar,1,npar); */
                   3525: 
                   3526: 
                   3527: }
                   3528: 
                   3529: /*************** hessian matrix ****************/
                   3530: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
                   3531: { /* Around values of x, computes the function func and returns the scales delti and hessian */
                   3532:   int i;
                   3533:   int l=1, lmax=20;
                   3534:   double k1,k2, res, fx;
                   3535:   double p2[MAXPARM+1]; /* identical to x */
                   3536:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   3537:   int k=0,kmax=10;
                   3538:   double l1;
                   3539: 
                   3540:   fx=func(x);
                   3541:   for (i=1;i<=npar;i++) p2[i]=x[i];
                   3542:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
                   3543:     l1=pow(10,l);
                   3544:     delts=delt;
                   3545:     for(k=1 ; k <kmax; k=k+1){
                   3546:       delt = delta*(l1*k);
                   3547:       p2[theta]=x[theta] +delt;
                   3548:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
                   3549:       p2[theta]=x[theta]-delt;
                   3550:       k2=func(p2)-fx;
                   3551:       /*res= (k1-2.0*fx+k2)/delt/delt; */
                   3552:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
                   3553:       
                   3554: #ifdef DEBUGHESSII
                   3555:       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);
                   3556:       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);
                   3557: #endif
                   3558:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   3559:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   3560:        k=kmax;
                   3561:       }
                   3562:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
                   3563:        k=kmax; l=lmax*10;
                   3564:       }
                   3565:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   3566:        delts=delt;
                   3567:       }
                   3568:     } /* End loop k */
                   3569:   }
                   3570:   delti[theta]=delts;
                   3571:   return res; 
                   3572:   
                   3573: }
                   3574: 
                   3575: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
                   3576: {
                   3577:   int i;
                   3578:   int l=1, lmax=20;
                   3579:   double k1,k2,k3,k4,res,fx;
                   3580:   double p2[MAXPARM+1];
                   3581:   int k, kmax=1;
                   3582:   double v1, v2, cv12, lc1, lc2;
                   3583: 
                   3584:   int firstime=0;
                   3585:   
                   3586:   fx=func(x);
                   3587:   for (k=1; k<=kmax; k=k+10) {
                   3588:     for (i=1;i<=npar;i++) p2[i]=x[i];
                   3589:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3590:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
                   3591:     k1=func(p2)-fx;
                   3592:   
                   3593:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3594:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
                   3595:     k2=func(p2)-fx;
                   3596:   
                   3597:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3598:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
                   3599:     k3=func(p2)-fx;
                   3600:   
                   3601:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3602:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
                   3603:     k4=func(p2)-fx;
                   3604:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   3605:     if(k1*k2*k3*k4 <0.){
                   3606:       firstime=1;
                   3607:       kmax=kmax+10;
                   3608:     }
                   3609:     if(kmax >=10 || firstime ==1){
                   3610:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you may increase ftol=%.2e\n",thetai,thetaj, ftol);
                   3611:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you may increase ftol=%.2e\n",thetai,thetaj, ftol);
                   3612:       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);
                   3613:       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);
                   3614:     }
                   3615: #ifdef DEBUGHESSIJ
                   3616:     v1=hess[thetai][thetai];
                   3617:     v2=hess[thetaj][thetaj];
                   3618:     cv12=res;
                   3619:     /* Computing eigen value of Hessian matrix */
                   3620:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3621:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3622:     if ((lc2 <0) || (lc1 <0) ){
                   3623:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3624:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3625:       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);
                   3626:       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);
                   3627:     }
                   3628: #endif
                   3629:   }
                   3630:   return res;
                   3631: }
                   3632: 
                   3633:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   3634: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   3635: /* { */
                   3636: /*   int i; */
                   3637: /*   int l=1, lmax=20; */
                   3638: /*   double k1,k2,k3,k4,res,fx; */
                   3639: /*   double p2[MAXPARM+1]; */
                   3640: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   3641: /*   int k=0,kmax=10; */
                   3642: /*   double l1; */
                   3643:   
                   3644: /*   fx=func(x); */
                   3645: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   3646: /*     l1=pow(10,l); */
                   3647: /*     delts=delt; */
                   3648: /*     for(k=1 ; k <kmax; k=k+1){ */
                   3649: /*       delt = delti*(l1*k); */
                   3650: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   3651: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3652: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3653: /*       k1=func(p2)-fx; */
                   3654:       
                   3655: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3656: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3657: /*       k2=func(p2)-fx; */
                   3658:       
                   3659: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3660: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3661: /*       k3=func(p2)-fx; */
                   3662:       
                   3663: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3664: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3665: /*       k4=func(p2)-fx; */
                   3666: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   3667: /* #ifdef DEBUGHESSIJ */
                   3668: /*       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); */
                   3669: /*       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); */
                   3670: /* #endif */
                   3671: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   3672: /*     k=kmax; */
                   3673: /*       } */
                   3674: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   3675: /*     k=kmax; l=lmax*10; */
                   3676: /*       } */
                   3677: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   3678: /*     delts=delt; */
                   3679: /*       } */
                   3680: /*     } /\* End loop k *\/ */
                   3681: /*   } */
                   3682: /*   delti[theta]=delts; */
                   3683: /*   return res;  */
                   3684: /* } */
                   3685: 
                   3686: 
                   3687: /************** Inverse of matrix **************/
                   3688: void ludcmp(double **a, int n, int *indx, double *d) 
                   3689: { 
                   3690:   int i,imax,j,k; 
                   3691:   double big,dum,sum,temp; 
                   3692:   double *vv; 
                   3693:  
                   3694:   vv=vector(1,n); 
                   3695:   *d=1.0; 
                   3696:   for (i=1;i<=n;i++) { 
                   3697:     big=0.0; 
                   3698:     for (j=1;j<=n;j++) 
                   3699:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   3700:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   3701:     vv[i]=1.0/big; 
                   3702:   } 
                   3703:   for (j=1;j<=n;j++) { 
                   3704:     for (i=1;i<j;i++) { 
                   3705:       sum=a[i][j]; 
                   3706:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   3707:       a[i][j]=sum; 
                   3708:     } 
                   3709:     big=0.0; 
                   3710:     for (i=j;i<=n;i++) { 
                   3711:       sum=a[i][j]; 
                   3712:       for (k=1;k<j;k++) 
                   3713:        sum -= a[i][k]*a[k][j]; 
                   3714:       a[i][j]=sum; 
                   3715:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   3716:        big=dum; 
                   3717:        imax=i; 
                   3718:       } 
                   3719:     } 
                   3720:     if (j != imax) { 
                   3721:       for (k=1;k<=n;k++) { 
                   3722:        dum=a[imax][k]; 
                   3723:        a[imax][k]=a[j][k]; 
                   3724:        a[j][k]=dum; 
                   3725:       } 
                   3726:       *d = -(*d); 
                   3727:       vv[imax]=vv[j]; 
                   3728:     } 
                   3729:     indx[j]=imax; 
                   3730:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   3731:     if (j != n) { 
                   3732:       dum=1.0/(a[j][j]); 
                   3733:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   3734:     } 
                   3735:   } 
                   3736:   free_vector(vv,1,n);  /* Doesn't work */
                   3737: ;
                   3738: } 
                   3739: 
                   3740: void lubksb(double **a, int n, int *indx, double b[]) 
                   3741: { 
                   3742:   int i,ii=0,ip,j; 
                   3743:   double sum; 
                   3744:  
                   3745:   for (i=1;i<=n;i++) { 
                   3746:     ip=indx[i]; 
                   3747:     sum=b[ip]; 
                   3748:     b[ip]=b[i]; 
                   3749:     if (ii) 
                   3750:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   3751:     else if (sum) ii=i; 
                   3752:     b[i]=sum; 
                   3753:   } 
                   3754:   for (i=n;i>=1;i--) { 
                   3755:     sum=b[i]; 
                   3756:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   3757:     b[i]=sum/a[i][i]; 
                   3758:   } 
                   3759: } 
                   3760: 
                   3761: void pstamp(FILE *fichier)
                   3762: {
                   3763:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
                   3764: }
                   3765: 
                   3766: /************ Frequencies ********************/
                   3767:  void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
                   3768:                                                                         int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[],  \
                   3769:                                                                         int firstpass,  int lastpass, int stepm, int weightopt, char model[])
                   3770:  {  /* Some frequencies */
                   3771:   
1.2     ! brouard  3772:    int i, m, jk, j1, bool, z1,j;
        !          3773:    int iind=0, iage=0;
        !          3774:    int mi; /* Effective wave */
        !          3775:    int first;
        !          3776:    double ***freq; /* Frequencies */
        !          3777:    double *pp, **prop, *posprop, *pospropt;
        !          3778:    double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
        !          3779:    char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
        !          3780:    double agebegin, ageend;
        !          3781:     
        !          3782:    pp=vector(1,nlstate);
        !          3783:    prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
        !          3784:    posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
        !          3785:    pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
        !          3786:    /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
        !          3787:    strcpy(fileresp,"P_");
        !          3788:    strcat(fileresp,fileresu);
        !          3789:    /*strcat(fileresphtm,fileresu);*/
        !          3790:    if((ficresp=fopen(fileresp,"w"))==NULL) {
        !          3791:      printf("Problem with prevalence resultfile: %s\n", fileresp);
        !          3792:      fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
        !          3793:      exit(0);
        !          3794:    }
1.1       brouard  3795: 
1.2     ! brouard  3796:    strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
        !          3797:    if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
        !          3798:      printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
        !          3799:      fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
        !          3800:      fflush(ficlog);
        !          3801:      exit(70); 
        !          3802:    }
        !          3803:    else{
        !          3804:      fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.1       brouard  3805: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   3806: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.2     ! brouard  3807:             fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
        !          3808:    }
        !          3809:    fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies and prevalence by age at begin of transition</h4>\n",fileresphtm, fileresphtm);
1.1       brouard  3810:     
1.2     ! brouard  3811:    strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
        !          3812:    if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
        !          3813:      printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
        !          3814:      fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
        !          3815:      fflush(ficlog);
        !          3816:      exit(70); 
        !          3817:    }
        !          3818:    else{
        !          3819:      fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.1       brouard  3820: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   3821: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.2     ! brouard  3822:             fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
        !          3823:    }
        !          3824:    fprintf(ficresphtmfr,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies of all effective transitions by age at begin of transition </h4>Unknown status is -1<br/>\n",fileresphtmfr, fileresphtmfr);
1.1       brouard  3825: 
1.2     ! brouard  3826:    freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
        !          3827:    j1=0;
1.1       brouard  3828:   
1.2     ! brouard  3829:    j=cptcoveff;
        !          3830:    if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.1       brouard  3831: 
1.2     ! brouard  3832:    first=1;
1.1       brouard  3833: 
1.2     ! brouard  3834:    /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
        !          3835:       reference=low_education V1=0,V2=0
        !          3836:       med_educ                V1=1 V2=0, 
        !          3837:       high_educ               V1=0 V2=1
        !          3838:       Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
        !          3839:    */
1.1       brouard  3840: 
1.2     ! brouard  3841:    for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){ /* Loop on covariates combination */
        !          3842:      posproptt=0.;
        !          3843:      /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
        !          3844:        scanf("%d", i);*/
        !          3845:      for (i=-5; i<=nlstate+ndeath; i++)  
        !          3846:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
        !          3847:         for(m=iagemin; m <= iagemax+3; m++)
        !          3848:           freq[i][jk][m]=0;
        !          3849:       
        !          3850:      for (i=1; i<=nlstate; i++)  {
        !          3851:        for(m=iagemin; m <= iagemax+3; m++)
        !          3852:         prop[i][m]=0;
        !          3853:        posprop[i]=0;
        !          3854:        pospropt[i]=0;
        !          3855:      }
1.1       brouard  3856:       
1.2     ! brouard  3857:      dateintsum=0;
        !          3858:      k2cpt=0;
        !          3859:      /* For that comination of covariate j1, we count and print the frequencies */
        !          3860:      for (iind=1; iind<=imx; iind++) { /* For each individual iind */
        !          3861:        bool=1;
        !          3862:        if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
        !          3863:         for (z1=1; z1<=cptcoveff; z1++) {      
        !          3864:           if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
        !          3865:             /* Tests if the value of each of the covariates of i is equal to filter j1 */
        !          3866:             bool=0;
        !          3867:             /* 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", 
1.1       brouard  3868:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   3869:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.2     ! brouard  3870:             /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
        !          3871:           } 
        !          3872:         } /* end z1 */
        !          3873:        } /* cptcovn > 0 */
        !          3874: 
        !          3875:        if (bool==1){ /* We selected an individual iin satisfying combination j1 */
        !          3876:         /* for(m=firstpass; m<=lastpass; m++){ */
        !          3877:         for(mi=1; mi<wav[iind];mi++){
        !          3878:           m=mw[mi][iind];
        !          3879:           /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
        !          3880:              and mw[mi+1][iind]. dh depends on stepm. */
        !          3881:           agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
        !          3882:           ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
        !          3883:           if(m >=firstpass && m <=lastpass){
        !          3884:             k2=anint[m][iind]+(mint[m][iind]/12.);
        !          3885:             /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
        !          3886:             if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
        !          3887:             if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
        !          3888:             if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
        !          3889:               prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
        !          3890:             if (m<lastpass) {
        !          3891:               /* if(s[m][iind]==4 && s[m+1][iind]==4) */
        !          3892:               /*   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]); */
        !          3893:               if(s[m][iind]==-1)
        !          3894:                 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.));
        !          3895:               freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
        !          3896:               /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
        !          3897:               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 */
        !          3898:             }
        !          3899:           }  
        !          3900:           if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99)) {
        !          3901:             dateintsum=dateintsum+k2;
        !          3902:             k2cpt++;
        !          3903:             /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
        !          3904:           }
        !          3905:           /*}*/
        !          3906:         } /* end m */
        !          3907:        } /* end bool */
        !          3908:      } /* end iind = 1 to imx */
1.1       brouard  3909:        /* prop[s][age] is feeded for any initial and valid live state as well as
1.2     ! brouard  3910:          freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
1.1       brouard  3911: 
                   3912: 
1.2     ! brouard  3913:      /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
        !          3914:      pstamp(ficresp);
        !          3915:      if  (cptcovn>0) {
        !          3916:        fprintf(ficresp, "\n#********** Variable "); 
        !          3917:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
        !          3918:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
        !          3919:        for (z1=1; z1<=cptcoveff; z1++){
        !          3920:         fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
        !          3921:         fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
        !          3922:         fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
        !          3923:        }
        !          3924:        fprintf(ficresp, "**********\n#");
        !          3925:        fprintf(ficresphtm, "**********</h3>\n");
        !          3926:        fprintf(ficresphtmfr, "**********</h3>\n");
        !          3927:        fprintf(ficlog, "\n#********** Variable "); 
        !          3928:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
        !          3929:        fprintf(ficlog, "**********\n");
        !          3930:      }
        !          3931:      fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
        !          3932:      for(i=1; i<=nlstate;i++) {
        !          3933:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
        !          3934:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
        !          3935:      }
        !          3936:      fprintf(ficresp, "\n");
        !          3937:      fprintf(ficresphtm, "\n");
1.1       brouard  3938:       
1.2     ! brouard  3939:      /* Header of frequency table by age */
        !          3940:      fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
        !          3941:      fprintf(ficresphtmfr,"<th>Age</th> ");
        !          3942:      for(jk=-1; jk <=nlstate+ndeath; jk++){
        !          3943:        for(m=-1; m <=nlstate+ndeath; m++){
        !          3944:         if(jk!=0 && m!=0)
        !          3945:           fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
        !          3946:        }
        !          3947:      }
        !          3948:      fprintf(ficresphtmfr, "\n");
1.1       brouard  3949:       
1.2     ! brouard  3950:      /* For each age */
        !          3951:      for(iage=iagemin; iage <= iagemax+3; iage++){
        !          3952:        fprintf(ficresphtm,"<tr>");
        !          3953:        if(iage==iagemax+1){
        !          3954:         fprintf(ficlog,"1");
        !          3955:         fprintf(ficresphtmfr,"<tr><th>0</th> ");
        !          3956:        }else if(iage==iagemax+2){
        !          3957:         fprintf(ficlog,"0");
        !          3958:         fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
        !          3959:        }else if(iage==iagemax+3){
        !          3960:         fprintf(ficlog,"Total");
        !          3961:         fprintf(ficresphtmfr,"<tr><th>Total</th> ");
        !          3962:        }else{
        !          3963:         if(first==1){
        !          3964:           first=0;
        !          3965:           printf("See log file for details...\n");
        !          3966:         }
        !          3967:         fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
        !          3968:         fprintf(ficlog,"Age %d", iage);
        !          3969:        }
        !          3970:        for(jk=1; jk <=nlstate ; jk++){
        !          3971:         for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
        !          3972:           pp[jk] += freq[jk][m][iage]; 
        !          3973:        }
        !          3974:        for(jk=1; jk <=nlstate ; jk++){
        !          3975:         for(m=-1, pos=0; m <=0 ; m++)
        !          3976:           pos += freq[jk][m][iage];
        !          3977:         if(pp[jk]>=1.e-10){
        !          3978:           if(first==1){
        !          3979:             printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
        !          3980:           }
        !          3981:           fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
        !          3982:         }else{
        !          3983:           if(first==1)
        !          3984:             printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
        !          3985:           fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
        !          3986:         }
        !          3987:        }
        !          3988: 
        !          3989:        for(jk=1; jk <=nlstate ; jk++){ 
        !          3990:         /* posprop[jk]=0; */
        !          3991:         for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
        !          3992:           pp[jk] += freq[jk][m][iage];
        !          3993:        }       /* pp[jk] is the total number of transitions starting from state jk and any ending status until this age */
        !          3994: 
        !          3995:        for(jk=1,pos=0, pospropta=0.; jk <=nlstate ; jk++){
        !          3996:         pos += pp[jk]; /* pos is the total number of transitions until this age */
        !          3997:         posprop[jk] += prop[jk][iage]; /* prop is the number of transitions from a live state
        !          3998:                                           from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
        !          3999:         pospropta += prop[jk][iage]; /* prop is the number of transitions from a live state
        !          4000:                                         from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
        !          4001:        }
        !          4002:        for(jk=1; jk <=nlstate ; jk++){
        !          4003:         if(pos>=1.e-5){
        !          4004:           if(first==1)
        !          4005:             printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
        !          4006:           fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
        !          4007:         }else{
        !          4008:           if(first==1)
        !          4009:             printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
        !          4010:           fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
        !          4011:         }
        !          4012:         if( iage <= iagemax){
        !          4013:           if(pos>=1.e-5){
        !          4014:             fprintf(ficresp," %d %.5f %.0f %.0f",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
        !          4015:             fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
        !          4016:             /*probs[iage][jk][j1]= pp[jk]/pos;*/
        !          4017:             /*printf("\niage=%d jk=%d j1=%d %.5f %.0f %.0f %f",iage,jk,j1,pp[jk]/pos, pp[jk],pos,probs[iage][jk][j1]);*/
        !          4018:           }
        !          4019:           else{
        !          4020:             fprintf(ficresp," %d NaNq %.0f %.0f",iage,prop[jk][iage],pospropta);
        !          4021:             fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[jk][iage],pospropta);
        !          4022:           }
        !          4023:         }
        !          4024:         pospropt[jk] +=posprop[jk];
        !          4025:        } /* end loop jk */
        !          4026:        /* pospropt=0.; */
        !          4027:        for(jk=-1; jk <=nlstate+ndeath; jk++){
        !          4028:         for(m=-1; m <=nlstate+ndeath; m++){
        !          4029:           if(freq[jk][m][iage] !=0 ) { /* minimizing output */
        !          4030:             if(first==1){
        !          4031:               printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]);
        !          4032:             }
        !          4033:             fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iage]);
        !          4034:           }
        !          4035:           if(jk!=0 && m!=0)
        !          4036:             fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][iage]);
        !          4037:         }
        !          4038:        } /* end loop jk */
        !          4039:        posproptt=0.; 
        !          4040:        for(jk=1; jk <=nlstate; jk++){
        !          4041:         posproptt += pospropt[jk];
        !          4042:        }
        !          4043:        fprintf(ficresphtmfr,"</tr>\n ");
        !          4044:        if(iage <= iagemax){
        !          4045:         fprintf(ficresp,"\n");
        !          4046:         fprintf(ficresphtm,"</tr>\n");
        !          4047:        }
        !          4048:        if(first==1)
        !          4049:         printf("Others in log...\n");
        !          4050:        fprintf(ficlog,"\n");
        !          4051:      } /* end loop age iage */
        !          4052:      fprintf(ficresphtm,"<tr><th>Tot</th>");
        !          4053:      for(jk=1; jk <=nlstate ; jk++){
        !          4054:        if(posproptt < 1.e-5){
        !          4055:         fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[jk],posproptt);  
        !          4056:        }else{
        !          4057:         fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[jk]/posproptt,pospropt[jk],posproptt);   
        !          4058:        }
        !          4059:      }
        !          4060:      fprintf(ficresphtm,"</tr>\n");
        !          4061:      fprintf(ficresphtm,"</table>\n");
        !          4062:      fprintf(ficresphtmfr,"</table>\n");
        !          4063:      if(posproptt < 1.e-5){
        !          4064:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
        !          4065:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
        !          4066:        fprintf(ficres,"\n  This combination (%d) is not valid and no result will be produced\n\n",j1);
        !          4067:        invalidvarcomb[j1]=1;
        !          4068:      }else{
        !          4069:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
        !          4070:        invalidvarcomb[j1]=0;
        !          4071:      }
        !          4072:      fprintf(ficresphtmfr,"</table>\n");
        !          4073:    } /* end selected combination of covariate j1 */
        !          4074:    dateintmean=dateintsum/k2cpt; 
1.1       brouard  4075:                 
1.2     ! brouard  4076:    fclose(ficresp);
        !          4077:    fclose(ficresphtm);
        !          4078:    fclose(ficresphtmfr);
        !          4079:    free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);
        !          4080:    free_vector(pospropt,1,nlstate);
        !          4081:    free_vector(posprop,1,nlstate);
        !          4082:    free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);
        !          4083:    free_vector(pp,1,nlstate);
        !          4084:    /* End of Freq */
1.1       brouard  4085:  }
                   4086: 
                   4087: /************ Prevalence ********************/
                   4088:  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)
                   4089:  {  
                   4090:    /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   4091:       in each health status at the date of interview (if between dateprev1 and dateprev2).
                   4092:       We still use firstpass and lastpass as another selection.
                   4093:    */
                   4094:  
                   4095:    int i, m, jk, j1, bool, z1,j;
                   4096:    int mi; /* Effective wave */
                   4097:    int iage;
                   4098:    double agebegin, ageend;
                   4099: 
                   4100:    double **prop;
                   4101:    double posprop; 
                   4102:    double  y2; /* in fractional years */
                   4103:    int iagemin, iagemax;
                   4104:    int first; /** to stop verbosity which is redirected to log file */
                   4105: 
                   4106:    iagemin= (int) agemin;
                   4107:    iagemax= (int) agemax;
                   4108:    /*pp=vector(1,nlstate);*/
                   4109:    prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   4110:    /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   4111:    j1=0;
                   4112:   
                   4113:    /*j=cptcoveff;*/
                   4114:    if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   4115:   
                   4116:    first=1;
                   4117:    for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   4118:      for (i=1; i<=nlstate; i++)  
                   4119:        for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)
                   4120:         prop[i][iage]=0.0;
                   4121:     
                   4122:      for (i=1; i<=imx; i++) { /* Each individual */
                   4123:        bool=1;
                   4124:        if  (cptcovn>0) {  /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   4125:         for (z1=1; z1<=cptcoveff; z1++) /* For each covariate, look at the value for individual i and checks if it is equal to the corresponding value of this covariate according to current combination j1*/
                   4126:           if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
                   4127:             bool=0;
                   4128:        } 
                   4129:        if (bool==1) { /* For this combination of covariates values, this individual fits */
                   4130:         /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   4131:         for(mi=1; mi<wav[i];mi++){
                   4132:           m=mw[mi][i];
                   4133:           agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   4134:           /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   4135:           if(m >=firstpass && m <=lastpass){
                   4136:             y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   4137:             if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   4138:               if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   4139:               if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   4140:               if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){
                   4141:                 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); 
                   4142:                 exit(1);
                   4143:               }
                   4144:               if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   4145:                 /*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]]);*/
                   4146:                 prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   4147:                 prop[s[m][i]][iagemax+3] += weight[i]; 
                   4148:               } /* end valid statuses */ 
                   4149:             } /* end selection of dates */
                   4150:           } /* end selection of waves */
                   4151:         } /* end effective waves */
                   4152:        } /* end bool */
                   4153:      }
                   4154:      for(i=iagemin; i <= iagemax+3; i++){  
                   4155:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   4156:         posprop += prop[jk][i]; 
                   4157:        } 
                   4158:       
                   4159:        for(jk=1; jk <=nlstate ; jk++){     
                   4160:         if( i <=  iagemax){ 
                   4161:           if(posprop>=1.e-5){ 
                   4162:             probs[i][jk][j1]= prop[jk][i]/posprop;
                   4163:           } else{
                   4164:             if(first==1){
                   4165:               first=0;
                   4166:               printf("Warning Observed prevalence probs[%d][%d][%d]=%lf because of lack of cases\nSee others on log file...\n",jk,i,j1,probs[i][jk][j1]);
                   4167:             }
                   4168:           }
                   4169:         } 
                   4170:        }/* end jk */ 
                   4171:      }/* end i */ 
                   4172:      /*} *//* end i1 */
                   4173:    } /* end j1 */
                   4174:   
                   4175:    /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   4176:    /*free_vector(pp,1,nlstate);*/
                   4177:    free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   4178:  }  /* End of prevalence */
                   4179: 
                   4180: /************* Waves Concatenation ***************/
                   4181: 
                   4182: 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)
                   4183: {
                   4184:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   4185:      Death is a valid wave (if date is known).
                   4186:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   4187:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4188:      and mw[mi+1][i]. dh depends on stepm.
                   4189:      */
                   4190: 
1.2     ! brouard  4191:   int i=0, mi=0, m=0, mli=0;
1.1       brouard  4192:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   4193:      double sum=0., jmean=0.;*/
1.2     ! brouard  4194:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.1       brouard  4195:   int j, k=0,jk, ju, jl;
                   4196:   double sum=0.;
                   4197:   jmin=100000;
                   4198:   jmax=-1;
                   4199:   jmean=0.;
1.2     ! brouard  4200: 
        !          4201: /* Treating live states */
1.1       brouard  4202:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.2     ! brouard  4203:     mi=0;  /* First valid wave */
        !          4204:                mli=0; /* Last valid wave? */
1.1       brouard  4205:     m=firstpass;
                   4206:     while(s[m][i] <= nlstate){  /* a live state */
1.2     ! brouard  4207:                        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 */
        !          4208:                                mli=m-1;/* mw[++mi][i]=m-1; */
        !          4209:                        }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 */
        !          4210:                                mw[++mi][i]=m;
        !          4211:                                mli=m;
        !          4212:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
        !          4213:       if(m < lastpass){ /* m < lastpass, standard case */
        !          4214:                                m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.1       brouard  4215:       }
1.2     ! brouard  4216:                        else{ /* m >= lastpass, eventual special issue with warning */
        !          4217: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
        !          4218:                                break;
        !          4219: #else
        !          4220:                                if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
        !          4221:                                        if(firsthree == 0){
        !          4222:                                                printf("Information! Unknown status for individual %ld line=%d occurred at last wave %d at known date %d/%d. Please, check if your unknown date of death %d/%d means a live state %d at wave %d. This case(%d)/wave(%d) contributes to the likelihood as pi. .\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], (int) moisdc[i], (int) andc[i], s[m][i], m, i, m);
        !          4223:                                                firsthree=1;
        !          4224:                                        }
        !          4225:                                        fprintf(ficlog,"Information! Unknown status for individual %ld line=%d occurred at last wave %d at known date %d/%d. Please, check if your unknown date of death %d/%d means a live state %d at wave %d. This case(%d)/wave(%d) contributes to the likelihood as pi. .\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], (int) moisdc[i], (int) andc[i], s[m][i], m, i, m);
        !          4226:                                        mw[++mi][i]=m;
        !          4227:                                        mli=m;
        !          4228:                                }
        !          4229:                                if(s[m][i]==-2){ /* Vital status is really unknown */
        !          4230:                                        nbwarn++;
        !          4231:                                        if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
        !          4232:                                                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);
        !          4233:                                                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);
        !          4234:                                        }
        !          4235:                                        break;
        !          4236:                                }
        !          4237:                                break;
        !          4238: #endif
        !          4239:                        }/* End m >= lastpass */
1.1       brouard  4240:     }/* end while */
1.2     ! brouard  4241: 
        !          4242:        /* mi is the last effective wave, m is lastpass, mw[j][i] gives the # of j-th effective wave for individual i */
1.1       brouard  4243:     /* After last pass */
1.2     ! brouard  4244: /* Treating death states */
1.1       brouard  4245:     if (s[m][i] > nlstate){  /* In a death state */
1.2     ! brouard  4246:                        /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
        !          4247:                        /* } */
1.1       brouard  4248:       mi++;    /* Death is another wave */
                   4249:       /* if(mi==0)  never been interviewed correctly before death */
1.2     ! brouard  4250:                        /* Only death is a correct wave */
1.1       brouard  4251:       mw[mi][i]=m;
1.2     ! brouard  4252:     }
        !          4253: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
        !          4254:                else if ((int) andc[i] != 9999) { /* Status is negative. A death occured after lastpass, we can't take it into account because of potential bias */
1.1       brouard  4255:       /* m++; */
                   4256:       /* mi++; */
                   4257:       /* s[m][i]=nlstate+1;  /\* We are setting the status to the last of non live state *\/ */
                   4258:       /* mw[mi][i]=m; */
                   4259:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.2     ! brouard  4260:                                if((andc[i]+moisdc[i]/12.) <=(anint[m][i]+mint[m][i]/12.)){ /* death occured before last wave and status should have been death instead of -1 */
        !          4261:                                        nbwarn++;
        !          4262:                                        if(firstfiv==0){
        !          4263:                                                printf("Warning! Death for individual %ld line=%d occurred at %d/%d before last wave %d interviewed at %d/%d and should have been coded as death instead of '%d'. This case (%d)/wave (%d) is contributing to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], i,m );
        !          4264:                                                firstfiv=1;
        !          4265:                                        }else{
        !          4266:                                                fprintf(ficlog,"Warning! Death for individual %ld line=%d occurred at %d/%d before last wave %d interviewed at %d/%d and should have been coded as death instead of '%d'. This case (%d)/wave (%d) is contributing to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], i,m );
        !          4267:                                        }
        !          4268:                                }else{ /* Death occured afer last wave potential bias */
        !          4269:                                        nberr++;
        !          4270:                                        if(firstwo==0){
        !          4271:                                                printf("Error! Death for individual %ld line=%d occurred at %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
        !          4272:                                                firstwo=1;
        !          4273:                                        }
        !          4274:                                        fprintf(ficlog,"Error! Death for individual %ld line=%d occurred at %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
        !          4275:                                }
1.1       brouard  4276:       }else{ /* end date of interview is known */
1.2     ! brouard  4277:                                /* death is known but not confirmed by death status at any wave */
        !          4278:                                if(firstfour==0){
        !          4279:                                        printf("Error! Death for individual %ld line=%d  occurred %d/%d but not confirmed by any death status for any wave, including last wave %d at unknown date %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
        !          4280:                                        firstfour=1;
        !          4281:                                }
        !          4282:                                fprintf(ficlog,"Error! Death for individual %ld line=%d  occurred %d/%d but not confirmed by any death status for any wave, including last wave %d at unknown date %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
1.1       brouard  4283:       }
1.2     ! brouard  4284:     } /* end if date of death is known */
        !          4285: #endif
        !          4286:     wav[i]=mi; /* mi should be the last effective wave (or mli) */
        !          4287:     /* wav[i]=mw[mi][i]; */
1.1       brouard  4288:     if(mi==0){
                   4289:       nbwarn++;
                   4290:       if(first==0){
1.2     ! brouard  4291:                                printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
        !          4292:                                first=1;
1.1       brouard  4293:       }
                   4294:       if(first==1){
1.2     ! brouard  4295:                                fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.1       brouard  4296:       }
                   4297:     } /* end mi==0 */
                   4298:   } /* End individuals */
                   4299:   /* wav and mw are no more changed */
1.2     ! brouard  4300:        
1.1       brouard  4301:   
                   4302:   for(i=1; i<=imx; i++){
                   4303:     for(mi=1; mi<wav[i];mi++){
                   4304:       if (stepm <=0)
1.2     ! brouard  4305:                                dh[mi][i]=1;
1.1       brouard  4306:       else{
1.2     ! brouard  4307:                                if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
        !          4308:                                        if (agedc[i] < 2*AGESUP) {
        !          4309:                                                j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
        !          4310:                                                if(j==0) j=1;  /* Survives at least one month after exam */
        !          4311:                                                else if(j<0){
        !          4312:                                                        nberr++;
        !          4313:                                                        printf("Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
        !          4314:                                                        j=1; /* Temporary Dangerous patch */
        !          4315:                                                        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);
        !          4316:                                                        fprintf(ficlog,"Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
        !          4317:                                                        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);
        !          4318:                                                }
        !          4319:                                                k=k+1;
        !          4320:                                                if (j >= jmax){
        !          4321:                                                        jmax=j;
        !          4322:                                                        ijmax=i;
        !          4323:                                                }
        !          4324:                                                if (j <= jmin){
        !          4325:                                                        jmin=j;
        !          4326:                                                        ijmin=i;
        !          4327:                                                }
        !          4328:                                                sum=sum+j;
        !          4329:                                                /*if (j<0) printf("j=%d num=%d \n",j,i);*/
        !          4330:                                                /*        printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
        !          4331:                                        }
        !          4332:                                }
        !          4333:                                else{
        !          4334:                                        j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.1       brouard  4335: /*       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]); */
1.2     ! brouard  4336:                                        
        !          4337:                                        k=k+1;
        !          4338:                                        if (j >= jmax) {
        !          4339:                                                jmax=j;
        !          4340:                                                ijmax=i;
        !          4341:                                        }
        !          4342:                                        else if (j <= jmin){
        !          4343:                                                jmin=j;
        !          4344:                                                ijmin=i;
        !          4345:                                        }
        !          4346:                                        /*          if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
        !          4347:                                        /*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]);*/
        !          4348:                                        if(j<0){
        !          4349:                                                nberr++;
        !          4350:                                                printf("Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
        !          4351:                                                fprintf(ficlog,"Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
        !          4352:                                        }
        !          4353:                                        sum=sum+j;
        !          4354:                                }
        !          4355:                                jk= j/stepm;
        !          4356:                                jl= j -jk*stepm;
        !          4357:                                ju= j -(jk+1)*stepm;
        !          4358:                                if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
        !          4359:                                        if(jl==0){
        !          4360:                                                dh[mi][i]=jk;
        !          4361:                                                bh[mi][i]=0;
        !          4362:                                        }else{ /* We want a negative bias in order to only have interpolation ie
        !          4363:                                                                        * to avoid the price of an extra matrix product in likelihood */
        !          4364:                                                dh[mi][i]=jk+1;
        !          4365:                                                bh[mi][i]=ju;
        !          4366:                                        }
        !          4367:                                }else{
        !          4368:                                        if(jl <= -ju){
        !          4369:                                                dh[mi][i]=jk;
        !          4370:                                                bh[mi][i]=jl;   /* bias is positive if real duration
        !          4371:                                                                                                         * is higher than the multiple of stepm and negative otherwise.
        !          4372:                                                                                                         */
        !          4373:                                        }
        !          4374:                                        else{
        !          4375:                                                dh[mi][i]=jk+1;
        !          4376:                                                bh[mi][i]=ju;
        !          4377:                                        }
        !          4378:                                        if(dh[mi][i]==0){
        !          4379:                                                dh[mi][i]=1; /* At least one step */
        !          4380:                                                bh[mi][i]=ju; /* At least one step */
        !          4381:                                                /*  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);*/
        !          4382:                                        }
        !          4383:                                } /* end if mle */
1.1       brouard  4384:       }
                   4385:     } /* end wave */
                   4386:   }
                   4387:   jmean=sum/k;
                   4388:   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);
                   4389:   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);
                   4390:  }
                   4391: 
                   4392: /*********** Tricode ****************************/
                   4393:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
                   4394: {
                   4395:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   4396:   /*     Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   4397:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   4398:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
                   4399:    * nbcode[Tvar[5]][1]= nbcode[2][1]=0, nbcode[2][2]=1 (usually);
                   4400:   */
                   4401: 
                   4402:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   4403:   int modmaxcovj=0; /* Modality max of covariates j */
                   4404:   int cptcode=0; /* Modality max of covariates j */
                   4405:   int modmincovj=0; /* Modality min of covariates j */
                   4406: 
                   4407: 
                   4408:   /* cptcoveff=0;  */
                   4409:        *cptcov=0;
                   4410:  
                   4411:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
                   4412: 
                   4413:   /* Loop on covariates without age and products */
                   4414:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
                   4415:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
                   4416:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
                   4417:                                                                                                                                modality of this covariate Vj*/ 
                   4418:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   4419:                                                                                                                                                * If product of Vn*Vm, still boolean *:
                   4420:                                                                                                                                                * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   4421:                                                                                                                                                * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   4422:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   4423:                                      modality of the nth covariate of individual i. */
                   4424:       if (ij > modmaxcovj)
                   4425:         modmaxcovj=ij; 
                   4426:       else if (ij < modmincovj) 
                   4427:                                modmincovj=ij; 
                   4428:       if ((ij < -1) && (ij > NCOVMAX)){
                   4429:                                printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   4430:                                exit(1);
                   4431:       }else
                   4432:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   4433:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   4434:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   4435:       /* getting the maximum value of the modality of the covariate
                   4436:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   4437:         female is 1, then modmaxcovj=1.*/
                   4438:     } /* end for loop on individuals i */
                   4439:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
                   4440:     fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
                   4441:     cptcode=modmaxcovj;
                   4442:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   4443:    /*for (i=0; i<=cptcode; i++) {*/
                   4444:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
                   4445:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   4446:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   4447:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
                   4448:                                if( k != -1){
                   4449:                                        ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
                   4450:                                                                                                                 covariate for which somebody answered excluding 
                   4451:                                                                                                                 undefined. Usually 2: 0 and 1. */
                   4452:                                }
                   4453:                                ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
                   4454:                                                                                                                                covariate for which somebody answered including 
                   4455:                                                                                                                                undefined. Usually 3: -1, 0 and 1. */
                   4456:       }
                   4457:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
1.2     ! brouard  4458:                         * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.1       brouard  4459:     } /* Ndum[-1] number of undefined modalities */
                   4460:                
                   4461:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   4462:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   4463:        If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
                   4464:        modmincovj=3; modmaxcovj = 7;
                   4465:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   4466:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   4467:        defining two dummy variables: variables V1_1 and V1_2.
                   4468:        nbcode[Tvar[j]][ij]=k;
                   4469:        nbcode[Tvar[j]][1]=0;
                   4470:        nbcode[Tvar[j]][2]=1;
                   4471:        nbcode[Tvar[j]][3]=2;
                   4472:        To be continued (not working yet).
                   4473:     */
                   4474:     ij=0; /* ij is similar to i but can jump over null modalities */
                   4475:     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*/
                   4476:        if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   4477:                                break;
                   4478:                        }
1.2     ! brouard  4479:                        ij++;
        !          4480:                        nbcode[Tvar[j]][ij]=i;  /* stores the original value of modality i in an array nbcode, ij modality from 1 to last non-nul modality.*/
        !          4481:                        cptcode = ij; /* New max modality for covar j */
1.1       brouard  4482:     } /* end of loop on modality i=-1 to 1 or more */
1.2     ! brouard  4483:                
1.1       brouard  4484:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   4485:     /*         /\*recode from 0 *\/ */
                   4486:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   4487:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   4488:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   4489:     /*         } */
                   4490:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   4491:     /*         if (ij > ncodemax[j]) { */
                   4492:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   4493:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   4494:     /*           break; */
                   4495:     /*         } */
                   4496:     /*   }  /\* end of loop on modality k *\/ */
                   4497:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   4498:   
                   4499:        for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   4500:   
                   4501:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   4502:                /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   4503:                ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
                   4504:                Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.2     ! brouard  4505:        } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
1.1       brouard  4506:        
                   4507:        ij=0;
                   4508:        for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   4509:                /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   4510:                if((Ndum[i]!=0) && (i<=ncovcol)){
                   4511:                        ij++;
                   4512:                        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   4513:                        Tvaraff[ij]=i; /*For printing (unclear) */
                   4514:                }else{
                   4515:                        /* Tvaraff[ij]=0; */
                   4516:                }
                   4517:        }
                   4518:        /* ij--; */
                   4519:        /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.2     ! brouard  4520:        *cptcov=ij; /*Number of total real effective covariates: effective
        !          4521:                                                         * because they can be excluded from the model and real
        !          4522:                                                         * if in the model but excluded because missing values*/
1.1       brouard  4523: }
                   4524: 
                   4525: 
                   4526: /*********** Health Expectancies ****************/
                   4527: 
                   4528: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
                   4529: 
                   4530: {
                   4531:   /* Health expectancies, no variances */
                   4532:   int i, j, nhstepm, hstepm, h, nstepm;
                   4533:   int nhstepma, nstepma; /* Decreasing with age */
                   4534:   double age, agelim, hf;
                   4535:   double ***p3mat;
                   4536:   double eip;
                   4537: 
                   4538:   pstamp(ficreseij);
                   4539:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   4540:   fprintf(ficreseij,"# Age");
                   4541:   for(i=1; i<=nlstate;i++){
                   4542:     for(j=1; j<=nlstate;j++){
                   4543:       fprintf(ficreseij," e%1d%1d ",i,j);
                   4544:     }
                   4545:     fprintf(ficreseij," e%1d. ",i);
                   4546:   }
                   4547:   fprintf(ficreseij,"\n");
                   4548: 
                   4549:   
                   4550:   if(estepm < stepm){
                   4551:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4552:   }
                   4553:   else  hstepm=estepm;   
                   4554:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   4555:    * This is mainly to measure the difference between two models: for example
                   4556:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   4557:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   4558:    * progression in between and thus overestimating or underestimating according
                   4559:    * to the curvature of the survival function. If, for the same date, we 
                   4560:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   4561:    * to compare the new estimate of Life expectancy with the same linear 
                   4562:    * hypothesis. A more precise result, taking into account a more precise
                   4563:    * curvature will be obtained if estepm is as small as stepm. */
                   4564: 
                   4565:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4566:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4567:      nhstepm is the number of hstepm from age to agelim 
                   4568:      nstepm is the number of stepm from age to agelin. 
                   4569:      Look at hpijx to understand the reason of that which relies in memory size
                   4570:      and note for a fixed period like estepm months */
                   4571:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   4572:      survival function given by stepm (the optimization length). Unfortunately it
                   4573:      means that if the survival funtion is printed only each two years of age and if
                   4574:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4575:      results. So we changed our mind and took the option of the best precision.
                   4576:   */
                   4577:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4578: 
                   4579:   agelim=AGESUP;
                   4580:   /* If stepm=6 months */
                   4581:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   4582:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   4583:     
                   4584: /* nhstepm age range expressed in number of stepm */
                   4585:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4586:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4587:   /* if (stepm >= YEARM) hstepm=1;*/
                   4588:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4589:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4590: 
                   4591:   for (age=bage; age<=fage; age ++){ 
                   4592:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4593:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4594:     /* if (stepm >= YEARM) hstepm=1;*/
                   4595:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   4596: 
                   4597:     /* If stepm=6 months */
                   4598:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   4599:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   4600:     
                   4601:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   4602:     
                   4603:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4604:     
                   4605:     printf("%d|",(int)age);fflush(stdout);
                   4606:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   4607:     
                   4608:     /* Computing expectancies */
                   4609:     for(i=1; i<=nlstate;i++)
                   4610:       for(j=1; j<=nlstate;j++)
                   4611:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   4612:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   4613:          
                   4614:          /* 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]);*/
                   4615: 
                   4616:        }
                   4617: 
                   4618:     fprintf(ficreseij,"%3.0f",age );
                   4619:     for(i=1; i<=nlstate;i++){
                   4620:       eip=0;
                   4621:       for(j=1; j<=nlstate;j++){
                   4622:        eip +=eij[i][j][(int)age];
                   4623:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   4624:       }
                   4625:       fprintf(ficreseij,"%9.4f", eip );
                   4626:     }
                   4627:     fprintf(ficreseij,"\n");
                   4628:     
                   4629:   }
                   4630:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4631:   printf("\n");
                   4632:   fprintf(ficlog,"\n");
                   4633:   
                   4634: }
                   4635: 
                   4636: 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[] )
                   4637: 
                   4638: {
                   4639:   /* Covariances of health expectancies eij and of total life expectancies according
                   4640:      to initial status i, ei. .
                   4641:   */
                   4642:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   4643:   int nhstepma, nstepma; /* Decreasing with age */
                   4644:   double age, agelim, hf;
                   4645:   double ***p3matp, ***p3matm, ***varhe;
                   4646:   double **dnewm,**doldm;
                   4647:   double *xp, *xm;
                   4648:   double **gp, **gm;
                   4649:   double ***gradg, ***trgradg;
                   4650:   int theta;
                   4651: 
                   4652:   double eip, vip;
                   4653: 
                   4654:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   4655:   xp=vector(1,npar);
                   4656:   xm=vector(1,npar);
                   4657:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   4658:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   4659:   
                   4660:   pstamp(ficresstdeij);
                   4661:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   4662:   fprintf(ficresstdeij,"# Age");
                   4663:   for(i=1; i<=nlstate;i++){
                   4664:     for(j=1; j<=nlstate;j++)
                   4665:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   4666:     fprintf(ficresstdeij," e%1d. ",i);
                   4667:   }
                   4668:   fprintf(ficresstdeij,"\n");
                   4669: 
                   4670:   pstamp(ficrescveij);
                   4671:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   4672:   fprintf(ficrescveij,"# Age");
                   4673:   for(i=1; i<=nlstate;i++)
                   4674:     for(j=1; j<=nlstate;j++){
                   4675:       cptj= (j-1)*nlstate+i;
                   4676:       for(i2=1; i2<=nlstate;i2++)
                   4677:        for(j2=1; j2<=nlstate;j2++){
                   4678:          cptj2= (j2-1)*nlstate+i2;
                   4679:          if(cptj2 <= cptj)
                   4680:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   4681:        }
                   4682:     }
                   4683:   fprintf(ficrescveij,"\n");
                   4684:   
                   4685:   if(estepm < stepm){
                   4686:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4687:   }
                   4688:   else  hstepm=estepm;   
                   4689:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   4690:    * This is mainly to measure the difference between two models: for example
                   4691:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   4692:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   4693:    * progression in between and thus overestimating or underestimating according
                   4694:    * to the curvature of the survival function. If, for the same date, we 
                   4695:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   4696:    * to compare the new estimate of Life expectancy with the same linear 
                   4697:    * hypothesis. A more precise result, taking into account a more precise
                   4698:    * curvature will be obtained if estepm is as small as stepm. */
                   4699: 
                   4700:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4701:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4702:      nhstepm is the number of hstepm from age to agelim 
                   4703:      nstepm is the number of stepm from age to agelin. 
                   4704:      Look at hpijx to understand the reason of that which relies in memory size
                   4705:      and note for a fixed period like estepm months */
                   4706:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   4707:      survival function given by stepm (the optimization length). Unfortunately it
                   4708:      means that if the survival funtion is printed only each two years of age and if
                   4709:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4710:      results. So we changed our mind and took the option of the best precision.
                   4711:   */
                   4712:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4713: 
                   4714:   /* If stepm=6 months */
                   4715:   /* nhstepm age range expressed in number of stepm */
                   4716:   agelim=AGESUP;
                   4717:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   4718:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4719:   /* if (stepm >= YEARM) hstepm=1;*/
                   4720:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4721:   
                   4722:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4723:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4724:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   4725:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   4726:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   4727:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   4728: 
                   4729:   for (age=bage; age<=fage; age ++){ 
                   4730:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4731:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4732:     /* if (stepm >= YEARM) hstepm=1;*/
                   4733:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   4734:                
                   4735:     /* If stepm=6 months */
                   4736:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   4737:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   4738:     
                   4739:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4740:                
                   4741:     /* Computing  Variances of health expectancies */
                   4742:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   4743:        decrease memory allocation */
                   4744:     for(theta=1; theta <=npar; theta++){
                   4745:       for(i=1; i<=npar; i++){ 
                   4746:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4747:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   4748:       }
                   4749:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   4750:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   4751:                        
                   4752:       for(j=1; j<= nlstate; j++){
                   4753:        for(i=1; i<=nlstate; i++){
                   4754:          for(h=0; h<=nhstepm-1; h++){
                   4755:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   4756:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   4757:          }
                   4758:        }
                   4759:       }
                   4760:                        
                   4761:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   4762:        for(h=0; h<=nhstepm-1; h++){
                   4763:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   4764:        }
                   4765:     }/* End theta */
                   4766:     
                   4767:     
                   4768:     for(h=0; h<=nhstepm-1; h++)
                   4769:       for(j=1; j<=nlstate*nlstate;j++)
                   4770:        for(theta=1; theta <=npar; theta++)
                   4771:          trgradg[h][j][theta]=gradg[h][theta][j];
                   4772:     
                   4773:                
                   4774:     for(ij=1;ij<=nlstate*nlstate;ij++)
                   4775:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   4776:        varhe[ij][ji][(int)age] =0.;
                   4777:                
                   4778:     printf("%d|",(int)age);fflush(stdout);
                   4779:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   4780:     for(h=0;h<=nhstepm-1;h++){
                   4781:       for(k=0;k<=nhstepm-1;k++){
                   4782:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   4783:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   4784:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   4785:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   4786:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   4787:       }
                   4788:     }
                   4789:                
                   4790:     /* Computing expectancies */
                   4791:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   4792:     for(i=1; i<=nlstate;i++)
                   4793:       for(j=1; j<=nlstate;j++)
                   4794:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   4795:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   4796:                                        
                   4797:          /* 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]);*/
                   4798:                                        
                   4799:        }
                   4800:                
                   4801:     fprintf(ficresstdeij,"%3.0f",age );
                   4802:     for(i=1; i<=nlstate;i++){
                   4803:       eip=0.;
                   4804:       vip=0.;
                   4805:       for(j=1; j<=nlstate;j++){
                   4806:        eip += eij[i][j][(int)age];
                   4807:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   4808:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   4809:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   4810:       }
                   4811:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   4812:     }
                   4813:     fprintf(ficresstdeij,"\n");
                   4814:                
                   4815:     fprintf(ficrescveij,"%3.0f",age );
                   4816:     for(i=1; i<=nlstate;i++)
                   4817:       for(j=1; j<=nlstate;j++){
                   4818:        cptj= (j-1)*nlstate+i;
                   4819:        for(i2=1; i2<=nlstate;i2++)
                   4820:          for(j2=1; j2<=nlstate;j2++){
                   4821:            cptj2= (j2-1)*nlstate+i2;
                   4822:            if(cptj2 <= cptj)
                   4823:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   4824:          }
                   4825:       }
                   4826:     fprintf(ficrescveij,"\n");
                   4827:                
                   4828:   }
                   4829:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   4830:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   4831:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   4832:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   4833:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4834:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4835:   printf("\n");
                   4836:   fprintf(ficlog,"\n");
                   4837:        
                   4838:   free_vector(xm,1,npar);
                   4839:   free_vector(xp,1,npar);
                   4840:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   4841:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   4842:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   4843: }
                   4844:  
                   4845: /************ Variance ******************/
                   4846:  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[])
                   4847:  {
                   4848:    /* Variance of health expectancies */
                   4849:    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   4850:    /* double **newm;*/
                   4851:    /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   4852:   
                   4853:    /* int movingaverage(); */
                   4854:    double **dnewm,**doldm;
                   4855:    double **dnewmp,**doldmp;
                   4856:    int i, j, nhstepm, hstepm, h, nstepm ;
                   4857:    int k;
                   4858:    double *xp;
                   4859:    double **gp, **gm;  /* for var eij */
                   4860:    double ***gradg, ***trgradg; /*for var eij */
                   4861:    double **gradgp, **trgradgp; /* for var p point j */
                   4862:    double *gpp, *gmp; /* for var p point j */
                   4863:    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   4864:    double ***p3mat;
                   4865:    double age,agelim, hf;
                   4866:    /* double ***mobaverage; */
                   4867:    int theta;
                   4868:    char digit[4];
                   4869:    char digitp[25];
                   4870: 
                   4871:    char fileresprobmorprev[FILENAMELENGTH];
                   4872: 
                   4873:    if(popbased==1){
                   4874:      if(mobilav!=0)
                   4875:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   4876:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   4877:    }
                   4878:    else 
                   4879:      strcpy(digitp,"-STABLBASED_");
                   4880: 
                   4881:    /* if (mobilav!=0) { */
                   4882:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   4883:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   4884:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   4885:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   4886:    /*   } */
                   4887:    /* } */
                   4888: 
                   4889:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   4890:    sprintf(digit,"%-d",ij);
                   4891:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   4892:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   4893:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   4894:    strcat(fileresprobmorprev,fileresu);
                   4895:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   4896:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   4897:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   4898:    }
                   4899:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4900:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4901:    pstamp(ficresprobmorprev);
                   4902:    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);
                   4903:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   4904:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4905:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   4906:      for(i=1; i<=nlstate;i++)
                   4907:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   4908:    }  
                   4909:    fprintf(ficresprobmorprev,"\n");
                   4910:   
                   4911:    fprintf(ficgp,"\n# Routine varevsij");
                   4912:    fprintf(ficgp,"\nunset title \n");
                   4913:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   4914:    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");
                   4915:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   4916:    /*   } */
                   4917:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4918:    pstamp(ficresvij);
                   4919:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   4920:    if(popbased==1)
                   4921:      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);
                   4922:    else
                   4923:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   4924:    fprintf(ficresvij,"# Age");
                   4925:    for(i=1; i<=nlstate;i++)
                   4926:      for(j=1; j<=nlstate;j++)
                   4927:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   4928:    fprintf(ficresvij,"\n");
                   4929: 
                   4930:    xp=vector(1,npar);
                   4931:    dnewm=matrix(1,nlstate,1,npar);
                   4932:    doldm=matrix(1,nlstate,1,nlstate);
                   4933:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   4934:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4935: 
                   4936:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   4937:    gpp=vector(nlstate+1,nlstate+ndeath);
                   4938:    gmp=vector(nlstate+1,nlstate+ndeath);
                   4939:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   4940:   
                   4941:    if(estepm < stepm){
                   4942:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   4943:    }
                   4944:    else  hstepm=estepm;   
                   4945:    /* For example we decided to compute the life expectancy with the smallest unit */
                   4946:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4947:       nhstepm is the number of hstepm from age to agelim 
                   4948:       nstepm is the number of stepm from age to agelim. 
                   4949:       Look at function hpijx to understand why because of memory size limitations, 
                   4950:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   4951:       survival function given by stepm (the optimization length). Unfortunately it
                   4952:       means that if the survival funtion is printed every two years of age and if
                   4953:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4954:       results. So we changed our mind and took the option of the best precision.
                   4955:    */
                   4956:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4957:    agelim = AGESUP;
                   4958:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4959:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4960:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4961:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4962:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   4963:      gp=matrix(0,nhstepm,1,nlstate);
                   4964:      gm=matrix(0,nhstepm,1,nlstate);
                   4965:                
                   4966:                
                   4967:      for(theta=1; theta <=npar; theta++){
                   4968:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   4969:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4970:        }
                   4971:                        
                   4972:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   4973:                        
                   4974:        if (popbased==1) {
                   4975:         if(mobilav ==0){
                   4976:           for(i=1; i<=nlstate;i++)
                   4977:             prlim[i][i]=probs[(int)age][i][ij];
                   4978:         }else{ /* mobilav */ 
                   4979:           for(i=1; i<=nlstate;i++)
                   4980:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   4981:         }
                   4982:        }
                   4983:                        
                   4984:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
                   4985:        for(j=1; j<= nlstate; j++){
                   4986:         for(h=0; h<=nhstepm; h++){
                   4987:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   4988:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4989:         }
                   4990:        }
                   4991:        /* Next for computing probability of death (h=1 means
                   4992:          computed over hstepm matrices product = hstepm*stepm months) 
                   4993:          as a weighted average of prlim.
                   4994:        */
                   4995:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4996:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   4997:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   4998:        }    
                   4999:        /* end probability of death */
                   5000:                        
                   5001:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   5002:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   5003:                        
                   5004:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
                   5005:                        
                   5006:        if (popbased==1) {
                   5007:         if(mobilav ==0){
                   5008:           for(i=1; i<=nlstate;i++)
                   5009:             prlim[i][i]=probs[(int)age][i][ij];
                   5010:         }else{ /* mobilav */ 
                   5011:           for(i=1; i<=nlstate;i++)
                   5012:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5013:         }
                   5014:        }
                   5015:                        
                   5016:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   5017:                        
                   5018:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   5019:         for(h=0; h<=nhstepm; h++){
                   5020:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   5021:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5022:         }
                   5023:        }
                   5024:        /* This for computing probability of death (h=1 means
                   5025:          computed over hstepm matrices product = hstepm*stepm months) 
                   5026:          as a weighted average of prlim.
                   5027:        */
                   5028:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5029:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   5030:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   5031:        }    
                   5032:        /* end probability of death */
                   5033:                        
                   5034:        for(j=1; j<= nlstate; j++) /* vareij */
                   5035:         for(h=0; h<=nhstepm; h++){
                   5036:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   5037:         }
                   5038:                        
                   5039:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   5040:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   5041:        }
                   5042:                        
                   5043:      } /* End theta */
                   5044:                
                   5045:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   5046:                
                   5047:      for(h=0; h<=nhstepm; h++) /* veij */
                   5048:        for(j=1; j<=nlstate;j++)
                   5049:         for(theta=1; theta <=npar; theta++)
                   5050:           trgradg[h][j][theta]=gradg[h][theta][j];
                   5051:                
                   5052:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   5053:        for(theta=1; theta <=npar; theta++)
                   5054:         trgradgp[j][theta]=gradgp[theta][j];
                   5055:                
                   5056:                
                   5057:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5058:      for(i=1;i<=nlstate;i++)
                   5059:        for(j=1;j<=nlstate;j++)
                   5060:         vareij[i][j][(int)age] =0.;
                   5061:                
                   5062:      for(h=0;h<=nhstepm;h++){
                   5063:        for(k=0;k<=nhstepm;k++){
                   5064:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   5065:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   5066:         for(i=1;i<=nlstate;i++)
                   5067:           for(j=1;j<=nlstate;j++)
                   5068:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   5069:        }
                   5070:      }
                   5071:                
                   5072:      /* pptj */
                   5073:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   5074:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   5075:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   5076:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   5077:         varppt[j][i]=doldmp[j][i];
                   5078:      /* end ppptj */
                   5079:      /*  x centered again */
                   5080:                
                   5081:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
                   5082:                
                   5083:      if (popbased==1) {
                   5084:        if(mobilav ==0){
                   5085:         for(i=1; i<=nlstate;i++)
                   5086:           prlim[i][i]=probs[(int)age][i][ij];
                   5087:        }else{ /* mobilav */ 
                   5088:         for(i=1; i<=nlstate;i++)
                   5089:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   5090:        }
                   5091:      }
                   5092:                
                   5093:      /* This for computing probability of death (h=1 means
                   5094:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   5095:        as a weighted average of prlim.
                   5096:      */
                   5097:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   5098:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5099:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   5100:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   5101:      }    
                   5102:      /* end probability of death */
                   5103:                
                   5104:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   5105:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5106:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   5107:        for(i=1; i<=nlstate;i++){
                   5108:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   5109:        }
                   5110:      } 
                   5111:      fprintf(ficresprobmorprev,"\n");
                   5112:                
                   5113:      fprintf(ficresvij,"%.0f ",age );
                   5114:      for(i=1; i<=nlstate;i++)
                   5115:        for(j=1; j<=nlstate;j++){
                   5116:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   5117:        }
                   5118:      fprintf(ficresvij,"\n");
                   5119:      free_matrix(gp,0,nhstepm,1,nlstate);
                   5120:      free_matrix(gm,0,nhstepm,1,nlstate);
                   5121:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   5122:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   5123:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5124:    } /* End age */
                   5125:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   5126:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   5127:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   5128:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   5129:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   5130:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   5131:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   5132:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   5133:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   5134:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   5135:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5136:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5137:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   5138:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   5139:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   5140:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   5141:    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);
                   5142:    /*  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);
                   5143:     */
                   5144:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   5145:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   5146: 
                   5147:    free_vector(xp,1,npar);
                   5148:    free_matrix(doldm,1,nlstate,1,nlstate);
                   5149:    free_matrix(dnewm,1,nlstate,1,npar);
                   5150:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5151:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   5152:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5153:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5154:    fclose(ficresprobmorprev);
                   5155:    fflush(ficgp);
                   5156:    fflush(fichtm); 
                   5157:  }  /* end varevsij */
                   5158: 
                   5159: /************ Variance of prevlim ******************/
                   5160:  void varprevlim(char fileres[], double **varpl, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int *ncvyearp, int ij, char strstart[])
                   5161: {
                   5162:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   5163:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   5164: 
                   5165:   double **dnewm,**doldm;
                   5166:   int i, j, nhstepm, hstepm;
                   5167:   double *xp;
                   5168:   double *gp, *gm;
                   5169:   double **gradg, **trgradg;
                   5170:   double **mgm, **mgp;
                   5171:   double age,agelim;
                   5172:   int theta;
                   5173:   
                   5174:   pstamp(ficresvpl);
                   5175:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   5176:   fprintf(ficresvpl,"# Age");
                   5177:   for(i=1; i<=nlstate;i++)
                   5178:       fprintf(ficresvpl," %1d-%1d",i,i);
                   5179:   fprintf(ficresvpl,"\n");
                   5180: 
                   5181:   xp=vector(1,npar);
                   5182:   dnewm=matrix(1,nlstate,1,npar);
                   5183:   doldm=matrix(1,nlstate,1,nlstate);
                   5184:   
                   5185:   hstepm=1*YEARM; /* Every year of age */
                   5186:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   5187:   agelim = AGESUP;
                   5188:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5189:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5190:     if (stepm >= YEARM) hstepm=1;
                   5191:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   5192:     gradg=matrix(1,npar,1,nlstate);
                   5193:     mgp=matrix(1,npar,1,nlstate);
                   5194:     mgm=matrix(1,npar,1,nlstate);
                   5195:     gp=vector(1,nlstate);
                   5196:     gm=vector(1,nlstate);
                   5197: 
                   5198:     for(theta=1; theta <=npar; theta++){
                   5199:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   5200:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5201:       }
                   5202:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   5203:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   5204:       else
                   5205:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   5206:       for(i=1;i<=nlstate;i++){
                   5207:        gp[i] = prlim[i][i];
                   5208:        mgp[theta][i] = prlim[i][i];
                   5209:       }
                   5210:       for(i=1; i<=npar; i++) /* Computes gradient */
                   5211:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   5212:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   5213:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   5214:       else
                   5215:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   5216:       for(i=1;i<=nlstate;i++){
                   5217:        gm[i] = prlim[i][i];
                   5218:        mgm[theta][i] = prlim[i][i];
                   5219:       }
                   5220:       for(i=1;i<=nlstate;i++)
                   5221:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   5222:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   5223:     } /* End theta */
                   5224: 
                   5225:     trgradg =matrix(1,nlstate,1,npar);
                   5226: 
                   5227:     for(j=1; j<=nlstate;j++)
                   5228:       for(theta=1; theta <=npar; theta++)
                   5229:        trgradg[j][theta]=gradg[theta][j];
                   5230:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5231:     /*   printf("\nmgm mgp %d ",(int)age); */
                   5232:     /*   for(j=1; j<=nlstate;j++){ */
                   5233:     /*         printf(" %d ",j); */
                   5234:     /*         for(theta=1; theta <=npar; theta++) */
                   5235:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   5236:     /*         printf("\n "); */
                   5237:     /*   } */
                   5238:     /* } */
                   5239:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5240:     /*   printf("\n gradg %d ",(int)age); */
                   5241:     /*   for(j=1; j<=nlstate;j++){ */
                   5242:     /*         printf("%d ",j); */
                   5243:     /*         for(theta=1; theta <=npar; theta++) */
                   5244:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   5245:     /*         printf("\n "); */
                   5246:     /*   } */
                   5247:     /* } */
                   5248: 
                   5249:     for(i=1;i<=nlstate;i++)
                   5250:       varpl[i][(int)age] =0.;
                   5251:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   5252:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5253:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   5254:     }else{
                   5255:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5256:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   5257:     }
                   5258:     for(i=1;i<=nlstate;i++)
                   5259:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   5260: 
                   5261:     fprintf(ficresvpl,"%.0f ",age );
                   5262:     for(i=1; i<=nlstate;i++)
                   5263:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   5264:     fprintf(ficresvpl,"\n");
                   5265:     free_vector(gp,1,nlstate);
                   5266:     free_vector(gm,1,nlstate);
                   5267:     free_matrix(mgm,1,npar,1,nlstate);
                   5268:     free_matrix(mgp,1,npar,1,nlstate);
                   5269:     free_matrix(gradg,1,npar,1,nlstate);
                   5270:     free_matrix(trgradg,1,nlstate,1,npar);
                   5271:   } /* End age */
                   5272: 
                   5273:   free_vector(xp,1,npar);
                   5274:   free_matrix(doldm,1,nlstate,1,npar);
                   5275:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   5276: 
                   5277: }
                   5278: 
                   5279: /************ Variance of one-step probabilities  ******************/
                   5280: 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[])
                   5281:  {
                   5282:    int i, j=0,  k1, l1, tj;
                   5283:    int k2, l2, j1,  z1;
                   5284:    int k=0, l;
                   5285:    int first=1, first1, first2;
                   5286:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   5287:    double **dnewm,**doldm;
                   5288:    double *xp;
                   5289:    double *gp, *gm;
                   5290:    double **gradg, **trgradg;
                   5291:    double **mu;
                   5292:    double age, cov[NCOVMAX+1];
                   5293:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   5294:    int theta;
                   5295:    char fileresprob[FILENAMELENGTH];
                   5296:    char fileresprobcov[FILENAMELENGTH];
                   5297:    char fileresprobcor[FILENAMELENGTH];
                   5298:    double ***varpij;
                   5299: 
                   5300:    strcpy(fileresprob,"PROB_"); 
                   5301:    strcat(fileresprob,fileres);
                   5302:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   5303:      printf("Problem with resultfile: %s\n", fileresprob);
                   5304:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   5305:    }
                   5306:    strcpy(fileresprobcov,"PROBCOV_"); 
                   5307:    strcat(fileresprobcov,fileresu);
                   5308:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   5309:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   5310:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   5311:    }
                   5312:    strcpy(fileresprobcor,"PROBCOR_"); 
                   5313:    strcat(fileresprobcor,fileresu);
                   5314:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   5315:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   5316:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   5317:    }
                   5318:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5319:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5320:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5321:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5322:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5323:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5324:    pstamp(ficresprob);
                   5325:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   5326:    fprintf(ficresprob,"# Age");
                   5327:    pstamp(ficresprobcov);
                   5328:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   5329:    fprintf(ficresprobcov,"# Age");
                   5330:    pstamp(ficresprobcor);
                   5331:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   5332:    fprintf(ficresprobcor,"# Age");
                   5333: 
                   5334: 
                   5335:    for(i=1; i<=nlstate;i++)
                   5336:      for(j=1; j<=(nlstate+ndeath);j++){
                   5337:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   5338:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   5339:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   5340:      }  
                   5341:    /* fprintf(ficresprob,"\n");
                   5342:       fprintf(ficresprobcov,"\n");
                   5343:       fprintf(ficresprobcor,"\n");
                   5344:    */
                   5345:    xp=vector(1,npar);
                   5346:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5347:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   5348:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   5349:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   5350:    first=1;
                   5351:    fprintf(ficgp,"\n# Routine varprob");
                   5352:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   5353:    fprintf(fichtm,"\n");
                   5354: 
                   5355:    fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of one-step probabilities (drawings)</a></h4> this page is important in order to visualize confidence intervals and especially correlation between disability and recovery, or more generally, way in and way back.</li>\n",optionfilehtmcov);
                   5356:    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);
                   5357:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
                   5358: and drawn. It helps understanding how is the covariance between two incidences.\
                   5359:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   5360:    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. \
                   5361: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   5362: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   5363: standard deviations wide on each axis. <br>\
                   5364:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   5365:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   5366: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   5367: 
                   5368:    cov[1]=1;
                   5369:    /* tj=cptcoveff; */
                   5370:    tj = (int) pow(2,cptcoveff);
                   5371:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   5372:    j1=0;
1.2     ! brouard  5373:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.1       brouard  5374:      if  (cptcovn>0) {
                   5375:        fprintf(ficresprob, "\n#********** Variable "); 
                   5376:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   5377:        fprintf(ficresprob, "**********\n#\n");
                   5378:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   5379:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   5380:        fprintf(ficresprobcov, "**********\n#\n");
                   5381:                        
                   5382:        fprintf(ficgp, "\n#********** Variable "); 
                   5383:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   5384:        fprintf(ficgp, "**********\n#\n");
                   5385:                        
                   5386:                        
                   5387:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   5388:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   5389:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   5390:                        
                   5391:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   5392:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   5393:        fprintf(ficresprobcor, "**********\n#");    
                   5394:        if(invalidvarcomb[j1]){
                   5395:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   5396:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   5397:         continue;
                   5398:        }
                   5399:      }
                   5400:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   5401:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5402:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   5403:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   5404:      for (age=bage; age<=fage; age ++){ 
                   5405:        cov[2]=age;
                   5406:        if(nagesqr==1)
                   5407:         cov[3]= age*age;
                   5408:        for (k=1; k<=cptcovn;k++) {
                   5409:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   5410:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   5411:                                                                    * 1  1 1 1 1
                   5412:                                                                    * 2  2 1 1 1
                   5413:                                                                    * 3  1 2 1 1
                   5414:                                                                    */
                   5415:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   5416:        }
                   5417:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   5418:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   5419:        for (k=1; k<=cptcovprod;k++)
                   5420:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   5421:                        
                   5422:                        
                   5423:        for(theta=1; theta <=npar; theta++){
                   5424:         for(i=1; i<=npar; i++)
                   5425:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   5426:                                
                   5427:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   5428:                                
                   5429:         k=0;
                   5430:         for(i=1; i<= (nlstate); i++){
                   5431:           for(j=1; j<=(nlstate+ndeath);j++){
                   5432:             k=k+1;
                   5433:             gp[k]=pmmij[i][j];
                   5434:           }
                   5435:         }
                   5436:                                
                   5437:         for(i=1; i<=npar; i++)
                   5438:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   5439:                                
                   5440:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   5441:         k=0;
                   5442:         for(i=1; i<=(nlstate); i++){
                   5443:           for(j=1; j<=(nlstate+ndeath);j++){
                   5444:             k=k+1;
                   5445:             gm[k]=pmmij[i][j];
                   5446:           }
                   5447:         }
                   5448:                                
                   5449:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   5450:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   5451:        }
                   5452: 
                   5453:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   5454:         for(theta=1; theta <=npar; theta++)
                   5455:           trgradg[j][theta]=gradg[theta][j];
                   5456:                        
                   5457:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   5458:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   5459:                        
                   5460:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   5461:                        
                   5462:        k=0;
                   5463:        for(i=1; i<=(nlstate); i++){
                   5464:         for(j=1; j<=(nlstate+ndeath);j++){
                   5465:           k=k+1;
                   5466:           mu[k][(int) age]=pmmij[i][j];
                   5467:         }
                   5468:        }
                   5469:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   5470:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   5471:           varpij[i][j][(int)age] = doldm[i][j];
                   5472:                        
                   5473:        /*printf("\n%d ",(int)age);
                   5474:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5475:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5476:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5477:         }*/
                   5478:                        
                   5479:        fprintf(ficresprob,"\n%d ",(int)age);
                   5480:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   5481:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   5482:                        
                   5483:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   5484:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   5485:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5486:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   5487:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   5488:        }
                   5489:        i=0;
                   5490:        for (k=1; k<=(nlstate);k++){
                   5491:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   5492:           i++;
                   5493:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   5494:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   5495:           for (j=1; j<=i;j++){
                   5496:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   5497:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   5498:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   5499:           }
                   5500:         }
                   5501:        }/* end of loop for state */
                   5502:      } /* end of loop for age */
                   5503:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   5504:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   5505:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   5506:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   5507:     
                   5508:      /* Confidence intervalle of pij  */
                   5509:      /*
                   5510:        fprintf(ficgp,"\nunset parametric;unset label");
                   5511:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   5512:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   5513:        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);
                   5514:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   5515:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   5516:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   5517:      */
                   5518:                
                   5519:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   5520:      first1=1;first2=2;
                   5521:      for (k2=1; k2<=(nlstate);k2++){
                   5522:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   5523:         if(l2==k2) continue;
                   5524:         j=(k2-1)*(nlstate+ndeath)+l2;
                   5525:         for (k1=1; k1<=(nlstate);k1++){
                   5526:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   5527:             if(l1==k1) continue;
                   5528:             i=(k1-1)*(nlstate+ndeath)+l1;
                   5529:             if(i<=j) continue;
                   5530:             for (age=bage; age<=fage; age ++){ 
                   5531:               if ((int)age %5==0){
                   5532:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   5533:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   5534:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   5535:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   5536:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   5537:                 c12=cv12/sqrt(v1*v2);
                   5538:                 /* Computing eigen value of matrix of covariance */
                   5539:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5540:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5541:                 if ((lc2 <0) || (lc1 <0) ){
                   5542:                   if(first2==1){
                   5543:                     first1=0;
                   5544:                     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);
                   5545:                   }
                   5546:                   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);
                   5547:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   5548:                   /* lc2=fabs(lc2); */
                   5549:                 }
                   5550:                                                                
                   5551:                 /* Eigen vectors */
                   5552:                 v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   5553:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   5554:                 v21=(lc1-v1)/cv12*v11;
                   5555:                 v12=-v21;
                   5556:                 v22=v11;
                   5557:                 tnalp=v21/v11;
                   5558:                 if(first1==1){
                   5559:                   first1=0;
                   5560:                   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);
                   5561:                 }
                   5562:                 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);
                   5563:                 /*printf(fignu*/
                   5564:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   5565:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   5566:                 if(first==1){
                   5567:                   first=0;
                   5568:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   5569:                   fprintf(ficgp,"\nset parametric;unset label");
                   5570:                   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);
                   5571:                   fprintf(ficgp,"\nset ter svg size 640, 480");
                   5572:                   fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
                   5573:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
                   5574: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
                   5575:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   5576:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5577:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5578:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   5579:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5580:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   5581:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   5582:                   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",      \
                   5583:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                                                         \
                   5584:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   5585:                 }else{
                   5586:                   first=0;
                   5587:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   5588:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   5589:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   5590:                   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", \
                   5591:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                 \
                   5592:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   5593:                 }/* if first */
                   5594:               } /* age mod 5 */
                   5595:             } /* end loop age */
                   5596:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5597:             first=1;
                   5598:           } /*l12 */
                   5599:         } /* k12 */
                   5600:        } /*l1 */
                   5601:      }/* k1 */
                   5602:    }  /* loop on combination of covariates j1 */
                   5603:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   5604:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   5605:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   5606:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   5607:    free_vector(xp,1,npar);
                   5608:    fclose(ficresprob);
                   5609:    fclose(ficresprobcov);
                   5610:    fclose(ficresprobcor);
                   5611:    fflush(ficgp);
                   5612:    fflush(fichtmcov);
                   5613:  }
                   5614: 
                   5615: 
                   5616: /******************* Printing html file ***********/
                   5617: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
                   5618:                  int lastpass, int stepm, int weightopt, char model[],\
                   5619:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   5620:                  int popforecast, int prevfcast, int backcast, int estepm , \
                   5621:                  double jprev1, double mprev1,double anprev1, double dateprev1, \
                   5622:                  double jprev2, double mprev2,double anprev2, double dateprev2){
                   5623:   int jj1, k1, i1, cpt;
                   5624: 
                   5625:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   5626:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   5627: </ul>");
                   5628:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   5629:    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",
                   5630:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   5631:    fprintf(fichtm,"<li> - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> (html file) ",
                   5632:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   5633:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
                   5634:    fprintf(fichtm,"\
                   5635:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   5636:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
                   5637:    fprintf(fichtm,"\
                   5638:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   5639:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   5640:    fprintf(fichtm,"\
                   5641:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   5642:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
                   5643:    fprintf(fichtm,"\
                   5644:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   5645:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   5646:    fprintf(fichtm,"\
                   5647:  - (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): \
                   5648:    <a href=\"%s\">%s</a> <br>\n",
                   5649:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
                   5650:    if(prevfcast==1){
                   5651:      fprintf(fichtm,"\
                   5652:  - Prevalence projections by age and states:                           \
                   5653:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
                   5654:    }
                   5655: 
                   5656:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   5657: 
                   5658:    m=pow(2,cptcoveff);
                   5659:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   5660: 
                   5661:    jj1=0;
                   5662:    for(k1=1; k1<=m;k1++){
                   5663: 
                   5664:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   5665:      jj1++;
                   5666:      if (cptcovn > 0) {
                   5667:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   5668:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   5669:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
                   5670:         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
                   5671:        }
                   5672:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   5673:        if(invalidvarcomb[k1]){
                   5674:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   5675:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   5676:         continue;
                   5677:        }
                   5678:      }
                   5679:      /* aij, bij */
                   5680:      fprintf(fichtm,"<br>- Logit model (yours is: 1+age+%s), for example: logit(pij)=log(pij/pii)= aij+ bij age + V1 age + etc. as a function of age: <a href=\"%s_%d-1.svg\">%s_%d-1.svg</a><br> \
                   5681: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
                   5682:      /* Pij */
                   5683:      fprintf(fichtm,"<br>\n- P<sub>ij</sub> or conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s_%d-2.svg\">%s_%d-2.svg</a><br> \
                   5684: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
                   5685:      /* Quasi-incidences */
                   5686:      fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
                   5687:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
                   5688:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
                   5689: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
                   5690: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
                   5691:      /* Survival functions (period) in state j */
                   5692:      for(cpt=1; cpt<=nlstate;cpt++){
                   5693:        fprintf(fichtm,"<br>\n- Survival functions in state %d. Or probability to survive in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> \
                   5694: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
                   5695:      }
                   5696:      /* State specific survival functions (period) */
                   5697:      for(cpt=1; cpt<=nlstate;cpt++){
                   5698:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
                   5699:  Or probability to survive in various states (1 to %d) being in state %d at different ages.    \
                   5700:  <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> <img src=\"%s_%d-%d.svg\">", cpt, nlstate, cpt, subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1);
                   5701:      }
                   5702:      /* Period (stable) prevalence in each health state */
                   5703:      for(cpt=1; cpt<=nlstate;cpt++){
                   5704:        fprintf(fichtm,"<br>\n- Convergence to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a><br> \
                   5705: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
                   5706:      }
                   5707:      if(backcast==1){
                   5708:        /* Period (stable) back prevalence in each health state */
                   5709:        for(cpt=1; cpt<=nlstate;cpt++){
                   5710:         fprintf(fichtm,"<br>\n- Convergence to period (stable) back prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a><br> \
                   5711: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1);
                   5712:        }
                   5713:      }
                   5714:      if(prevfcast==1){
                   5715:        /* Projection of prevalence up to period (stable) prevalence in each health state */
                   5716:        for(cpt=1; cpt<=nlstate;cpt++){
                   5717:         fprintf(fichtm,"<br>\n- Projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f) up to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> \
                   5718: <img src=\"%s_%d-%d.svg\">", dateprev1, dateprev2, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1);
                   5719:        }
                   5720:      }
                   5721:         
                   5722:      for(cpt=1; cpt<=nlstate;cpt++) {
                   5723:        fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies in each alive state (1 to %d) (or area under each survival functions): <a href=\"%s_%d%d.svg\">%s_%d%d.svg</a> <br> \
                   5724: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
                   5725:      }
                   5726:      /* } /\* end i1 *\/ */
                   5727:    }/* End k1 */
                   5728:    fprintf(fichtm,"</ul>");
                   5729: 
                   5730:    fprintf(fichtm,"\
                   5731: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
                   5732:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
                   5733:  - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
                   5734: But because parameters are usually highly correlated (a higher incidence of disability \
                   5735: and a higher incidence of recovery can give very close observed transition) it might \
                   5736: be very useful to look not only at linear confidence intervals estimated from the \
                   5737: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   5738: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   5739: covariance matrix of the one-step probabilities. \
                   5740: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
                   5741: 
                   5742:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   5743:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   5744:    fprintf(fichtm,"\
                   5745:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   5746:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
                   5747: 
                   5748:    fprintf(fichtm,"\
                   5749:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   5750:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   5751:    fprintf(fichtm,"\
                   5752:  - 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): \
                   5753:    <a href=\"%s\">%s</a> <br>\n</li>",
                   5754:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
                   5755:    fprintf(fichtm,"\
                   5756:  - (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): \
                   5757:    <a href=\"%s\">%s</a> <br>\n</li>",
                   5758:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
                   5759:    fprintf(fichtm,"\
                   5760:  - Variances and covariances of health expectancies by age. Status (i) based health expectancies (in state j), e<sup>ij</sup> are weighted by the period prevalences in each state i (if popbased=1, an additional computation is done using the cross-sectional prevalences, i.e population based) (estepm=%d months): <a href=\"%s\">%s</a><br>\n",
                   5761:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   5762:    fprintf(fichtm,"\
                   5763:  - 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",
                   5764:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   5765:    fprintf(fichtm,"\
                   5766:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
                   5767:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   5768: 
                   5769: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   5770: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   5771: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   5772: /*     <br>",fileres,fileres,fileres,fileres); */
                   5773: /*  else  */
                   5774: /*    fprintf(fichtm,"\n No population forecast: popforecast = %d (instead of 1) or stepm = %d (instead of 1) or model=%s (instead of .)<br><br></li>\n",popforecast, stepm, model); */
                   5775:    fflush(fichtm);
                   5776:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   5777: 
                   5778:    m=pow(2,cptcoveff);
                   5779:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   5780: 
                   5781:    jj1=0;
                   5782:    for(k1=1; k1<=m;k1++){
                   5783:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   5784:      jj1++;
                   5785:      if (cptcovn > 0) {
                   5786:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   5787:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   5788:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
                   5789:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   5790: 
                   5791:        if(invalidvarcomb[k1]){
                   5792:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   5793:         continue;
                   5794:        }
                   5795:      }
                   5796:      for(cpt=1; cpt<=nlstate;cpt++) {
                   5797:        fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
                   5798: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d.svg\"> %s_%d-%d.svg</a>\n <br>\
                   5799: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);  
                   5800:      }
                   5801:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
                   5802: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   5803: true period expectancies (those weighted with period prevalences are also\
                   5804:  drawn in addition to the population based expectancies computed using\
                   5805:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg</a>\n<br>\
                   5806: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
                   5807:      /* } /\* end i1 *\/ */
                   5808:    }/* End k1 */
                   5809:    fprintf(fichtm,"</ul>");
                   5810:    fflush(fichtm);
                   5811: }
                   5812: 
                   5813: /******************* Gnuplot file **************/
1.2     ! brouard  5814: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
1.1       brouard  5815: 
                   5816:   char dirfileres[132],optfileres[132];
                   5817:   char gplotcondition[132];
                   5818:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
                   5819:   int lv=0, vlv=0, kl=0;
                   5820:   int ng=0;
                   5821:   int vpopbased;
                   5822:   int ioffset; /* variable offset for columns */
                   5823: 
                   5824: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   5825: /*     printf("Problem with file %s",optionfilegnuplot); */
                   5826: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   5827: /*   } */
                   5828: 
                   5829:   /*#ifdef windows */
                   5830:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5831:   /*#endif */
                   5832:   m=pow(2,cptcoveff);
                   5833: 
                   5834:   /* Contribution to likelihood */
                   5835:   /* Plot the probability implied in the likelihood */
                   5836:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   5837:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   5838:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   5839:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   5840: /* nice for mle=4 plot by number of matrix products.
                   5841:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   5842: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
                   5843:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   5844:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   5845:   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));
                   5846:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   5847:   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));
                   5848:   for (i=1; i<= nlstate ; i ++) {
                   5849:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   5850:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   5851:     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);
                   5852:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   5853:       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);
                   5854:     }
                   5855:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   5856:   }
                   5857:   /* 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 */               
                   5858:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   5859:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   5860:   fprintf(ficgp,"\nset out;unset log\n");
                   5861:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   5862: 
                   5863:   strcpy(dirfileres,optionfilefiname);
                   5864:   strcpy(optfileres,"vpl");
                   5865:   /* 1eme*/
                   5866:   for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
                   5867:     for (k1=1; k1<= m ; k1 ++) { /* For each valid combination of covariate */
                   5868:       /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   5869:       fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
                   5870:       for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   5871:        lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   5872:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5873:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5874:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5875:        vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   5876:        /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
                   5877:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   5878:       }
                   5879:       fprintf(ficgp,"\n#\n");
                   5880:       if(invalidvarcomb[k1]){
                   5881:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   5882:        continue;
                   5883:       }
                   5884: 
                   5885:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
                   5886:       fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
                   5887:       fprintf(ficgp,"set xlabel \"Age\" \n\
                   5888: set ylabel \"Probability\" \n  \
                   5889: set ter svg size 640, 480\n    \
                   5890: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
                   5891:                        
                   5892:       for (i=1; i<= nlstate ; i ++) {
                   5893:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5894:        else        fprintf(ficgp," %%*lf (%%*lf)");
                   5895:       }
                   5896:       fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1);
                   5897:       for (i=1; i<= nlstate ; i ++) {
                   5898:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5899:        else fprintf(ficgp," %%*lf (%%*lf)");
                   5900:       } 
                   5901:       fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1); 
                   5902:       for (i=1; i<= nlstate ; i ++) {
                   5903:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5904:        else fprintf(ficgp," %%*lf (%%*lf)");
                   5905:       }  
                   5906:       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));
                   5907:       if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
                   5908:        /* 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); */
                   5909:        fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1 */
                   5910:        if(cptcoveff ==0){
                   5911:          fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line ",  2+(cpt-1),  cpt );
                   5912:        }else{
                   5913:          kl=0;
                   5914:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   5915:            lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   5916:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5917:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5918:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5919:            vlv= nbcode[Tvaraff[k]][lv];
                   5920:            kl++;
                   5921:            /* 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 *\/ */
                   5922:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   5923:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   5924:            /* ''  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*/
                   5925:            if(k==cptcoveff){
                   5926:              fprintf(ficgp,"$%d==%d && $%d==%d)? $%d : 1/0) t 'Backward prevalence in state %d' with line ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv], \
                   5927:                      6+(cpt-1),  cpt );
                   5928:            }else{
                   5929:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   5930:              kl++;
                   5931:            }
                   5932:          } /* end covariate */
                   5933:        } /* end if no covariate */
                   5934:       } /* end if backcast */
                   5935:       fprintf(ficgp,"\nset out \n");
                   5936:     } /* k1 */
                   5937:   } /* cpt */
                   5938:   /*2 eme*/
                   5939:   for (k1=1; k1<= m ; k1 ++) { 
                   5940: 
                   5941:     fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
                   5942:     for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5943:       lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5944:       /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5945:       /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5946:       /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5947:       vlv= nbcode[Tvaraff[k]][lv];
                   5948:       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   5949:     }
                   5950:     fprintf(ficgp,"\n#\n");
                   5951:     if(invalidvarcomb[k1]){
                   5952:       fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   5953:       continue;
                   5954:     }
                   5955:                        
                   5956:     fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
                   5957:     for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   5958:       if(vpopbased==0)
                   5959:        fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   5960:       else
                   5961:        fprintf(ficgp,"\nreplot ");
                   5962:       for (i=1; i<= nlstate+1 ; i ++) {
                   5963:        k=2*i;
                   5964:        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ?$4 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1, vpopbased);
                   5965:        for (j=1; j<= nlstate+1 ; j ++) {
                   5966:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5967:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5968:        }   
                   5969:        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   5970:        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   5971:        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ? $4-$5*2 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1,vpopbased);
                   5972:        for (j=1; j<= nlstate+1 ; j ++) {
                   5973:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5974:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5975:        }   
                   5976:        fprintf(ficgp,"\" t\"\" w l lt 0,");
                   5977:        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ? $4+$5*2 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1,vpopbased);
                   5978:        for (j=1; j<= nlstate+1 ; j ++) {
                   5979:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5980:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5981:        }   
                   5982:        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   5983:        else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   5984:       } /* state */
                   5985:     } /* vpopbased */
                   5986:     fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
                   5987:   } /* k1 */
                   5988:        
                   5989:        
                   5990:   /*3eme*/
                   5991:   for (k1=1; k1<= m ; k1 ++) { 
                   5992: 
                   5993:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   5994:       fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  cov=%d state=%d",k1, cpt);
                   5995:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5996:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5997:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5998:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5999:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6000:        vlv= nbcode[Tvaraff[k]][lv];
                   6001:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6002:       }
                   6003:       fprintf(ficgp,"\n#\n");
                   6004:       if(invalidvarcomb[k1]){
                   6005:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6006:        continue;
                   6007:       }
                   6008:                        
                   6009:       /*       k=2+nlstate*(2*cpt-2); */
                   6010:       k=2+(nlstate+1)*(cpt-1);
                   6011:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
                   6012:       fprintf(ficgp,"set ter svg size 640, 480\n\
                   6013: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileresu,"E_"),k1-1,k1-1,k,cpt);
                   6014:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   6015:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   6016:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   6017:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   6018:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   6019:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   6020:                                
                   6021:       */
                   6022:       for (i=1; i< nlstate ; i ++) {
                   6023:        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+i,cpt,i+1);
                   6024:        /*      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);*/
                   6025:                                
                   6026:       } 
                   6027:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
                   6028:     }
                   6029:   }
                   6030:   
                   6031:   /* 4eme */
                   6032:   /* Survival functions (period) from state i in state j by initial state i */
                   6033:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   6034: 
                   6035:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   6036:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   6037:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6038:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6039:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6040:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6041:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6042:        vlv= nbcode[Tvaraff[k]][lv];
                   6043:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6044:       }
                   6045:       fprintf(ficgp,"\n#\n");
                   6046:       if(invalidvarcomb[k1]){
                   6047:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6048:        continue;
                   6049:       }
                   6050:                        
                   6051:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
                   6052:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   6053: set ter svg size 640, 480\n                                                                                                                                                                                    \
                   6054: unset log y\n                                                                                                                                                                                                                                          \
                   6055: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   6056:       k=3;
                   6057:       for (i=1; i<= nlstate ; i ++){
                   6058:        if(i==1){
                   6059:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6060:        }else{
                   6061:          fprintf(ficgp,", '' ");
                   6062:        }
                   6063:        l=(nlstate+ndeath)*(i-1)+1;
                   6064:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6065:        for (j=2; j<= nlstate+ndeath ; j ++)
                   6066:          fprintf(ficgp,"+$%d",k+l+j-1);
                   6067:        fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   6068:       } /* nlstate */
                   6069:       fprintf(ficgp,"\nset out\n");
                   6070:     } /* end cpt state*/ 
                   6071:   } /* end covariate */  
                   6072:        
                   6073: /* 5eme */
                   6074:   /* Survival functions (period) from state i in state j by final state j */
                   6075:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
                   6076:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.2     ! brouard  6077:                        
1.1       brouard  6078:       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);
                   6079:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6080:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6081:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6082:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6083:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6084:        vlv= nbcode[Tvaraff[k]][lv];
                   6085:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6086:       }
                   6087:       fprintf(ficgp,"\n#\n");
                   6088:       if(invalidvarcomb[k1]){
1.2     ! brouard  6089:                                fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
        !          6090:                                continue;
1.1       brouard  6091:       }
                   6092:                        
                   6093:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
                   6094:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   6095: set ter svg size 640, 480\n                                                                                                                                                                                    \
                   6096: unset log y\n                                                                                                                                                                                                                                          \
                   6097: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   6098:       k=3;
                   6099:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
1.2     ! brouard  6100:                                if(j==1)
        !          6101:                                        fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
        !          6102:                                else
        !          6103:                                        fprintf(ficgp,", '' ");
        !          6104:                                l=(nlstate+ndeath)*(cpt-1) +j;
        !          6105:                                fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
        !          6106:                                /* for (i=2; i<= nlstate+ndeath ; i ++) */
        !          6107:                                /*   fprintf(ficgp,"+$%d",k+l+i-1); */
        !          6108:                                fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
1.1       brouard  6109:       } /* nlstate */
                   6110:       fprintf(ficgp,", '' ");
                   6111:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   6112:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
1.2     ! brouard  6113:                                l=(nlstate+ndeath)*(cpt-1) +j;
        !          6114:                                if(j < nlstate)
        !          6115:                                        fprintf(ficgp,"$%d +",k+l);
        !          6116:                                else
        !          6117:                                        fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
1.1       brouard  6118:       }
                   6119:       fprintf(ficgp,"\nset out\n");
                   6120:     } /* end cpt state*/ 
                   6121:   } /* end covariate */  
                   6122:        
                   6123: /* 6eme */
                   6124:   /* CV preval stable (period) for each covariate */
                   6125:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
                   6126:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.2     ! brouard  6127:                        
1.1       brouard  6128:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   6129:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6130:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6131:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6132:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6133:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6134:        vlv= nbcode[Tvaraff[k]][lv];
                   6135:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6136:       }
                   6137:       fprintf(ficgp,"\n#\n");
                   6138:       if(invalidvarcomb[k1]){
1.2     ! brouard  6139:                                fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
        !          6140:                                continue;
1.1       brouard  6141:       }
1.2     ! brouard  6142:                        
1.1       brouard  6143:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
                   6144:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.2     ! brouard  6145: set ter svg size 640, 480\n                                                                                                                                                                             \
        !          6146: unset log y\n                                                                                                                                                                                                                                   \
1.1       brouard  6147: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   6148:       k=3; /* Offset */
                   6149:       for (i=1; i<= nlstate ; i ++){
1.2     ! brouard  6150:                                if(i==1)
        !          6151:                                        fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
        !          6152:                                else
        !          6153:                                        fprintf(ficgp,", '' ");
        !          6154:                                l=(nlstate+ndeath)*(i-1)+1;
        !          6155:                                fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
        !          6156:                                for (j=2; j<= nlstate ; j ++)
        !          6157:                                        fprintf(ficgp,"+$%d",k+l+j-1);
        !          6158:                                fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.1       brouard  6159:       } /* nlstate */
                   6160:       fprintf(ficgp,"\nset out\n");
                   6161:     } /* end cpt state*/ 
                   6162:   } /* end covariate */  
1.2     ! brouard  6163:        
        !          6164:        
1.1       brouard  6165: /* 7eme */
                   6166:   if(backcast == 1){
                   6167:     /* CV back preval stable (period) for each covariate */
                   6168:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
                   6169:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   6170:        fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   6171:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6172:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6173:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6174:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6175:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.2     ! brouard  6176:                                        vlv= nbcode[Tvaraff[k]][lv];
        !          6177:                                        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
        !          6178:                                }
        !          6179:                                fprintf(ficgp,"\n#\n");
        !          6180:                                if(invalidvarcomb[k1]){
        !          6181:                                        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
        !          6182:                                        continue;
        !          6183:                                }
1.1       brouard  6184:                                
1.2     ! brouard  6185:                                fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1);
        !          6186:                                fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.1       brouard  6187: set ter svg size 640, 480\n                                                                                                                                                                                    \
                   6188: unset log y\n                                                                                                                                                                                                                                          \
                   6189: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.2     ! brouard  6190:                                k=3; /* Offset */
        !          6191:                                for (i=1; i<= nlstate ; i ++){
        !          6192:                                        if(i==1)
        !          6193:                                                fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
        !          6194:                                        else
        !          6195:                                                fprintf(ficgp,", '' ");
        !          6196:                                        /* l=(nlstate+ndeath)*(i-1)+1; */
        !          6197:                                        l=(nlstate+ndeath)*(cpt-1)+1;
        !          6198:                                        /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
        !          6199:                                        /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
        !          6200:                                        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */
        !          6201:                                        /* for (j=2; j<= nlstate ; j ++) */
        !          6202:                                        /*      fprintf(ficgp,"+$%d",k+l+j-1); */
        !          6203:                                        /*      /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
        !          6204:                                        fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
        !          6205:                                } /* nlstate */
        !          6206:                                fprintf(ficgp,"\nset out\n");
1.1       brouard  6207:       } /* end cpt state*/ 
                   6208:     } /* end covariate */  
                   6209:   } /* End if backcast */
                   6210:   
                   6211:   /* 8eme */
                   6212:   if(prevfcast==1){
                   6213:     /* Projection from cross-sectional to stable (period) for each covariate */
                   6214:     
                   6215:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
                   6216:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   6217:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
                   6218:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   6219:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   6220:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6221:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6222:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6223:          vlv= nbcode[Tvaraff[k]][lv];
                   6224:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6225:        }
                   6226:        fprintf(ficgp,"\n#\n");
                   6227:        if(invalidvarcomb[k1]){
                   6228:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6229:          continue;
                   6230:        }
                   6231:                                
1.2     ! brouard  6232:                                fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
        !          6233:                                fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
        !          6234:                                fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
        !          6235: set ter svg size 640, 480\n                                                                                                                                                                                    \
        !          6236: unset log y\n                                                                                                                                                                                                                                          \
1.1       brouard  6237: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   6238:        for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   6239:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6240:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6241:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6242:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6243:          if(i==1){
                   6244:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   6245:          }else{
                   6246:            fprintf(ficgp,",\\\n '' ");
                   6247:          }
                   6248:          if(cptcoveff ==0){ /* No covariate */
                   6249:            ioffset=2; /* Age is in 2 */
                   6250:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6251:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6252:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6253:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6254:            fprintf(ficgp," u %d:(", ioffset); 
                   6255:            if(i==nlstate+1)
                   6256:              fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ",                      \
                   6257:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6258:            else
                   6259:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",                      \
                   6260:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6261:          }else{ /* more than 2 covariates */
                   6262:            if(cptcoveff ==1){
                   6263:              ioffset=4; /* Age is in 4 */
                   6264:            }else{
                   6265:              ioffset=6; /* Age is in 6 */
                   6266:              /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6267:              /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   6268:            }   
                   6269:            fprintf(ficgp," u %d:(",ioffset); 
                   6270:            kl=0;
                   6271:            strcpy(gplotcondition,"(");
                   6272:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   6273:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   6274:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6275:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6276:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6277:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   6278:              kl++;
                   6279:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   6280:              kl++;
                   6281:              if(k <cptcoveff && cptcoveff>1)
                   6282:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   6283:            }
                   6284:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   6285:            /* 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 *\/ */
                   6286:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6287:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6288:            /* ''  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*/
                   6289:            if(i==nlstate+1){
                   6290:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ", gplotcondition, \
                   6291:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6292:            }else{
                   6293:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   6294:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6295:            }
                   6296:          } /* end if covariate */
                   6297:        } /* nlstate */
                   6298:        fprintf(ficgp,"\nset out\n");
                   6299:       } /* end cpt state*/
                   6300:     } /* end covariate */
                   6301:   } /* End if prevfcast */
                   6302:        
                   6303:        
                   6304:   /* proba elementaires */
                   6305:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
                   6306:   for(i=1,jk=1; i <=nlstate; i++){
                   6307:     fprintf(ficgp,"# initial state %d\n",i);
                   6308:     for(k=1; k <=(nlstate+ndeath); k++){
                   6309:       if (k != i) {
1.2     ! brouard  6310:                                fprintf(ficgp,"#   current state %d\n",k);
        !          6311:                                for(j=1; j <=ncovmodel; j++){
        !          6312:                                        fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
        !          6313:                                        jk++; 
        !          6314:                                }
        !          6315:                                fprintf(ficgp,"\n");
1.1       brouard  6316:       }
                   6317:     }
                   6318:   }
                   6319:   fprintf(ficgp,"##############\n#\n");
1.2     ! brouard  6320:        
1.1       brouard  6321:   /*goto avoid;*/
                   6322:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
                   6323:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   6324:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   6325:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   6326:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   6327:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6328:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6329:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6330:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6331:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   6332:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6333:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   6334:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   6335:   fprintf(ficgp,"#\n");
                   6336:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
                   6337:     fprintf(ficgp,"# ng=%d\n",ng);
                   6338:     fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
                   6339:     for(jk=1; jk <=m; jk++) {
                   6340:       fprintf(ficgp,"#    jk=%d\n",jk);
                   6341:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
                   6342:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   6343:       if (ng==1){
                   6344:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   6345:        fprintf(ficgp,"\nunset log y");
                   6346:       }else if (ng==2){
                   6347:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   6348:        fprintf(ficgp,"\nset log y");
                   6349:       }else if (ng==3){
                   6350:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   6351:        fprintf(ficgp,"\nset log y");
                   6352:       }else
                   6353:        fprintf(ficgp,"\nunset title ");
                   6354:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   6355:       i=1;
                   6356:       for(k2=1; k2<=nlstate; k2++) {
                   6357:        k3=i;
                   6358:        for(k=1; k<=(nlstate+ndeath); k++) {
                   6359:          if (k != k2){
                   6360:            switch( ng) {
                   6361:            case 1:
                   6362:              if(nagesqr==0)
                   6363:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   6364:              else /* nagesqr =1 */
                   6365:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6366:              break;
                   6367:            case 2: /* ng=2 */
                   6368:              if(nagesqr==0)
                   6369:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   6370:              else /* nagesqr =1 */
                   6371:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6372:              break;
                   6373:            case 3:
                   6374:              if(nagesqr==0)
                   6375:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   6376:              else /* nagesqr =1 */
                   6377:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   6378:              break;
                   6379:            }
                   6380:            ij=1;/* To be checked else nbcode[0][0] wrong */
                   6381:            for(j=3; j <=ncovmodel-nagesqr; j++) {
                   6382:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
                   6383:              if(ij <=cptcovage) { /* Bug valgrind */
                   6384:                if((j-2)==Tage[ij]) { /* Bug valgrind */
                   6385:                  fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   6386:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   6387:                  ij++;
                   6388:                }
                   6389:              }
                   6390:              else
                   6391:                fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   6392:            }
                   6393:          }else{
                   6394:            i=i-ncovmodel;
                   6395:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   6396:              fprintf(ficgp," (1.");
                   6397:          }
                   6398:           
                   6399:          if(ng != 1){
                   6400:            fprintf(ficgp,")/(1");
                   6401:             
                   6402:            for(k1=1; k1 <=nlstate; k1++){ 
                   6403:              if(nagesqr==0)
                   6404:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   6405:              else /* nagesqr =1 */
                   6406:                fprintf(ficgp,"+exp(p%d+p%d*x+p%d*x*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1,k3+(k1-1)*ncovmodel+1+nagesqr);
                   6407:               
                   6408:              ij=1;
                   6409:              for(j=3; j <=ncovmodel-nagesqr; j++){
                   6410:                if(ij <=cptcovage) { /* Bug valgrind */
                   6411:                  if((j-2)==Tage[ij]) { /* Bug valgrind */
                   6412:                    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   6413:                    /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   6414:                    ij++;
                   6415:                  }
                   6416:                }
                   6417:                else
                   6418:                  fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   6419:              }
                   6420:              fprintf(ficgp,")");
                   6421:            }
                   6422:            fprintf(ficgp,")");
                   6423:            if(ng ==2)
                   6424:              fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   6425:            else /* ng= 3 */
                   6426:              fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   6427:          }else{ /* end ng <> 1 */
                   6428:            if( k !=k2) /* logit p11 is hard to draw */
                   6429:              fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
                   6430:          }
                   6431:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   6432:            fprintf(ficgp,",");
                   6433:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   6434:            fprintf(ficgp,",");
                   6435:          i=i+ncovmodel;
                   6436:        } /* end k */
                   6437:       } /* end k2 */
                   6438:       fprintf(ficgp,"\n set out\n");
                   6439:     } /* end jk */
                   6440:   } /* end ng */
                   6441:   /* avoid: */
                   6442:   fflush(ficgp); 
                   6443: }  /* end gnuplot */
                   6444: 
                   6445: 
                   6446: /*************** Moving average **************/
                   6447: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
                   6448:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
                   6449:    
                   6450:    int i, cpt, cptcod;
                   6451:    int modcovmax =1;
                   6452:    int mobilavrange, mob;
                   6453:    int iage=0;
                   6454: 
                   6455:    double sum=0.;
                   6456:    double age;
                   6457:    double *sumnewp, *sumnewm;
                   6458:    double *agemingood, *agemaxgood; /* Currently identical for all covariates */
                   6459:   
                   6460:   
                   6461:    /* modcovmax=2*cptcoveff;/\* Max number of modalities. We suppose  */
                   6462:    /*             a covariate has 2 modalities, should be equal to ncovcombmax  *\/ */
                   6463: 
                   6464:    sumnewp = vector(1,ncovcombmax);
                   6465:    sumnewm = vector(1,ncovcombmax);
                   6466:    agemingood = vector(1,ncovcombmax); 
                   6467:    agemaxgood = vector(1,ncovcombmax);
                   6468: 
                   6469:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   6470:      sumnewm[cptcod]=0.;
                   6471:      sumnewp[cptcod]=0.;
                   6472:      agemingood[cptcod]=0;
                   6473:      agemaxgood[cptcod]=0;
                   6474:    }
                   6475:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   6476:   
                   6477:    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   6478:      if(mobilav==1) mobilavrange=5; /* default */
                   6479:      else mobilavrange=mobilav;
                   6480:      for (age=bage; age<=fage; age++)
                   6481:        for (i=1; i<=nlstate;i++)
                   6482:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   6483:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   6484:      /* We keep the original values on the extreme ages bage, fage and for 
                   6485:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   6486:        we use a 5 terms etc. until the borders are no more concerned. 
                   6487:      */ 
                   6488:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   6489:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   6490:         for (i=1; i<=nlstate;i++){
                   6491:           for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   6492:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   6493:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   6494:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   6495:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   6496:             }
                   6497:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   6498:           }
                   6499:         }
                   6500:        }/* end age */
                   6501:      }/* end mob */
                   6502:    }else
                   6503:      return -1;
                   6504:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   6505:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   6506:      if(invalidvarcomb[cptcod]){
                   6507:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   6508:        continue;
                   6509:      }
                   6510: 
                   6511:      agemingood[cptcod]=fage-(mob-1)/2;
                   6512:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
                   6513:        sumnewm[cptcod]=0.;
                   6514:        for (i=1; i<=nlstate;i++){
                   6515:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   6516:        }
                   6517:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   6518:         agemingood[cptcod]=age;
                   6519:        }else{ /* bad */
                   6520:         for (i=1; i<=nlstate;i++){
                   6521:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   6522:         } /* i */
                   6523:        } /* end bad */
                   6524:      }/* age */
                   6525:      sum=0.;
                   6526:      for (i=1; i<=nlstate;i++){
                   6527:        sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   6528:      }
                   6529:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   6530:        printf("For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one at any descending age!\n",cptcod);
                   6531:        /* for (i=1; i<=nlstate;i++){ */
                   6532:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   6533:        /* } /\* i *\/ */
                   6534:      } /* end bad */
                   6535:      /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   6536:      /* From youngest, finding the oldest wrong */
                   6537:      agemaxgood[cptcod]=bage+(mob-1)/2;
                   6538:      for (age=bage+(mob-1)/2; age<=fage; age++){
                   6539:        sumnewm[cptcod]=0.;
                   6540:        for (i=1; i<=nlstate;i++){
                   6541:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   6542:        }
                   6543:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   6544:         agemaxgood[cptcod]=age;
                   6545:        }else{ /* bad */
                   6546:         for (i=1; i<=nlstate;i++){
                   6547:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   6548:         } /* i */
                   6549:        } /* end bad */
                   6550:      }/* age */
                   6551:      sum=0.;
                   6552:      for (i=1; i<=nlstate;i++){
                   6553:        sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   6554:      }
                   6555:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   6556:        printf("For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one at any ascending age!\n",cptcod);
                   6557:        /* for (i=1; i<=nlstate;i++){ */
                   6558:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   6559:        /* } /\* i *\/ */
                   6560:      } /* end bad */
                   6561:                
                   6562:      for (age=bage; age<=fage; age++){
                   6563:        printf("%d %d ", cptcod, (int)age);
                   6564:        sumnewp[cptcod]=0.;
                   6565:        sumnewm[cptcod]=0.;
                   6566:        for (i=1; i<=nlstate;i++){
                   6567:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   6568:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   6569:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   6570:        }
                   6571:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   6572:      }
                   6573:      /* printf("\n"); */
                   6574:      /* } */
                   6575:      /* brutal averaging */
                   6576:      for (i=1; i<=nlstate;i++){
                   6577:        for (age=1; age<=bage; age++){
                   6578:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   6579:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   6580:        }       
                   6581:        for (age=fage; age<=AGESUP; age++){
                   6582:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   6583:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   6584:        }
                   6585:      } /* end i status */
                   6586:      for (i=nlstate+1; i<=nlstate+ndeath;i++){
                   6587:        for (age=1; age<=AGESUP; age++){
                   6588:         /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
                   6589:         mobaverage[(int)age][i][cptcod]=0.;
                   6590:        }
                   6591:      }
                   6592:    }/* end cptcod */
                   6593:    free_vector(sumnewm,1, ncovcombmax);
                   6594:    free_vector(sumnewp,1, ncovcombmax);
                   6595:    free_vector(agemaxgood,1, ncovcombmax);
                   6596:    free_vector(agemingood,1, ncovcombmax);
                   6597:    return 0;
                   6598:  }/* End movingaverage */
                   6599:  
                   6600: 
                   6601: /************** Forecasting ******************/
                   6602: void prevforecast(char fileres[], double anproj1, double mproj1, double jproj1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anproj2, double p[], int cptcoveff){
                   6603:   /* proj1, year, month, day of starting projection 
                   6604:      agemin, agemax range of age
                   6605:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   6606:      anproj2 year of en of projection (same day and month as proj1).
                   6607:   */
                   6608:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
                   6609:   double agec; /* generic age */
                   6610:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   6611:   double *popeffectif,*popcount;
                   6612:   double ***p3mat;
                   6613:   /* double ***mobaverage; */
                   6614:   char fileresf[FILENAMELENGTH];
                   6615: 
                   6616:   agelim=AGESUP;
                   6617:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   6618:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   6619:      We still use firstpass and lastpass as another selection.
                   6620:   */
                   6621:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   6622:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   6623:  
                   6624:   strcpy(fileresf,"F_"); 
                   6625:   strcat(fileresf,fileresu);
                   6626:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   6627:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   6628:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   6629:   }
                   6630:   printf("Computing forecasting: result on file '%s', please wait... \n", fileresf);
                   6631:   fprintf(ficlog,"Computing forecasting: result on file '%s', please wait... \n", fileresf);
                   6632: 
                   6633:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   6634: 
                   6635: 
                   6636:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6637:   if (stepm<=12) stepsize=1;
                   6638:   if(estepm < stepm){
                   6639:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6640:   }
                   6641:   else  hstepm=estepm;   
                   6642: 
                   6643:   hstepm=hstepm/stepm; 
                   6644:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   6645:                                fractional in yp1 */
                   6646:   anprojmean=yp;
                   6647:   yp2=modf((yp1*12),&yp);
                   6648:   mprojmean=yp;
                   6649:   yp1=modf((yp2*30.5),&yp);
                   6650:   jprojmean=yp;
                   6651:   if(jprojmean==0) jprojmean=1;
                   6652:   if(mprojmean==0) jprojmean=1;
                   6653: 
                   6654:   i1=cptcoveff;
                   6655:   if (cptcovn < 1){i1=1;}
                   6656:   
                   6657:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   6658:   
                   6659:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   6660: 
                   6661: /*           if (h==(int)(YEARM*yearp)){ */
                   6662:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   6663:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   6664:       k=k+1;
                   6665:       fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   6666:       for(j=1;j<=cptcoveff;j++) {
                   6667:                                fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6668:       }
                   6669:       fprintf(ficresf," yearproj age");
                   6670:       for(j=1; j<=nlstate+ndeath;j++){ 
                   6671:                                for(i=1; i<=nlstate;i++)              
                   6672:           fprintf(ficresf," p%d%d",i,j);
                   6673:                                fprintf(ficresf," wp.%d",j);
                   6674:       }
                   6675:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
                   6676:                                fprintf(ficresf,"\n");
                   6677:                                fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   6678:                                for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   6679:                                        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   6680:                                        nhstepm = nhstepm/hstepm; 
                   6681:                                        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6682:                                        oldm=oldms;savm=savms;
                   6683:                                        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
                   6684:                                        
                   6685:                                        for (h=0; h<=nhstepm; h++){
                   6686:                                                if (h*hstepm/YEARM*stepm ==yearp) {
                   6687:               fprintf(ficresf,"\n");
                   6688:               for(j=1;j<=cptcoveff;j++) 
                   6689:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6690:                                                        fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   6691:                                                } 
                   6692:                                                for(j=1; j<=nlstate+ndeath;j++) {
                   6693:                                                        ppij=0.;
                   6694:                                                        for(i=1; i<=nlstate;i++) {
                   6695:                                                                if (mobilav==1) 
                   6696:                                                                        ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   6697:                                                                else {
                   6698:                                                                        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   6699:                                                                }
                   6700:                                                                if (h*hstepm/YEARM*stepm== yearp) {
                   6701:                                                                        fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   6702:                                                                }
                   6703:                                                        } /* end i */
                   6704:                                                        if (h*hstepm/YEARM*stepm==yearp) {
                   6705:                                                                fprintf(ficresf," %.3f", ppij);
                   6706:                                                        }
                   6707:                                                }/* end j */
                   6708:                                        } /* end h */
                   6709:                                        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6710:                                } /* end agec */
                   6711:       } /* end yearp */
                   6712:     } /* end cptcod */
                   6713:   } /* end  cptcov */
                   6714:        
                   6715:   fclose(ficresf);
                   6716:   printf("End of Computing forecasting \n");
                   6717:   fprintf(ficlog,"End of Computing forecasting\n");
                   6718: 
                   6719: }
                   6720: 
                   6721: /* /\************** Back Forecasting ******************\/ */
                   6722: /* void prevbackforecast(char fileres[], double anback1, double mback1, double jback1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anback2, double p[], int cptcoveff){ */
                   6723: /*   /\* back1, year, month, day of starting backection  */
                   6724: /*      agemin, agemax range of age */
                   6725: /*      dateprev1 dateprev2 range of dates during which prevalence is computed */
                   6726: /*      anback2 year of en of backection (same day and month as back1). */
                   6727: /*   *\/ */
                   6728: /*   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
                   6729: /*   double agec; /\* generic age *\/ */
                   6730: /*   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
                   6731: /*   double *popeffectif,*popcount; */
                   6732: /*   double ***p3mat; */
                   6733: /*   /\* double ***mobaverage; *\/ */
                   6734: /*   char fileresfb[FILENAMELENGTH]; */
                   6735:        
                   6736: /*   agelim=AGESUP; */
                   6737: /*   /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
                   6738: /*      in each health status at the date of interview (if between dateprev1 and dateprev2). */
                   6739: /*      We still use firstpass and lastpass as another selection. */
                   6740: /*   *\/ */
                   6741: /*   /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
                   6742: /*   /\*             firstpass, lastpass,  stepm,  weightopt, model); *\/ */
                   6743: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   6744:        
                   6745: /*   strcpy(fileresfb,"FB_");  */
                   6746: /*   strcat(fileresfb,fileresu); */
                   6747: /*   if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
                   6748: /*     printf("Problem with back forecast resultfile: %s\n", fileresfb); */
                   6749: /*     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
                   6750: /*   } */
                   6751: /*   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   6752: /*   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   6753:        
                   6754: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
                   6755:        
                   6756: /*   /\* if (mobilav!=0) { *\/ */
                   6757: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   6758: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   6759: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   6760: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   6761: /*   /\*   } *\/ */
                   6762: /*   /\* } *\/ */
                   6763:        
                   6764: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   6765: /*   if (stepm<=12) stepsize=1; */
                   6766: /*   if(estepm < stepm){ */
                   6767: /*     printf ("Problem %d lower than %d\n",estepm, stepm); */
                   6768: /*   } */
                   6769: /*   else  hstepm=estepm;    */
                   6770:        
                   6771: /*   hstepm=hstepm/stepm;  */
                   6772: /*   yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   6773: /*                                fractional in yp1 *\/ */
                   6774: /*   anprojmean=yp; */
                   6775: /*   yp2=modf((yp1*12),&yp); */
                   6776: /*   mprojmean=yp; */
                   6777: /*   yp1=modf((yp2*30.5),&yp); */
                   6778: /*   jprojmean=yp; */
                   6779: /*   if(jprojmean==0) jprojmean=1; */
                   6780: /*   if(mprojmean==0) jprojmean=1; */
                   6781:        
                   6782: /*   i1=cptcoveff; */
                   6783: /*   if (cptcovn < 1){i1=1;} */
                   6784:   
                   6785: /*   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);  */
                   6786:   
                   6787: /*   fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
                   6788:        
                   6789: /*     /\*           if (h==(int)(YEARM*yearp)){ *\/ */
                   6790: /*   for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
                   6791: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   6792: /*       k=k+1; */
                   6793: /*       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
                   6794: /*       for(j=1;j<=cptcoveff;j++) { */
                   6795: /*                             fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   6796: /*       } */
                   6797: /*       fprintf(ficresfb," yearbproj age"); */
                   6798: /*       for(j=1; j<=nlstate+ndeath;j++){  */
                   6799: /*                             for(i=1; i<=nlstate;i++)               */
                   6800: /*           fprintf(ficresfb," p%d%d",i,j); */
                   6801: /*                             fprintf(ficresfb," p.%d",j); */
                   6802: /*       } */
                   6803: /*       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {  */
                   6804: /*                             /\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  *\/ */
                   6805: /*                             fprintf(ficresfb,"\n"); */
                   6806: /*                             fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);    */
                   6807: /*                             for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   6808: /*                                     nhstepm=(int) rint((agelim-agec)*YEARM/stepm);  */
                   6809: /*                                     nhstepm = nhstepm/hstepm;  */
                   6810: /*                                     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   6811: /*                                     oldm=oldms;savm=savms; */
                   6812: /*                                     hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k);       */
                   6813: /*                                     for (h=0; h<=nhstepm; h++){ */
                   6814: /*                                             if (h*hstepm/YEARM*stepm ==yearp) { */
                   6815: /*               fprintf(ficresfb,"\n"); */
                   6816: /*               for(j=1;j<=cptcoveff;j++)  */
                   6817: /*                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   6818: /*                                                     fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
                   6819: /*                                             }  */
                   6820: /*                                             for(j=1; j<=nlstate+ndeath;j++) { */
                   6821: /*                                                     ppij=0.; */
                   6822: /*                                                     for(i=1; i<=nlstate;i++) { */
                   6823: /*                                                             if (mobilav==1)  */
                   6824: /*                                                                     ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
                   6825: /*                                                             else { */
                   6826: /*                                                                     ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
                   6827: /*                                                             } */
                   6828: /*                                                             if (h*hstepm/YEARM*stepm== yearp) { */
                   6829: /*                                                                     fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
                   6830: /*                                                             } */
                   6831: /*                                                     } /\* end i *\/ */
                   6832: /*                                                     if (h*hstepm/YEARM*stepm==yearp) { */
                   6833: /*                                                             fprintf(ficresfb," %.3f", ppij); */
                   6834: /*                                                     } */
                   6835: /*                                             }/\* end j *\/ */
                   6836: /*                                     } /\* end h *\/ */
                   6837: /*                                     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   6838: /*                             } /\* end agec *\/ */
                   6839: /*       } /\* end yearp *\/ */
                   6840: /*     } /\* end cptcod *\/ */
                   6841: /*   } /\* end  cptcov *\/ */
                   6842:        
                   6843: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   6844:        
                   6845: /*   fclose(ficresfb); */
                   6846: /*   printf("End of Computing Back forecasting \n"); */
                   6847: /*   fprintf(ficlog,"End of Computing Back forecasting\n"); */
                   6848:        
                   6849: /* } */
                   6850: 
                   6851: /************** Forecasting *****not tested NB*************/
                   6852: void populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){
                   6853:   
                   6854:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   6855:   int *popage;
                   6856:   double calagedatem, agelim, kk1, kk2;
                   6857:   double *popeffectif,*popcount;
                   6858:   double ***p3mat,***tabpop,***tabpopprev;
                   6859:   /* double ***mobaverage; */
                   6860:   char filerespop[FILENAMELENGTH];
                   6861: 
                   6862:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6863:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6864:   agelim=AGESUP;
                   6865:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   6866:   
                   6867:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   6868:   
                   6869:   
                   6870:   strcpy(filerespop,"POP_"); 
                   6871:   strcat(filerespop,fileresu);
                   6872:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   6873:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   6874:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   6875:   }
                   6876:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   6877:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   6878: 
                   6879:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   6880: 
                   6881:   /* if (mobilav!=0) { */
                   6882:   /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6883:   /*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ */
                   6884:   /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6885:   /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6886:   /*   } */
                   6887:   /* } */
                   6888: 
                   6889:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6890:   if (stepm<=12) stepsize=1;
                   6891:   
                   6892:   agelim=AGESUP;
                   6893:   
                   6894:   hstepm=1;
                   6895:   hstepm=hstepm/stepm; 
                   6896:        
                   6897:   if (popforecast==1) {
                   6898:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   6899:       printf("Problem with population file : %s\n",popfile);exit(0);
                   6900:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   6901:     } 
                   6902:     popage=ivector(0,AGESUP);
                   6903:     popeffectif=vector(0,AGESUP);
                   6904:     popcount=vector(0,AGESUP);
                   6905:     
                   6906:     i=1;   
                   6907:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   6908:     
                   6909:     imx=i;
                   6910:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   6911:   }
                   6912:   
                   6913:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   6914:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   6915:       k=k+1;
                   6916:       fprintf(ficrespop,"\n#******");
                   6917:       for(j=1;j<=cptcoveff;j++) {
                   6918:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6919:       }
                   6920:       fprintf(ficrespop,"******\n");
                   6921:       fprintf(ficrespop,"# Age");
                   6922:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   6923:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   6924:       
                   6925:       for (cpt=0; cpt<=0;cpt++) { 
                   6926:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   6927:        
                   6928:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   6929:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   6930:          nhstepm = nhstepm/hstepm; 
                   6931:          
                   6932:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6933:          oldm=oldms;savm=savms;
                   6934:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6935:          
                   6936:          for (h=0; h<=nhstepm; h++){
                   6937:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   6938:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   6939:            } 
                   6940:            for(j=1; j<=nlstate+ndeath;j++) {
                   6941:              kk1=0.;kk2=0;
                   6942:              for(i=1; i<=nlstate;i++) {              
                   6943:                if (mobilav==1) 
                   6944:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   6945:                else {
                   6946:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   6947:                }
                   6948:              }
                   6949:              if (h==(int)(calagedatem+12*cpt)){
                   6950:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   6951:                /*fprintf(ficrespop," %.3f", kk1);
                   6952:                  if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   6953:              }
                   6954:            }
                   6955:            for(i=1; i<=nlstate;i++){
                   6956:              kk1=0.;
                   6957:              for(j=1; j<=nlstate;j++){
                   6958:                kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   6959:              }
                   6960:              tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   6961:            }
                   6962:            
                   6963:            if (h==(int)(calagedatem+12*cpt))
                   6964:              for(j=1; j<=nlstate;j++) 
                   6965:                fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   6966:          }
                   6967:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6968:        }
                   6969:       }
                   6970:       
                   6971:       /******/
                   6972:       
                   6973:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   6974:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   6975:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   6976:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   6977:          nhstepm = nhstepm/hstepm; 
                   6978:          
                   6979:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6980:          oldm=oldms;savm=savms;
                   6981:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6982:          for (h=0; h<=nhstepm; h++){
                   6983:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   6984:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   6985:            } 
                   6986:            for(j=1; j<=nlstate+ndeath;j++) {
                   6987:              kk1=0.;kk2=0;
                   6988:              for(i=1; i<=nlstate;i++) {              
                   6989:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   6990:              }
                   6991:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   6992:            }
                   6993:          }
                   6994:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6995:        }
                   6996:       }
                   6997:     } 
                   6998:   }
                   6999:   
                   7000:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7001:   
                   7002:   if (popforecast==1) {
                   7003:     free_ivector(popage,0,AGESUP);
                   7004:     free_vector(popeffectif,0,AGESUP);
                   7005:     free_vector(popcount,0,AGESUP);
                   7006:   }
                   7007:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7008:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7009:   fclose(ficrespop);
                   7010: } /* End of popforecast */
                   7011:  
                   7012: int fileappend(FILE *fichier, char *optionfich)
                   7013: {
                   7014:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   7015:     printf("Problem with file: %s\n", optionfich);
                   7016:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   7017:     return (0);
                   7018:   }
                   7019:   fflush(fichier);
                   7020:   return (1);
                   7021: }
                   7022: 
                   7023: 
                   7024: /**************** function prwizard **********************/
                   7025: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   7026: {
                   7027: 
                   7028:   /* Wizard to print covariance matrix template */
                   7029: 
                   7030:   char ca[32], cb[32];
                   7031:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
                   7032:   int numlinepar;
                   7033: 
                   7034:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7035:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7036:   for(i=1; i <=nlstate; i++){
                   7037:     jj=0;
                   7038:     for(j=1; j <=nlstate+ndeath; j++){
                   7039:       if(j==i) continue;
                   7040:       jj++;
                   7041:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   7042:       printf("%1d%1d",i,j);
                   7043:       fprintf(ficparo,"%1d%1d",i,j);
                   7044:       for(k=1; k<=ncovmodel;k++){
                   7045:        /*        printf(" %lf",param[i][j][k]); */
                   7046:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   7047:        printf(" 0.");
                   7048:        fprintf(ficparo," 0.");
                   7049:       }
                   7050:       printf("\n");
                   7051:       fprintf(ficparo,"\n");
                   7052:     }
                   7053:   }
                   7054:   printf("# Scales (for hessian or gradient estimation)\n");
                   7055:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   7056:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   7057:   for(i=1; i <=nlstate; i++){
                   7058:     jj=0;
                   7059:     for(j=1; j <=nlstate+ndeath; j++){
                   7060:       if(j==i) continue;
                   7061:       jj++;
                   7062:       fprintf(ficparo,"%1d%1d",i,j);
                   7063:       printf("%1d%1d",i,j);
                   7064:       fflush(stdout);
                   7065:       for(k=1; k<=ncovmodel;k++){
                   7066:        /*      printf(" %le",delti3[i][j][k]); */
                   7067:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   7068:        printf(" 0.");
                   7069:        fprintf(ficparo," 0.");
                   7070:       }
                   7071:       numlinepar++;
                   7072:       printf("\n");
                   7073:       fprintf(ficparo,"\n");
                   7074:     }
                   7075:   }
                   7076:   printf("# Covariance matrix\n");
                   7077: /* # 121 Var(a12)\n\ */
                   7078: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7079: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7080: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7081: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7082: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7083: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7084: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7085:   fflush(stdout);
                   7086:   fprintf(ficparo,"# Covariance matrix\n");
                   7087:   /* # 121 Var(a12)\n\ */
                   7088:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7089:   /* #   ...\n\ */
                   7090:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   7091:   
                   7092:   for(itimes=1;itimes<=2;itimes++){
                   7093:     jj=0;
                   7094:     for(i=1; i <=nlstate; i++){
                   7095:       for(j=1; j <=nlstate+ndeath; j++){
                   7096:        if(j==i) continue;
                   7097:        for(k=1; k<=ncovmodel;k++){
                   7098:          jj++;
                   7099:          ca[0]= k+'a'-1;ca[1]='\0';
                   7100:          if(itimes==1){
                   7101:            printf("#%1d%1d%d",i,j,k);
                   7102:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   7103:          }else{
                   7104:            printf("%1d%1d%d",i,j,k);
                   7105:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   7106:            /*  printf(" %.5le",matcov[i][j]); */
                   7107:          }
                   7108:          ll=0;
                   7109:          for(li=1;li <=nlstate; li++){
                   7110:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   7111:              if(lj==li) continue;
                   7112:              for(lk=1;lk<=ncovmodel;lk++){
                   7113:                ll++;
                   7114:                if(ll<=jj){
                   7115:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   7116:                  if(ll<jj){
                   7117:                    if(itimes==1){
                   7118:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7119:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7120:                    }else{
                   7121:                      printf(" 0.");
                   7122:                      fprintf(ficparo," 0.");
                   7123:                    }
                   7124:                  }else{
                   7125:                    if(itimes==1){
                   7126:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   7127:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   7128:                    }else{
                   7129:                      printf(" 0.");
                   7130:                      fprintf(ficparo," 0.");
                   7131:                    }
                   7132:                  }
                   7133:                }
                   7134:              } /* end lk */
                   7135:            } /* end lj */
                   7136:          } /* end li */
                   7137:          printf("\n");
                   7138:          fprintf(ficparo,"\n");
                   7139:          numlinepar++;
                   7140:        } /* end k*/
                   7141:       } /*end j */
                   7142:     } /* end i */
                   7143:   } /* end itimes */
                   7144: 
                   7145: } /* end of prwizard */
                   7146: /******************* Gompertz Likelihood ******************************/
                   7147: double gompertz(double x[])
                   7148: { 
                   7149:   double A,B,L=0.0,sump=0.,num=0.;
                   7150:   int i,n=0; /* n is the size of the sample */
                   7151: 
                   7152:   for (i=1;i<=imx ; i++) {
                   7153:     sump=sump+weight[i];
                   7154:     /*    sump=sump+1;*/
                   7155:     num=num+1;
                   7156:   }
                   7157:  
                   7158:  
                   7159:   /* for (i=0; i<=imx; i++) 
                   7160:      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]);*/
                   7161: 
                   7162:   for (i=1;i<=imx ; i++)
                   7163:     {
                   7164:       if (cens[i] == 1 && wav[i]>1)
                   7165:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   7166:       
                   7167:       if (cens[i] == 0 && wav[i]>1)
                   7168:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   7169:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   7170:       
                   7171:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7172:       if (wav[i] > 1 ) { /* ??? */
                   7173:        L=L+A*weight[i];
                   7174:        /*      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]);*/
                   7175:       }
                   7176:     }
                   7177: 
                   7178:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7179:  
                   7180:   return -2*L*num/sump;
                   7181: }
                   7182: 
                   7183: #ifdef GSL
                   7184: /******************* Gompertz_f Likelihood ******************************/
                   7185: double gompertz_f(const gsl_vector *v, void *params)
                   7186: { 
                   7187:   double A,B,LL=0.0,sump=0.,num=0.;
                   7188:   double *x= (double *) v->data;
                   7189:   int i,n=0; /* n is the size of the sample */
                   7190: 
                   7191:   for (i=0;i<=imx-1 ; i++) {
                   7192:     sump=sump+weight[i];
                   7193:     /*    sump=sump+1;*/
                   7194:     num=num+1;
                   7195:   }
                   7196:  
                   7197:  
                   7198:   /* for (i=0; i<=imx; i++) 
                   7199:      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]);*/
                   7200:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   7201:   for (i=1;i<=imx ; i++)
                   7202:     {
                   7203:       if (cens[i] == 1 && wav[i]>1)
                   7204:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   7205:       
                   7206:       if (cens[i] == 0 && wav[i]>1)
                   7207:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   7208:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   7209:       
                   7210:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7211:       if (wav[i] > 1 ) { /* ??? */
                   7212:        LL=LL+A*weight[i];
                   7213:        /*      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]);*/
                   7214:       }
                   7215:     }
                   7216: 
                   7217:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7218:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   7219:  
                   7220:   return -2*LL*num/sump;
                   7221: }
                   7222: #endif
                   7223: 
                   7224: /******************* Printing html file ***********/
                   7225: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
                   7226:                  int lastpass, int stepm, int weightopt, char model[],\
                   7227:                  int imx,  double p[],double **matcov,double agemortsup){
                   7228:   int i,k;
                   7229: 
                   7230:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   7231:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   7232:   for (i=1;i<=2;i++) 
                   7233:     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]));
                   7234:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
                   7235:   fprintf(fichtm,"</ul>");
                   7236: 
                   7237: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   7238: 
                   7239:  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>");
                   7240: 
                   7241:  for (k=agegomp;k<(agemortsup-2);k++) 
                   7242:    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]);
                   7243: 
                   7244:  
                   7245:   fflush(fichtm);
                   7246: }
                   7247: 
                   7248: /******************* Gnuplot file **************/
                   7249: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   7250: 
                   7251:   char dirfileres[132],optfileres[132];
                   7252: 
                   7253:   int ng;
                   7254: 
                   7255: 
                   7256:   /*#ifdef windows */
                   7257:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   7258:     /*#endif */
                   7259: 
                   7260: 
                   7261:   strcpy(dirfileres,optionfilefiname);
                   7262:   strcpy(optfileres,"vpl");
                   7263:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
                   7264:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
                   7265:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
                   7266:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
                   7267:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   7268: 
                   7269: } 
                   7270: 
                   7271: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   7272: {
                   7273: 
                   7274:   /*-------- data file ----------*/
                   7275:   FILE *fic;
                   7276:   char dummy[]="                         ";
                   7277:   int i=0, j=0, n=0, iv=0;
                   7278:   int lstra;
                   7279:   int linei, month, year,iout;
                   7280:   char line[MAXLINE], linetmp[MAXLINE];
                   7281:   char stra[MAXLINE], strb[MAXLINE];
                   7282:   char *stratrunc;
                   7283: 
                   7284: 
                   7285: 
                   7286:   if((fic=fopen(datafile,"r"))==NULL)    {
                   7287:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   7288:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   7289:   }
                   7290: 
                   7291:   i=1;
                   7292:   linei=0;
                   7293:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   7294:     linei=linei+1;
                   7295:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   7296:       if(line[j] == '\t')
                   7297:        line[j] = ' ';
                   7298:     }
                   7299:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   7300:       ;
                   7301:     };
                   7302:     line[j+1]=0;  /* Trims blanks at end of line */
                   7303:     if(line[0]=='#'){
                   7304:       fprintf(ficlog,"Comment line\n%s\n",line);
                   7305:       printf("Comment line\n%s\n",line);
                   7306:       continue;
                   7307:     }
                   7308:     trimbb(linetmp,line); /* Trims multiple blanks in line */
                   7309:     strcpy(line, linetmp);
1.2     ! brouard  7310:     
        !          7311:     /* Loops on waves */
1.1       brouard  7312:     for (j=maxwav;j>=1;j--){
                   7313:       cutv(stra, strb, line, ' '); 
                   7314:       if(strb[0]=='.') { /* Missing status */
                   7315:        lval=-1;
                   7316:       }else{
                   7317:        errno=0;
                   7318:        lval=strtol(strb,&endptr,10); 
                   7319:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   7320:        if( strb[0]=='\0' || (*endptr != '\0')){
                   7321:          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);
                   7322:          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);
                   7323:          return 1;
                   7324:        }
                   7325:       }
1.2     ! brouard  7326:      
1.1       brouard  7327:       s[j][i]=lval;
1.2     ! brouard  7328: 
        !          7329:       /* Date of Interview */
1.1       brouard  7330:       strcpy(line,stra);
                   7331:       cutv(stra, strb,line,' ');
                   7332:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
                   7333:       }
                   7334:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.2     ! brouard  7335:                                month=99;
        !          7336:                                year=9999;
1.1       brouard  7337:       }else{
1.2     ! brouard  7338:                                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);
        !          7339:                                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);
        !          7340:                                return 1;
1.1       brouard  7341:       }
                   7342:       anint[j][i]= (double) year; 
                   7343:       mint[j][i]= (double)month; 
                   7344:       strcpy(line,stra);
                   7345:     } /* End loop on waves */
                   7346: 
                   7347:     /* Date of death */
                   7348:     cutv(stra, strb,line,' '); 
                   7349:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
                   7350:     }
                   7351:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
                   7352:       month=99;
                   7353:       year=9999;
                   7354:     }else{
                   7355:       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);
1.2     ! brouard  7356:                        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);
        !          7357:                        return 1;
1.1       brouard  7358:     }
                   7359:     andc[i]=(double) year; 
                   7360:     moisdc[i]=(double) month; 
                   7361:     strcpy(line,stra);
                   7362:     
                   7363:     /* Date of birth */
                   7364:     cutv(stra, strb,line,' '); 
                   7365:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
                   7366:     }
                   7367:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
                   7368:       month=99;
                   7369:       year=9999;
                   7370:     }else{
                   7371:       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);
                   7372:       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);
1.2     ! brouard  7373:                        return 1;
1.1       brouard  7374:     }
                   7375:     if (year==9999) {
                   7376:       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);
                   7377:       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);
1.2     ! brouard  7378:                        return 1;
1.1       brouard  7379: 
                   7380:     }
                   7381:     annais[i]=(double)(year);
                   7382:     moisnais[i]=(double)(month); 
                   7383:     strcpy(line,stra);
                   7384: 
                   7385:     /* Sample weight */
                   7386:     cutv(stra, strb,line,' '); 
                   7387:     errno=0;
                   7388:     dval=strtod(strb,&endptr); 
                   7389:     if( strb[0]=='\0' || (*endptr != '\0')){
                   7390:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   7391:       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);
                   7392:       fflush(ficlog);
                   7393:       return 1;
                   7394:     }
                   7395:     weight[i]=dval; 
                   7396:     strcpy(line,stra);
                   7397:     
                   7398:     /* Covariate values */
                   7399:     for (j=ncovcol;j>=1;j--){
                   7400:       cutv(stra, strb,line,' '); 
                   7401:       if(strb[0]=='.') { /* Missing covariate value */
1.2     ! brouard  7402:                                lval=-1;
1.1       brouard  7403:       }else{
1.2     ! brouard  7404:                                errno=0;
        !          7405:                                lval=strtol(strb,&endptr,10); 
        !          7406:                                if( strb[0]=='\0' || (*endptr != '\0')){
        !          7407:                                        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);
        !          7408:                                        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);
        !          7409:                                        return 1;
        !          7410:                                }
1.1       brouard  7411:       }
                   7412:       if(lval <-1 || lval >1){
1.2     ! brouard  7413:                                printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.1       brouard  7414:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7415:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   7416:  For example, for multinomial values like 1, 2 and 3,\n \
                   7417:  build V1=0 V2=0 for the reference value (1),\n \
                   7418:         V1=1 V2=0 for (2) \n \
                   7419:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   7420:  output of IMaCh is often meaningless.\n \
                   7421:  Exiting.\n",lval,linei, i,line,j);
1.2     ! brouard  7422:                                fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.1       brouard  7423:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7424:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   7425:  For example, for multinomial values like 1, 2 and 3,\n \
                   7426:  build V1=0 V2=0 for the reference value (1),\n \
                   7427:         V1=1 V2=0 for (2) \n \
                   7428:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   7429:  output of IMaCh is often meaningless.\n \
                   7430:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.2     ! brouard  7431:                                return 1;
1.1       brouard  7432:       }
                   7433:       covar[j][i]=(double)(lval);
                   7434:       strcpy(line,stra);
                   7435:     }  
                   7436:     lstra=strlen(stra);
                   7437:      
                   7438:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   7439:       stratrunc = &(stra[lstra-9]);
                   7440:       num[i]=atol(stratrunc);
                   7441:     }
                   7442:     else
                   7443:       num[i]=atol(stra);
                   7444:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   7445:       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;}*/
                   7446:     
                   7447:     i=i+1;
                   7448:   } /* End loop reading  data */
                   7449: 
                   7450:   *imax=i-1; /* Number of individuals */
                   7451:   fclose(fic);
                   7452:  
                   7453:   return (0);
                   7454:   /* endread: */
1.2     ! brouard  7455:        printf("Exiting readdata: ");
        !          7456:        fclose(fic);
        !          7457:        return (1);
        !          7458: }
1.1       brouard  7459: 
                   7460: void removespace(char *str) {
                   7461:   char *p1 = str, *p2 = str;
                   7462:   do
                   7463:     while (*p2 == ' ')
                   7464:       p2++;
                   7465:   while (*p1++ == *p2++);
                   7466: }
                   7467: 
1.2     ! brouard  7468: int decodemodel ( char model[], int lastobs)
        !          7469:  /**< This routine decode the model and returns:
        !          7470:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
        !          7471:        * - nagesqr = 1 if age*age in the model, otherwise 0.
        !          7472:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
        !          7473:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
        !          7474:        * - cptcovage number of covariates with age*products =2
        !          7475:        * - cptcovs number of simple covariates
        !          7476:        * - 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
        !          7477:        *     which is a new column after the 9 (ncovcol) variables. 
        !          7478:        * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
        !          7479:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
        !          7480:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
        !          7481:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
        !          7482:        */
1.1       brouard  7483: {
                   7484:   int i, j, k, ks;
                   7485:   int  j1, k1, k2;
                   7486:   char modelsav[80];
                   7487:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   7488:   char *strpt;
                   7489: 
                   7490:   /*removespace(model);*/
                   7491:   if (strlen(model) >1){ /* If there is at least 1 covariate */
                   7492:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
                   7493:     if (strstr(model,"AGE") !=0){
                   7494:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   7495:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
                   7496:       return 1;
                   7497:     }
                   7498:     if (strstr(model,"v") !=0){
                   7499:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   7500:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   7501:       return 1;
                   7502:     }
                   7503:     strcpy(modelsav,model); 
                   7504:     if ((strpt=strstr(model,"age*age")) !=0){
                   7505:       printf(" strpt=%s, model=%s\n",strpt, model);
                   7506:       if(strpt != model){
1.2     ! brouard  7507:                                printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.1       brouard  7508:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
                   7509:  corresponding column of parameters.\n",model);
1.2     ! brouard  7510:                                fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.1       brouard  7511:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
                   7512:  corresponding column of parameters.\n",model); fflush(ficlog);
1.2     ! brouard  7513:                                return 1;
        !          7514:                        }
1.1       brouard  7515: 
                   7516:       nagesqr=1;
                   7517:       if (strstr(model,"+age*age") !=0)
1.2     ! brouard  7518:                                substrchaine(modelsav, model, "+age*age");
1.1       brouard  7519:       else if (strstr(model,"age*age+") !=0)
1.2     ! brouard  7520:                                substrchaine(modelsav, model, "age*age+");
1.1       brouard  7521:       else 
1.2     ! brouard  7522:                                substrchaine(modelsav, model, "age*age");
1.1       brouard  7523:     }else
                   7524:       nagesqr=0;
                   7525:     if (strlen(modelsav) >1){
                   7526:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   7527:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.2     ! brouard  7528:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.1       brouard  7529:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.2     ! brouard  7530:                                                                                 * cst, age and age*age 
        !          7531:                                                                                 * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
        !          7532:                        /* including age products which are counted in cptcovage.
        !          7533:                         * but the covariates which are products must be treated 
        !          7534:                         * separately: ncovn=4- 2=2 (V1+V3). */
1.1       brouard  7535:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   7536:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
                   7537: 
                   7538:     
                   7539:       /*   Design
                   7540:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   7541:        *  <          ncovcol=8                >
                   7542:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   7543:        *   k=  1    2      3       4     5       6      7        8
                   7544:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   7545:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.2     ! brouard  7546:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
        !          7547:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.1       brouard  7548:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   7549:        *  Tage[++cptcovage]=k
                   7550:        *       if products, new covar are created after ncovcol with k1
                   7551:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   7552:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   7553:        *  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
                   7554:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   7555:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   7556:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   7557:        *  <          ncovcol=8                >
                   7558:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   7559:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   7560:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   7561:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   7562:        * p Tprod[1]@2={                         6, 5}
                   7563:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   7564:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   7565:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   7566:        *How to reorganize?
                   7567:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   7568:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   7569:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   7570:        * Struct []
                   7571:        */
                   7572: 
                   7573:       /* This loop fills the array Tvar from the string 'model'.*/
                   7574:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   7575:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   7576:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   7577:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   7578:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   7579:       /*       k=1 Tvar[1]=2 (from V2) */
                   7580:       /*       k=5 Tvar[5] */
                   7581:       /* for (k=1; k<=cptcovn;k++) { */
                   7582:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   7583:       /*       } */
                   7584:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
                   7585:       /*
                   7586:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   7587:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
                   7588:         Tvar[k]=0;
                   7589:       cptcovage=0;
                   7590:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
1.2     ! brouard  7591:                                cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
        !          7592:                                                                                                                                                                 modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
        !          7593:                                if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
        !          7594:                                /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
        !          7595:                                /*scanf("%d",i);*/
        !          7596:                                if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
        !          7597:                                        cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
        !          7598:                                        if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
        !          7599:                                                /* covar is not filled and then is empty */
        !          7600:                                                cptcovprod--;
        !          7601:                                                cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
        !          7602:                                                Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
        !          7603:                                                cptcovage++; /* Sums the number of covariates which include age as a product */
        !          7604:                                                Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
        !          7605:                                                /*printf("stre=%s ", stre);*/
        !          7606:                                        } else if (strcmp(strd,"age")==0) { /* or age*Vn */
        !          7607:                                                cptcovprod--;
        !          7608:                                                cutl(stre,strb,strc,'V');
        !          7609:                                                Tvar[k]=atoi(stre);
        !          7610:                                                cptcovage++;
        !          7611:                                                Tage[cptcovage]=k;
        !          7612:                                        } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
        !          7613:                                                /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
        !          7614:                                                cptcovn++;
        !          7615:                                                cptcovprodnoage++;k1++;
        !          7616:                                                cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
        !          7617:                                                Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
        !          7618:                                                                                                                                         because this model-covariate is a construction we invent a new column
        !          7619:                                                                                                                                         ncovcol + k1
        !          7620:                                                                                                                                         If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
        !          7621:                                                                                                                                         Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
        !          7622:                                                cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
        !          7623:                                                Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
        !          7624:                                                Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
        !          7625:                                                Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
        !          7626:                                                k2=k2+2;
        !          7627:                                                Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
        !          7628:                                                Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
        !          7629:                                                for (i=1; i<=lastobs;i++){
        !          7630:                                                        /* Computes the new covariate which is a product of
        !          7631:                                                                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
        !          7632:                                                        covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
        !          7633:                                                }
        !          7634:                                        } /* End age is not in the model */
        !          7635:                                } /* End if model includes a product */
        !          7636:                                else { /* no more sum */
        !          7637:                                        /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
        !          7638:                                        /*  scanf("%d",i);*/
        !          7639:                                        cutl(strd,strc,strb,'V');
        !          7640:                                        ks++; /**< Number of simple covariates */
        !          7641:                                        cptcovn++;
        !          7642:                                        Tvar[k]=atoi(strd);
        !          7643:                                }
        !          7644:                                strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
        !          7645:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
        !          7646:                                        scanf("%d",i);*/
1.1       brouard  7647:       } /* end of loop + on total covariates */
                   7648:     } /* end if strlen(modelsave == 0) age*age might exist */
                   7649:   } /* end if strlen(model == 0) */
                   7650:   
                   7651:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   7652:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   7653: 
                   7654:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.2     ! brouard  7655:                 printf("cptcovprod=%d ", cptcovprod);
        !          7656:                 fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
1.1       brouard  7657: 
1.2     ! brouard  7658:                 scanf("%d ",i);*/
        !          7659: /* Dispatching in quantitative and time varying covariates */
1.1       brouard  7660: 
                   7661: 
                   7662:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
                   7663:   /*endread:*/
1.2     ! brouard  7664:        printf("Exiting decodemodel: ");
        !          7665:        return (1);
1.1       brouard  7666: }
                   7667: 
                   7668: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
                   7669: {
                   7670:   int i, m;
                   7671:   int firstone=0;
                   7672:   
                   7673:   for (i=1; i<=imx; i++) {
                   7674:     for(m=2; (m<= maxwav); m++) {
                   7675:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   7676:        anint[m][i]=9999;
                   7677:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   7678:          s[m][i]=-1;
                   7679:       }
                   7680:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
                   7681:        *nberr = *nberr + 1;
                   7682:        if(firstone == 0){
                   7683:          firstone=1;
                   7684:        printf("Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results can be biased (%d) because status is a death state %d at wave %d. Wave dropped.\nOther similar cases in log file\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr,s[m][i],m);
                   7685:        }
                   7686:        fprintf(ficlog,"Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results can be biased (%d) because status is a death state %d at wave %d. Wave dropped.\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr,s[m][i],m);
                   7687:        s[m][i]=-1;
                   7688:       }
                   7689:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
                   7690:        (*nberr)++;
                   7691:        printf("Error! Month of death of individual %ld on line %d was unknown %2d, you should set it otherwise the information on the death is skipped and results are biased.\n",num[i],i,(int)moisdc[i]); 
                   7692:        fprintf(ficlog,"Error! Month of death of individual %ld on line %d was unknown %f, you should set it otherwise the information on the death is skipped and results are biased.\n",num[i],i,moisdc[i]); 
                   7693:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   7694:       }
                   7695:     }
                   7696:   }
                   7697: 
                   7698:   for (i=1; i<=imx; i++)  {
                   7699:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   7700:     for(m=firstpass; (m<= lastpass); m++){
                   7701:       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 */
                   7702:        if (s[m][i] >= nlstate+1) {
                   7703:          if(agedc[i]>0){
                   7704:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
                   7705:              agev[m][i]=agedc[i];
                   7706:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
                   7707:            }else {
                   7708:              if ((int)andc[i]!=9999){
                   7709:                nbwarn++;
                   7710:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   7711:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   7712:                agev[m][i]=-1;
                   7713:              }
                   7714:            }
                   7715:          } /* agedc > 0 */
                   7716:        } /* end if */
                   7717:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   7718:                                 years but with the precision of a month */
                   7719:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   7720:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   7721:            agev[m][i]=1;
                   7722:          else if(agev[m][i] < *agemin){ 
                   7723:            *agemin=agev[m][i];
                   7724:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   7725:          }
                   7726:          else if(agev[m][i] >*agemax){
                   7727:            *agemax=agev[m][i];
                   7728:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
                   7729:          }
                   7730:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   7731:          /*     agev[m][i] = age[i]+2*m;*/
                   7732:        } /* en if 9*/
                   7733:        else { /* =9 */
                   7734:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
                   7735:          agev[m][i]=1;
                   7736:          s[m][i]=-1;
                   7737:        }
                   7738:       }
                   7739:       else if(s[m][i]==0) /*= 0 Unknown */
                   7740:        agev[m][i]=1;
                   7741:       else{
                   7742:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   7743:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   7744:        agev[m][i]=0;
                   7745:       }
                   7746:     } /* End for lastpass */
                   7747:   }
                   7748:     
                   7749:   for (i=1; i<=imx; i++)  {
                   7750:     for(m=firstpass; (m<=lastpass); m++){
                   7751:       if (s[m][i] > (nlstate+ndeath)) {
                   7752:        (*nberr)++;
                   7753:        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);     
                   7754:        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);     
                   7755:        return 1;
                   7756:       }
                   7757:     }
                   7758:   }
                   7759: 
                   7760:   /*for (i=1; i<=imx; i++){
                   7761:   for (m=firstpass; (m<lastpass); m++){
                   7762:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   7763: }
                   7764: 
                   7765: }*/
                   7766: 
                   7767: 
                   7768:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   7769:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
                   7770: 
                   7771:   return (0);
                   7772:  /* endread:*/
                   7773:     printf("Exiting calandcheckages: ");
                   7774:     return (1);
                   7775: }
                   7776: 
                   7777: #if defined(_MSC_VER)
                   7778: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   7779: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   7780: //#include "stdafx.h"
                   7781: //#include <stdio.h>
                   7782: //#include <tchar.h>
                   7783: //#include <windows.h>
                   7784: //#include <iostream>
                   7785: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   7786: 
                   7787: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   7788: 
                   7789: BOOL IsWow64()
                   7790: {
                   7791:        BOOL bIsWow64 = FALSE;
                   7792: 
                   7793:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   7794:        //  (HANDLE, PBOOL);
                   7795: 
                   7796:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   7797: 
                   7798:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   7799:        const char funcName[] = "IsWow64Process";
                   7800:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   7801:                GetProcAddress(module, funcName);
                   7802: 
                   7803:        if (NULL != fnIsWow64Process)
                   7804:        {
                   7805:                if (!fnIsWow64Process(GetCurrentProcess(),
                   7806:                        &bIsWow64))
                   7807:                        //throw std::exception("Unknown error");
                   7808:                        printf("Unknown error\n");
                   7809:        }
                   7810:        return bIsWow64 != FALSE;
                   7811: }
                   7812: #endif
                   7813: 
                   7814: void syscompilerinfo(int logged)
                   7815:  {
                   7816:    /* #include "syscompilerinfo.h"*/
                   7817:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   7818:    /* /GS /W3 /Gy
                   7819:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   7820:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   7821:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
                   7822:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   7823:    */ 
                   7824:    /* 64 bits */
                   7825:    /*
                   7826:      /GS /W3 /Gy
                   7827:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   7828:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   7829:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   7830:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   7831:    /* Optimization are useless and O3 is slower than O2 */
                   7832:    /*
                   7833:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   7834:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   7835:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   7836:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   7837:    */
                   7838:    /* Link is */ /* /OUT:"visual studio
                   7839:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   7840:       /PDB:"visual studio
                   7841:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   7842:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   7843:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   7844:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   7845:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   7846:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   7847:       uiAccess='false'"
                   7848:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   7849:       /NOLOGO /TLBID:1
                   7850:    */
                   7851: #if defined __INTEL_COMPILER
                   7852: #if defined(__GNUC__)
                   7853:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   7854: #endif
                   7855: #elif defined(__GNUC__) 
                   7856: #ifndef  __APPLE__
                   7857: #include <gnu/libc-version.h>  /* Only on gnu */
                   7858: #endif
                   7859:    struct utsname sysInfo;
                   7860:    int cross = CROSS;
                   7861:    if (cross){
                   7862:           printf("Cross-");
                   7863:           if(logged) fprintf(ficlog, "Cross-");
                   7864:    }
                   7865: #endif
                   7866: 
                   7867: #include <stdint.h>
                   7868: 
                   7869:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
                   7870: #if defined(__clang__)
                   7871:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
                   7872: #endif
                   7873: #if defined(__ICC) || defined(__INTEL_COMPILER)
                   7874:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
                   7875: #endif
                   7876: #if defined(__GNUC__) || defined(__GNUG__)
                   7877:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
                   7878: #endif
                   7879: #if defined(__HP_cc) || defined(__HP_aCC)
                   7880:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
                   7881: #endif
                   7882: #if defined(__IBMC__) || defined(__IBMCPP__)
                   7883:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
                   7884: #endif
                   7885: #if defined(_MSC_VER)
                   7886:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
                   7887: #endif
                   7888: #if defined(__PGI)
                   7889:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
                   7890: #endif
                   7891: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
                   7892:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
                   7893: #endif
                   7894:    printf(" for "); if (logged) fprintf(ficlog, " for ");
                   7895:    
                   7896: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   7897: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   7898:     // Windows (x64 and x86)
                   7899:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
                   7900: #elif __unix__ // all unices, not all compilers
                   7901:     // Unix
                   7902:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
                   7903: #elif __linux__
                   7904:     // linux
                   7905:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
                   7906: #elif __APPLE__
                   7907:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
                   7908:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
                   7909: #endif
                   7910: 
                   7911: /*  __MINGW32__          */
                   7912: /*  __CYGWIN__  */
                   7913: /* __MINGW64__  */
                   7914: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   7915: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   7916: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   7917: /* _WIN64  // Defined for applications for Win64. */
                   7918: /* _M_X64 // Defined for compilations that target x64 processors. */
                   7919: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
                   7920: 
                   7921: #if UINTPTR_MAX == 0xffffffff
                   7922:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
                   7923: #elif UINTPTR_MAX == 0xffffffffffffffff
                   7924:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
                   7925: #else
                   7926:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
                   7927: #endif
                   7928: 
                   7929: #if defined(__GNUC__)
                   7930: # if defined(__GNUC_PATCHLEVEL__)
                   7931: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   7932:                             + __GNUC_MINOR__ * 100 \
                   7933:                             + __GNUC_PATCHLEVEL__)
                   7934: # else
                   7935: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   7936:                             + __GNUC_MINOR__ * 100)
                   7937: # endif
                   7938:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
                   7939:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
                   7940: 
                   7941:    if (uname(&sysInfo) != -1) {
                   7942:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
                   7943:         if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
                   7944:    }
                   7945:    else
                   7946:       perror("uname() error");
                   7947:    //#ifndef __INTEL_COMPILER 
                   7948: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
                   7949:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
                   7950:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
                   7951: #endif
                   7952: #endif
                   7953: 
                   7954:    //   void main()
                   7955:    //   {
                   7956: #if defined(_MSC_VER)
                   7957:    if (IsWow64()){
                   7958:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   7959:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   7960:    }
                   7961:    else{
                   7962:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   7963:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   7964:    }
                   7965:    //     printf("\nPress Enter to continue...");
                   7966:    //     getchar();
                   7967:    //   }
                   7968: 
                   7969: #endif
                   7970:    
                   7971: 
                   7972: }
                   7973: 
                   7974: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
                   7975:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   7976:   int i, j, k, i1 ;
                   7977:   /* double ftolpl = 1.e-10; */
                   7978:   double age, agebase, agelim;
                   7979:   double tot;
                   7980: 
                   7981:   strcpy(filerespl,"PL_");
                   7982:   strcat(filerespl,fileresu);
                   7983:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   7984:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   7985:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   7986:   }
                   7987:   printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   7988:   fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   7989:   pstamp(ficrespl);
                   7990:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
                   7991:   fprintf(ficrespl,"#Age ");
                   7992:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   7993:   fprintf(ficrespl,"\n");
                   7994:   
                   7995:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   7996: 
                   7997:   agebase=ageminpar;
                   7998:   agelim=agemaxpar;
                   7999: 
                   8000:   i1=pow(2,cptcoveff);
                   8001:   if (cptcovn < 1){i1=1;}
                   8002: 
                   8003:   for(k=1; k<=i1;k++){
                   8004:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   8005:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   8006:     //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   8007:     /* k=k+1; */
                   8008:     /* to clean */
                   8009:     //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   8010:     fprintf(ficrespl,"#******");
                   8011:     printf("#******");
                   8012:     fprintf(ficlog,"#******");
                   8013:     for(j=1;j<=cptcoveff;j++) {
                   8014:       fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8015:       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8016:       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8017:     }
                   8018:     fprintf(ficrespl,"******\n");
                   8019:     printf("******\n");
                   8020:     fprintf(ficlog,"******\n");
                   8021:                if(invalidvarcomb[k]){
                   8022:                                                printf("\nCombination (%d) ignored because no cases \n",k); 
                   8023:                                                fprintf(ficrespl,"#Combination (%d) ignored because no cases \n",k); 
                   8024:                                                fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   8025:                                                continue;
                   8026:                }
                   8027: 
                   8028:     fprintf(ficrespl,"#Age ");
                   8029:     for(j=1;j<=cptcoveff;j++) {
                   8030:       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8031:     }
                   8032:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   8033:     fprintf(ficrespl,"Total Years_to_converge\n");
                   8034:        
                   8035:     for (age=agebase; age<=agelim; age++){
                   8036:       /* for (age=agebase; age<=agebase; age++){ */
                   8037:       prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
                   8038:       fprintf(ficrespl,"%.0f ",age );
                   8039:       for(j=1;j<=cptcoveff;j++)
                   8040:                                                        fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8041:       tot=0.;
                   8042:       for(i=1; i<=nlstate;i++){
                   8043:                                                        tot +=  prlim[i][i];
                   8044:                                                        fprintf(ficrespl," %.5f", prlim[i][i]);
                   8045:       }
                   8046:       fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   8047:     } /* Age */
                   8048:     /* was end of cptcod */
                   8049:   } /* cptcov */
                   8050:   return 0;
                   8051: }
                   8052: 
                   8053: 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){
                   8054:        /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   8055:        
                   8056:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   8057:    * at any age between ageminpar and agemaxpar
                   8058:         */
                   8059:   int i, j, k, i1 ;
                   8060:   /* double ftolpl = 1.e-10; */
                   8061:   double age, agebase, agelim;
                   8062:   double tot;
                   8063:   /* double ***mobaverage; */
                   8064:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
                   8065: 
                   8066:   strcpy(fileresplb,"PLB_");
                   8067:   strcat(fileresplb,fileresu);
                   8068:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
                   8069:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   8070:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   8071:   }
                   8072:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   8073:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   8074:   pstamp(ficresplb);
                   8075:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
                   8076:   fprintf(ficresplb,"#Age ");
                   8077:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   8078:   fprintf(ficresplb,"\n");
                   8079:   
                   8080:   
                   8081:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   8082:   
                   8083:   agebase=ageminpar;
                   8084:   agelim=agemaxpar;
                   8085:   
                   8086:   
                   8087:   i1=pow(2,cptcoveff);
                   8088:   if (cptcovn < 1){i1=1;}
                   8089: 
                   8090:        for(k=1; k<=i1;k++){ 
                   8091:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   8092:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   8093:     //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   8094:     /* k=k+1; */
                   8095:     /* to clean */
                   8096:     //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   8097:     fprintf(ficresplb,"#******");
                   8098:     printf("#******");
                   8099:     fprintf(ficlog,"#******");
                   8100:     for(j=1;j<=cptcoveff;j++) {
                   8101:       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8102:       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8103:       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8104:     }
                   8105:     fprintf(ficresplb,"******\n");
                   8106:     printf("******\n");
                   8107:     fprintf(ficlog,"******\n");
                   8108:                if(invalidvarcomb[k]){
                   8109:                                                printf("\nCombination (%d) ignored because no cases \n",k); 
                   8110:                                                fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   8111:                                                fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   8112:                                                continue;
                   8113:                }
                   8114:     
                   8115:     fprintf(ficresplb,"#Age ");
                   8116:     for(j=1;j<=cptcoveff;j++) {
                   8117:       fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8118:     }
                   8119:     for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   8120:     fprintf(ficresplb,"Total Years_to_converge\n");
                   8121:     
                   8122:     
                   8123:     for (age=agebase; age<=agelim; age++){
                   8124:       /* for (age=agebase; age<=agebase; age++){ */
                   8125:       if(mobilavproj > 0){
                   8126:        /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   8127:        /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   8128:                                bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k);
                   8129:       }else if (mobilavproj == 0){
                   8130:                                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);
                   8131:                                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);
                   8132:                                exit(1);
                   8133:       }else{
                   8134:                                /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   8135:                                bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k);
                   8136:       }
                   8137:       fprintf(ficresplb,"%.0f ",age );
                   8138:       for(j=1;j<=cptcoveff;j++)
                   8139:                                fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8140:       tot=0.;
                   8141:       for(i=1; i<=nlstate;i++){
                   8142:                                tot +=  bprlim[i][i];
                   8143:                                fprintf(ficresplb," %.5f", bprlim[i][i]);
                   8144:       }
                   8145:       fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   8146:     } /* Age */
                   8147:     /* was end of cptcod */
                   8148:   } /* cptcov */
                   8149:   
                   8150:   /* hBijx(p, bage, fage); */
                   8151:   /* fclose(ficrespijb); */
                   8152:   
                   8153:   return 0;
                   8154: }
                   8155:  
                   8156: int hPijx(double *p, int bage, int fage){
                   8157:     /*------------- h Pij x at various ages ------------*/
                   8158: 
                   8159:   int stepsize;
                   8160:   int agelim;
                   8161:   int hstepm;
                   8162:   int nhstepm;
                   8163:   int h, i, i1, j, k;
                   8164: 
                   8165:   double agedeb;
                   8166:   double ***p3mat;
                   8167: 
                   8168:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   8169:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   8170:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   8171:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   8172:     }
                   8173:     printf("Computing pij: result on file '%s' \n", filerespij);
                   8174:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   8175:   
                   8176:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8177:     /*if (stepm<=24) stepsize=2;*/
                   8178: 
                   8179:     agelim=AGESUP;
                   8180:     hstepm=stepsize*YEARM; /* Every year of age */
                   8181:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   8182:                
                   8183:     /* hstepm=1;   aff par mois*/
                   8184:     pstamp(ficrespij);
                   8185:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   8186:     i1= pow(2,cptcoveff);
                   8187:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   8188:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   8189:                /*      k=k+1;  */
                   8190:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   8191:       fprintf(ficrespij,"\n#****** ");
                   8192:       for(j=1;j<=cptcoveff;j++) 
                   8193:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8194:       fprintf(ficrespij,"******\n");
                   8195:       
                   8196:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   8197:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   8198:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   8199:        
                   8200:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   8201:        
                   8202:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8203:        oldm=oldms;savm=savms;
                   8204:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   8205:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   8206:        for(i=1; i<=nlstate;i++)
                   8207:          for(j=1; j<=nlstate+ndeath;j++)
                   8208:            fprintf(ficrespij," %1d-%1d",i,j);
                   8209:        fprintf(ficrespij,"\n");
                   8210:        for (h=0; h<=nhstepm; h++){
                   8211:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   8212:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
                   8213:          for(i=1; i<=nlstate;i++)
                   8214:            for(j=1; j<=nlstate+ndeath;j++)
                   8215:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
                   8216:          fprintf(ficrespij,"\n");
                   8217:        }
                   8218:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8219:        fprintf(ficrespij,"\n");
                   8220:       }
                   8221:       /*}*/
                   8222:     }
                   8223:     return 0;
                   8224: }
                   8225:  
                   8226:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
                   8227:     /*------------- h Bij x at various ages ------------*/
                   8228: 
                   8229:   int stepsize;
                   8230:   /* int agelim; */
                   8231:        int ageminl;
                   8232:   int hstepm;
                   8233:   int nhstepm;
                   8234:   int h, i, i1, j, k;
                   8235:        
                   8236:   double agedeb;
                   8237:   double ***p3mat;
                   8238:        
                   8239:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   8240:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   8241:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   8242:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   8243:   }
                   8244:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   8245:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   8246:   
                   8247:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8248:   /*if (stepm<=24) stepsize=2;*/
                   8249:   
                   8250:   /* agelim=AGESUP; */
                   8251:   ageminl=30;
                   8252:   hstepm=stepsize*YEARM; /* Every year of age */
                   8253:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   8254:   
                   8255:   /* hstepm=1;   aff par mois*/
                   8256:   pstamp(ficrespijb);
                   8257:   fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
                   8258:   i1= pow(2,cptcoveff);
                   8259:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   8260:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   8261:   /*   k=k+1;  */
                   8262:   for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   8263:     fprintf(ficrespijb,"\n#****** ");
                   8264:     for(j=1;j<=cptcoveff;j++)
                   8265:       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8266:     fprintf(ficrespijb,"******\n");
                   8267:     if(invalidvarcomb[k]){
                   8268:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   8269:       continue;
                   8270:     }
                   8271:     
                   8272:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   8273:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   8274:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   8275:       nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
                   8276:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
                   8277:       
                   8278:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   8279:       
                   8280:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8281:       /* oldm=oldms;savm=savms; */
                   8282:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   8283:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
                   8284:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   8285:       fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
                   8286:       for(i=1; i<=nlstate;i++)
                   8287:        for(j=1; j<=nlstate+ndeath;j++)
                   8288:          fprintf(ficrespijb," %1d-%1d",i,j);
                   8289:       fprintf(ficrespijb,"\n");
                   8290:       for (h=0; h<=nhstepm; h++){
                   8291:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   8292:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   8293:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   8294:        for(i=1; i<=nlstate;i++)
                   8295:          for(j=1; j<=nlstate+ndeath;j++)
                   8296:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
                   8297:        fprintf(ficrespijb,"\n");
                   8298:       }
                   8299:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8300:       fprintf(ficrespijb,"\n");
                   8301:     }
                   8302:     /*}*/
                   8303:   }
                   8304:   return 0;
                   8305:  } /*  hBijx */
                   8306: 
                   8307: 
                   8308: /***********************************************/
                   8309: /**************** Main Program *****************/
                   8310: /***********************************************/
                   8311: 
                   8312: int main(int argc, char *argv[])
                   8313: {
                   8314: #ifdef GSL
                   8315:   const gsl_multimin_fminimizer_type *T;
                   8316:   size_t iteri = 0, it;
                   8317:   int rval = GSL_CONTINUE;
                   8318:   int status = GSL_SUCCESS;
                   8319:   double ssval;
                   8320: #endif
                   8321:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
                   8322:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
                   8323:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
                   8324:   int jj, ll, li, lj, lk;
                   8325:   int numlinepar=0; /* Current linenumber of parameter file */
                   8326:   int num_filled;
                   8327:   int itimes;
                   8328:   int NDIM=2;
                   8329:   int vpopbased=0;
                   8330: 
                   8331:   char ca[32], cb[32];
                   8332:   /*  FILE *fichtm; *//* Html File */
                   8333:   /* FILE *ficgp;*/ /*Gnuplot File */
                   8334:   struct stat info;
                   8335:   double agedeb=0.;
                   8336: 
                   8337:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
                   8338:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
                   8339: 
                   8340:   double fret;
                   8341:   double dum=0.; /* Dummy variable */
                   8342:   double ***p3mat;
                   8343:   /* double ***mobaverage; */
                   8344: 
                   8345:   char line[MAXLINE];
                   8346:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   8347: 
                   8348:   char model[MAXLINE], modeltemp[MAXLINE];
                   8349:   char pathr[MAXLINE], pathimach[MAXLINE]; 
                   8350:   char *tok, *val; /* pathtot */
                   8351:   int firstobs=1, lastobs=10;
                   8352:   int c,  h , cpt, c2;
                   8353:   int jl=0;
                   8354:   int i1, j1, jk, stepsize=0;
                   8355:   int count=0;
                   8356: 
                   8357:   int *tab; 
                   8358:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   8359:   int backcast=0;
                   8360:   int mobilav=0,popforecast=0;
                   8361:   int hstepm=0, nhstepm=0;
                   8362:   int agemortsup;
                   8363:   float  sumlpop=0.;
                   8364:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   8365:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   8366: 
                   8367:   double bage=0, fage=110., age, agelim=0., agebase=0.;
                   8368:   double ftolpl=FTOL;
                   8369:   double **prlim;
                   8370:   double **bprlim;
                   8371:   double ***param; /* Matrix of parameters */
                   8372:   double  *p;
                   8373:   double **matcov; /* Matrix of covariance */
                   8374:   double **hess; /* Hessian matrix */
                   8375:   double ***delti3; /* Scale */
                   8376:   double *delti; /* Scale */
                   8377:   double ***eij, ***vareij;
                   8378:   double **varpl; /* Variances of prevalence limits by age */
                   8379:   double *epj, vepp;
                   8380: 
                   8381:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   8382:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
                   8383: 
                   8384:   double **ximort;
                   8385:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
                   8386:   int *dcwave;
                   8387: 
                   8388:   char z[1]="c";
                   8389: 
                   8390:   /*char  *strt;*/
                   8391:   char strtend[80];
                   8392: 
                   8393: 
                   8394: /*   setlocale (LC_ALL, ""); */
                   8395: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   8396: /*   textdomain (PACKAGE); */
                   8397: /*   setlocale (LC_CTYPE, ""); */
                   8398: /*   setlocale (LC_MESSAGES, ""); */
                   8399: 
                   8400:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
                   8401:   rstart_time = time(NULL);  
                   8402:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   8403:   start_time = *localtime(&rstart_time);
                   8404:   curr_time=start_time;
                   8405:   /*tml = *localtime(&start_time.tm_sec);*/
                   8406:   /* strcpy(strstart,asctime(&tml)); */
                   8407:   strcpy(strstart,asctime(&start_time));
                   8408: 
                   8409: /*  printf("Localtime (at start)=%s",strstart); */
                   8410: /*  tp.tm_sec = tp.tm_sec +86400; */
                   8411: /*  tm = *localtime(&start_time.tm_sec); */
                   8412: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   8413: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   8414: /*   tmg.tm_hour=tmg.tm_hour + 1; */
                   8415: /*   tp.tm_sec = mktime(&tmg); */
                   8416: /*   strt=asctime(&tmg); */
                   8417: /*   printf("Time(after) =%s",strstart);  */
                   8418: /*  (void) time (&time_value);
                   8419: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   8420: *  tm = *localtime(&time_value);
                   8421: *  strstart=asctime(&tm);
                   8422: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   8423: */
                   8424: 
                   8425:   nberr=0; /* Number of errors and warnings */
                   8426:   nbwarn=0;
                   8427: #ifdef WIN32
                   8428:   _getcwd(pathcd, size);
                   8429: #else
                   8430:   getcwd(pathcd, size);
                   8431: #endif
                   8432:   syscompilerinfo(0);
                   8433:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
                   8434:   if(argc <=1){
                   8435:     printf("\nEnter the parameter file name: ");
                   8436:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   8437:       printf("ERROR Empty parameter file name\n");
                   8438:       goto end;
                   8439:     }
                   8440:     i=strlen(pathr);
                   8441:     if(pathr[i-1]=='\n')
                   8442:       pathr[i-1]='\0';
                   8443:     i=strlen(pathr);
                   8444:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
                   8445:       pathr[i-1]='\0';
                   8446:     }
                   8447:     i=strlen(pathr);
                   8448:     if( i==0 ){
                   8449:       printf("ERROR Empty parameter file name\n");
                   8450:       goto end;
                   8451:     }
                   8452:     for (tok = pathr; tok != NULL; ){
                   8453:       printf("Pathr |%s|\n",pathr);
                   8454:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   8455:       printf("val= |%s| pathr=%s\n",val,pathr);
                   8456:       strcpy (pathtot, val);
                   8457:       if(pathr[0] == '\0') break; /* Dirty */
                   8458:     }
                   8459:   }
                   8460:   else{
                   8461:     strcpy(pathtot,argv[1]);
                   8462:   }
                   8463:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   8464:   /*cygwin_split_path(pathtot,path,optionfile);
                   8465:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   8466:   /* cutv(path,optionfile,pathtot,'\\');*/
                   8467: 
                   8468:   /* Split argv[0], imach program to get pathimach */
                   8469:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   8470:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   8471:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   8472:  /*   strcpy(pathimach,argv[0]); */
                   8473:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   8474:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   8475:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
                   8476: #ifdef WIN32
                   8477:   _chdir(path); /* Can be a relative path */
                   8478:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   8479: #else
                   8480:   chdir(path); /* Can be a relative path */
                   8481:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   8482: #endif
                   8483:   printf("Current directory %s!\n",pathcd);
                   8484:   strcpy(command,"mkdir ");
                   8485:   strcat(command,optionfilefiname);
                   8486:   if((outcmd=system(command)) != 0){
                   8487:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
                   8488:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   8489:     /* fclose(ficlog); */
                   8490: /*     exit(1); */
                   8491:   }
                   8492: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   8493: /*     perror("mkdir"); */
                   8494: /*   } */
                   8495: 
                   8496:   /*-------- arguments in the command line --------*/
                   8497: 
                   8498:   /* Main Log file */
                   8499:   strcat(filelog, optionfilefiname);
                   8500:   strcat(filelog,".log");    /* */
                   8501:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   8502:     printf("Problem with logfile %s\n",filelog);
                   8503:     goto end;
                   8504:   }
                   8505:   fprintf(ficlog,"Log filename:%s\n",filelog);
                   8506:   fprintf(ficlog,"Version %s %s",version,fullversion);
                   8507:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   8508:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   8509:  path=%s \n\
                   8510:  optionfile=%s\n\
                   8511:  optionfilext=%s\n\
                   8512:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
                   8513: 
                   8514:   syscompilerinfo(1);
                   8515: 
                   8516:   printf("Local time (at start):%s",strstart);
                   8517:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   8518:   fflush(ficlog);
                   8519: /*   (void) gettimeofday(&curr_time,&tzp); */
                   8520: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
                   8521: 
                   8522:   /* */
                   8523:   strcpy(fileres,"r");
                   8524:   strcat(fileres, optionfilefiname);
                   8525:   strcat(fileresu, optionfilefiname); /* Without r in front */
                   8526:   strcat(fileres,".txt");    /* Other files have txt extension */
                   8527:   strcat(fileresu,".txt");    /* Other files have txt extension */
                   8528: 
                   8529:   /* Main ---------arguments file --------*/
                   8530: 
                   8531:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
                   8532:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   8533:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   8534:     fflush(ficlog);
                   8535:     /* goto end; */
                   8536:     exit(70); 
                   8537:   }
                   8538: 
                   8539: 
                   8540: 
                   8541:   strcpy(filereso,"o");
                   8542:   strcat(filereso,fileresu);
                   8543:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   8544:     printf("Problem with Output resultfile: %s\n", filereso);
                   8545:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   8546:     fflush(ficlog);
                   8547:     goto end;
                   8548:   }
                   8549: 
                   8550:   /* Reads comments: lines beginning with '#' */
                   8551:   numlinepar=0;
                   8552: 
                   8553:     /* First parameter line */
                   8554:   while(fgets(line, MAXLINE, ficpar)) {
                   8555:     /* If line starts with a # it is a comment */
                   8556:     if (line[0] == '#') {
                   8557:       numlinepar++;
                   8558:       fputs(line,stdout);
                   8559:       fputs(line,ficparo);
                   8560:       fputs(line,ficlog);
                   8561:       continue;
                   8562:     }else
                   8563:       break;
                   8564:   }
                   8565:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   8566:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   8567:     if (num_filled != 5) {
                   8568:       printf("Should be 5 parameters\n");
                   8569:     }
                   8570:     numlinepar++;
                   8571:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   8572:   }
                   8573:   /* Second parameter line */
                   8574:   while(fgets(line, MAXLINE, ficpar)) {
                   8575:     /* If line starts with a # it is a comment */
                   8576:     if (line[0] == '#') {
                   8577:       numlinepar++;
                   8578:       fputs(line,stdout);
                   8579:       fputs(line,ficparo);
                   8580:       fputs(line,ficlog);
                   8581:       continue;
                   8582:     }else
                   8583:       break;
                   8584:   }
                   8585:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
                   8586:                        &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   8587:     if (num_filled != 8) {
                   8588:       printf("Not 8 parameters, for example:ftol=1.e-8 stepm=12 ncovcol=2 nlstate=2 ndeath=1 maxwav=3 mle=1 weight=1\n");
                   8589:       printf("but line=%s\n",line);
                   8590:     }
                   8591:     printf("ftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n",ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt);
                   8592:   }
                   8593:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   8594:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   8595:   /* Third parameter line */
                   8596:   while(fgets(line, MAXLINE, ficpar)) {
                   8597:     /* If line starts with a # it is a comment */
                   8598:     if (line[0] == '#') {
                   8599:       numlinepar++;
                   8600:       fputs(line,stdout);
                   8601:       fputs(line,ficparo);
                   8602:       fputs(line,ficlog);
                   8603:       continue;
                   8604:     }else
                   8605:       break;
                   8606:   }
                   8607:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   8608:     if (num_filled == 0)
                   8609:             model[0]='\0';
                   8610:     else if (num_filled != 1){
                   8611:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   8612:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   8613:       model[0]='\0';
                   8614:       goto end;
                   8615:     }
                   8616:     else{
                   8617:       if (model[0]=='+'){
                   8618:        for(i=1; i<=strlen(model);i++)
                   8619:          modeltemp[i-1]=model[i];
                   8620:        strcpy(model,modeltemp); 
                   8621:       }
                   8622:     }
                   8623:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
                   8624:     printf("model=1+age+%s\n",model);fflush(stdout);
                   8625:   }
                   8626:   /* 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); */
                   8627:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   8628:   /* 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); */
                   8629:   fprintf(ficparo,"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);
                   8630:   fprintf(ficlog,"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);
                   8631:   fflush(ficlog);
                   8632:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   8633:   if(model[0]=='#'){
                   8634:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   8635:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   8636:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   8637:     if(mle != -1){
                   8638:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   8639:       exit(1);
                   8640:     }
                   8641:   }
                   8642:   while((c=getc(ficpar))=='#' && c!= EOF){
                   8643:     ungetc(c,ficpar);
                   8644:     fgets(line, MAXLINE, ficpar);
                   8645:     numlinepar++;
                   8646:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   8647:       z[0]=line[1];
                   8648:     }
                   8649:     /* printf("****line [1] = %c \n",line[1]); */
                   8650:     fputs(line, stdout);
                   8651:     //puts(line);
                   8652:     fputs(line,ficparo);
                   8653:     fputs(line,ficlog);
                   8654:   }
                   8655:   ungetc(c,ficpar);
                   8656: 
                   8657:    
                   8658:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
                   8659:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   8660:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   8661:      v1+v2*age+v2*v3 makes cptcovn = 3
                   8662:   */
                   8663:   if (strlen(model)>1) 
                   8664:     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*/
                   8665:   else
                   8666:     ncovmodel=2; /* Constant and age */
                   8667:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   8668:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
                   8669:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   8670:     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);
                   8671:     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);
                   8672:     fflush(stdout);
                   8673:     fclose (ficlog);
                   8674:     goto end;
                   8675:   }
                   8676:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   8677:   delti=delti3[1][1];
                   8678:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   8679:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   8680:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   8681:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   8682:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   8683:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   8684:     fclose (ficparo);
                   8685:     fclose (ficlog);
                   8686:     goto end;
                   8687:     exit(0);
                   8688:   }  else if(mle==-5) { /* Main Wizard */
                   8689:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   8690:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   8691:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   8692:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   8693:     matcov=matrix(1,npar,1,npar);
                   8694:     hess=matrix(1,npar,1,npar);
                   8695:   }  else{ /* Begin of mle != -1 or -5 */
                   8696:     /* Read guessed parameters */
                   8697:     /* Reads comments: lines beginning with '#' */
                   8698:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8699:       ungetc(c,ficpar);
                   8700:       fgets(line, MAXLINE, ficpar);
                   8701:       numlinepar++;
                   8702:       fputs(line,stdout);
                   8703:       fputs(line,ficparo);
                   8704:       fputs(line,ficlog);
                   8705:     }
                   8706:     ungetc(c,ficpar);
                   8707:     
                   8708:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   8709:     for(i=1; i <=nlstate; i++){
                   8710:                        j=0;
                   8711:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   8712:                                if(jj==i) continue;
                   8713:                                j++;
                   8714:                                fscanf(ficpar,"%1d%1d",&i1,&j1);
                   8715:                                if ((i1 != i) || (j1 != jj)){
                   8716:                                        printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   8717: It might be a problem of design; if ncovcol and the model are correct\n \
                   8718: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   8719:                                        exit(1);
                   8720:                                }
                   8721:                                fprintf(ficparo,"%1d%1d",i1,j1);
                   8722:                                if(mle==1)
                   8723:                                        printf("%1d%1d",i,jj);
                   8724:                                fprintf(ficlog,"%1d%1d",i,jj);
                   8725:                                for(k=1; k<=ncovmodel;k++){
                   8726:                                        fscanf(ficpar," %lf",&param[i][j][k]);
                   8727:                                        if(mle==1){
                   8728:                                                printf(" %lf",param[i][j][k]);
                   8729:                                                fprintf(ficlog," %lf",param[i][j][k]);
                   8730:                                        }
                   8731:                                        else
                   8732:                                                fprintf(ficlog," %lf",param[i][j][k]);
                   8733:                                        fprintf(ficparo," %lf",param[i][j][k]);
                   8734:                                }
                   8735:                                fscanf(ficpar,"\n");
                   8736:                                numlinepar++;
                   8737:                                if(mle==1)
                   8738:                                        printf("\n");
                   8739:                                fprintf(ficlog,"\n");
                   8740:                                fprintf(ficparo,"\n");
                   8741:       }
                   8742:     }  
                   8743:     fflush(ficlog);
                   8744: 
                   8745:     /* Reads scales values */
                   8746:     p=param[1][1];
                   8747:     
                   8748:     /* Reads comments: lines beginning with '#' */
                   8749:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8750:       ungetc(c,ficpar);
                   8751:       fgets(line, MAXLINE, ficpar);
                   8752:       numlinepar++;
                   8753:       fputs(line,stdout);
                   8754:       fputs(line,ficparo);
                   8755:       fputs(line,ficlog);
                   8756:     }
                   8757:     ungetc(c,ficpar);
                   8758: 
                   8759:     for(i=1; i <=nlstate; i++){
                   8760:       for(j=1; j <=nlstate+ndeath-1; j++){
                   8761:                                fscanf(ficpar,"%1d%1d",&i1,&j1);
                   8762:                                if ( (i1-i) * (j1-j) != 0){
                   8763:                                        printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   8764:                                        exit(1);
                   8765:                                }
                   8766:                                printf("%1d%1d",i,j);
                   8767:                                fprintf(ficparo,"%1d%1d",i1,j1);
                   8768:                                fprintf(ficlog,"%1d%1d",i1,j1);
                   8769:                                for(k=1; k<=ncovmodel;k++){
                   8770:                                        fscanf(ficpar,"%le",&delti3[i][j][k]);
                   8771:                                        printf(" %le",delti3[i][j][k]);
                   8772:                                        fprintf(ficparo," %le",delti3[i][j][k]);
                   8773:                                        fprintf(ficlog," %le",delti3[i][j][k]);
                   8774:                                }
                   8775:                                fscanf(ficpar,"\n");
                   8776:                                numlinepar++;
                   8777:                                printf("\n");
                   8778:                                fprintf(ficparo,"\n");
                   8779:                                fprintf(ficlog,"\n");
                   8780:       }
                   8781:     }
                   8782:     fflush(ficlog);
                   8783:                
                   8784:     /* Reads covariance matrix */
                   8785:     delti=delti3[1][1];
                   8786:                
                   8787:                
                   8788:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   8789:                
                   8790:     /* Reads comments: lines beginning with '#' */
                   8791:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8792:       ungetc(c,ficpar);
                   8793:       fgets(line, MAXLINE, ficpar);
                   8794:       numlinepar++;
                   8795:       fputs(line,stdout);
                   8796:       fputs(line,ficparo);
                   8797:       fputs(line,ficlog);
                   8798:     }
                   8799:     ungetc(c,ficpar);
                   8800:                
                   8801:     matcov=matrix(1,npar,1,npar);
                   8802:     hess=matrix(1,npar,1,npar);
                   8803:     for(i=1; i <=npar; i++)
                   8804:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   8805:                
                   8806:     /* Scans npar lines */
                   8807:     for(i=1; i <=npar; i++){
                   8808:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
                   8809:       if(count != 3){
                   8810:                                printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   8811: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   8812: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   8813:                                fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   8814: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   8815: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   8816:                                exit(1);
                   8817:       }else{
                   8818:                                if(mle==1)
                   8819:                                        printf("%1d%1d%1d",i1,j1,jk);
                   8820:                        }
                   8821:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
                   8822:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
                   8823:       for(j=1; j <=i; j++){
                   8824:                                fscanf(ficpar," %le",&matcov[i][j]);
                   8825:                                if(mle==1){
                   8826:                                        printf(" %.5le",matcov[i][j]);
                   8827:                                }
                   8828:                                fprintf(ficlog," %.5le",matcov[i][j]);
                   8829:                                fprintf(ficparo," %.5le",matcov[i][j]);
                   8830:       }
                   8831:       fscanf(ficpar,"\n");
                   8832:       numlinepar++;
                   8833:       if(mle==1)
                   8834:                                printf("\n");
                   8835:       fprintf(ficlog,"\n");
                   8836:       fprintf(ficparo,"\n");
                   8837:     }
                   8838:     /* End of read covariance matrix npar lines */
                   8839:     for(i=1; i <=npar; i++)
                   8840:       for(j=i+1;j<=npar;j++)
                   8841:                                matcov[i][j]=matcov[j][i];
                   8842:     
                   8843:     if(mle==1)
                   8844:       printf("\n");
                   8845:     fprintf(ficlog,"\n");
                   8846:     
                   8847:     fflush(ficlog);
                   8848:     
                   8849:     /*-------- Rewriting parameter file ----------*/
                   8850:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   8851:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   8852:     strcat(rfileres,".");    /* */
                   8853:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   8854:     if((ficres =fopen(rfileres,"w"))==NULL) {
                   8855:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   8856:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   8857:     }
1.2     ! brouard  8858:     fprintf(ficres,"#IMaCh version %s\n",version);
1.1       brouard  8859:   }    /* End of mle != -3 */
                   8860:   
                   8861:   /*  Main data
                   8862:    */
                   8863:   n= lastobs;
                   8864:   num=lvector(1,n);
                   8865:   moisnais=vector(1,n);
                   8866:   annais=vector(1,n);
                   8867:   moisdc=vector(1,n);
                   8868:   andc=vector(1,n);
                   8869:   weight=vector(1,n);
                   8870:   agedc=vector(1,n);
                   8871:   cod=ivector(1,n);
                   8872:   for(i=1;i<=n;i++){
                   8873:                num[i]=0;
                   8874:                moisnais[i]=0;
                   8875:                annais[i]=0;
                   8876:                moisdc[i]=0;
                   8877:                andc[i]=0;
                   8878:                agedc[i]=0;
                   8879:                cod[i]=0;
                   8880:                weight[i]=1.0; /* Equal weights, 1 by default */
                   8881:        }
                   8882:   mint=matrix(1,maxwav,1,n);
                   8883:   anint=matrix(1,maxwav,1,n);
                   8884:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
                   8885:   tab=ivector(1,NCOVMAX);
                   8886:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
                   8887:   ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
                   8888: 
                   8889:   /* Reads data from file datafile */
                   8890:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   8891:     goto end;
                   8892: 
                   8893:   /* Calculation of the number of parameters from char model */
                   8894:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   8895:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   8896:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   8897:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   8898:        k=1 Tvar[1]=2 (from V2)
                   8899:     */
                   8900:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   8901:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   8902:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   8903:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   8904:   */
                   8905:   /* For model-covariate k tells which data-covariate to use but
                   8906:     because this model-covariate is a construction we invent a new column
                   8907:     ncovcol + k1
                   8908:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   8909:     Tvar[3=V1*V4]=4+1 etc */
                   8910:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
                   8911:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   8912:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   8913:   */
                   8914:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   8915:   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
                   8916:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   8917:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
                   8918:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
                   8919:                         4 covariates (3 plus signs)
                   8920:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   8921:                      */  
                   8922: 
                   8923: /* Main decodemodel */
                   8924: 
                   8925: 
1.2     ! brouard  8926:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.1       brouard  8927:     goto end;
                   8928: 
                   8929:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   8930:     nbwarn++;
                   8931:     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); 
                   8932:     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); 
                   8933:   }
                   8934:     /*  if(mle==1){*/
                   8935:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   8936:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
                   8937:   }
                   8938: 
                   8939:     /*-calculation of age at interview from date of interview and age at death -*/
                   8940:   agev=matrix(1,maxwav,1,imx);
                   8941: 
                   8942:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   8943:     goto end;
                   8944: 
                   8945: 
                   8946:   agegomp=(int)agemin;
                   8947:   free_vector(moisnais,1,n);
                   8948:   free_vector(annais,1,n);
                   8949:   /* free_matrix(mint,1,maxwav,1,n);
                   8950:      free_matrix(anint,1,maxwav,1,n);*/
                   8951:   /* free_vector(moisdc,1,n); */
                   8952:   /* free_vector(andc,1,n); */
                   8953:   /* */
                   8954:   
                   8955:   wav=ivector(1,imx);
                   8956:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   8957:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   8958:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   8959:   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.*/
                   8960:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   8961:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
                   8962:    
                   8963:   /* Concatenates waves */
                   8964:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   8965:      Death is a valid wave (if date is known).
                   8966:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   8967:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   8968:      and mw[mi+1][i]. dh depends on stepm.
                   8969:   */
                   8970: 
                   8971:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
                   8972:   /* */
                   8973:  
                   8974:   free_vector(moisdc,1,n);
                   8975:   free_vector(andc,1,n);
                   8976: 
                   8977:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   8978:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   8979:   ncodemax[1]=1;
                   8980:   Ndum =ivector(-1,NCOVMAX);  
                   8981:        cptcoveff=0;
                   8982:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   8983:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
                   8984:        }
                   8985:        
                   8986:        ncovcombmax=pow(2,cptcoveff);
                   8987:        invalidvarcomb=ivector(1, ncovcombmax); 
                   8988:        for(i=1;i<ncovcombmax;i++)
                   8989:                invalidvarcomb[i]=0;
                   8990: 
                   8991:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
                   8992:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
                   8993:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
                   8994: 
                   8995:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
                   8996:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
                   8997:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
                   8998:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   8999:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   9000:    * (currently 0 or 1) in the data.
                   9001:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   9002:    * corresponding modality (h,j).
                   9003:    */
                   9004: 
                   9005:   h=0;
                   9006:   /*if (cptcovn > 0) */
                   9007:   m=pow(2,cptcoveff);
                   9008:  
                   9009:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
                   9010:           * For k=4 covariates, h goes from 1 to m=2**k
                   9011:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   9012:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   9013:           *     h\k   1     2     3     4
                   9014:           *______________________________  
                   9015:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   9016:           *     2     2     1     1     1
                   9017:           *     3 i=2 1     2     1     1
                   9018:           *     4     2     2     1     1
                   9019:           *     5 i=3 1 i=2 1     2     1
                   9020:           *     6     2     1     2     1
                   9021:           *     7 i=4 1     2     2     1
                   9022:           *     8     2     2     2     1
                   9023:           *     9 i=5 1 i=3 1 i=2 1     2
                   9024:           *    10     2     1     1     2
                   9025:           *    11 i=6 1     2     1     2
                   9026:           *    12     2     2     1     2
                   9027:           *    13 i=7 1 i=4 1     2     2    
                   9028:           *    14     2     1     2     2
                   9029:           *    15 i=8 1     2     2     2
                   9030:           *    16     2     2     2     2
                   9031:           */
                   9032:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
                   9033:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   9034:      * and the value of each covariate?
                   9035:      * V1=1, V2=1, V3=2, V4=1 ?
                   9036:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   9037:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   9038:      * In order to get the real value in the data, we use nbcode
                   9039:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   9040:      * We are keeping this crazy system in order to be able (in the future?) 
                   9041:      * to have more than 2 values (0 or 1) for a covariate.
                   9042:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   9043:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   9044:      *              bbbbbbbb
                   9045:      *              76543210     
                   9046:      *   h-1        00000101 (6-1=5)
                   9047:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
                   9048:      *           &
                   9049:      *     1        00000001 (1)
                   9050:      *              00000000        = 1 & ((h-1) >> (k-1))
                   9051:      *          +1= 00000001 =1 
                   9052:      *
                   9053:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   9054:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   9055:      *    >>k'            11
                   9056:      *          &   00000001
                   9057:      *            = 00000001
                   9058:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   9059:      * Reverse h=6 and m=16?
                   9060:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   9061:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   9062:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   9063:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   9064:      * V3=decodtabm(14,3,2**4)=2
                   9065:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   9066:      *(h-1) >> (j-1)    0011 =13 >> 2
                   9067:      *          &1 000000001
                   9068:      *           = 000000001
                   9069:      *         +1= 000000010 =2
                   9070:      *                  2211
                   9071:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   9072:      *                  V3=2
                   9073:                 * codtabm and decodtabm are identical
                   9074:      */
                   9075: 
                   9076: 
                   9077:  free_ivector(Ndum,-1,NCOVMAX);
                   9078: 
                   9079: 
                   9080:     
                   9081:   /* Initialisation of ----------- gnuplot -------------*/
                   9082:   strcpy(optionfilegnuplot,optionfilefiname);
                   9083:   if(mle==-3)
                   9084:     strcat(optionfilegnuplot,"-MORT_");
                   9085:   strcat(optionfilegnuplot,".gp");
                   9086: 
                   9087:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   9088:     printf("Problem with file %s",optionfilegnuplot);
                   9089:   }
                   9090:   else{
                   9091:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
                   9092:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
                   9093:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   9094:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
                   9095:   }
                   9096:   /*  fclose(ficgp);*/
                   9097: 
                   9098: 
                   9099:   /* Initialisation of --------- index.htm --------*/
                   9100: 
                   9101:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   9102:   if(mle==-3)
                   9103:     strcat(optionfilehtm,"-MORT_");
                   9104:   strcat(optionfilehtm,".htm");
                   9105:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
                   9106:     printf("Problem with %s \n",optionfilehtm);
                   9107:     exit(0);
                   9108:   }
                   9109: 
                   9110:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   9111:   strcat(optionfilehtmcov,"-cov.htm");
                   9112:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   9113:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   9114:   }
                   9115:   else{
                   9116:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   9117: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   9118: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
                   9119:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   9120:   }
                   9121: 
                   9122:   fprintf(fichtm,"<html><head>\n<head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n<title>IMaCh %s</title></head>\n <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n<font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>-EUROREVES-Institut de longévité-2013-2016-Japan Society for the Promotion of Sciences 日本学術振興会 (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br>  \
                   9123: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   9124: <font size=\"2\">IMaCh-%s <br> %s</font> \
                   9125: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   9126: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
                   9127: \n\
                   9128: <hr  size=\"2\" color=\"#EC5E5E\">\
                   9129:  <ul><li><h4>Parameter files</h4>\n\
                   9130:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   9131:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   9132:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   9133:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   9134:  - Date and time at start: %s</ul>\n",\
                   9135:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   9136:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   9137:          fileres,fileres,\
                   9138:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   9139:   fflush(fichtm);
                   9140: 
                   9141:   strcpy(pathr,path);
                   9142:   strcat(pathr,optionfilefiname);
                   9143: #ifdef WIN32
                   9144:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   9145: #else
                   9146:   chdir(optionfilefiname); /* Move to directory named optionfile */
                   9147: #endif
                   9148:          
                   9149:   
                   9150:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   9151:                 and for any valid combination of covariates
                   9152:      and prints on file fileres'p'. */
                   9153:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart,   \
                   9154:              firstpass, lastpass,  stepm,  weightopt, model);
                   9155: 
                   9156:   fprintf(fichtm,"\n");
                   9157:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   9158: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   9159: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   9160:          imx,agemin,agemax,jmin,jmax,jmean);
                   9161:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   9162:        oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   9163:        newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   9164:        savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   9165:        oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   9166: 
                   9167:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   9168:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   9169:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   9170: 
                   9171:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
                   9172:   /* For mortality only */
                   9173:   if (mle==-3){
                   9174:     ximort=matrix(1,NDIM,1,NDIM); 
                   9175:                for(i=1;i<=NDIM;i++)
                   9176:                        for(j=1;j<=NDIM;j++)
                   9177:                                ximort[i][j]=0.;
                   9178:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
                   9179:     cens=ivector(1,n);
                   9180:     ageexmed=vector(1,n);
                   9181:     agecens=vector(1,n);
                   9182:     dcwave=ivector(1,n);
1.2     ! brouard  9183:                
1.1       brouard  9184:     for (i=1; i<=imx; i++){
                   9185:       dcwave[i]=-1;
                   9186:       for (m=firstpass; m<=lastpass; m++)
                   9187:                                if (s[m][i]>nlstate) {
                   9188:                                        dcwave[i]=m;
                   9189:                                        /*      printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   9190:                                        break;
                   9191:                                }
                   9192:     }
                   9193:                
                   9194:     for (i=1; i<=imx; i++) {
                   9195:       if (wav[i]>0){
                   9196:                                ageexmed[i]=agev[mw[1][i]][i];
                   9197:                                j=wav[i];
                   9198:                                agecens[i]=1.; 
                   9199:                                
                   9200:                                if (ageexmed[i]> 1 && wav[i] > 0){
                   9201:                                        agecens[i]=agev[mw[j][i]][i];
                   9202:                                        cens[i]= 1;
                   9203:                                }else if (ageexmed[i]< 1) 
                   9204:                                        cens[i]= -1;
                   9205:                                if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   9206:                                        cens[i]=0 ;
                   9207:       }
                   9208:       else cens[i]=-1;
                   9209:     }
                   9210:     
                   9211:     for (i=1;i<=NDIM;i++) {
                   9212:       for (j=1;j<=NDIM;j++)
                   9213:                                ximort[i][j]=(i == j ? 1.0 : 0.0);
                   9214:     }
                   9215:     
                   9216:     /*p[1]=0.0268; p[NDIM]=0.083;*/
                   9217:     /*printf("%lf %lf", p[1], p[2]);*/
                   9218:     
                   9219:     
                   9220: #ifdef GSL
                   9221:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
                   9222: #else
                   9223:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
                   9224: #endif
                   9225:     strcpy(filerespow,"POW-MORT_"); 
                   9226:     strcat(filerespow,fileresu);
                   9227:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   9228:       printf("Problem with resultfile: %s\n", filerespow);
                   9229:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   9230:     }
                   9231: #ifdef GSL
                   9232:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
                   9233: #else
                   9234:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   9235: #endif
                   9236:     /*  for (i=1;i<=nlstate;i++)
                   9237:        for(j=1;j<=nlstate+ndeath;j++)
                   9238:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   9239:     */
                   9240:     fprintf(ficrespow,"\n");
                   9241: #ifdef GSL
                   9242:     /* gsl starts here */ 
                   9243:     T = gsl_multimin_fminimizer_nmsimplex;
                   9244:     gsl_multimin_fminimizer *sfm = NULL;
                   9245:     gsl_vector *ss, *x;
                   9246:     gsl_multimin_function minex_func;
                   9247: 
                   9248:     /* Initial vertex size vector */
                   9249:     ss = gsl_vector_alloc (NDIM);
                   9250:     
                   9251:     if (ss == NULL){
                   9252:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   9253:     }
                   9254:     /* Set all step sizes to 1 */
                   9255:     gsl_vector_set_all (ss, 0.001);
                   9256: 
                   9257:     /* Starting point */
                   9258:     
                   9259:     x = gsl_vector_alloc (NDIM);
                   9260:     
                   9261:     if (x == NULL){
                   9262:       gsl_vector_free(ss);
                   9263:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   9264:     }
                   9265:   
                   9266:     /* Initialize method and iterate */
                   9267:     /*     p[1]=0.0268; p[NDIM]=0.083; */
                   9268:     /*     gsl_vector_set(x, 0, 0.0268); */
                   9269:     /*     gsl_vector_set(x, 1, 0.083); */
                   9270:     gsl_vector_set(x, 0, p[1]);
                   9271:     gsl_vector_set(x, 1, p[2]);
                   9272: 
                   9273:     minex_func.f = &gompertz_f;
                   9274:     minex_func.n = NDIM;
                   9275:     minex_func.params = (void *)&p; /* ??? */
                   9276:     
                   9277:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   9278:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   9279:     
                   9280:     printf("Iterations beginning .....\n\n");
                   9281:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   9282: 
                   9283:     iteri=0;
                   9284:     while (rval == GSL_CONTINUE){
                   9285:       iteri++;
                   9286:       status = gsl_multimin_fminimizer_iterate(sfm);
                   9287:       
                   9288:       if (status) printf("error: %s\n", gsl_strerror (status));
                   9289:       fflush(0);
                   9290:       
                   9291:       if (status) 
                   9292:         break;
                   9293:       
                   9294:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   9295:       ssval = gsl_multimin_fminimizer_size (sfm);
                   9296:       
                   9297:       if (rval == GSL_SUCCESS)
                   9298:         printf ("converged to a local maximum at\n");
                   9299:       
                   9300:       printf("%5d ", iteri);
                   9301:       for (it = 0; it < NDIM; it++){
                   9302:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   9303:       }
                   9304:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   9305:     }
                   9306:     
                   9307:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   9308:     
                   9309:     gsl_vector_free(x); /* initial values */
                   9310:     gsl_vector_free(ss); /* inital step size */
                   9311:     for (it=0; it<NDIM; it++){
                   9312:       p[it+1]=gsl_vector_get(sfm->x,it);
                   9313:       fprintf(ficrespow," %.12lf", p[it]);
                   9314:     }
                   9315:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   9316: #endif
                   9317: #ifdef POWELL
                   9318:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   9319: #endif  
                   9320:     fclose(ficrespow);
                   9321:     
                   9322:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
                   9323: 
                   9324:     for(i=1; i <=NDIM; i++)
                   9325:       for(j=i+1;j<=NDIM;j++)
                   9326:                                matcov[i][j]=matcov[j][i];
                   9327:     
                   9328:     printf("\nCovariance matrix\n ");
                   9329:     fprintf(ficlog,"\nCovariance matrix\n ");
                   9330:     for(i=1; i <=NDIM; i++) {
                   9331:       for(j=1;j<=NDIM;j++){ 
                   9332:                                printf("%f ",matcov[i][j]);
                   9333:                                fprintf(ficlog,"%f ",matcov[i][j]);
                   9334:       }
                   9335:       printf("\n ");  fprintf(ficlog,"\n ");
                   9336:     }
                   9337:     
                   9338:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
                   9339:     for (i=1;i<=NDIM;i++) {
                   9340:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   9341:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   9342:     }
                   9343:     lsurv=vector(1,AGESUP);
                   9344:     lpop=vector(1,AGESUP);
                   9345:     tpop=vector(1,AGESUP);
                   9346:     lsurv[agegomp]=100000;
                   9347:     
                   9348:     for (k=agegomp;k<=AGESUP;k++) {
                   9349:       agemortsup=k;
                   9350:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   9351:     }
                   9352:     
                   9353:     for (k=agegomp;k<agemortsup;k++)
                   9354:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   9355:     
                   9356:     for (k=agegomp;k<agemortsup;k++){
                   9357:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   9358:       sumlpop=sumlpop+lpop[k];
                   9359:     }
                   9360:     
                   9361:     tpop[agegomp]=sumlpop;
                   9362:     for (k=agegomp;k<(agemortsup-3);k++){
                   9363:       /*  tpop[k+1]=2;*/
                   9364:       tpop[k+1]=tpop[k]-lpop[k];
                   9365:     }
                   9366:     
                   9367:     
                   9368:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   9369:     for (k=agegomp;k<(agemortsup-2);k++) 
                   9370:       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]);
                   9371:     
                   9372:     
                   9373:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   9374:                ageminpar=50;
                   9375:                agemaxpar=100;
                   9376:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   9377:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   9378: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9379: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   9380:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   9381: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9382: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   9383:     }else{
                   9384:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   9385:                        fprintf(ficlog,"Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   9386:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   9387:                }
                   9388:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
                   9389:                     stepm, weightopt,\
                   9390:                     model,imx,p,matcov,agemortsup);
                   9391:     
                   9392:     free_vector(lsurv,1,AGESUP);
                   9393:     free_vector(lpop,1,AGESUP);
                   9394:     free_vector(tpop,1,AGESUP);
                   9395:     free_matrix(ximort,1,NDIM,1,NDIM);
                   9396:     free_ivector(cens,1,n);
                   9397:     free_vector(agecens,1,n);
                   9398:     free_ivector(dcwave,1,n);
                   9399: #ifdef GSL
                   9400: #endif
                   9401:   } /* Endof if mle==-3 mortality only */
                   9402:   /* Standard  */
                   9403:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   9404:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   9405:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   9406:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   9407:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   9408:     for (k=1; k<=npar;k++)
                   9409:       printf(" %d %8.5f",k,p[k]);
                   9410:     printf("\n");
                   9411:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   9412:       /* mlikeli uses func not funcone */
                   9413:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   9414:     }
                   9415:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   9416:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   9417:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   9418:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   9419:     }
                   9420:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
                   9421:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   9422:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   9423:     for (k=1; k<=npar;k++)
                   9424:       printf(" %d %8.5f",k,p[k]);
                   9425:     printf("\n");
                   9426:     
                   9427:     /*--------- results files --------------*/
                   9428:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle= 0 weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate, ndeath, maxwav, weightopt,model);
                   9429:     
                   9430:     
                   9431:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9432:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9433:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9434:     for(i=1,jk=1; i <=nlstate; i++){
                   9435:       for(k=1; k <=(nlstate+ndeath); k++){
                   9436:                                if (k != i) {
                   9437:                                        printf("%d%d ",i,k);
                   9438:                                        fprintf(ficlog,"%d%d ",i,k);
                   9439:                                        fprintf(ficres,"%1d%1d ",i,k);
                   9440:                                        for(j=1; j <=ncovmodel; j++){
                   9441:                                                printf("%12.7f ",p[jk]);
                   9442:                                                fprintf(ficlog,"%12.7f ",p[jk]);
                   9443:                                                fprintf(ficres,"%12.7f ",p[jk]);
                   9444:                                                jk++; 
                   9445:                                        }
                   9446:                                        printf("\n");
                   9447:                                        fprintf(ficlog,"\n");
                   9448:                                        fprintf(ficres,"\n");
                   9449:                                }
                   9450:       }
                   9451:     }
                   9452:     if(mle != 0){
                   9453:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
                   9454:       ftolhess=ftol; /* Usually correct */
                   9455:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   9456:       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");
                   9457:       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");
                   9458:       for(i=1,jk=1; i <=nlstate; i++){
                   9459:                                for(k=1; k <=(nlstate+ndeath); k++){
                   9460:                                        if (k != i) {
                   9461:                                                printf("%d%d ",i,k);
                   9462:                                                fprintf(ficlog,"%d%d ",i,k);
                   9463:                                                for(j=1; j <=ncovmodel; j++){
                   9464:                                                        printf("%12.7f W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
                   9465:                                                        fprintf(ficlog,"%12.7f W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
                   9466:                                                        jk++; 
                   9467:                                                }
                   9468:                                                printf("\n");
                   9469:                                                fprintf(ficlog,"\n");
                   9470:                                        }
                   9471:                                }
                   9472:       }
                   9473:     } /* end of hesscov and Wald tests */
                   9474:                
                   9475:     /*  */
                   9476:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   9477:     printf("# Scales (for hessian or gradient estimation)\n");
                   9478:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   9479:     for(i=1,jk=1; i <=nlstate; i++){
                   9480:       for(j=1; j <=nlstate+ndeath; j++){
                   9481:                                if (j!=i) {
                   9482:                                        fprintf(ficres,"%1d%1d",i,j);
                   9483:                                        printf("%1d%1d",i,j);
                   9484:                                        fprintf(ficlog,"%1d%1d",i,j);
                   9485:                                        for(k=1; k<=ncovmodel;k++){
                   9486:                                                printf(" %.5e",delti[jk]);
                   9487:                                                fprintf(ficlog," %.5e",delti[jk]);
                   9488:                                                fprintf(ficres," %.5e",delti[jk]);
                   9489:                                                jk++;
                   9490:                                        }
                   9491:                                        printf("\n");
                   9492:                                        fprintf(ficlog,"\n");
                   9493:                                        fprintf(ficres,"\n");
                   9494:                                }
                   9495:       }
                   9496:     }
                   9497:     
                   9498:     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");
                   9499:     if(mle >= 1) /* To big for the screen */
                   9500:       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");
                   9501:     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");
                   9502:     /* # 121 Var(a12)\n\ */
                   9503:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9504:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   9505:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   9506:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   9507:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   9508:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   9509:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   9510:     
                   9511:     
                   9512:     /* Just to have a covariance matrix which will be more understandable
                   9513:        even is we still don't want to manage dictionary of variables
                   9514:     */
                   9515:     for(itimes=1;itimes<=2;itimes++){
                   9516:       jj=0;
                   9517:       for(i=1; i <=nlstate; i++){
                   9518:                                for(j=1; j <=nlstate+ndeath; j++){
                   9519:                                        if(j==i) continue;
                   9520:                                        for(k=1; k<=ncovmodel;k++){
                   9521:                                                jj++;
                   9522:                                                ca[0]= k+'a'-1;ca[1]='\0';
                   9523:                                                if(itimes==1){
                   9524:                                                        if(mle>=1)
                   9525:                                                                printf("#%1d%1d%d",i,j,k);
                   9526:                                                        fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   9527:                                                        fprintf(ficres,"#%1d%1d%d",i,j,k);
                   9528:                                                }else{
                   9529:                                                        if(mle>=1)
                   9530:                                                                printf("%1d%1d%d",i,j,k);
                   9531:                                                        fprintf(ficlog,"%1d%1d%d",i,j,k);
                   9532:                                                        fprintf(ficres,"%1d%1d%d",i,j,k);
                   9533:                                                }
                   9534:                                                ll=0;
                   9535:                                                for(li=1;li <=nlstate; li++){
                   9536:                                                        for(lj=1;lj <=nlstate+ndeath; lj++){
                   9537:                                                                if(lj==li) continue;
                   9538:                                                                for(lk=1;lk<=ncovmodel;lk++){
                   9539:                                                                        ll++;
                   9540:                                                                        if(ll<=jj){
                   9541:                                                                                cb[0]= lk +'a'-1;cb[1]='\0';
                   9542:                                                                                if(ll<jj){
                   9543:                                                                                        if(itimes==1){
                   9544:                                                                                                if(mle>=1)
                   9545:                                                                                                        printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9546:                                                                                                fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9547:                                                                                                fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9548:                                                                                        }else{
                   9549:                                                                                                if(mle>=1)
                   9550:                                                                                                        printf(" %.5e",matcov[jj][ll]); 
                   9551:                                                                                                fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   9552:                                                                                                fprintf(ficres," %.5e",matcov[jj][ll]); 
                   9553:                                                                                        }
                   9554:                                                                                }else{
                   9555:                                                                                        if(itimes==1){
                   9556:                                                                                                if(mle>=1)
                   9557:                                                                                                        printf(" Var(%s%1d%1d)",ca,i,j);
                   9558:                                                                                                fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   9559:                                                                                                fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   9560:                                                                                        }else{
                   9561:                                                                                                if(mle>=1)
                   9562:                                                                                                        printf(" %.7e",matcov[jj][ll]); 
                   9563:                                                                                                fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   9564:                                                                                                fprintf(ficres," %.7e",matcov[jj][ll]); 
                   9565:                                                                                        }
                   9566:                                                                                }
                   9567:                                                                        }
                   9568:                                                                } /* end lk */
                   9569:                                                        } /* end lj */
                   9570:                                                } /* end li */
                   9571:                                                if(mle>=1)
                   9572:                                                        printf("\n");
                   9573:                                                fprintf(ficlog,"\n");
                   9574:                                                fprintf(ficres,"\n");
                   9575:                                                numlinepar++;
                   9576:                                        } /* end k*/
                   9577:                                } /*end j */
                   9578:       } /* end i */
                   9579:     } /* end itimes */
                   9580:     
                   9581:     fflush(ficlog);
                   9582:     fflush(ficres);
                   9583:                while(fgets(line, MAXLINE, ficpar)) {
                   9584:                        /* If line starts with a # it is a comment */
                   9585:                        if (line[0] == '#') {
                   9586:                                numlinepar++;
                   9587:                                fputs(line,stdout);
                   9588:                                fputs(line,ficparo);
                   9589:                                fputs(line,ficlog);
                   9590:                                continue;
                   9591:                        }else
                   9592:                                break;
                   9593:                }
                   9594:                
                   9595:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   9596:     /*   ungetc(c,ficpar); */
                   9597:     /*   fgets(line, MAXLINE, ficpar); */
                   9598:     /*   fputs(line,stdout); */
                   9599:     /*   fputs(line,ficparo); */
                   9600:     /* } */
                   9601:     /* ungetc(c,ficpar); */
                   9602:     
                   9603:     estepm=0;
                   9604:     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){
                   9605:                        
                   9606:                        if (num_filled != 6) {
                   9607:                                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);
                   9608:                                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);
                   9609:                                goto end;
                   9610:                        }
                   9611:                        printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   9612:                }
                   9613:                /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   9614:                /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   9615:                
                   9616:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
                   9617:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   9618:     if (fage <= 2) {
                   9619:       bage = ageminpar;
                   9620:       fage = agemaxpar;
                   9621:     }
                   9622:     
                   9623:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   9624:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   9625:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   9626:                
                   9627:     /* Other stuffs, more or less useful */    
                   9628:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9629:       ungetc(c,ficpar);
                   9630:       fgets(line, MAXLINE, ficpar);
                   9631:       fputs(line,stdout);
                   9632:       fputs(line,ficparo);
                   9633:     }
                   9634:     ungetc(c,ficpar);
                   9635:     
                   9636:     fscanf(ficpar,"begin-prev-date=%lf/%lf/%lf end-prev-date=%lf/%lf/%lf mov_average=%d\n",&jprev1, &mprev1,&anprev1,&jprev2, &mprev2,&anprev2,&mobilav);
                   9637:     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);
                   9638:     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);
                   9639:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   9640:     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);
                   9641:     
                   9642:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9643:       ungetc(c,ficpar);
                   9644:       fgets(line, MAXLINE, ficpar);
                   9645:       fputs(line,stdout);
                   9646:       fputs(line,ficparo);
                   9647:     }
                   9648:     ungetc(c,ficpar);
                   9649:     
                   9650:     
                   9651:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   9652:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   9653:     
                   9654:     fscanf(ficpar,"pop_based=%d\n",&popbased);
                   9655:     fprintf(ficlog,"pop_based=%d\n",popbased);
                   9656:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   9657:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   9658:     
                   9659:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9660:       ungetc(c,ficpar);
                   9661:       fgets(line, MAXLINE, ficpar);
                   9662:       fputs(line,stdout);
                   9663:       fputs(line,ficparo);
                   9664:     }
                   9665:     ungetc(c,ficpar);
                   9666:     
                   9667:     fscanf(ficpar,"prevforecast=%d starting-proj-date=%lf/%lf/%lf final-proj-date=%lf/%lf/%lf mobil_average=%d\n",&prevfcast,&jproj1,&mproj1,&anproj1,&jproj2,&mproj2,&anproj2,&mobilavproj);
                   9668:     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);
                   9669:     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);
                   9670:     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);
                   9671:     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);
                   9672:     /* day and month of proj2 are not used but only year anproj2.*/
                   9673:     
                   9674:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9675:       ungetc(c,ficpar);
                   9676:       fgets(line, MAXLINE, ficpar);
                   9677:       fputs(line,stdout);
                   9678:       fputs(line,ficparo);
                   9679:     }
                   9680:     ungetc(c,ficpar);
                   9681:     
                   9682:     fscanf(ficpar,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",&backcast,&jback1,&mback1,&anback1,&jback2,&mback2,&anback2,&mobilavproj);
1.2     ! brouard  9683:     fprintf(ficparo,"backcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
        !          9684:     fprintf(ficlog,"backcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
        !          9685:     fprintf(ficres,"backcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
1.1       brouard  9686:     /* day and month of proj2 are not used but only year anproj2.*/
                   9687:     
                   9688:     
                   9689:                /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   9690:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
                   9691:     
                   9692:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   9693:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
                   9694:                        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   9695: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9696: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   9697:                        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   9698: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9699: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   9700:     }else{
                   9701:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
                   9702:     }
                   9703:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
                   9704:                                                                 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
                   9705:                                                                 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
                   9706:                
                   9707:                /*------------ free_vector  -------------*/
                   9708:                /*  chdir(path); */
                   9709:                
                   9710:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   9711:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   9712:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   9713:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
                   9714:     free_lvector(num,1,n);
                   9715:     free_vector(agedc,1,n);
                   9716:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   9717:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   9718:     fclose(ficparo);
                   9719:     fclose(ficres);
                   9720:                
                   9721:                
                   9722:     /* Other results (useful)*/
                   9723:                
                   9724:                
                   9725:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   9726:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   9727:     prlim=matrix(1,nlstate,1,nlstate);
                   9728:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
                   9729:     fclose(ficrespl);
                   9730: 
                   9731:     /*------------- h Pij x at various ages ------------*/
                   9732:     /*#include "hpijx.h"*/
                   9733:     hPijx(p, bage, fage);
                   9734:     fclose(ficrespij);
                   9735: 
                   9736:     /* ncovcombmax=  pow(2,cptcoveff); */
                   9737:     /*-------------- Variance of one-step probabilities---*/
                   9738:     k=1;
                   9739:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   9740: 
                   9741:     /* Prevalence for each covariates in probs[age][status][cov] */
                   9742:     probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   9743:     for(i=1;i<=AGESUP;i++)
                   9744:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
                   9745:                                for(k=1;k<=ncovcombmax;k++)
                   9746:                                        probs[i][j][k]=0.;
                   9747:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   9748:     if (mobilav!=0 ||mobilavproj !=0 ) {
                   9749:       mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   9750:                        for(i=1;i<=AGESUP;i++)
                   9751:                                for(j=1;j<=nlstate;j++)
                   9752:                                        for(k=1;k<=ncovcombmax;k++)
                   9753:                                                mobaverages[i][j][k]=0.;
                   9754:       mobaverage=mobaverages;
                   9755:       if (mobilav!=0) {
                   9756:                                if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   9757:                                        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   9758:                                        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   9759:                                }
                   9760:       }
                   9761:       /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
                   9762:       /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   9763:       else if (mobilavproj !=0) {
                   9764:                                if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   9765:                                        fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   9766:                                        printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   9767:                                }
                   9768:       }
                   9769:     }/* end if moving average */
                   9770:                
                   9771:     /*---------- Forecasting ------------------*/
                   9772:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   9773:     if(prevfcast==1){
                   9774:       /*    if(stepm ==1){*/
                   9775:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
                   9776:     }
                   9777:     if(backcast==1){
                   9778:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   9779:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   9780:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   9781: 
                   9782:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   9783: 
                   9784:       bprlim=matrix(1,nlstate,1,nlstate);
                   9785:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   9786:       fclose(ficresplb);
                   9787: 
                   9788:       hBijx(p, bage, fage, mobaverage);
                   9789:       fclose(ficrespijb);
                   9790:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   9791: 
                   9792:       /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
                   9793:         bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   9794:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   9795:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   9796:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   9797:     }
                   9798:     
                   9799:  
                   9800:     /* ------ Other prevalence ratios------------ */
                   9801: 
                   9802:     free_ivector(wav,1,imx);
                   9803:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   9804:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   9805:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
                   9806:                
                   9807:                
                   9808:     /*---------- Health expectancies, no variances ------------*/
                   9809:                
                   9810:     strcpy(filerese,"E_");
                   9811:     strcat(filerese,fileresu);
                   9812:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   9813:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   9814:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   9815:     }
                   9816:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   9817:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
                   9818:                
                   9819:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   9820:       fprintf(ficreseij,"\n#****** ");
                   9821:       for(j=1;j<=cptcoveff;j++) {
                   9822:                                fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9823:       }
                   9824:       fprintf(ficreseij,"******\n");
                   9825:       
                   9826:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   9827:       oldm=oldms;savm=savms;
                   9828:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   9829:       
                   9830:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   9831:     }
                   9832:     fclose(ficreseij);
                   9833:     printf("done evsij\n");fflush(stdout);
                   9834:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
                   9835:                
                   9836:     /*---------- Health expectancies and variances ------------*/
                   9837:                
                   9838:                
                   9839:     strcpy(filerest,"T_");
                   9840:     strcat(filerest,fileresu);
                   9841:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   9842:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   9843:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   9844:     }
                   9845:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   9846:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
                   9847:                
                   9848: 
                   9849:     strcpy(fileresstde,"STDE_");
                   9850:     strcat(fileresstde,fileresu);
                   9851:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   9852:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   9853:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   9854:     }
                   9855:     printf("  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   9856:     fprintf(ficlog,"  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   9857: 
                   9858:     strcpy(filerescve,"CVE_");
                   9859:     strcat(filerescve,fileresu);
                   9860:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   9861:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   9862:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   9863:     }
                   9864:     printf("    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   9865:     fprintf(ficlog,"    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   9866: 
                   9867:     strcpy(fileresv,"V_");
                   9868:     strcat(fileresv,fileresu);
                   9869:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   9870:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   9871:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   9872:     }
                   9873:     printf("      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
                   9874:     fprintf(ficlog,"      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
                   9875: 
                   9876:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9877:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9878:           
                   9879:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   9880:       fprintf(ficrest,"\n#****** ");
                   9881:       for(j=1;j<=cptcoveff;j++) 
                   9882:                                fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9883:       fprintf(ficrest,"******\n");
                   9884:       
                   9885:       fprintf(ficresstdeij,"\n#****** ");
                   9886:       fprintf(ficrescveij,"\n#****** ");
                   9887:       for(j=1;j<=cptcoveff;j++) {
                   9888:                                fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9889:                                fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9890:       }
                   9891:       fprintf(ficresstdeij,"******\n");
                   9892:       fprintf(ficrescveij,"******\n");
                   9893:       
                   9894:       fprintf(ficresvij,"\n#****** ");
                   9895:       for(j=1;j<=cptcoveff;j++) 
                   9896:                                fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9897:       fprintf(ficresvij,"******\n");
                   9898:       
                   9899:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   9900:       oldm=oldms;savm=savms;
                   9901:       printf(" cvevsij %d, ",k);
                   9902:       fprintf(ficlog, " cvevsij %d, ",k);
                   9903:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
                   9904:       printf(" end cvevsij \n ");
                   9905:       fprintf(ficlog, " end cvevsij \n ");
                   9906:       
                   9907:       /*
                   9908:        */
                   9909:       /* goto endfree; */
                   9910:       
                   9911:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   9912:       pstamp(ficrest);
                   9913:       
                   9914:       
                   9915:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   9916:                                oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   9917:                                cptcod= 0; /* To be deleted */
                   9918:                                printf("varevsij %d \n",vpopbased);
                   9919:                                fprintf(ficlog, "varevsij %d \n",vpopbased);
                   9920:                                varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); /* cptcod not initialized Intel */
                   9921:                                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 ");
                   9922:                                if(vpopbased==1)
                   9923:                                        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);
                   9924:                                else
                   9925:                                        fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   9926:                                fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   9927:                                for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   9928:                                fprintf(ficrest,"\n");
                   9929:                                /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   9930:                                epj=vector(1,nlstate+1);
                   9931:                                printf("Computing age specific period (stable) prevalences in each health state \n");
                   9932:                                fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
                   9933:                                for(age=bage; age <=fage ;age++){
                   9934:                                        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
                   9935:                                        if (vpopbased==1) {
                   9936:                                                if(mobilav ==0){
                   9937:                                                        for(i=1; i<=nlstate;i++)
                   9938:                                                                prlim[i][i]=probs[(int)age][i][k];
                   9939:                                                }else{ /* mobilav */ 
                   9940:                                                        for(i=1; i<=nlstate;i++)
                   9941:                                                                prlim[i][i]=mobaverage[(int)age][i][k];
                   9942:                                                }
                   9943:                                        }
                   9944:          
                   9945:                                        fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   9946:                                        /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   9947:                                        /* printf(" age %4.0f ",age); */
                   9948:                                        for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   9949:                                                for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   9950:                                                        epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   9951:                                                        /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   9952:                                                        /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   9953:                                                }
                   9954:                                                epj[nlstate+1] +=epj[j];
                   9955:                                        }
                   9956:                                        /* printf(" age %4.0f \n",age); */
                   9957:          
                   9958:                                        for(i=1, vepp=0.;i <=nlstate;i++)
                   9959:                                                for(j=1;j <=nlstate;j++)
                   9960:                                                        vepp += vareij[i][j][(int)age];
                   9961:                                        fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   9962:                                        for(j=1;j <=nlstate;j++){
                   9963:                                                fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   9964:                                        }
                   9965:                                        fprintf(ficrest,"\n");
                   9966:                                }
                   9967:       } /* End vpopbased */
                   9968:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   9969:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   9970:       free_vector(epj,1,nlstate+1);
                   9971:       printf("done \n");fflush(stdout);
                   9972:       fprintf(ficlog,"done\n");fflush(ficlog);
                   9973:       
                   9974:       /*}*/
                   9975:     } /* End k */
                   9976:     free_vector(weight,1,n);
                   9977:     free_imatrix(Tvard,1,NCOVMAX,1,2);
                   9978:     free_imatrix(s,1,maxwav+1,1,n);
                   9979:     free_matrix(anint,1,maxwav,1,n); 
                   9980:     free_matrix(mint,1,maxwav,1,n);
                   9981:     free_ivector(cod,1,n);
                   9982:     free_ivector(tab,1,NCOVMAX);
                   9983:     fclose(ficresstdeij);
                   9984:     fclose(ficrescveij);
                   9985:     fclose(ficresvij);
                   9986:     fclose(ficrest);
                   9987:     printf("done Health expectancies\n");fflush(stdout);
                   9988:     fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
                   9989:     fclose(ficpar);
                   9990:   
                   9991:     /*------- Variance of period (stable) prevalence------*/   
                   9992: 
                   9993:     strcpy(fileresvpl,"VPL_");
                   9994:     strcat(fileresvpl,fileresu);
                   9995:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   9996:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   9997:       exit(0);
                   9998:     }
                   9999:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   10000:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
                   10001: 
                   10002:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   10003:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   10004:           
                   10005:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   10006:        fprintf(ficresvpl,"\n#****** ");
                   10007:                        for(j=1;j<=cptcoveff;j++) 
                   10008:                                fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10009:                        fprintf(ficresvpl,"******\n");
                   10010:       
                   10011:                        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10012:                        oldm=oldms;savm=savms;
                   10013:                        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
                   10014:                        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   10015:       /*}*/
                   10016:     }
                   10017:                
                   10018:     fclose(ficresvpl);
                   10019:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
                   10020:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
                   10021: 
                   10022:     /*---------- End : free ----------------*/
                   10023:     if (mobilav!=0 ||mobilavproj !=0)
                   10024:       free_ma3x(mobaverages,1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   10025:     free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   10026:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   10027:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   10028:   }  /* mle==-3 arrives here for freeing */
                   10029:  /* endfree:*/
                   10030:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   10031:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   10032:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   10033:     free_matrix(covar,0,NCOVMAX,1,n);
                   10034:     free_matrix(matcov,1,npar,1,npar);
                   10035:     free_matrix(hess,1,npar,1,npar);
                   10036:     /*free_vector(delti,1,npar);*/
                   10037:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   10038:     free_matrix(agev,1,maxwav,1,imx);
                   10039:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   10040: 
                   10041:     free_ivector(ncodemax,1,NCOVMAX);
                   10042:     free_ivector(ncodemaxwundef,1,NCOVMAX);
                   10043:     free_ivector(Tvar,1,NCOVMAX);
                   10044:     free_ivector(Tprod,1,NCOVMAX);
                   10045:     free_ivector(Tvaraff,1,NCOVMAX);
                   10046:     free_ivector(invalidvarcomb,1,ncovcombmax);
                   10047:     free_ivector(Tage,1,NCOVMAX);
                   10048: 
                   10049:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   10050:     /* free_imatrix(codtab,1,100,1,10); */
                   10051:   fflush(fichtm);
                   10052:   fflush(ficgp);
                   10053:   
                   10054: 
                   10055:   if((nberr >0) || (nbwarn>0)){
                   10056:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   10057:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d. Please look at the log file for details.\n",nberr,nbwarn);
                   10058:   }else{
                   10059:     printf("End of Imach\n");
                   10060:     fprintf(ficlog,"End of Imach\n");
                   10061:   }
                   10062:   printf("See log file on %s\n",filelog);
                   10063:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
                   10064:   /*(void) gettimeofday(&end_time,&tzp);*/
                   10065:   rend_time = time(NULL);  
                   10066:   end_time = *localtime(&rend_time);
                   10067:   /* tml = *localtime(&end_time.tm_sec); */
                   10068:   strcpy(strtend,asctime(&end_time));
                   10069:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   10070:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
                   10071:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   10072: 
                   10073:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   10074:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   10075:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   10076:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   10077: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   10078:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   10079:   fclose(fichtm);
                   10080:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   10081:   fclose(fichtmcov);
                   10082:   fclose(ficgp);
                   10083:   fclose(ficlog);
                   10084:   /*------ End -----------*/
                   10085: 
                   10086: 
                   10087:    printf("Before Current directory %s!\n",pathcd);
                   10088: #ifdef WIN32
                   10089:    if (_chdir(pathcd) != 0)
                   10090:           printf("Can't move to directory %s!\n",path);
                   10091:    if(_getcwd(pathcd,MAXLINE) > 0)
                   10092: #else
                   10093:    if(chdir(pathcd) != 0)
                   10094:           printf("Can't move to directory %s!\n", path);
                   10095:    if (getcwd(pathcd, MAXLINE) > 0)
                   10096: #endif 
                   10097:     printf("Current directory %s!\n",pathcd);
                   10098:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   10099:   sprintf(plotcmd,"gnuplot");
                   10100: #ifdef _WIN32
                   10101:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   10102: #endif
                   10103:   if(!stat(plotcmd,&info)){
                   10104:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
                   10105:     if(!stat(getenv("GNUPLOTBIN"),&info)){
                   10106:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
                   10107:     }else
                   10108:       strcpy(pplotcmd,plotcmd);
                   10109: #ifdef __unix
                   10110:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   10111:     if(!stat(plotcmd,&info)){
                   10112:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
                   10113:     }else
                   10114:       strcpy(pplotcmd,plotcmd);
                   10115: #endif
                   10116:   }else
                   10117:     strcpy(pplotcmd,plotcmd);
                   10118:   
                   10119:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
                   10120:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
                   10121: 
                   10122:   if((outcmd=system(plotcmd)) != 0){
                   10123:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
                   10124:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
                   10125:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
                   10126:     if((outcmd=system(plotcmd)) != 0)
                   10127:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
                   10128:   }
                   10129:   printf(" Successful, please wait...");
                   10130:   while (z[0] != 'q') {
                   10131:     /* chdir(path); */
                   10132:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
                   10133:     scanf("%s",z);
                   10134: /*     if (z[0] == 'c') system("./imach"); */
                   10135:     if (z[0] == 'e') {
                   10136: #ifdef __APPLE__
                   10137:       sprintf(pplotcmd, "open %s", optionfilehtm);
                   10138: #elif __linux
                   10139:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
                   10140: #else
                   10141:       sprintf(pplotcmd, "%s", optionfilehtm);
                   10142: #endif
                   10143:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   10144:       system(pplotcmd);
                   10145:     }
                   10146:     else if (z[0] == 'g') system(plotcmd);
                   10147:     else if (z[0] == 'q') exit(0);
                   10148:   }
                   10149:   end:
                   10150:   while (z[0] != 'q') {
                   10151:     printf("\nType  q for exiting: "); fflush(stdout);
                   10152:     scanf("%s",z);
                   10153:   }
                   10154: }

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