File:  [Local Repository] / imach / src / imach.c
Revision 1.185: download - view: text, annotated - select for diffs
Wed Mar 11 13:26:42 2015 UTC (9 years, 2 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
Summary: Inclusion of compile and links command line for Intel Compiler

    1: /* $Id: imach.c,v 1.185 2015/03/11 13:26:42 brouard Exp $
    2:   $State: Exp $
    3:   $Log: imach.c,v $
    4:   Revision 1.185  2015/03/11 13:26:42  brouard
    5:   Summary: Inclusion of compile and links command line for Intel Compiler
    6: 
    7:   Revision 1.184  2015/03/11 11:52:39  brouard
    8:   Summary: Back from Windows 8. Intel Compiler
    9: 
   10:   Revision 1.183  2015/03/10 20:34:32  brouard
   11:   Summary: 0.98q0, trying with directest, mnbrak fixed
   12: 
   13:   We use directest instead of original Powell test; probably no
   14:   incidence on the results, but better justifications;
   15:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
   16:   wrong results.
   17: 
   18:   Revision 1.182  2015/02/12 08:19:57  brouard
   19:   Summary: Trying to keep directest which seems simpler and more general
   20:   Author: Nicolas Brouard
   21: 
   22:   Revision 1.181  2015/02/11 23:22:24  brouard
   23:   Summary: Comments on Powell added
   24: 
   25:   Author:
   26: 
   27:   Revision 1.180  2015/02/11 17:33:45  brouard
   28:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
   29: 
   30:   Revision 1.179  2015/01/04 09:57:06  brouard
   31:   Summary: back to OS/X
   32: 
   33:   Revision 1.178  2015/01/04 09:35:48  brouard
   34:   *** empty log message ***
   35: 
   36:   Revision 1.177  2015/01/03 18:40:56  brouard
   37:   Summary: Still testing ilc32 on OSX
   38: 
   39:   Revision 1.176  2015/01/03 16:45:04  brouard
   40:   *** empty log message ***
   41: 
   42:   Revision 1.175  2015/01/03 16:33:42  brouard
   43:   *** empty log message ***
   44: 
   45:   Revision 1.174  2015/01/03 16:15:49  brouard
   46:   Summary: Still in cross-compilation
   47: 
   48:   Revision 1.173  2015/01/03 12:06:26  brouard
   49:   Summary: trying to detect cross-compilation
   50: 
   51:   Revision 1.172  2014/12/27 12:07:47  brouard
   52:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
   53: 
   54:   Revision 1.171  2014/12/23 13:26:59  brouard
   55:   Summary: Back from Visual C
   56: 
   57:   Still problem with utsname.h on Windows
   58: 
   59:   Revision 1.170  2014/12/23 11:17:12  brouard
   60:   Summary: Cleaning some \%% back to %%
   61: 
   62:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
   63: 
   64:   Revision 1.169  2014/12/22 23:08:31  brouard
   65:   Summary: 0.98p
   66: 
   67:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
   68: 
   69:   Revision 1.168  2014/12/22 15:17:42  brouard
   70:   Summary: update
   71: 
   72:   Revision 1.167  2014/12/22 13:50:56  brouard
   73:   Summary: Testing uname and compiler version and if compiled 32 or 64
   74: 
   75:   Testing on Linux 64
   76: 
   77:   Revision 1.166  2014/12/22 11:40:47  brouard
   78:   *** empty log message ***
   79: 
   80:   Revision 1.165  2014/12/16 11:20:36  brouard
   81:   Summary: After compiling on Visual C
   82: 
   83:   * imach.c (Module): Merging 1.61 to 1.162
   84: 
   85:   Revision 1.164  2014/12/16 10:52:11  brouard
   86:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
   87: 
   88:   * imach.c (Module): Merging 1.61 to 1.162
   89: 
   90:   Revision 1.163  2014/12/16 10:30:11  brouard
   91:   * imach.c (Module): Merging 1.61 to 1.162
   92: 
   93:   Revision 1.162  2014/09/25 11:43:39  brouard
   94:   Summary: temporary backup 0.99!
   95: 
   96:   Revision 1.1  2014/09/16 11:06:58  brouard
   97:   Summary: With some code (wrong) for nlopt
   98: 
   99:   Author:
  100: 
  101:   Revision 1.161  2014/09/15 20:41:41  brouard
  102:   Summary: Problem with macro SQR on Intel compiler
  103: 
  104:   Revision 1.160  2014/09/02 09:24:05  brouard
  105:   *** empty log message ***
  106: 
  107:   Revision 1.159  2014/09/01 10:34:10  brouard
  108:   Summary: WIN32
  109:   Author: Brouard
  110: 
  111:   Revision 1.158  2014/08/27 17:11:51  brouard
  112:   *** empty log message ***
  113: 
  114:   Revision 1.157  2014/08/27 16:26:55  brouard
  115:   Summary: Preparing windows Visual studio version
  116:   Author: Brouard
  117: 
  118:   In order to compile on Visual studio, time.h is now correct and time_t
  119:   and tm struct should be used. difftime should be used but sometimes I
  120:   just make the differences in raw time format (time(&now).
  121:   Trying to suppress #ifdef LINUX
  122:   Add xdg-open for __linux in order to open default browser.
  123: 
  124:   Revision 1.156  2014/08/25 20:10:10  brouard
  125:   *** empty log message ***
  126: 
  127:   Revision 1.155  2014/08/25 18:32:34  brouard
  128:   Summary: New compile, minor changes
  129:   Author: Brouard
  130: 
  131:   Revision 1.154  2014/06/20 17:32:08  brouard
  132:   Summary: Outputs now all graphs of convergence to period prevalence
  133: 
  134:   Revision 1.153  2014/06/20 16:45:46  brouard
  135:   Summary: If 3 live state, convergence to period prevalence on same graph
  136:   Author: Brouard
  137: 
  138:   Revision 1.152  2014/06/18 17:54:09  brouard
  139:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
  140: 
  141:   Revision 1.151  2014/06/18 16:43:30  brouard
  142:   *** empty log message ***
  143: 
  144:   Revision 1.150  2014/06/18 16:42:35  brouard
  145:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
  146:   Author: brouard
  147: 
  148:   Revision 1.149  2014/06/18 15:51:14  brouard
  149:   Summary: Some fixes in parameter files errors
  150:   Author: Nicolas Brouard
  151: 
  152:   Revision 1.148  2014/06/17 17:38:48  brouard
  153:   Summary: Nothing new
  154:   Author: Brouard
  155: 
  156:   Just a new packaging for OS/X version 0.98nS
  157: 
  158:   Revision 1.147  2014/06/16 10:33:11  brouard
  159:   *** empty log message ***
  160: 
  161:   Revision 1.146  2014/06/16 10:20:28  brouard
  162:   Summary: Merge
  163:   Author: Brouard
  164: 
  165:   Merge, before building revised version.
  166: 
  167:   Revision 1.145  2014/06/10 21:23:15  brouard
  168:   Summary: Debugging with valgrind
  169:   Author: Nicolas Brouard
  170: 
  171:   Lot of changes in order to output the results with some covariates
  172:   After the Edimburgh REVES conference 2014, it seems mandatory to
  173:   improve the code.
  174:   No more memory valgrind error but a lot has to be done in order to
  175:   continue the work of splitting the code into subroutines.
  176:   Also, decodemodel has been improved. Tricode is still not
  177:   optimal. nbcode should be improved. Documentation has been added in
  178:   the source code.
  179: 
  180:   Revision 1.143  2014/01/26 09:45:38  brouard
  181:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
  182: 
  183:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  184:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
  185: 
  186:   Revision 1.142  2014/01/26 03:57:36  brouard
  187:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
  188: 
  189:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  190: 
  191:   Revision 1.141  2014/01/26 02:42:01  brouard
  192:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  193: 
  194:   Revision 1.140  2011/09/02 10:37:54  brouard
  195:   Summary: times.h is ok with mingw32 now.
  196: 
  197:   Revision 1.139  2010/06/14 07:50:17  brouard
  198:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
  199:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
  200: 
  201:   Revision 1.138  2010/04/30 18:19:40  brouard
  202:   *** empty log message ***
  203: 
  204:   Revision 1.137  2010/04/29 18:11:38  brouard
  205:   (Module): Checking covariates for more complex models
  206:   than V1+V2. A lot of change to be done. Unstable.
  207: 
  208:   Revision 1.136  2010/04/26 20:30:53  brouard
  209:   (Module): merging some libgsl code. Fixing computation
  210:   of likelione (using inter/intrapolation if mle = 0) in order to
  211:   get same likelihood as if mle=1.
  212:   Some cleaning of code and comments added.
  213: 
  214:   Revision 1.135  2009/10/29 15:33:14  brouard
  215:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  216: 
  217:   Revision 1.134  2009/10/29 13:18:53  brouard
  218:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  219: 
  220:   Revision 1.133  2009/07/06 10:21:25  brouard
  221:   just nforces
  222: 
  223:   Revision 1.132  2009/07/06 08:22:05  brouard
  224:   Many tings
  225: 
  226:   Revision 1.131  2009/06/20 16:22:47  brouard
  227:   Some dimensions resccaled
  228: 
  229:   Revision 1.130  2009/05/26 06:44:34  brouard
  230:   (Module): Max Covariate is now set to 20 instead of 8. A
  231:   lot of cleaning with variables initialized to 0. Trying to make
  232:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
  233: 
  234:   Revision 1.129  2007/08/31 13:49:27  lievre
  235:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
  236: 
  237:   Revision 1.128  2006/06/30 13:02:05  brouard
  238:   (Module): Clarifications on computing e.j
  239: 
  240:   Revision 1.127  2006/04/28 18:11:50  brouard
  241:   (Module): Yes the sum of survivors was wrong since
  242:   imach-114 because nhstepm was no more computed in the age
  243:   loop. Now we define nhstepma in the age loop.
  244:   (Module): In order to speed up (in case of numerous covariates) we
  245:   compute health expectancies (without variances) in a first step
  246:   and then all the health expectancies with variances or standard
  247:   deviation (needs data from the Hessian matrices) which slows the
  248:   computation.
  249:   In the future we should be able to stop the program is only health
  250:   expectancies and graph are needed without standard deviations.
  251: 
  252:   Revision 1.126  2006/04/28 17:23:28  brouard
  253:   (Module): Yes the sum of survivors was wrong since
  254:   imach-114 because nhstepm was no more computed in the age
  255:   loop. Now we define nhstepma in the age loop.
  256:   Version 0.98h
  257: 
  258:   Revision 1.125  2006/04/04 15:20:31  lievre
  259:   Errors in calculation of health expectancies. Age was not initialized.
  260:   Forecasting file added.
  261: 
  262:   Revision 1.124  2006/03/22 17:13:53  lievre
  263:   Parameters are printed with %lf instead of %f (more numbers after the comma).
  264:   The log-likelihood is printed in the log file
  265: 
  266:   Revision 1.123  2006/03/20 10:52:43  brouard
  267:   * imach.c (Module): <title> changed, corresponds to .htm file
  268:   name. <head> headers where missing.
  269: 
  270:   * imach.c (Module): Weights can have a decimal point as for
  271:   English (a comma might work with a correct LC_NUMERIC environment,
  272:   otherwise the weight is truncated).
  273:   Modification of warning when the covariates values are not 0 or
  274:   1.
  275:   Version 0.98g
  276: 
  277:   Revision 1.122  2006/03/20 09:45:41  brouard
  278:   (Module): Weights can have a decimal point as for
  279:   English (a comma might work with a correct LC_NUMERIC environment,
  280:   otherwise the weight is truncated).
  281:   Modification of warning when the covariates values are not 0 or
  282:   1.
  283:   Version 0.98g
  284: 
  285:   Revision 1.121  2006/03/16 17:45:01  lievre
  286:   * imach.c (Module): Comments concerning covariates added
  287: 
  288:   * imach.c (Module): refinements in the computation of lli if
  289:   status=-2 in order to have more reliable computation if stepm is
  290:   not 1 month. Version 0.98f
  291: 
  292:   Revision 1.120  2006/03/16 15:10:38  lievre
  293:   (Module): refinements in the computation of lli if
  294:   status=-2 in order to have more reliable computation if stepm is
  295:   not 1 month. Version 0.98f
  296: 
  297:   Revision 1.119  2006/03/15 17:42:26  brouard
  298:   (Module): Bug if status = -2, the loglikelihood was
  299:   computed as likelihood omitting the logarithm. Version O.98e
  300: 
  301:   Revision 1.118  2006/03/14 18:20:07  brouard
  302:   (Module): varevsij Comments added explaining the second
  303:   table of variances if popbased=1 .
  304:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  305:   (Module): Function pstamp added
  306:   (Module): Version 0.98d
  307: 
  308:   Revision 1.117  2006/03/14 17:16:22  brouard
  309:   (Module): varevsij Comments added explaining the second
  310:   table of variances if popbased=1 .
  311:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  312:   (Module): Function pstamp added
  313:   (Module): Version 0.98d
  314: 
  315:   Revision 1.116  2006/03/06 10:29:27  brouard
  316:   (Module): Variance-covariance wrong links and
  317:   varian-covariance of ej. is needed (Saito).
  318: 
  319:   Revision 1.115  2006/02/27 12:17:45  brouard
  320:   (Module): One freematrix added in mlikeli! 0.98c
  321: 
  322:   Revision 1.114  2006/02/26 12:57:58  brouard
  323:   (Module): Some improvements in processing parameter
  324:   filename with strsep.
  325: 
  326:   Revision 1.113  2006/02/24 14:20:24  brouard
  327:   (Module): Memory leaks checks with valgrind and:
  328:   datafile was not closed, some imatrix were not freed and on matrix
  329:   allocation too.
  330: 
  331:   Revision 1.112  2006/01/30 09:55:26  brouard
  332:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
  333: 
  334:   Revision 1.111  2006/01/25 20:38:18  brouard
  335:   (Module): Lots of cleaning and bugs added (Gompertz)
  336:   (Module): Comments can be added in data file. Missing date values
  337:   can be a simple dot '.'.
  338: 
  339:   Revision 1.110  2006/01/25 00:51:50  brouard
  340:   (Module): Lots of cleaning and bugs added (Gompertz)
  341: 
  342:   Revision 1.109  2006/01/24 19:37:15  brouard
  343:   (Module): Comments (lines starting with a #) are allowed in data.
  344: 
  345:   Revision 1.108  2006/01/19 18:05:42  lievre
  346:   Gnuplot problem appeared...
  347:   To be fixed
  348: 
  349:   Revision 1.107  2006/01/19 16:20:37  brouard
  350:   Test existence of gnuplot in imach path
  351: 
  352:   Revision 1.106  2006/01/19 13:24:36  brouard
  353:   Some cleaning and links added in html output
  354: 
  355:   Revision 1.105  2006/01/05 20:23:19  lievre
  356:   *** empty log message ***
  357: 
  358:   Revision 1.104  2005/09/30 16:11:43  lievre
  359:   (Module): sump fixed, loop imx fixed, and simplifications.
  360:   (Module): If the status is missing at the last wave but we know
  361:   that the person is alive, then we can code his/her status as -2
  362:   (instead of missing=-1 in earlier versions) and his/her
  363:   contributions to the likelihood is 1 - Prob of dying from last
  364:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
  365:   the healthy state at last known wave). Version is 0.98
  366: 
  367:   Revision 1.103  2005/09/30 15:54:49  lievre
  368:   (Module): sump fixed, loop imx fixed, and simplifications.
  369: 
  370:   Revision 1.102  2004/09/15 17:31:30  brouard
  371:   Add the possibility to read data file including tab characters.
  372: 
  373:   Revision 1.101  2004/09/15 10:38:38  brouard
  374:   Fix on curr_time
  375: 
  376:   Revision 1.100  2004/07/12 18:29:06  brouard
  377:   Add version for Mac OS X. Just define UNIX in Makefile
  378: 
  379:   Revision 1.99  2004/06/05 08:57:40  brouard
  380:   *** empty log message ***
  381: 
  382:   Revision 1.98  2004/05/16 15:05:56  brouard
  383:   New version 0.97 . First attempt to estimate force of mortality
  384:   directly from the data i.e. without the need of knowing the health
  385:   state at each age, but using a Gompertz model: log u =a + b*age .
  386:   This is the basic analysis of mortality and should be done before any
  387:   other analysis, in order to test if the mortality estimated from the
  388:   cross-longitudinal survey is different from the mortality estimated
  389:   from other sources like vital statistic data.
  390: 
  391:   The same imach parameter file can be used but the option for mle should be -3.
  392: 
  393:   Agnès, who wrote this part of the code, tried to keep most of the
  394:   former routines in order to include the new code within the former code.
  395: 
  396:   The output is very simple: only an estimate of the intercept and of
  397:   the slope with 95% confident intervals.
  398: 
  399:   Current limitations:
  400:   A) Even if you enter covariates, i.e. with the
  401:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
  402:   B) There is no computation of Life Expectancy nor Life Table.
  403: 
  404:   Revision 1.97  2004/02/20 13:25:42  lievre
  405:   Version 0.96d. Population forecasting command line is (temporarily)
  406:   suppressed.
  407: 
  408:   Revision 1.96  2003/07/15 15:38:55  brouard
  409:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
  410:   rewritten within the same printf. Workaround: many printfs.
  411: 
  412:   Revision 1.95  2003/07/08 07:54:34  brouard
  413:   * imach.c (Repository):
  414:   (Repository): Using imachwizard code to output a more meaningful covariance
  415:   matrix (cov(a12,c31) instead of numbers.
  416: 
  417:   Revision 1.94  2003/06/27 13:00:02  brouard
  418:   Just cleaning
  419: 
  420:   Revision 1.93  2003/06/25 16:33:55  brouard
  421:   (Module): On windows (cygwin) function asctime_r doesn't
  422:   exist so I changed back to asctime which exists.
  423:   (Module): Version 0.96b
  424: 
  425:   Revision 1.92  2003/06/25 16:30:45  brouard
  426:   (Module): On windows (cygwin) function asctime_r doesn't
  427:   exist so I changed back to asctime which exists.
  428: 
  429:   Revision 1.91  2003/06/25 15:30:29  brouard
  430:   * imach.c (Repository): Duplicated warning errors corrected.
  431:   (Repository): Elapsed time after each iteration is now output. It
  432:   helps to forecast when convergence will be reached. Elapsed time
  433:   is stamped in powell.  We created a new html file for the graphs
  434:   concerning matrix of covariance. It has extension -cov.htm.
  435: 
  436:   Revision 1.90  2003/06/24 12:34:15  brouard
  437:   (Module): Some bugs corrected for windows. Also, when
  438:   mle=-1 a template is output in file "or"mypar.txt with the design
  439:   of the covariance matrix to be input.
  440: 
  441:   Revision 1.89  2003/06/24 12:30:52  brouard
  442:   (Module): Some bugs corrected for windows. Also, when
  443:   mle=-1 a template is output in file "or"mypar.txt with the design
  444:   of the covariance matrix to be input.
  445: 
  446:   Revision 1.88  2003/06/23 17:54:56  brouard
  447:   * 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.
  448: 
  449:   Revision 1.87  2003/06/18 12:26:01  brouard
  450:   Version 0.96
  451: 
  452:   Revision 1.86  2003/06/17 20:04:08  brouard
  453:   (Module): Change position of html and gnuplot routines and added
  454:   routine fileappend.
  455: 
  456:   Revision 1.85  2003/06/17 13:12:43  brouard
  457:   * imach.c (Repository): Check when date of death was earlier that
  458:   current date of interview. It may happen when the death was just
  459:   prior to the death. In this case, dh was negative and likelihood
  460:   was wrong (infinity). We still send an "Error" but patch by
  461:   assuming that the date of death was just one stepm after the
  462:   interview.
  463:   (Repository): Because some people have very long ID (first column)
  464:   we changed int to long in num[] and we added a new lvector for
  465:   memory allocation. But we also truncated to 8 characters (left
  466:   truncation)
  467:   (Repository): No more line truncation errors.
  468: 
  469:   Revision 1.84  2003/06/13 21:44:43  brouard
  470:   * imach.c (Repository): Replace "freqsummary" at a correct
  471:   place. It differs from routine "prevalence" which may be called
  472:   many times. Probs is memory consuming and must be used with
  473:   parcimony.
  474:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
  475: 
  476:   Revision 1.83  2003/06/10 13:39:11  lievre
  477:   *** empty log message ***
  478: 
  479:   Revision 1.82  2003/06/05 15:57:20  brouard
  480:   Add log in  imach.c and  fullversion number is now printed.
  481: 
  482: */
  483: /*
  484:    Interpolated Markov Chain
  485: 
  486:   Short summary of the programme:
  487:   
  488:   This program computes Healthy Life Expectancies from
  489:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
  490:   first survey ("cross") where individuals from different ages are
  491:   interviewed on their health status or degree of disability (in the
  492:   case of a health survey which is our main interest) -2- at least a
  493:   second wave of interviews ("longitudinal") which measure each change
  494:   (if any) in individual health status.  Health expectancies are
  495:   computed from the time spent in each health state according to a
  496:   model. More health states you consider, more time is necessary to reach the
  497:   Maximum Likelihood of the parameters involved in the model.  The
  498:   simplest model is the multinomial logistic model where pij is the
  499:   probability to be observed in state j at the second wave
  500:   conditional to be observed in state i at the first wave. Therefore
  501:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
  502:   'age' is age and 'sex' is a covariate. If you want to have a more
  503:   complex model than "constant and age", you should modify the program
  504:   where the markup *Covariates have to be included here again* invites
  505:   you to do it.  More covariates you add, slower the
  506:   convergence.
  507: 
  508:   The advantage of this computer programme, compared to a simple
  509:   multinomial logistic model, is clear when the delay between waves is not
  510:   identical for each individual. Also, if a individual missed an
  511:   intermediate interview, the information is lost, but taken into
  512:   account using an interpolation or extrapolation.  
  513: 
  514:   hPijx is the probability to be observed in state i at age x+h
  515:   conditional to the observed state i at age x. The delay 'h' can be
  516:   split into an exact number (nh*stepm) of unobserved intermediate
  517:   states. This elementary transition (by month, quarter,
  518:   semester or year) is modelled as a multinomial logistic.  The hPx
  519:   matrix is simply the matrix product of nh*stepm elementary matrices
  520:   and the contribution of each individual to the likelihood is simply
  521:   hPijx.
  522: 
  523:   Also this programme outputs the covariance matrix of the parameters but also
  524:   of the life expectancies. It also computes the period (stable) prevalence. 
  525:   
  526:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
  527:            Institut national d'études démographiques, Paris.
  528:   This software have been partly granted by Euro-REVES, a concerted action
  529:   from the European Union.
  530:   It is copyrighted identically to a GNU software product, ie programme and
  531:   software can be distributed freely for non commercial use. Latest version
  532:   can be accessed at http://euroreves.ined.fr/imach .
  533: 
  534:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
  535:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
  536:   
  537:   **********************************************************************/
  538: /*
  539:   main
  540:   read parameterfile
  541:   read datafile
  542:   concatwav
  543:   freqsummary
  544:   if (mle >= 1)
  545:     mlikeli
  546:   print results files
  547:   if mle==1 
  548:      computes hessian
  549:   read end of parameter file: agemin, agemax, bage, fage, estepm
  550:       begin-prev-date,...
  551:   open gnuplot file
  552:   open html file
  553:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
  554:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
  555:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
  556:     freexexit2 possible for memory heap.
  557: 
  558:   h Pij x                         | pij_nom  ficrestpij
  559:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
  560:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
  561:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
  562: 
  563:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
  564:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
  565:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
  566:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
  567:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
  568: 
  569:   forecasting if prevfcast==1 prevforecast call prevalence()
  570:   health expectancies
  571:   Variance-covariance of DFLE
  572:   prevalence()
  573:    movingaverage()
  574:   varevsij() 
  575:   if popbased==1 varevsij(,popbased)
  576:   total life expectancies
  577:   Variance of period (stable) prevalence
  578:  end
  579: */
  580: 
  581: #define POWELL /* Instead of NLOPT */
  582: /* #define POWELLORIGINAL */ /* Don't use Directest to decide new direction but original Powell test */
  583: /* #define MNBRAKORIGINAL */ /* Don't use mnbrak fix */
  584: 
  585: #include <math.h>
  586: #include <stdio.h>
  587: #include <stdlib.h>
  588: #include <string.h>
  589: 
  590: #ifdef _WIN32
  591: #include <io.h>
  592: #include <windows.h>
  593: #include <tchar.h>
  594: #else
  595: #include <unistd.h>
  596: #endif
  597: 
  598: #include <limits.h>
  599: #include <sys/types.h>
  600: 
  601: #if defined(__GNUC__)
  602: #include <sys/utsname.h> /* Doesn't work on Windows */
  603: #endif
  604: 
  605: #include <sys/stat.h>
  606: #include <errno.h>
  607: /* extern int errno; */
  608: 
  609: /* #ifdef LINUX */
  610: /* #include <time.h> */
  611: /* #include "timeval.h" */
  612: /* #else */
  613: /* #include <sys/time.h> */
  614: /* #endif */
  615: 
  616: #include <time.h>
  617: 
  618: #ifdef GSL
  619: #include <gsl/gsl_errno.h>
  620: #include <gsl/gsl_multimin.h>
  621: #endif
  622: 
  623: 
  624: #ifdef NLOPT
  625: #include <nlopt.h>
  626: typedef struct {
  627:   double (* function)(double [] );
  628: } myfunc_data ;
  629: #endif
  630: 
  631: /* #include <libintl.h> */
  632: /* #define _(String) gettext (String) */
  633: 
  634: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
  635: 
  636: #define GNUPLOTPROGRAM "gnuplot"
  637: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
  638: #define FILENAMELENGTH 132
  639: 
  640: #define	GLOCK_ERROR_NOPATH		-1	/* empty path */
  641: #define	GLOCK_ERROR_GETCWD		-2	/* cannot get cwd */
  642: 
  643: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
  644: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
  645: 
  646: #define NINTERVMAX 8
  647: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
  648: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
  649: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
  650: #define codtabm(h,k)  1 & (h-1) >> (k-1) ;
  651: #define MAXN 20000
  652: #define YEARM 12. /**< Number of months per year */
  653: #define AGESUP 130
  654: #define AGEBASE 40
  655: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
  656: #ifdef _WIN32
  657: #define DIRSEPARATOR '\\'
  658: #define CHARSEPARATOR "\\"
  659: #define ODIRSEPARATOR '/'
  660: #else
  661: #define DIRSEPARATOR '/'
  662: #define CHARSEPARATOR "/"
  663: #define ODIRSEPARATOR '\\'
  664: #endif
  665: 
  666: /* $Id: imach.c,v 1.185 2015/03/11 13:26:42 brouard Exp $ */
  667: /* $State: Exp $ */
  668: 
  669: char version[]="Imach version 0.98q0, March 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
  670: char fullversion[]="$Revision: 1.185 $ $Date: 2015/03/11 13:26:42 $"; 
  671: char strstart[80];
  672: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
  673: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
  674: int nvar=0, nforce=0; /* Number of variables, number of forces */
  675: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
  676: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
  677: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
  678: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
  679: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
  680: int cptcovprodnoage=0; /**< Number of covariate products without age */   
  681: int cptcoveff=0; /* Total number of covariates to vary for printing results */
  682: int cptcov=0; /* Working variable */
  683: int npar=NPARMAX;
  684: int nlstate=2; /* Number of live states */
  685: int ndeath=1; /* Number of dead states */
  686: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
  687: int popbased=0;
  688: 
  689: int *wav; /* Number of waves for this individuual 0 is possible */
  690: int maxwav=0; /* Maxim number of waves */
  691: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
  692: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
  693: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
  694: 		   to the likelihood and the sum of weights (done by funcone)*/
  695: int mle=1, weightopt=0;
  696: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
  697: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
  698: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
  699: 	   * wave mi and wave mi+1 is not an exact multiple of stepm. */
  700: int countcallfunc=0;  /* Count the number of calls to func */
  701: double jmean=1; /* Mean space between 2 waves */
  702: double **matprod2(); /* test */
  703: double **oldm, **newm, **savm; /* Working pointers to matrices */
  704: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
  705: /*FILE *fic ; */ /* Used in readdata only */
  706: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
  707: FILE *ficlog, *ficrespow;
  708: int globpr=0; /* Global variable for printing or not */
  709: double fretone; /* Only one call to likelihood */
  710: long ipmx=0; /* Number of contributions */
  711: double sw; /* Sum of weights */
  712: char filerespow[FILENAMELENGTH];
  713: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
  714: FILE *ficresilk;
  715: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
  716: FILE *ficresprobmorprev;
  717: FILE *fichtm, *fichtmcov; /* Html File */
  718: FILE *ficreseij;
  719: char filerese[FILENAMELENGTH];
  720: FILE *ficresstdeij;
  721: char fileresstde[FILENAMELENGTH];
  722: FILE *ficrescveij;
  723: char filerescve[FILENAMELENGTH];
  724: FILE  *ficresvij;
  725: char fileresv[FILENAMELENGTH];
  726: FILE  *ficresvpl;
  727: char fileresvpl[FILENAMELENGTH];
  728: char title[MAXLINE];
  729: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
  730: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
  731: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
  732: char command[FILENAMELENGTH];
  733: int  outcmd=0;
  734: 
  735: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
  736: 
  737: char filelog[FILENAMELENGTH]; /* Log file */
  738: char filerest[FILENAMELENGTH];
  739: char fileregp[FILENAMELENGTH];
  740: char popfile[FILENAMELENGTH];
  741: 
  742: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
  743: 
  744: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
  745: /* struct timezone tzp; */
  746: /* extern int gettimeofday(); */
  747: struct tm tml, *gmtime(), *localtime();
  748: 
  749: extern time_t time();
  750: 
  751: struct tm start_time, end_time, curr_time, last_time, forecast_time;
  752: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
  753: struct tm tm;
  754: 
  755: char strcurr[80], strfor[80];
  756: 
  757: char *endptr;
  758: long lval;
  759: double dval;
  760: 
  761: #define NR_END 1
  762: #define FREE_ARG char*
  763: #define FTOL 1.0e-10
  764: 
  765: #define NRANSI 
  766: #define ITMAX 200 
  767: 
  768: #define TOL 2.0e-4 
  769: 
  770: #define CGOLD 0.3819660 
  771: #define ZEPS 1.0e-10 
  772: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
  773: 
  774: #define GOLD 1.618034 
  775: #define GLIMIT 100.0 
  776: #define TINY 1.0e-20 
  777: 
  778: static double maxarg1,maxarg2;
  779: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
  780: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
  781:   
  782: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
  783: #define rint(a) floor(a+0.5)
  784: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
  785: #define mytinydouble 1.0e-16
  786: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
  787: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
  788: /* static double dsqrarg; */
  789: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
  790: static double sqrarg;
  791: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
  792: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
  793: int agegomp= AGEGOMP;
  794: 
  795: int imx; 
  796: int stepm=1;
  797: /* Stepm, step in month: minimum step interpolation*/
  798: 
  799: int estepm;
  800: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
  801: 
  802: int m,nb;
  803: long *num;
  804: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
  805: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
  806: double **pmmij, ***probs;
  807: double *ageexmed,*agecens;
  808: double dateintmean=0;
  809: 
  810: double *weight;
  811: int **s; /* Status */
  812: double *agedc;
  813: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
  814: 		  * covar=matrix(0,NCOVMAX,1,n); 
  815: 		  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
  816: double  idx; 
  817: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
  818: int *Ndum; /** Freq of modality (tricode */
  819: int **codtab; /**< codtab=imatrix(1,100,1,10); */
  820: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
  821: double *lsurv, *lpop, *tpop;
  822: 
  823: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
  824: double ftolhess; /**< Tolerance for computing hessian */
  825: 
  826: /**************** split *************************/
  827: static	int split( char *path, char *dirc, char *name, char *ext, char *finame )
  828: {
  829:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
  830:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
  831:   */ 
  832:   char	*ss;				/* pointer */
  833:   int	l1, l2;				/* length counters */
  834: 
  835:   l1 = strlen(path );			/* length of path */
  836:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
  837:   ss= strrchr( path, DIRSEPARATOR );		/* find last / */
  838:   if ( ss == NULL ) {			/* no directory, so determine current directory */
  839:     strcpy( name, path );		/* we got the fullname name because no directory */
  840:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
  841:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
  842:     /* get current working directory */
  843:     /*    extern  char* getcwd ( char *buf , int len);*/
  844: #ifdef WIN32
  845:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
  846: #else
  847: 	if (getcwd(dirc, FILENAME_MAX) == NULL) {
  848: #endif
  849:       return( GLOCK_ERROR_GETCWD );
  850:     }
  851:     /* got dirc from getcwd*/
  852:     printf(" DIRC = %s \n",dirc);
  853:   } else {				/* strip direcotry from path */
  854:     ss++;				/* after this, the filename */
  855:     l2 = strlen( ss );			/* length of filename */
  856:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
  857:     strcpy( name, ss );		/* save file name */
  858:     strncpy( dirc, path, l1 - l2 );	/* now the directory */
  859:     dirc[l1-l2] = 0;			/* add zero */
  860:     printf(" DIRC2 = %s \n",dirc);
  861:   }
  862:   /* We add a separator at the end of dirc if not exists */
  863:   l1 = strlen( dirc );			/* length of directory */
  864:   if( dirc[l1-1] != DIRSEPARATOR ){
  865:     dirc[l1] =  DIRSEPARATOR;
  866:     dirc[l1+1] = 0; 
  867:     printf(" DIRC3 = %s \n",dirc);
  868:   }
  869:   ss = strrchr( name, '.' );		/* find last / */
  870:   if (ss >0){
  871:     ss++;
  872:     strcpy(ext,ss);			/* save extension */
  873:     l1= strlen( name);
  874:     l2= strlen(ss)+1;
  875:     strncpy( finame, name, l1-l2);
  876:     finame[l1-l2]= 0;
  877:   }
  878: 
  879:   return( 0 );				/* we're done */
  880: }
  881: 
  882: 
  883: /******************************************/
  884: 
  885: void replace_back_to_slash(char *s, char*t)
  886: {
  887:   int i;
  888:   int lg=0;
  889:   i=0;
  890:   lg=strlen(t);
  891:   for(i=0; i<= lg; i++) {
  892:     (s[i] = t[i]);
  893:     if (t[i]== '\\') s[i]='/';
  894:   }
  895: }
  896: 
  897: char *trimbb(char *out, char *in)
  898: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
  899:   char *s;
  900:   s=out;
  901:   while (*in != '\0'){
  902:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
  903:       in++;
  904:     }
  905:     *out++ = *in++;
  906:   }
  907:   *out='\0';
  908:   return s;
  909: }
  910: 
  911: char *cutl(char *blocc, char *alocc, char *in, char occ)
  912: {
  913:   /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ' 
  914:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
  915:      gives blocc="abcdef2ghi" and alocc="j".
  916:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
  917:   */
  918:   char *s, *t;
  919:   t=in;s=in;
  920:   while ((*in != occ) && (*in != '\0')){
  921:     *alocc++ = *in++;
  922:   }
  923:   if( *in == occ){
  924:     *(alocc)='\0';
  925:     s=++in;
  926:   }
  927:  
  928:   if (s == t) {/* occ not found */
  929:     *(alocc-(in-s))='\0';
  930:     in=s;
  931:   }
  932:   while ( *in != '\0'){
  933:     *blocc++ = *in++;
  934:   }
  935: 
  936:   *blocc='\0';
  937:   return t;
  938: }
  939: char *cutv(char *blocc, char *alocc, char *in, char occ)
  940: {
  941:   /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ' 
  942:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
  943:      gives blocc="abcdef2ghi" and alocc="j".
  944:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
  945:   */
  946:   char *s, *t;
  947:   t=in;s=in;
  948:   while (*in != '\0'){
  949:     while( *in == occ){
  950:       *blocc++ = *in++;
  951:       s=in;
  952:     }
  953:     *blocc++ = *in++;
  954:   }
  955:   if (s == t) /* occ not found */
  956:     *(blocc-(in-s))='\0';
  957:   else
  958:     *(blocc-(in-s)-1)='\0';
  959:   in=s;
  960:   while ( *in != '\0'){
  961:     *alocc++ = *in++;
  962:   }
  963: 
  964:   *alocc='\0';
  965:   return s;
  966: }
  967: 
  968: int nbocc(char *s, char occ)
  969: {
  970:   int i,j=0;
  971:   int lg=20;
  972:   i=0;
  973:   lg=strlen(s);
  974:   for(i=0; i<= lg; i++) {
  975:   if  (s[i] == occ ) j++;
  976:   }
  977:   return j;
  978: }
  979: 
  980: /* void cutv(char *u,char *v, char*t, char occ) */
  981: /* { */
  982: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
  983: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
  984: /*      gives u="abcdef2ghi" and v="j" *\/ */
  985: /*   int i,lg,j,p=0; */
  986: /*   i=0; */
  987: /*   lg=strlen(t); */
  988: /*   for(j=0; j<=lg-1; j++) { */
  989: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
  990: /*   } */
  991: 
  992: /*   for(j=0; j<p; j++) { */
  993: /*     (u[j] = t[j]); */
  994: /*   } */
  995: /*      u[p]='\0'; */
  996: 
  997: /*    for(j=0; j<= lg; j++) { */
  998: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
  999: /*   } */
 1000: /* } */
 1001: 
 1002: #ifdef _WIN32
 1003: char * strsep(char **pp, const char *delim)
 1004: {
 1005:   char *p, *q;
 1006:          
 1007:   if ((p = *pp) == NULL)
 1008:     return 0;
 1009:   if ((q = strpbrk (p, delim)) != NULL)
 1010:   {
 1011:     *pp = q + 1;
 1012:     *q = '\0';
 1013:   }
 1014:   else
 1015:     *pp = 0;
 1016:   return p;
 1017: }
 1018: #endif
 1019: 
 1020: /********************** nrerror ********************/
 1021: 
 1022: void nrerror(char error_text[])
 1023: {
 1024:   fprintf(stderr,"ERREUR ...\n");
 1025:   fprintf(stderr,"%s\n",error_text);
 1026:   exit(EXIT_FAILURE);
 1027: }
 1028: /*********************** vector *******************/
 1029: double *vector(int nl, int nh)
 1030: {
 1031:   double *v;
 1032:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
 1033:   if (!v) nrerror("allocation failure in vector");
 1034:   return v-nl+NR_END;
 1035: }
 1036: 
 1037: /************************ free vector ******************/
 1038: void free_vector(double*v, int nl, int nh)
 1039: {
 1040:   free((FREE_ARG)(v+nl-NR_END));
 1041: }
 1042: 
 1043: /************************ivector *******************************/
 1044: int *ivector(long nl,long nh)
 1045: {
 1046:   int *v;
 1047:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
 1048:   if (!v) nrerror("allocation failure in ivector");
 1049:   return v-nl+NR_END;
 1050: }
 1051: 
 1052: /******************free ivector **************************/
 1053: void free_ivector(int *v, long nl, long nh)
 1054: {
 1055:   free((FREE_ARG)(v+nl-NR_END));
 1056: }
 1057: 
 1058: /************************lvector *******************************/
 1059: long *lvector(long nl,long nh)
 1060: {
 1061:   long *v;
 1062:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
 1063:   if (!v) nrerror("allocation failure in ivector");
 1064:   return v-nl+NR_END;
 1065: }
 1066: 
 1067: /******************free lvector **************************/
 1068: void free_lvector(long *v, long nl, long nh)
 1069: {
 1070:   free((FREE_ARG)(v+nl-NR_END));
 1071: }
 1072: 
 1073: /******************* imatrix *******************************/
 1074: int **imatrix(long nrl, long nrh, long ncl, long nch) 
 1075:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
 1076: { 
 1077:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
 1078:   int **m; 
 1079:   
 1080:   /* allocate pointers to rows */ 
 1081:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
 1082:   if (!m) nrerror("allocation failure 1 in matrix()"); 
 1083:   m += NR_END; 
 1084:   m -= nrl; 
 1085:   
 1086:   
 1087:   /* allocate rows and set pointers to them */ 
 1088:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
 1089:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
 1090:   m[nrl] += NR_END; 
 1091:   m[nrl] -= ncl; 
 1092:   
 1093:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
 1094:   
 1095:   /* return pointer to array of pointers to rows */ 
 1096:   return m; 
 1097: } 
 1098: 
 1099: /****************** free_imatrix *************************/
 1100: void free_imatrix(m,nrl,nrh,ncl,nch)
 1101:       int **m;
 1102:       long nch,ncl,nrh,nrl; 
 1103:      /* free an int matrix allocated by imatrix() */ 
 1104: { 
 1105:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
 1106:   free((FREE_ARG) (m+nrl-NR_END)); 
 1107: } 
 1108: 
 1109: /******************* matrix *******************************/
 1110: double **matrix(long nrl, long nrh, long ncl, long nch)
 1111: {
 1112:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
 1113:   double **m;
 1114: 
 1115:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1116:   if (!m) nrerror("allocation failure 1 in matrix()");
 1117:   m += NR_END;
 1118:   m -= nrl;
 1119: 
 1120:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1121:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1122:   m[nrl] += NR_END;
 1123:   m[nrl] -= ncl;
 1124: 
 1125:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1126:   return m;
 1127:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
 1128: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
 1129: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
 1130:    */
 1131: }
 1132: 
 1133: /*************************free matrix ************************/
 1134: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
 1135: {
 1136:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1137:   free((FREE_ARG)(m+nrl-NR_END));
 1138: }
 1139: 
 1140: /******************* ma3x *******************************/
 1141: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
 1142: {
 1143:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
 1144:   double ***m;
 1145: 
 1146:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1147:   if (!m) nrerror("allocation failure 1 in matrix()");
 1148:   m += NR_END;
 1149:   m -= nrl;
 1150: 
 1151:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1152:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1153:   m[nrl] += NR_END;
 1154:   m[nrl] -= ncl;
 1155: 
 1156:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1157: 
 1158:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
 1159:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
 1160:   m[nrl][ncl] += NR_END;
 1161:   m[nrl][ncl] -= nll;
 1162:   for (j=ncl+1; j<=nch; j++) 
 1163:     m[nrl][j]=m[nrl][j-1]+nlay;
 1164:   
 1165:   for (i=nrl+1; i<=nrh; i++) {
 1166:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
 1167:     for (j=ncl+1; j<=nch; j++) 
 1168:       m[i][j]=m[i][j-1]+nlay;
 1169:   }
 1170:   return m; 
 1171:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
 1172:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
 1173:   */
 1174: }
 1175: 
 1176: /*************************free ma3x ************************/
 1177: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
 1178: {
 1179:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
 1180:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1181:   free((FREE_ARG)(m+nrl-NR_END));
 1182: }
 1183: 
 1184: /*************** function subdirf ***********/
 1185: char *subdirf(char fileres[])
 1186: {
 1187:   /* Caution optionfilefiname is hidden */
 1188:   strcpy(tmpout,optionfilefiname);
 1189:   strcat(tmpout,"/"); /* Add to the right */
 1190:   strcat(tmpout,fileres);
 1191:   return tmpout;
 1192: }
 1193: 
 1194: /*************** function subdirf2 ***********/
 1195: char *subdirf2(char fileres[], char *preop)
 1196: {
 1197:   
 1198:   /* Caution optionfilefiname is hidden */
 1199:   strcpy(tmpout,optionfilefiname);
 1200:   strcat(tmpout,"/");
 1201:   strcat(tmpout,preop);
 1202:   strcat(tmpout,fileres);
 1203:   return tmpout;
 1204: }
 1205: 
 1206: /*************** function subdirf3 ***********/
 1207: char *subdirf3(char fileres[], char *preop, char *preop2)
 1208: {
 1209:   
 1210:   /* Caution optionfilefiname is hidden */
 1211:   strcpy(tmpout,optionfilefiname);
 1212:   strcat(tmpout,"/");
 1213:   strcat(tmpout,preop);
 1214:   strcat(tmpout,preop2);
 1215:   strcat(tmpout,fileres);
 1216:   return tmpout;
 1217: }
 1218: 
 1219: char *asc_diff_time(long time_sec, char ascdiff[])
 1220: {
 1221:   long sec_left, days, hours, minutes;
 1222:   days = (time_sec) / (60*60*24);
 1223:   sec_left = (time_sec) % (60*60*24);
 1224:   hours = (sec_left) / (60*60) ;
 1225:   sec_left = (sec_left) %(60*60);
 1226:   minutes = (sec_left) /60;
 1227:   sec_left = (sec_left) % (60);
 1228:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
 1229:   return ascdiff;
 1230: }
 1231: 
 1232: /***************** f1dim *************************/
 1233: extern int ncom; 
 1234: extern double *pcom,*xicom;
 1235: extern double (*nrfunc)(double []); 
 1236:  
 1237: double f1dim(double x) 
 1238: { 
 1239:   int j; 
 1240:   double f;
 1241:   double *xt; 
 1242:  
 1243:   xt=vector(1,ncom); 
 1244:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
 1245:   f=(*nrfunc)(xt); 
 1246:   free_vector(xt,1,ncom); 
 1247:   return f; 
 1248: } 
 1249: 
 1250: /*****************brent *************************/
 1251: double brent(double ax, double bx, double cx, double (*f)(double), double tol, 	double *xmin) 
 1252: { 
 1253:   int iter; 
 1254:   double a,b,d,etemp;
 1255:   double fu=0,fv,fw,fx;
 1256:   double ftemp=0.;
 1257:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
 1258:   double e=0.0; 
 1259:  
 1260:   a=(ax < cx ? ax : cx); 
 1261:   b=(ax > cx ? ax : cx); 
 1262:   x=w=v=bx; 
 1263:   fw=fv=fx=(*f)(x); 
 1264:   for (iter=1;iter<=ITMAX;iter++) { 
 1265:     xm=0.5*(a+b); 
 1266:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
 1267:     /*		if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
 1268:     printf(".");fflush(stdout);
 1269:     fprintf(ficlog,".");fflush(ficlog);
 1270: #ifdef DEBUGBRENT
 1271:     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);
 1272:     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);
 1273:     /*		if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
 1274: #endif
 1275:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
 1276:       *xmin=x; 
 1277:       return fx; 
 1278:     } 
 1279:     ftemp=fu;
 1280:     if (fabs(e) > tol1) { 
 1281:       r=(x-w)*(fx-fv); 
 1282:       q=(x-v)*(fx-fw); 
 1283:       p=(x-v)*q-(x-w)*r; 
 1284:       q=2.0*(q-r); 
 1285:       if (q > 0.0) p = -p; 
 1286:       q=fabs(q); 
 1287:       etemp=e; 
 1288:       e=d; 
 1289:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
 1290: 	d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1291:       else { 
 1292: 	d=p/q; 
 1293: 	u=x+d; 
 1294: 	if (u-a < tol2 || b-u < tol2) 
 1295: 	  d=SIGN(tol1,xm-x); 
 1296:       } 
 1297:     } else { 
 1298:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1299:     } 
 1300:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
 1301:     fu=(*f)(u); 
 1302:     if (fu <= fx) { 
 1303:       if (u >= x) a=x; else b=x; 
 1304:       SHFT(v,w,x,u) 
 1305:       SHFT(fv,fw,fx,fu) 
 1306:     } else { 
 1307:       if (u < x) a=u; else b=u; 
 1308:       if (fu <= fw || w == x) { 
 1309: 	v=w; 
 1310: 	w=u; 
 1311: 	fv=fw; 
 1312: 	fw=fu; 
 1313:       } else if (fu <= fv || v == x || v == w) { 
 1314: 	v=u; 
 1315: 	fv=fu; 
 1316:       } 
 1317:     } 
 1318:   } 
 1319:   nrerror("Too many iterations in brent"); 
 1320:   *xmin=x; 
 1321:   return fx; 
 1322: } 
 1323: 
 1324: /****************** mnbrak ***********************/
 1325: 
 1326: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
 1327: 	    double (*func)(double)) 
 1328: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
 1329: the downhill direction (defined by the function as evaluated at the initial points) and returns
 1330: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
 1331: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
 1332:    */
 1333:   double ulim,u,r,q, dum;
 1334:   double fu; 
 1335:  
 1336:   *fa=(*func)(*ax); 
 1337:   *fb=(*func)(*bx); 
 1338:   if (*fb > *fa) { 
 1339:     SHFT(dum,*ax,*bx,dum) 
 1340:     SHFT(dum,*fb,*fa,dum) 
 1341:   } 
 1342:   *cx=(*bx)+GOLD*(*bx-*ax); 
 1343:   *fc=(*func)(*cx); 
 1344: #ifdef DEBUG
 1345:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
 1346:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
 1347: #endif
 1348:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
 1349:     r=(*bx-*ax)*(*fb-*fc); 
 1350:     q=(*bx-*cx)*(*fb-*fa); 
 1351:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
 1352:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
 1353:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
 1354:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
 1355:       fu=(*func)(u); 
 1356: #ifdef DEBUG
 1357:       /* f(x)=A(x-u)**2+f(u) */
 1358:       double A, fparabu; 
 1359:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 1360:       fparabu= *fa - A*(*ax-u)*(*ax-u);
 1361:       printf("mnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf, fparabu=%.12f)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu);
 1362:       fprintf(ficlog, "mnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf, fparabu=%.12f)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu);
 1363:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
 1364:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
 1365:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
 1366:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
 1367: #endif 
 1368: #ifdef MNBRAKORIGINAL
 1369: #else
 1370:       if (fu > *fc) {
 1371: #ifdef DEBUG
 1372:       printf("mnbrak4  fu > fc \n");
 1373:       fprintf(ficlog, "mnbrak4 fu > fc\n");
 1374: #endif
 1375: 	/* 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 *\/  */
 1376: 	/* SHFT(*fa,*fc,fu,*fc) /\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\/ */
 1377: 	dum=u; /* Shifting c and u */
 1378: 	u = *cx;
 1379: 	*cx = dum;
 1380: 	dum = fu;
 1381: 	fu = *fc;
 1382: 	*fc =dum;
 1383:       } else { /* end */
 1384: #ifdef DEBUG
 1385:       printf("mnbrak3  fu < fc \n");
 1386:       fprintf(ficlog, "mnbrak3 fu < fc\n");
 1387: #endif
 1388: 	dum=u; /* Shifting c and u */
 1389: 	u = *cx;
 1390: 	*cx = dum;
 1391: 	dum = fu;
 1392: 	fu = *fc;
 1393: 	*fc =dum;
 1394:       }
 1395: #endif
 1396:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
 1397: #ifdef DEBUG
 1398:       printf("mnbrak2  u after c but before ulim\n");
 1399:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
 1400: #endif
 1401:       fu=(*func)(u); 
 1402:       if (fu < *fc) { 
 1403: #ifdef DEBUG
 1404:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
 1405:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
 1406: #endif
 1407: 	SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
 1408: 	SHFT(*fb,*fc,fu,(*func)(u)) 
 1409:       } 
 1410:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
 1411: #ifdef DEBUG
 1412:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
 1413:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
 1414: #endif
 1415:       u=ulim; 
 1416:       fu=(*func)(u); 
 1417:     } else { /* u could be left to b (if r > q parabola has a maximum) */
 1418: #ifdef DEBUG
 1419:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
 1420:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
 1421: #endif
 1422:       u=(*cx)+GOLD*(*cx-*bx); 
 1423:       fu=(*func)(u); 
 1424:     } /* end tests */
 1425:     SHFT(*ax,*bx,*cx,u) 
 1426:     SHFT(*fa,*fb,*fc,fu) 
 1427: #ifdef DEBUG
 1428:       printf("mnbrak2 (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu);
 1429:       fprintf(ficlog, "mnbrak2 (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu);
 1430: #endif
 1431:   } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
 1432: } 
 1433: 
 1434: /*************** linmin ************************/
 1435: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
 1436: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
 1437: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
 1438: the value of func at the returned location p . This is actually all accomplished by calling the
 1439: routines mnbrak and brent .*/
 1440: int ncom; 
 1441: double *pcom,*xicom;
 1442: double (*nrfunc)(double []); 
 1443:  
 1444: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
 1445: { 
 1446:   double brent(double ax, double bx, double cx, 
 1447: 	       double (*f)(double), double tol, double *xmin); 
 1448:   double f1dim(double x); 
 1449:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
 1450: 	      double *fc, double (*func)(double)); 
 1451:   int j; 
 1452:   double xx,xmin,bx,ax; 
 1453:   double fx,fb,fa;
 1454:  
 1455:   ncom=n; 
 1456:   pcom=vector(1,n); 
 1457:   xicom=vector(1,n); 
 1458:   nrfunc=func; 
 1459:   for (j=1;j<=n;j++) { 
 1460:     pcom[j]=p[j]; 
 1461:     xicom[j]=xi[j]; 
 1462:   } 
 1463:   ax=0.0; 
 1464:   xx=1.0; 
 1465:   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
 1466:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Find a minimum P+lambda n in that direction (lambdamin), with TOL between abscisses */
 1467: #ifdef DEBUG
 1468:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1469:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1470: #endif
 1471:   for (j=1;j<=n;j++) { 
 1472:     xi[j] *= xmin; 
 1473:     p[j] += xi[j]; 
 1474:   } 
 1475:   free_vector(xicom,1,n); 
 1476:   free_vector(pcom,1,n); 
 1477: } 
 1478: 
 1479: 
 1480: /*************** powell ************************/
 1481: /*
 1482: Minimization of a function func of n variables. Input consists of an initial starting point
 1483: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
 1484: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
 1485: such that failure to decrease by more than this amount on one iteration signals doneness. On
 1486: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
 1487: function value at p , and iter is the number of iterations taken. The routine linmin is used.
 1488:  */
 1489: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
 1490: 	    double (*func)(double [])) 
 1491: { 
 1492:   void linmin(double p[], double xi[], int n, double *fret, 
 1493: 	      double (*func)(double [])); 
 1494:   int i,ibig,j; 
 1495:   double del,t,*pt,*ptt,*xit;
 1496:   double directest;
 1497:   double fp,fptt;
 1498:   double *xits;
 1499:   int niterf, itmp;
 1500: 
 1501:   pt=vector(1,n); 
 1502:   ptt=vector(1,n); 
 1503:   xit=vector(1,n); 
 1504:   xits=vector(1,n); 
 1505:   *fret=(*func)(p); 
 1506:   for (j=1;j<=n;j++) pt[j]=p[j]; 
 1507:     rcurr_time = time(NULL);  
 1508:   for (*iter=1;;++(*iter)) { 
 1509:     fp=(*fret); 
 1510:     ibig=0; 
 1511:     del=0.0; 
 1512:     rlast_time=rcurr_time;
 1513:     /* (void) gettimeofday(&curr_time,&tzp); */
 1514:     rcurr_time = time(NULL);  
 1515:     curr_time = *localtime(&rcurr_time);
 1516:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
 1517:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
 1518: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
 1519:    for (i=1;i<=n;i++) {
 1520:       printf(" %d %.12f",i, p[i]);
 1521:       fprintf(ficlog," %d %.12lf",i, p[i]);
 1522:       fprintf(ficrespow," %.12lf", p[i]);
 1523:     }
 1524:     printf("\n");
 1525:     fprintf(ficlog,"\n");
 1526:     fprintf(ficrespow,"\n");fflush(ficrespow);
 1527:     if(*iter <=3){
 1528:       tml = *localtime(&rcurr_time);
 1529:       strcpy(strcurr,asctime(&tml));
 1530:       rforecast_time=rcurr_time; 
 1531:       itmp = strlen(strcurr);
 1532:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
 1533: 	strcurr[itmp-1]='\0';
 1534:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1535:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1536:       for(niterf=10;niterf<=30;niterf+=10){
 1537: 	rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
 1538: 	forecast_time = *localtime(&rforecast_time);
 1539: 	strcpy(strfor,asctime(&forecast_time));
 1540: 	itmp = strlen(strfor);
 1541: 	if(strfor[itmp-1]=='\n')
 1542: 	strfor[itmp-1]='\0';
 1543: 	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);
 1544: 	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);
 1545:       }
 1546:     }
 1547:     for (i=1;i<=n;i++) { 
 1548:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; 
 1549:       fptt=(*fret); 
 1550: #ifdef DEBUG
 1551: 	  printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1552: 	  fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1553: #endif
 1554:       printf("%d",i);fflush(stdout);
 1555:       fprintf(ficlog,"%d",i);fflush(ficlog);
 1556:       linmin(p,xit,n,fret,func); /* xit[n] has been loaded for direction i */
 1557:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions 
 1558: 				       because that direction will be replaced unless the gain del is small
 1559: 				      in comparison with the 'probable' gain, mu^2, with the last average direction.
 1560: 				      Unless the n directions are conjugate some gain in the determinant may be obtained
 1561: 				      with the new direction.
 1562: 				      */
 1563: 	del=fabs(fptt-(*fret)); 
 1564: 	ibig=i; 
 1565:       } 
 1566: #ifdef DEBUG
 1567:       printf("%d %.12e",i,(*fret));
 1568:       fprintf(ficlog,"%d %.12e",i,(*fret));
 1569:       for (j=1;j<=n;j++) {
 1570: 	xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
 1571: 	printf(" x(%d)=%.12e",j,xit[j]);
 1572: 	fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
 1573:       }
 1574:       for(j=1;j<=n;j++) {
 1575: 	printf(" p(%d)=%.12e",j,p[j]);
 1576: 	fprintf(ficlog," p(%d)=%.12e",j,p[j]);
 1577:       }
 1578:       printf("\n");
 1579:       fprintf(ficlog,"\n");
 1580: #endif
 1581:     } /* end i */
 1582:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
 1583: #ifdef DEBUG
 1584:       int k[2],l;
 1585:       k[0]=1;
 1586:       k[1]=-1;
 1587:       printf("Max: %.12e",(*func)(p));
 1588:       fprintf(ficlog,"Max: %.12e",(*func)(p));
 1589:       for (j=1;j<=n;j++) {
 1590: 	printf(" %.12e",p[j]);
 1591: 	fprintf(ficlog," %.12e",p[j]);
 1592:       }
 1593:       printf("\n");
 1594:       fprintf(ficlog,"\n");
 1595:       for(l=0;l<=1;l++) {
 1596: 	for (j=1;j<=n;j++) {
 1597: 	  ptt[j]=p[j]+(p[j]-pt[j])*k[l];
 1598: 	  printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1599: 	  fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1600: 	}
 1601: 	printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1602: 	fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1603:       }
 1604: #endif
 1605: 
 1606: 
 1607:       free_vector(xit,1,n); 
 1608:       free_vector(xits,1,n); 
 1609:       free_vector(ptt,1,n); 
 1610:       free_vector(pt,1,n); 
 1611:       return; 
 1612:     } 
 1613:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
 1614:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
 1615:       ptt[j]=2.0*p[j]-pt[j]; 
 1616:       xit[j]=p[j]-pt[j]; 
 1617:       pt[j]=p[j]; 
 1618:     } 
 1619:     fptt=(*func)(ptt); /* f_3 */
 1620:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
 1621:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
 1622:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
 1623:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
 1624:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
 1625:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
 1626:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
 1627:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
 1628: #ifdef NRCORIGINAL
 1629:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
 1630: #else
 1631:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
 1632:       t= t- del*SQR(fp-fptt);
 1633: #endif
 1634:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If del was big enough we change it for a new direction */
 1635: #ifdef DEBUG
 1636:       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);
 1637:       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);
 1638:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 1639: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 1640:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 1641: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 1642:       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);
 1643:       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);
 1644: #endif
 1645: #ifdef POWELLORIGINAL
 1646:       if (t < 0.0) { /* Then we use it for new direction */
 1647: #else
 1648:       if (directest*t < 0.0) { /* Contradiction between both tests */
 1649:       printf("directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
 1650:       printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 1651:       fprintf(ficlog,"directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
 1652:       fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 1653:     } 
 1654:       if (directest < 0.0) { /* Then we use it for new direction */
 1655: #endif
 1656: 	linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction.*/
 1657: 	for (j=1;j<=n;j++) { 
 1658: 	  xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
 1659: 	  xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
 1660: 	}
 1661: 	printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 1662: 	fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 1663: 
 1664: #ifdef DEBUG
 1665: 	printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1666: 	fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1667: 	for(j=1;j<=n;j++){
 1668: 	  printf(" %.12e",xit[j]);
 1669: 	  fprintf(ficlog," %.12e",xit[j]);
 1670: 	}
 1671: 	printf("\n");
 1672: 	fprintf(ficlog,"\n");
 1673: #endif
 1674:       } /* end of t negative */
 1675:     } /* end if (fptt < fp)  */
 1676:   } 
 1677: } 
 1678: 
 1679: /**** Prevalence limit (stable or period prevalence)  ****************/
 1680: 
 1681: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
 1682: {
 1683:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
 1684:      matrix by transitions matrix until convergence is reached */
 1685:   
 1686:   int i, ii,j,k;
 1687:   double min, max, maxmin, maxmax,sumnew=0.;
 1688:   /* double **matprod2(); */ /* test */
 1689:   double **out, cov[NCOVMAX+1], **pmij();
 1690:   double **newm;
 1691:   double agefin, delaymax=50 ; /* Max number of years to converge */
 1692:   
 1693:   for (ii=1;ii<=nlstate+ndeath;ii++)
 1694:     for (j=1;j<=nlstate+ndeath;j++){
 1695:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1696:     }
 1697:   
 1698:   cov[1]=1.;
 1699:   
 1700:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 1701:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
 1702:     newm=savm;
 1703:     /* Covariates have to be included here again */
 1704:     cov[2]=agefin;
 1705:     
 1706:     for (k=1; k<=cptcovn;k++) {
 1707:       cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 1708:       /*printf("prevalim ij=%d k=%d Tvar[%d]=%d nbcode=%d cov=%lf codtab[%d][Tvar[%d]]=%d \n",ij,k, k, Tvar[k],nbcode[Tvar[k]][codtab[ij][Tvar[k]]],cov[2+k], ij, k, codtab[ij][Tvar[k]]);*/
 1709:     }
 1710:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 1711:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
 1712:     /*   cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]]; */
 1713:     
 1714:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 1715:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 1716:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 1717:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 1718:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 1719:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
 1720:     
 1721:     savm=oldm;
 1722:     oldm=newm;
 1723:     maxmax=0.;
 1724:     for(j=1;j<=nlstate;j++){
 1725:       min=1.;
 1726:       max=0.;
 1727:       for(i=1; i<=nlstate; i++) {
 1728: 	sumnew=0;
 1729: 	for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
 1730: 	prlim[i][j]= newm[i][j]/(1-sumnew);
 1731:         /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
 1732: 	max=FMAX(max,prlim[i][j]);
 1733: 	min=FMIN(min,prlim[i][j]);
 1734:       }
 1735:       maxmin=max-min;
 1736:       maxmax=FMAX(maxmax,maxmin);
 1737:     } /* j loop */
 1738:     if(maxmax < ftolpl){
 1739:       return prlim;
 1740:     }
 1741:   } /* age loop */
 1742:   return prlim; /* should not reach here */
 1743: }
 1744: 
 1745: /*************** transition probabilities ***************/ 
 1746: 
 1747: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 1748: {
 1749:   /* According to parameters values stored in x and the covariate's values stored in cov,
 1750:      computes the probability to be observed in state j being in state i by appying the
 1751:      model to the ncovmodel covariates (including constant and age).
 1752:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 1753:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 1754:      ncth covariate in the global vector x is given by the formula:
 1755:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 1756:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 1757:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 1758:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 1759:      Outputs ps[i][j] the probability to be observed in j being in j according to
 1760:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 1761:   */
 1762:   double s1, lnpijopii;
 1763:   /*double t34;*/
 1764:   int i,j, nc, ii, jj;
 1765: 
 1766:     for(i=1; i<= nlstate; i++){
 1767:       for(j=1; j<i;j++){
 1768: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 1769: 	  /*lnpijopii += param[i][j][nc]*cov[nc];*/
 1770: 	  lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 1771: /* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 1772: 	}
 1773: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 1774: /* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 1775:       }
 1776:       for(j=i+1; j<=nlstate+ndeath;j++){
 1777: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 1778: 	  /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 1779: 	  lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 1780: /* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 1781: 	}
 1782: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 1783:       }
 1784:     }
 1785:     
 1786:     for(i=1; i<= nlstate; i++){
 1787:       s1=0;
 1788:       for(j=1; j<i; j++){
 1789: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 1790: 	/*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 1791:       }
 1792:       for(j=i+1; j<=nlstate+ndeath; j++){
 1793: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 1794: 	/*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 1795:       }
 1796:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 1797:       ps[i][i]=1./(s1+1.);
 1798:       /* Computing other pijs */
 1799:       for(j=1; j<i; j++)
 1800: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 1801:       for(j=i+1; j<=nlstate+ndeath; j++)
 1802: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 1803:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 1804:     } /* end i */
 1805:     
 1806:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 1807:       for(jj=1; jj<= nlstate+ndeath; jj++){
 1808: 	ps[ii][jj]=0;
 1809: 	ps[ii][ii]=1;
 1810:       }
 1811:     }
 1812:     
 1813:     
 1814:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 1815:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 1816:     /* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 1817:     /*   } */
 1818:     /*   printf("\n "); */
 1819:     /* } */
 1820:     /* printf("\n ");printf("%lf ",cov[2]);*/
 1821:     /*
 1822:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
 1823:       goto end;*/
 1824:     return ps;
 1825: }
 1826: 
 1827: /**************** Product of 2 matrices ******************/
 1828: 
 1829: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
 1830: {
 1831:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
 1832:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
 1833:   /* in, b, out are matrice of pointers which should have been initialized 
 1834:      before: only the contents of out is modified. The function returns
 1835:      a pointer to pointers identical to out */
 1836:   int i, j, k;
 1837:   for(i=nrl; i<= nrh; i++)
 1838:     for(k=ncolol; k<=ncoloh; k++){
 1839:       out[i][k]=0.;
 1840:       for(j=ncl; j<=nch; j++)
 1841:   	out[i][k] +=in[i][j]*b[j][k];
 1842:     }
 1843:   return out;
 1844: }
 1845: 
 1846: 
 1847: /************* Higher Matrix Product ***************/
 1848: 
 1849: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
 1850: {
 1851:   /* Computes the transition matrix starting at age 'age' over 
 1852:      'nhstepm*hstepm*stepm' months (i.e. until
 1853:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
 1854:      nhstepm*hstepm matrices. 
 1855:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
 1856:      (typically every 2 years instead of every month which is too big 
 1857:      for the memory).
 1858:      Model is determined by parameters x and covariates have to be 
 1859:      included manually here. 
 1860: 
 1861:      */
 1862: 
 1863:   int i, j, d, h, k;
 1864:   double **out, cov[NCOVMAX+1];
 1865:   double **newm;
 1866: 
 1867:   /* Hstepm could be zero and should return the unit matrix */
 1868:   for (i=1;i<=nlstate+ndeath;i++)
 1869:     for (j=1;j<=nlstate+ndeath;j++){
 1870:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 1871:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 1872:     }
 1873:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 1874:   for(h=1; h <=nhstepm; h++){
 1875:     for(d=1; d <=hstepm; d++){
 1876:       newm=savm;
 1877:       /* Covariates have to be included here again */
 1878:       cov[1]=1.;
 1879:       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
 1880:       for (k=1; k<=cptcovn;k++) 
 1881: 	cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 1882:       for (k=1; k<=cptcovage;k++)
 1883: 	cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
 1884:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
 1885: 	cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 1886: 
 1887: 
 1888:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 1889:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 1890:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
 1891: 		   pmij(pmmij,cov,ncovmodel,x,nlstate));
 1892:       savm=oldm;
 1893:       oldm=newm;
 1894:     }
 1895:     for(i=1; i<=nlstate+ndeath; i++)
 1896:       for(j=1;j<=nlstate+ndeath;j++) {
 1897: 	po[i][j][h]=newm[i][j];
 1898: 	/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 1899:       }
 1900:     /*printf("h=%d ",h);*/
 1901:   } /* end h */
 1902: /*     printf("\n H=%d \n",h); */
 1903:   return po;
 1904: }
 1905: 
 1906: #ifdef NLOPT
 1907:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
 1908:   double fret;
 1909:   double *xt;
 1910:   int j;
 1911:   myfunc_data *d2 = (myfunc_data *) pd;
 1912: /* xt = (p1-1); */
 1913:   xt=vector(1,n); 
 1914:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
 1915: 
 1916:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
 1917:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
 1918:   printf("Function = %.12lf ",fret);
 1919:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
 1920:   printf("\n");
 1921:  free_vector(xt,1,n);
 1922:   return fret;
 1923: }
 1924: #endif
 1925: 
 1926: /*************** log-likelihood *************/
 1927: double func( double *x)
 1928: {
 1929:   int i, ii, j, k, mi, d, kk;
 1930:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 1931:   double **out;
 1932:   double sw; /* Sum of weights */
 1933:   double lli; /* Individual log likelihood */
 1934:   int s1, s2;
 1935:   double bbh, survp;
 1936:   long ipmx;
 1937:   /*extern weight */
 1938:   /* We are differentiating ll according to initial status */
 1939:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 1940:   /*for(i=1;i<imx;i++) 
 1941:     printf(" %d\n",s[4][i]);
 1942:   */
 1943: 
 1944:   ++countcallfunc;
 1945: 
 1946:   cov[1]=1.;
 1947: 
 1948:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 1949: 
 1950:   if(mle==1){
 1951:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1952:       /* Computes the values of the ncovmodel covariates of the model
 1953: 	 depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
 1954: 	 Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
 1955: 	 to be observed in j being in i according to the model.
 1956:        */
 1957:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
 1958: 	cov[2+k]=covar[Tvar[k]][i];
 1959:       }
 1960:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
 1961: 	 is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
 1962: 	 has been calculated etc */
 1963:       for(mi=1; mi<= wav[i]-1; mi++){
 1964: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1965: 	  for (j=1;j<=nlstate+ndeath;j++){
 1966: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1967: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1968: 	  }
 1969: 	for(d=0; d<dh[mi][i]; d++){
 1970: 	  newm=savm;
 1971: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1972: 	  for (kk=1; kk<=cptcovage;kk++) {
 1973: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
 1974: 	  }
 1975: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1976: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1977: 	  savm=oldm;
 1978: 	  oldm=newm;
 1979: 	} /* end mult */
 1980:       
 1981: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 1982: 	/* But now since version 0.9 we anticipate for bias at large stepm.
 1983: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 1984: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
 1985: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
 1986: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 1987: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
 1988: 	 * probability in order to take into account the bias as a fraction of the way
 1989: 	 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
 1990: 	 * -stepm/2 to stepm/2 .
 1991: 	 * For stepm=1 the results are the same as for previous versions of Imach.
 1992: 	 * For stepm > 1 the results are less biased than in previous versions. 
 1993: 	 */
 1994: 	s1=s[mw[mi][i]][i];
 1995: 	s2=s[mw[mi+1][i]][i];
 1996: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1997: 	/* bias bh is positive if real duration
 1998: 	 * is higher than the multiple of stepm and negative otherwise.
 1999: 	 */
 2000: 	/* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
 2001: 	if( s2 > nlstate){ 
 2002: 	  /* i.e. if s2 is a death state and if the date of death is known 
 2003: 	     then the contribution to the likelihood is the probability to 
 2004: 	     die between last step unit time and current  step unit time, 
 2005: 	     which is also equal to probability to die before dh 
 2006: 	     minus probability to die before dh-stepm . 
 2007: 	     In version up to 0.92 likelihood was computed
 2008: 	as if date of death was unknown. Death was treated as any other
 2009: 	health state: the date of the interview describes the actual state
 2010: 	and not the date of a change in health state. The former idea was
 2011: 	to consider that at each interview the state was recorded
 2012: 	(healthy, disable or death) and IMaCh was corrected; but when we
 2013: 	introduced the exact date of death then we should have modified
 2014: 	the contribution of an exact death to the likelihood. This new
 2015: 	contribution is smaller and very dependent of the step unit
 2016: 	stepm. It is no more the probability to die between last interview
 2017: 	and month of death but the probability to survive from last
 2018: 	interview up to one month before death multiplied by the
 2019: 	probability to die within a month. Thanks to Chris
 2020: 	Jackson for correcting this bug.  Former versions increased
 2021: 	mortality artificially. The bad side is that we add another loop
 2022: 	which slows down the processing. The difference can be up to 10%
 2023: 	lower mortality.
 2024: 	  */
 2025: 	/* If, at the beginning of the maximization mostly, the
 2026: 	   cumulative probability or probability to be dead is
 2027: 	   constant (ie = 1) over time d, the difference is equal to
 2028: 	   0.  out[s1][3] = savm[s1][3]: probability, being at state
 2029: 	   s1 at precedent wave, to be dead a month before current
 2030: 	   wave is equal to probability, being at state s1 at
 2031: 	   precedent wave, to be dead at mont of the current
 2032: 	   wave. Then the observed probability (that this person died)
 2033: 	   is null according to current estimated parameter. In fact,
 2034: 	   it should be very low but not zero otherwise the log go to
 2035: 	   infinity.
 2036: 	*/
 2037: /* #ifdef INFINITYORIGINAL */
 2038: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 2039: /* #else */
 2040: /* 	  if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
 2041: /* 	    lli=log(mytinydouble); */
 2042: /* 	  else */
 2043: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 2044: /* #endif */
 2045: 	    lli=log(out[s1][s2] - savm[s1][s2]);
 2046: 
 2047: 	} else if  (s2==-2) {
 2048: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 2049: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2050: 	  /*survp += out[s1][j]; */
 2051: 	  lli= log(survp);
 2052: 	}
 2053: 	
 2054:  	else if  (s2==-4) { 
 2055: 	  for (j=3,survp=0. ; j<=nlstate; j++)  
 2056: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2057:  	  lli= log(survp); 
 2058:  	} 
 2059: 
 2060:  	else if  (s2==-5) { 
 2061:  	  for (j=1,survp=0. ; j<=2; j++)  
 2062: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2063:  	  lli= log(survp); 
 2064:  	} 
 2065: 	
 2066: 	else{
 2067: 	  lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2068: 	  /*  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 */
 2069: 	} 
 2070: 	/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 2071: 	/*if(lli ==000.0)*/
 2072: 	/*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); */
 2073:   	ipmx +=1;
 2074: 	sw += weight[i];
 2075: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2076: 	/* if (lli < log(mytinydouble)){ */
 2077: 	/*   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); */
 2078: 	/*   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]); */
 2079: 	/* } */
 2080:       } /* end of wave */
 2081:     } /* end of individual */
 2082:   }  else if(mle==2){
 2083:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2084:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 2085:       for(mi=1; mi<= wav[i]-1; mi++){
 2086: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2087: 	  for (j=1;j<=nlstate+ndeath;j++){
 2088: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2089: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2090: 	  }
 2091: 	for(d=0; d<=dh[mi][i]; d++){
 2092: 	  newm=savm;
 2093: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2094: 	  for (kk=1; kk<=cptcovage;kk++) {
 2095: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 2096: 	  }
 2097: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2098: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2099: 	  savm=oldm;
 2100: 	  oldm=newm;
 2101: 	} /* end mult */
 2102:       
 2103: 	s1=s[mw[mi][i]][i];
 2104: 	s2=s[mw[mi+1][i]][i];
 2105: 	bbh=(double)bh[mi][i]/(double)stepm; 
 2106: 	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 */
 2107: 	ipmx +=1;
 2108: 	sw += weight[i];
 2109: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2110:       } /* end of wave */
 2111:     } /* end of individual */
 2112:   }  else if(mle==3){  /* exponential inter-extrapolation */
 2113:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2114:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 2115:       for(mi=1; mi<= wav[i]-1; mi++){
 2116: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2117: 	  for (j=1;j<=nlstate+ndeath;j++){
 2118: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2119: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2120: 	  }
 2121: 	for(d=0; d<dh[mi][i]; d++){
 2122: 	  newm=savm;
 2123: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2124: 	  for (kk=1; kk<=cptcovage;kk++) {
 2125: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 2126: 	  }
 2127: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2128: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2129: 	  savm=oldm;
 2130: 	  oldm=newm;
 2131: 	} /* end mult */
 2132:       
 2133: 	s1=s[mw[mi][i]][i];
 2134: 	s2=s[mw[mi+1][i]][i];
 2135: 	bbh=(double)bh[mi][i]/(double)stepm; 
 2136: 	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 */
 2137: 	ipmx +=1;
 2138: 	sw += weight[i];
 2139: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2140:       } /* end of wave */
 2141:     } /* end of individual */
 2142:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
 2143:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2144:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 2145:       for(mi=1; mi<= wav[i]-1; mi++){
 2146: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2147: 	  for (j=1;j<=nlstate+ndeath;j++){
 2148: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2149: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2150: 	  }
 2151: 	for(d=0; d<dh[mi][i]; d++){
 2152: 	  newm=savm;
 2153: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2154: 	  for (kk=1; kk<=cptcovage;kk++) {
 2155: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 2156: 	  }
 2157: 	
 2158: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2159: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2160: 	  savm=oldm;
 2161: 	  oldm=newm;
 2162: 	} /* end mult */
 2163:       
 2164: 	s1=s[mw[mi][i]][i];
 2165: 	s2=s[mw[mi+1][i]][i];
 2166: 	if( s2 > nlstate){ 
 2167: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 2168: 	}else{
 2169: 	  lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 2170: 	}
 2171: 	ipmx +=1;
 2172: 	sw += weight[i];
 2173: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2174: /* 	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]); */
 2175:       } /* end of wave */
 2176:     } /* end of individual */
 2177:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
 2178:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2179:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 2180:       for(mi=1; mi<= wav[i]-1; mi++){
 2181: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2182: 	  for (j=1;j<=nlstate+ndeath;j++){
 2183: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2184: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2185: 	  }
 2186: 	for(d=0; d<dh[mi][i]; d++){
 2187: 	  newm=savm;
 2188: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2189: 	  for (kk=1; kk<=cptcovage;kk++) {
 2190: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 2191: 	  }
 2192: 	
 2193: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2194: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2195: 	  savm=oldm;
 2196: 	  oldm=newm;
 2197: 	} /* end mult */
 2198:       
 2199: 	s1=s[mw[mi][i]][i];
 2200: 	s2=s[mw[mi+1][i]][i];
 2201: 	lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 2202: 	ipmx +=1;
 2203: 	sw += weight[i];
 2204: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2205: 	/*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]);*/
 2206:       } /* end of wave */
 2207:     } /* end of individual */
 2208:   } /* End of if */
 2209:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 2210:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 2211:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 2212:   return -l;
 2213: }
 2214: 
 2215: /*************** log-likelihood *************/
 2216: double funcone( double *x)
 2217: {
 2218:   /* Same as likeli but slower because of a lot of printf and if */
 2219:   int i, ii, j, k, mi, d, kk;
 2220:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 2221:   double **out;
 2222:   double lli; /* Individual log likelihood */
 2223:   double llt;
 2224:   int s1, s2;
 2225:   double bbh, survp;
 2226:   /*extern weight */
 2227:   /* We are differentiating ll according to initial status */
 2228:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 2229:   /*for(i=1;i<imx;i++) 
 2230:     printf(" %d\n",s[4][i]);
 2231:   */
 2232:   cov[1]=1.;
 2233: 
 2234:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 2235: 
 2236:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2237:     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 2238:     for(mi=1; mi<= wav[i]-1; mi++){
 2239:       for (ii=1;ii<=nlstate+ndeath;ii++)
 2240: 	for (j=1;j<=nlstate+ndeath;j++){
 2241: 	  oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2242: 	  savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2243: 	}
 2244:       for(d=0; d<dh[mi][i]; d++){
 2245: 	newm=savm;
 2246: 	cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2247: 	for (kk=1; kk<=cptcovage;kk++) {
 2248: 	  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 2249: 	}
 2250: 	/* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2251: 	out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2252: 		     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2253: 	/* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
 2254: 	/* 	     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
 2255: 	savm=oldm;
 2256: 	oldm=newm;
 2257:       } /* end mult */
 2258:       
 2259:       s1=s[mw[mi][i]][i];
 2260:       s2=s[mw[mi+1][i]][i];
 2261:       bbh=(double)bh[mi][i]/(double)stepm; 
 2262:       /* bias is positive if real duration
 2263:        * is higher than the multiple of stepm and negative otherwise.
 2264:        */
 2265:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
 2266: 	lli=log(out[s1][s2] - savm[s1][s2]);
 2267:       } else if  (s2==-2) {
 2268: 	for (j=1,survp=0. ; j<=nlstate; j++) 
 2269: 	  survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2270: 	lli= log(survp);
 2271:       }else if (mle==1){
 2272: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2273:       } else if(mle==2){
 2274: 	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 */
 2275:       } else if(mle==3){  /* exponential inter-extrapolation */
 2276: 	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 */
 2277:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
 2278: 	lli=log(out[s1][s2]); /* Original formula */
 2279:       } else{  /* mle=0 back to 1 */
 2280: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2281: 	/*lli=log(out[s1][s2]); */ /* Original formula */
 2282:       } /* End of if */
 2283:       ipmx +=1;
 2284:       sw += weight[i];
 2285:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2286:       /*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]); */
 2287:       if(globpr){
 2288: 	fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
 2289:  %11.6f %11.6f %11.6f ", \
 2290: 		num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
 2291: 		2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
 2292: 	for(k=1,llt=0.,l=0.; k<=nlstate; k++){
 2293: 	  llt +=ll[k]*gipmx/gsw;
 2294: 	  fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
 2295: 	}
 2296: 	fprintf(ficresilk," %10.6f\n", -llt);
 2297:       }
 2298:     } /* end of wave */
 2299:   } /* end of individual */
 2300:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 2301:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 2302:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 2303:   if(globpr==0){ /* First time we count the contributions and weights */
 2304:     gipmx=ipmx;
 2305:     gsw=sw;
 2306:   }
 2307:   return -l;
 2308: }
 2309: 
 2310: 
 2311: /*************** function likelione ***********/
 2312: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
 2313: {
 2314:   /* This routine should help understanding what is done with 
 2315:      the selection of individuals/waves and
 2316:      to check the exact contribution to the likelihood.
 2317:      Plotting could be done.
 2318:    */
 2319:   int k;
 2320: 
 2321:   if(*globpri !=0){ /* Just counts and sums, no printings */
 2322:     strcpy(fileresilk,"ilk"); 
 2323:     strcat(fileresilk,fileres);
 2324:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
 2325:       printf("Problem with resultfile: %s\n", fileresilk);
 2326:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
 2327:     }
 2328:     fprintf(ficresilk, "#individual(line's_record) s1 s2 wave# effective_wave# number_of_matrices_product pij weight -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");
 2329:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
 2330:     /* 	i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
 2331:     for(k=1; k<=nlstate; k++) 
 2332:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
 2333:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
 2334:   }
 2335: 
 2336:   *fretone=(*funcone)(p);
 2337:   if(*globpri !=0){
 2338:     fclose(ficresilk);
 2339:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
 2340:     fflush(fichtm); 
 2341:   } 
 2342:   return;
 2343: }
 2344: 
 2345: 
 2346: /*********** Maximum Likelihood Estimation ***************/
 2347: 
 2348: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
 2349: {
 2350:   int i,j, iter=0;
 2351:   double **xi;
 2352:   double fret;
 2353:   double fretone; /* Only one call to likelihood */
 2354:   /*  char filerespow[FILENAMELENGTH];*/
 2355: 
 2356: #ifdef NLOPT
 2357:   int creturn;
 2358:   nlopt_opt opt;
 2359:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
 2360:   double *lb;
 2361:   double minf; /* the minimum objective value, upon return */
 2362:   double * p1; /* Shifted parameters from 0 instead of 1 */
 2363:   myfunc_data dinst, *d = &dinst;
 2364: #endif
 2365: 
 2366: 
 2367:   xi=matrix(1,npar,1,npar);
 2368:   for (i=1;i<=npar;i++)
 2369:     for (j=1;j<=npar;j++)
 2370:       xi[i][j]=(i==j ? 1.0 : 0.0);
 2371:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
 2372:   strcpy(filerespow,"pow"); 
 2373:   strcat(filerespow,fileres);
 2374:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
 2375:     printf("Problem with resultfile: %s\n", filerespow);
 2376:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 2377:   }
 2378:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
 2379:   for (i=1;i<=nlstate;i++)
 2380:     for(j=1;j<=nlstate+ndeath;j++)
 2381:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 2382:   fprintf(ficrespow,"\n");
 2383: #ifdef POWELL
 2384:   powell(p,xi,npar,ftol,&iter,&fret,func);
 2385: #endif
 2386: 
 2387: #ifdef NLOPT
 2388: #ifdef NEWUOA
 2389:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
 2390: #else
 2391:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
 2392: #endif
 2393:   lb=vector(0,npar-1);
 2394:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
 2395:   nlopt_set_lower_bounds(opt, lb);
 2396:   nlopt_set_initial_step1(opt, 0.1);
 2397:   
 2398:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
 2399:   d->function = func;
 2400:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
 2401:   nlopt_set_min_objective(opt, myfunc, d);
 2402:   nlopt_set_xtol_rel(opt, ftol);
 2403:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
 2404:     printf("nlopt failed! %d\n",creturn); 
 2405:   }
 2406:   else {
 2407:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
 2408:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
 2409:     iter=1; /* not equal */
 2410:   }
 2411:   nlopt_destroy(opt);
 2412: #endif
 2413:   free_matrix(xi,1,npar,1,npar);
 2414:   fclose(ficrespow);
 2415:   printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2416:   fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2417:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2418: 
 2419: }
 2420: 
 2421: /**** Computes Hessian and covariance matrix ***/
 2422: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
 2423: {
 2424:   double  **a,**y,*x,pd;
 2425:   double **hess;
 2426:   int i, j;
 2427:   int *indx;
 2428: 
 2429:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
 2430:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
 2431:   void lubksb(double **a, int npar, int *indx, double b[]) ;
 2432:   void ludcmp(double **a, int npar, int *indx, double *d) ;
 2433:   double gompertz(double p[]);
 2434:   hess=matrix(1,npar,1,npar);
 2435: 
 2436:   printf("\nCalculation of the hessian matrix. Wait...\n");
 2437:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
 2438:   for (i=1;i<=npar;i++){
 2439:     printf("%d",i);fflush(stdout);
 2440:     fprintf(ficlog,"%d",i);fflush(ficlog);
 2441:    
 2442:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
 2443:     
 2444:     /*  printf(" %f ",p[i]);
 2445: 	printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
 2446:   }
 2447:   
 2448:   for (i=1;i<=npar;i++) {
 2449:     for (j=1;j<=npar;j++)  {
 2450:       if (j>i) { 
 2451: 	printf(".%d%d",i,j);fflush(stdout);
 2452: 	fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
 2453: 	hess[i][j]=hessij(p,delti,i,j,func,npar);
 2454: 	
 2455: 	hess[j][i]=hess[i][j];    
 2456: 	/*printf(" %lf ",hess[i][j]);*/
 2457:       }
 2458:     }
 2459:   }
 2460:   printf("\n");
 2461:   fprintf(ficlog,"\n");
 2462: 
 2463:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
 2464:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
 2465:   
 2466:   a=matrix(1,npar,1,npar);
 2467:   y=matrix(1,npar,1,npar);
 2468:   x=vector(1,npar);
 2469:   indx=ivector(1,npar);
 2470:   for (i=1;i<=npar;i++)
 2471:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
 2472:   ludcmp(a,npar,indx,&pd);
 2473: 
 2474:   for (j=1;j<=npar;j++) {
 2475:     for (i=1;i<=npar;i++) x[i]=0;
 2476:     x[j]=1;
 2477:     lubksb(a,npar,indx,x);
 2478:     for (i=1;i<=npar;i++){ 
 2479:       matcov[i][j]=x[i];
 2480:     }
 2481:   }
 2482: 
 2483:   printf("\n#Hessian matrix#\n");
 2484:   fprintf(ficlog,"\n#Hessian matrix#\n");
 2485:   for (i=1;i<=npar;i++) { 
 2486:     for (j=1;j<=npar;j++) { 
 2487:       printf("%.3e ",hess[i][j]);
 2488:       fprintf(ficlog,"%.3e ",hess[i][j]);
 2489:     }
 2490:     printf("\n");
 2491:     fprintf(ficlog,"\n");
 2492:   }
 2493: 
 2494:   /* Recompute Inverse */
 2495:   for (i=1;i<=npar;i++)
 2496:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
 2497:   ludcmp(a,npar,indx,&pd);
 2498: 
 2499:   /*  printf("\n#Hessian matrix recomputed#\n");
 2500: 
 2501:   for (j=1;j<=npar;j++) {
 2502:     for (i=1;i<=npar;i++) x[i]=0;
 2503:     x[j]=1;
 2504:     lubksb(a,npar,indx,x);
 2505:     for (i=1;i<=npar;i++){ 
 2506:       y[i][j]=x[i];
 2507:       printf("%.3e ",y[i][j]);
 2508:       fprintf(ficlog,"%.3e ",y[i][j]);
 2509:     }
 2510:     printf("\n");
 2511:     fprintf(ficlog,"\n");
 2512:   }
 2513:   */
 2514: 
 2515:   free_matrix(a,1,npar,1,npar);
 2516:   free_matrix(y,1,npar,1,npar);
 2517:   free_vector(x,1,npar);
 2518:   free_ivector(indx,1,npar);
 2519:   free_matrix(hess,1,npar,1,npar);
 2520: 
 2521: 
 2522: }
 2523: 
 2524: /*************** hessian matrix ****************/
 2525: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
 2526: {
 2527:   int i;
 2528:   int l=1, lmax=20;
 2529:   double k1,k2;
 2530:   double p2[MAXPARM+1]; /* identical to x */
 2531:   double res;
 2532:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 2533:   double fx;
 2534:   int k=0,kmax=10;
 2535:   double l1;
 2536: 
 2537:   fx=func(x);
 2538:   for (i=1;i<=npar;i++) p2[i]=x[i];
 2539:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
 2540:     l1=pow(10,l);
 2541:     delts=delt;
 2542:     for(k=1 ; k <kmax; k=k+1){
 2543:       delt = delta*(l1*k);
 2544:       p2[theta]=x[theta] +delt;
 2545:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
 2546:       p2[theta]=x[theta]-delt;
 2547:       k2=func(p2)-fx;
 2548:       /*res= (k1-2.0*fx+k2)/delt/delt; */
 2549:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
 2550:       
 2551: #ifdef DEBUGHESS
 2552:       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);
 2553:       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);
 2554: #endif
 2555:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
 2556:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 2557: 	k=kmax;
 2558:       }
 2559:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
 2560: 	k=kmax; l=lmax*10;
 2561:       }
 2562:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
 2563: 	delts=delt;
 2564:       }
 2565:     }
 2566:   }
 2567:   delti[theta]=delts;
 2568:   return res; 
 2569:   
 2570: }
 2571: 
 2572: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
 2573: {
 2574:   int i;
 2575:   int l=1, lmax=20;
 2576:   double k1,k2,k3,k4,res,fx;
 2577:   double p2[MAXPARM+1];
 2578:   int k;
 2579: 
 2580:   fx=func(x);
 2581:   for (k=1; k<=2; k++) {
 2582:     for (i=1;i<=npar;i++) p2[i]=x[i];
 2583:     p2[thetai]=x[thetai]+delti[thetai]/k;
 2584:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 2585:     k1=func(p2)-fx;
 2586:   
 2587:     p2[thetai]=x[thetai]+delti[thetai]/k;
 2588:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 2589:     k2=func(p2)-fx;
 2590:   
 2591:     p2[thetai]=x[thetai]-delti[thetai]/k;
 2592:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 2593:     k3=func(p2)-fx;
 2594:   
 2595:     p2[thetai]=x[thetai]-delti[thetai]/k;
 2596:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 2597:     k4=func(p2)-fx;
 2598:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
 2599: #ifdef DEBUG
 2600:     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);
 2601:     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);
 2602: #endif
 2603:   }
 2604:   return res;
 2605: }
 2606: 
 2607: /************** Inverse of matrix **************/
 2608: void ludcmp(double **a, int n, int *indx, double *d) 
 2609: { 
 2610:   int i,imax,j,k; 
 2611:   double big,dum,sum,temp; 
 2612:   double *vv; 
 2613:  
 2614:   vv=vector(1,n); 
 2615:   *d=1.0; 
 2616:   for (i=1;i<=n;i++) { 
 2617:     big=0.0; 
 2618:     for (j=1;j<=n;j++) 
 2619:       if ((temp=fabs(a[i][j])) > big) big=temp; 
 2620:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
 2621:     vv[i]=1.0/big; 
 2622:   } 
 2623:   for (j=1;j<=n;j++) { 
 2624:     for (i=1;i<j;i++) { 
 2625:       sum=a[i][j]; 
 2626:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
 2627:       a[i][j]=sum; 
 2628:     } 
 2629:     big=0.0; 
 2630:     for (i=j;i<=n;i++) { 
 2631:       sum=a[i][j]; 
 2632:       for (k=1;k<j;k++) 
 2633: 	sum -= a[i][k]*a[k][j]; 
 2634:       a[i][j]=sum; 
 2635:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
 2636: 	big=dum; 
 2637: 	imax=i; 
 2638:       } 
 2639:     } 
 2640:     if (j != imax) { 
 2641:       for (k=1;k<=n;k++) { 
 2642: 	dum=a[imax][k]; 
 2643: 	a[imax][k]=a[j][k]; 
 2644: 	a[j][k]=dum; 
 2645:       } 
 2646:       *d = -(*d); 
 2647:       vv[imax]=vv[j]; 
 2648:     } 
 2649:     indx[j]=imax; 
 2650:     if (a[j][j] == 0.0) a[j][j]=TINY; 
 2651:     if (j != n) { 
 2652:       dum=1.0/(a[j][j]); 
 2653:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
 2654:     } 
 2655:   } 
 2656:   free_vector(vv,1,n);  /* Doesn't work */
 2657: ;
 2658: } 
 2659: 
 2660: void lubksb(double **a, int n, int *indx, double b[]) 
 2661: { 
 2662:   int i,ii=0,ip,j; 
 2663:   double sum; 
 2664:  
 2665:   for (i=1;i<=n;i++) { 
 2666:     ip=indx[i]; 
 2667:     sum=b[ip]; 
 2668:     b[ip]=b[i]; 
 2669:     if (ii) 
 2670:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
 2671:     else if (sum) ii=i; 
 2672:     b[i]=sum; 
 2673:   } 
 2674:   for (i=n;i>=1;i--) { 
 2675:     sum=b[i]; 
 2676:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
 2677:     b[i]=sum/a[i][i]; 
 2678:   } 
 2679: } 
 2680: 
 2681: void pstamp(FILE *fichier)
 2682: {
 2683:   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
 2684: }
 2685: 
 2686: /************ Frequencies ********************/
 2687: void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[])
 2688: {  /* Some frequencies */
 2689:   
 2690:   int i, m, jk, j1, bool, z1,j;
 2691:   int first;
 2692:   double ***freq; /* Frequencies */
 2693:   double *pp, **prop;
 2694:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
 2695:   char fileresp[FILENAMELENGTH];
 2696:   
 2697:   pp=vector(1,nlstate);
 2698:   prop=matrix(1,nlstate,iagemin,iagemax+3);
 2699:   strcpy(fileresp,"p");
 2700:   strcat(fileresp,fileres);
 2701:   if((ficresp=fopen(fileresp,"w"))==NULL) {
 2702:     printf("Problem with prevalence resultfile: %s\n", fileresp);
 2703:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
 2704:     exit(0);
 2705:   }
 2706:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
 2707:   j1=0;
 2708:   
 2709:   j=cptcoveff;
 2710:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 2711: 
 2712:   first=1;
 2713: 
 2714:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
 2715:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
 2716:   /*    j1++; */
 2717:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
 2718:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
 2719: 	scanf("%d", i);*/
 2720:       for (i=-5; i<=nlstate+ndeath; i++)  
 2721: 	for (jk=-5; jk<=nlstate+ndeath; jk++)  
 2722: 	  for(m=iagemin; m <= iagemax+3; m++)
 2723: 	    freq[i][jk][m]=0;
 2724:       
 2725:       for (i=1; i<=nlstate; i++)  
 2726: 	for(m=iagemin; m <= iagemax+3; m++)
 2727: 	  prop[i][m]=0;
 2728:       
 2729:       dateintsum=0;
 2730:       k2cpt=0;
 2731:       for (i=1; i<=imx; i++) {
 2732: 	bool=1;
 2733: 	if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
 2734: 	  for (z1=1; z1<=cptcoveff; z1++)       
 2735:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
 2736:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
 2737:               bool=0;
 2738:               /* printf("bool=%d i=%d, z1=%d, Tvaraff[%d]=%d, covar[Tvarff][%d]=%2f, codtab[%d][%d]=%d, nbcode[Tvaraff][codtab[%d][%d]=%d, j1=%d\n", 
 2739:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
 2740:                 j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
 2741:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
 2742:             } 
 2743: 	}
 2744:  
 2745: 	if (bool==1){
 2746: 	  for(m=firstpass; m<=lastpass; m++){
 2747: 	    k2=anint[m][i]+(mint[m][i]/12.);
 2748: 	    /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
 2749: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 2750: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 2751: 	      if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
 2752: 	      if (m<lastpass) {
 2753: 		freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
 2754: 		freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
 2755: 	      }
 2756: 	      
 2757: 	      if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
 2758: 		dateintsum=dateintsum+k2;
 2759: 		k2cpt++;
 2760: 	      }
 2761: 	      /*}*/
 2762: 	  }
 2763: 	}
 2764:       } /* end i */
 2765:        
 2766:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 2767:       pstamp(ficresp);
 2768:       if  (cptcovn>0) {
 2769: 	fprintf(ficresp, "\n#********** Variable "); 
 2770: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2771: 	fprintf(ficresp, "**********\n#");
 2772: 	fprintf(ficlog, "\n#********** Variable "); 
 2773: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2774: 	fprintf(ficlog, "**********\n#");
 2775:       }
 2776:       for(i=1; i<=nlstate;i++) 
 2777: 	fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
 2778:       fprintf(ficresp, "\n");
 2779:       
 2780:       for(i=iagemin; i <= iagemax+3; i++){
 2781: 	if(i==iagemax+3){
 2782: 	  fprintf(ficlog,"Total");
 2783: 	}else{
 2784: 	  if(first==1){
 2785: 	    first=0;
 2786: 	    printf("See log file for details...\n");
 2787: 	  }
 2788: 	  fprintf(ficlog,"Age %d", i);
 2789: 	}
 2790: 	for(jk=1; jk <=nlstate ; jk++){
 2791: 	  for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
 2792: 	    pp[jk] += freq[jk][m][i]; 
 2793: 	}
 2794: 	for(jk=1; jk <=nlstate ; jk++){
 2795: 	  for(m=-1, pos=0; m <=0 ; m++)
 2796: 	    pos += freq[jk][m][i];
 2797: 	  if(pp[jk]>=1.e-10){
 2798: 	    if(first==1){
 2799: 	      printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 2800: 	    }
 2801: 	    fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 2802: 	  }else{
 2803: 	    if(first==1)
 2804: 	      printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 2805: 	    fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 2806: 	  }
 2807: 	}
 2808: 
 2809: 	for(jk=1; jk <=nlstate ; jk++){
 2810: 	  for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
 2811: 	    pp[jk] += freq[jk][m][i];
 2812: 	}	
 2813: 	for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
 2814: 	  pos += pp[jk];
 2815: 	  posprop += prop[jk][i];
 2816: 	}
 2817: 	for(jk=1; jk <=nlstate ; jk++){
 2818: 	  if(pos>=1.e-5){
 2819: 	    if(first==1)
 2820: 	      printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 2821: 	    fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 2822: 	  }else{
 2823: 	    if(first==1)
 2824: 	      printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 2825: 	    fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 2826: 	  }
 2827: 	  if( i <= iagemax){
 2828: 	    if(pos>=1.e-5){
 2829: 	      fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
 2830: 	      /*probs[i][jk][j1]= pp[jk]/pos;*/
 2831: 	      /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
 2832: 	    }
 2833: 	    else
 2834: 	      fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
 2835: 	  }
 2836: 	}
 2837: 	
 2838: 	for(jk=-1; jk <=nlstate+ndeath; jk++)
 2839: 	  for(m=-1; m <=nlstate+ndeath; m++)
 2840: 	    if(freq[jk][m][i] !=0 ) {
 2841: 	    if(first==1)
 2842: 	      printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
 2843: 	      fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
 2844: 	    }
 2845: 	if(i <= iagemax)
 2846: 	  fprintf(ficresp,"\n");
 2847: 	if(first==1)
 2848: 	  printf("Others in log...\n");
 2849: 	fprintf(ficlog,"\n");
 2850:       }
 2851:       /*}*/
 2852:   }
 2853:   dateintmean=dateintsum/k2cpt; 
 2854:  
 2855:   fclose(ficresp);
 2856:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
 2857:   free_vector(pp,1,nlstate);
 2858:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
 2859:   /* End of Freq */
 2860: }
 2861: 
 2862: /************ Prevalence ********************/
 2863: 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)
 2864: {  
 2865:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 2866:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 2867:      We still use firstpass and lastpass as another selection.
 2868:   */
 2869:  
 2870:   int i, m, jk, j1, bool, z1,j;
 2871: 
 2872:   double **prop;
 2873:   double posprop; 
 2874:   double  y2; /* in fractional years */
 2875:   int iagemin, iagemax;
 2876:   int first; /** to stop verbosity which is redirected to log file */
 2877: 
 2878:   iagemin= (int) agemin;
 2879:   iagemax= (int) agemax;
 2880:   /*pp=vector(1,nlstate);*/
 2881:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
 2882:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
 2883:   j1=0;
 2884:   
 2885:   /*j=cptcoveff;*/
 2886:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 2887:   
 2888:   first=1;
 2889:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
 2890:     /*for(i1=1; i1<=ncodemax[k1];i1++){
 2891:       j1++;*/
 2892:       
 2893:       for (i=1; i<=nlstate; i++)  
 2894: 	for(m=iagemin; m <= iagemax+3; m++)
 2895: 	  prop[i][m]=0.0;
 2896:      
 2897:       for (i=1; i<=imx; i++) { /* Each individual */
 2898: 	bool=1;
 2899: 	if  (cptcovn>0) {
 2900: 	  for (z1=1; z1<=cptcoveff; z1++) 
 2901: 	    if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
 2902: 	      bool=0;
 2903: 	} 
 2904: 	if (bool==1) { 
 2905: 	  for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
 2906: 	    y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
 2907: 	    if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
 2908: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 2909: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 2910: 	      if((int)agev[m][i] <iagemin || (int)agev[m][i] >iagemax+3) printf("Error on individual =%d agev[m][i]=%f m=%d\n",i, agev[m][i],m); 
 2911:  	      if (s[m][i]>0 && s[m][i]<=nlstate) { 
 2912: 		/*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]]);*/
 2913:  		prop[s[m][i]][(int)agev[m][i]] += weight[i];
 2914:  		prop[s[m][i]][iagemax+3] += weight[i]; 
 2915:  	      } 
 2916: 	    }
 2917: 	  } /* end selection of waves */
 2918: 	}
 2919:       }
 2920:       for(i=iagemin; i <= iagemax+3; i++){  
 2921:  	for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
 2922:  	  posprop += prop[jk][i]; 
 2923:  	} 
 2924: 	
 2925:  	for(jk=1; jk <=nlstate ; jk++){	    
 2926:  	  if( i <=  iagemax){ 
 2927:  	    if(posprop>=1.e-5){ 
 2928:  	      probs[i][jk][j1]= prop[jk][i]/posprop;
 2929:  	    } else{
 2930: 	      if(first==1){
 2931: 		first=0;
 2932: 		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]);
 2933: 	      }
 2934: 	    }
 2935:  	  } 
 2936:  	}/* end jk */ 
 2937:       }/* end i */ 
 2938:     /*} *//* end i1 */
 2939:   } /* end j1 */
 2940:   
 2941:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
 2942:   /*free_vector(pp,1,nlstate);*/
 2943:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
 2944: }  /* End of prevalence */
 2945: 
 2946: /************* Waves Concatenation ***************/
 2947: 
 2948: 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)
 2949: {
 2950:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 2951:      Death is a valid wave (if date is known).
 2952:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
 2953:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 2954:      and mw[mi+1][i]. dh depends on stepm.
 2955:      */
 2956: 
 2957:   int i, mi, m;
 2958:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
 2959:      double sum=0., jmean=0.;*/
 2960:   int first;
 2961:   int j, k=0,jk, ju, jl;
 2962:   double sum=0.;
 2963:   first=0;
 2964:   jmin=100000;
 2965:   jmax=-1;
 2966:   jmean=0.;
 2967:   for(i=1; i<=imx; i++){
 2968:     mi=0;
 2969:     m=firstpass;
 2970:     while(s[m][i] <= nlstate){
 2971:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
 2972: 	mw[++mi][i]=m;
 2973:       if(m >=lastpass)
 2974: 	break;
 2975:       else
 2976: 	m++;
 2977:     }/* end while */
 2978:     if (s[m][i] > nlstate){
 2979:       mi++;	/* Death is another wave */
 2980:       /* if(mi==0)  never been interviewed correctly before death */
 2981: 	 /* Only death is a correct wave */
 2982:       mw[mi][i]=m;
 2983:     }
 2984: 
 2985:     wav[i]=mi;
 2986:     if(mi==0){
 2987:       nbwarn++;
 2988:       if(first==0){
 2989: 	printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
 2990: 	first=1;
 2991:       }
 2992:       if(first==1){
 2993: 	fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
 2994:       }
 2995:     } /* end mi==0 */
 2996:   } /* End individuals */
 2997: 
 2998:   for(i=1; i<=imx; i++){
 2999:     for(mi=1; mi<wav[i];mi++){
 3000:       if (stepm <=0)
 3001: 	dh[mi][i]=1;
 3002:       else{
 3003: 	if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
 3004: 	  if (agedc[i] < 2*AGESUP) {
 3005: 	    j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
 3006: 	    if(j==0) j=1;  /* Survives at least one month after exam */
 3007: 	    else if(j<0){
 3008: 	      nberr++;
 3009: 	      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]);
 3010: 	      j=1; /* Temporary Dangerous patch */
 3011: 	      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);
 3012: 	      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]);
 3013: 	      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);
 3014: 	    }
 3015: 	    k=k+1;
 3016: 	    if (j >= jmax){
 3017: 	      jmax=j;
 3018: 	      ijmax=i;
 3019: 	    }
 3020: 	    if (j <= jmin){
 3021: 	      jmin=j;
 3022: 	      ijmin=i;
 3023: 	    }
 3024: 	    sum=sum+j;
 3025: 	    /*if (j<0) printf("j=%d num=%d \n",j,i);*/
 3026: 	    /*	  printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
 3027: 	  }
 3028: 	}
 3029: 	else{
 3030: 	  j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 3031: /* 	  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]); */
 3032: 
 3033: 	  k=k+1;
 3034: 	  if (j >= jmax) {
 3035: 	    jmax=j;
 3036: 	    ijmax=i;
 3037: 	  }
 3038: 	  else if (j <= jmin){
 3039: 	    jmin=j;
 3040: 	    ijmin=i;
 3041: 	  }
 3042: 	  /*	    if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
 3043: 	  /*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]);*/
 3044: 	  if(j<0){
 3045: 	    nberr++;
 3046: 	    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]);
 3047: 	    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]);
 3048: 	  }
 3049: 	  sum=sum+j;
 3050: 	}
 3051: 	jk= j/stepm;
 3052: 	jl= j -jk*stepm;
 3053: 	ju= j -(jk+1)*stepm;
 3054: 	if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
 3055: 	  if(jl==0){
 3056: 	    dh[mi][i]=jk;
 3057: 	    bh[mi][i]=0;
 3058: 	  }else{ /* We want a negative bias in order to only have interpolation ie
 3059: 		  * to avoid the price of an extra matrix product in likelihood */
 3060: 	    dh[mi][i]=jk+1;
 3061: 	    bh[mi][i]=ju;
 3062: 	  }
 3063: 	}else{
 3064: 	  if(jl <= -ju){
 3065: 	    dh[mi][i]=jk;
 3066: 	    bh[mi][i]=jl;	/* bias is positive if real duration
 3067: 				 * is higher than the multiple of stepm and negative otherwise.
 3068: 				 */
 3069: 	  }
 3070: 	  else{
 3071: 	    dh[mi][i]=jk+1;
 3072: 	    bh[mi][i]=ju;
 3073: 	  }
 3074: 	  if(dh[mi][i]==0){
 3075: 	    dh[mi][i]=1; /* At least one step */
 3076: 	    bh[mi][i]=ju; /* At least one step */
 3077: 	    /*  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);*/
 3078: 	  }
 3079: 	} /* end if mle */
 3080:       }
 3081:     } /* end wave */
 3082:   }
 3083:   jmean=sum/k;
 3084:   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);
 3085:   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);
 3086:  }
 3087: 
 3088: /*********** Tricode ****************************/
 3089: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
 3090: {
 3091:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
 3092:   /*	  Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
 3093:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
 3094:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
 3095:    * nbcode[Tvar[j]][1]= 
 3096:   */
 3097: 
 3098:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
 3099:   int modmaxcovj=0; /* Modality max of covariates j */
 3100:   int cptcode=0; /* Modality max of covariates j */
 3101:   int modmincovj=0; /* Modality min of covariates j */
 3102: 
 3103: 
 3104:   cptcoveff=0; 
 3105:  
 3106:   for (k=-1; k < maxncov; k++) Ndum[k]=0;
 3107:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
 3108: 
 3109:   /* Loop on covariates without age and products */
 3110:   for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
 3111:     for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the 
 3112: 			       modality of this covariate Vj*/ 
 3113:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
 3114: 				    * If product of Vn*Vm, still boolean *:
 3115: 				    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
 3116: 				    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
 3117:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
 3118: 				      modality of the nth covariate of individual i. */
 3119:       if (ij > modmaxcovj)
 3120:         modmaxcovj=ij; 
 3121:       else if (ij < modmincovj) 
 3122: 	modmincovj=ij; 
 3123:       if ((ij < -1) && (ij > NCOVMAX)){
 3124: 	printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
 3125: 	exit(1);
 3126:       }else
 3127:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
 3128:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
 3129:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
 3130:       /* getting the maximum value of the modality of the covariate
 3131: 	 (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
 3132: 	 female is 1, then modmaxcovj=1.*/
 3133:     }
 3134:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
 3135:     cptcode=modmaxcovj;
 3136:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
 3137:    /*for (i=0; i<=cptcode; i++) {*/
 3138:     for (i=modmincovj;  i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
 3139:       printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
 3140:       if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
 3141: 	ncodemax[j]++;  /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
 3142:       }
 3143:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
 3144: 	 historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
 3145:     } /* Ndum[-1] number of undefined modalities */
 3146: 
 3147:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
 3148:     /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
 3149:     /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
 3150:        modmincovj=3; modmaxcovj = 7;
 3151:        There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
 3152:        which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy 
 3153:        variables V1_1 and V1_2.
 3154:        nbcode[Tvar[j]][ij]=k;
 3155:        nbcode[Tvar[j]][1]=0;
 3156:        nbcode[Tvar[j]][2]=1;
 3157:        nbcode[Tvar[j]][3]=2;
 3158:     */
 3159:     ij=1; /* ij is similar to i but can jumps over null modalities */
 3160:     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
 3161:       for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
 3162: 	/*recode from 0 */
 3163: 	if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
 3164: 	  nbcode[Tvar[j]][ij]=k;  /* stores the modality in an array nbcode. 
 3165: 				     k is a modality. If we have model=V1+V1*sex 
 3166: 				     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
 3167: 	  ij++;
 3168: 	}
 3169: 	if (ij > ncodemax[j]) break; 
 3170:       }  /* end of loop on */
 3171:     } /* end of loop on modality */ 
 3172:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
 3173:   
 3174:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
 3175:   
 3176:   for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */ 
 3177:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
 3178:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
 3179:    Ndum[ij]++; 
 3180:  } 
 3181: 
 3182:  ij=1;
 3183:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
 3184:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
 3185:    if((Ndum[i]!=0) && (i<=ncovcol)){
 3186:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
 3187:      Tvaraff[ij]=i; /*For printing (unclear) */
 3188:      ij++;
 3189:    }else
 3190:        Tvaraff[ij]=0;
 3191:  }
 3192:  ij--;
 3193:  cptcoveff=ij; /*Number of total covariates*/
 3194: 
 3195: }
 3196: 
 3197: 
 3198: /*********** Health Expectancies ****************/
 3199: 
 3200: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
 3201: 
 3202: {
 3203:   /* Health expectancies, no variances */
 3204:   int i, j, nhstepm, hstepm, h, nstepm;
 3205:   int nhstepma, nstepma; /* Decreasing with age */
 3206:   double age, agelim, hf;
 3207:   double ***p3mat;
 3208:   double eip;
 3209: 
 3210:   pstamp(ficreseij);
 3211:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
 3212:   fprintf(ficreseij,"# Age");
 3213:   for(i=1; i<=nlstate;i++){
 3214:     for(j=1; j<=nlstate;j++){
 3215:       fprintf(ficreseij," e%1d%1d ",i,j);
 3216:     }
 3217:     fprintf(ficreseij," e%1d. ",i);
 3218:   }
 3219:   fprintf(ficreseij,"\n");
 3220: 
 3221:   
 3222:   if(estepm < stepm){
 3223:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3224:   }
 3225:   else  hstepm=estepm;   
 3226:   /* We compute the life expectancy from trapezoids spaced every estepm months
 3227:    * This is mainly to measure the difference between two models: for example
 3228:    * if stepm=24 months pijx are given only every 2 years and by summing them
 3229:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 3230:    * progression in between and thus overestimating or underestimating according
 3231:    * to the curvature of the survival function. If, for the same date, we 
 3232:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 3233:    * to compare the new estimate of Life expectancy with the same linear 
 3234:    * hypothesis. A more precise result, taking into account a more precise
 3235:    * curvature will be obtained if estepm is as small as stepm. */
 3236: 
 3237:   /* For example we decided to compute the life expectancy with the smallest unit */
 3238:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3239:      nhstepm is the number of hstepm from age to agelim 
 3240:      nstepm is the number of stepm from age to agelin. 
 3241:      Look at hpijx to understand the reason of that which relies in memory size
 3242:      and note for a fixed period like estepm months */
 3243:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3244:      survival function given by stepm (the optimization length). Unfortunately it
 3245:      means that if the survival funtion is printed only each two years of age and if
 3246:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3247:      results. So we changed our mind and took the option of the best precision.
 3248:   */
 3249:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3250: 
 3251:   agelim=AGESUP;
 3252:   /* If stepm=6 months */
 3253:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
 3254:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 3255:     
 3256: /* nhstepm age range expressed in number of stepm */
 3257:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3258:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3259:   /* if (stepm >= YEARM) hstepm=1;*/
 3260:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3261:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3262: 
 3263:   for (age=bage; age<=fage; age ++){ 
 3264:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3265:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3266:     /* if (stepm >= YEARM) hstepm=1;*/
 3267:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 3268: 
 3269:     /* If stepm=6 months */
 3270:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 3271:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 3272:     
 3273:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 3274:     
 3275:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3276:     
 3277:     printf("%d|",(int)age);fflush(stdout);
 3278:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 3279:     
 3280:     /* Computing expectancies */
 3281:     for(i=1; i<=nlstate;i++)
 3282:       for(j=1; j<=nlstate;j++)
 3283: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 3284: 	  eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
 3285: 	  
 3286: 	  /* 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]);*/
 3287: 
 3288: 	}
 3289: 
 3290:     fprintf(ficreseij,"%3.0f",age );
 3291:     for(i=1; i<=nlstate;i++){
 3292:       eip=0;
 3293:       for(j=1; j<=nlstate;j++){
 3294: 	eip +=eij[i][j][(int)age];
 3295: 	fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
 3296:       }
 3297:       fprintf(ficreseij,"%9.4f", eip );
 3298:     }
 3299:     fprintf(ficreseij,"\n");
 3300:     
 3301:   }
 3302:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3303:   printf("\n");
 3304:   fprintf(ficlog,"\n");
 3305:   
 3306: }
 3307: 
 3308: 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[] )
 3309: 
 3310: {
 3311:   /* Covariances of health expectancies eij and of total life expectancies according
 3312:    to initial status i, ei. .
 3313:   */
 3314:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
 3315:   int nhstepma, nstepma; /* Decreasing with age */
 3316:   double age, agelim, hf;
 3317:   double ***p3matp, ***p3matm, ***varhe;
 3318:   double **dnewm,**doldm;
 3319:   double *xp, *xm;
 3320:   double **gp, **gm;
 3321:   double ***gradg, ***trgradg;
 3322:   int theta;
 3323: 
 3324:   double eip, vip;
 3325: 
 3326:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
 3327:   xp=vector(1,npar);
 3328:   xm=vector(1,npar);
 3329:   dnewm=matrix(1,nlstate*nlstate,1,npar);
 3330:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
 3331:   
 3332:   pstamp(ficresstdeij);
 3333:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
 3334:   fprintf(ficresstdeij,"# Age");
 3335:   for(i=1; i<=nlstate;i++){
 3336:     for(j=1; j<=nlstate;j++)
 3337:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
 3338:     fprintf(ficresstdeij," e%1d. ",i);
 3339:   }
 3340:   fprintf(ficresstdeij,"\n");
 3341: 
 3342:   pstamp(ficrescveij);
 3343:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
 3344:   fprintf(ficrescveij,"# Age");
 3345:   for(i=1; i<=nlstate;i++)
 3346:     for(j=1; j<=nlstate;j++){
 3347:       cptj= (j-1)*nlstate+i;
 3348:       for(i2=1; i2<=nlstate;i2++)
 3349: 	for(j2=1; j2<=nlstate;j2++){
 3350: 	  cptj2= (j2-1)*nlstate+i2;
 3351: 	  if(cptj2 <= cptj)
 3352: 	    fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
 3353: 	}
 3354:     }
 3355:   fprintf(ficrescveij,"\n");
 3356:   
 3357:   if(estepm < stepm){
 3358:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3359:   }
 3360:   else  hstepm=estepm;   
 3361:   /* We compute the life expectancy from trapezoids spaced every estepm months
 3362:    * This is mainly to measure the difference between two models: for example
 3363:    * if stepm=24 months pijx are given only every 2 years and by summing them
 3364:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 3365:    * progression in between and thus overestimating or underestimating according
 3366:    * to the curvature of the survival function. If, for the same date, we 
 3367:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 3368:    * to compare the new estimate of Life expectancy with the same linear 
 3369:    * hypothesis. A more precise result, taking into account a more precise
 3370:    * curvature will be obtained if estepm is as small as stepm. */
 3371: 
 3372:   /* For example we decided to compute the life expectancy with the smallest unit */
 3373:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3374:      nhstepm is the number of hstepm from age to agelim 
 3375:      nstepm is the number of stepm from age to agelin. 
 3376:      Look at hpijx to understand the reason of that which relies in memory size
 3377:      and note for a fixed period like estepm months */
 3378:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3379:      survival function given by stepm (the optimization length). Unfortunately it
 3380:      means that if the survival funtion is printed only each two years of age and if
 3381:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3382:      results. So we changed our mind and took the option of the best precision.
 3383:   */
 3384:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3385: 
 3386:   /* If stepm=6 months */
 3387:   /* nhstepm age range expressed in number of stepm */
 3388:   agelim=AGESUP;
 3389:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
 3390:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3391:   /* if (stepm >= YEARM) hstepm=1;*/
 3392:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3393:   
 3394:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3395:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3396:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
 3397:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
 3398:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
 3399:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
 3400: 
 3401:   for (age=bage; age<=fage; age ++){ 
 3402:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3403:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3404:     /* if (stepm >= YEARM) hstepm=1;*/
 3405:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 3406: 
 3407:     /* If stepm=6 months */
 3408:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 3409:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 3410:     
 3411:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3412: 
 3413:     /* Computing  Variances of health expectancies */
 3414:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
 3415:        decrease memory allocation */
 3416:     for(theta=1; theta <=npar; theta++){
 3417:       for(i=1; i<=npar; i++){ 
 3418: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3419: 	xm[i] = x[i] - (i==theta ?delti[theta]:0);
 3420:       }
 3421:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
 3422:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
 3423:   
 3424:       for(j=1; j<= nlstate; j++){
 3425: 	for(i=1; i<=nlstate; i++){
 3426: 	  for(h=0; h<=nhstepm-1; h++){
 3427: 	    gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
 3428: 	    gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
 3429: 	  }
 3430: 	}
 3431:       }
 3432:      
 3433:       for(ij=1; ij<= nlstate*nlstate; ij++)
 3434: 	for(h=0; h<=nhstepm-1; h++){
 3435: 	  gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
 3436: 	}
 3437:     }/* End theta */
 3438:     
 3439:     
 3440:     for(h=0; h<=nhstepm-1; h++)
 3441:       for(j=1; j<=nlstate*nlstate;j++)
 3442: 	for(theta=1; theta <=npar; theta++)
 3443: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 3444:     
 3445: 
 3446:      for(ij=1;ij<=nlstate*nlstate;ij++)
 3447:       for(ji=1;ji<=nlstate*nlstate;ji++)
 3448: 	varhe[ij][ji][(int)age] =0.;
 3449: 
 3450:      printf("%d|",(int)age);fflush(stdout);
 3451:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 3452:      for(h=0;h<=nhstepm-1;h++){
 3453:       for(k=0;k<=nhstepm-1;k++){
 3454: 	matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
 3455: 	matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
 3456: 	for(ij=1;ij<=nlstate*nlstate;ij++)
 3457: 	  for(ji=1;ji<=nlstate*nlstate;ji++)
 3458: 	    varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
 3459:       }
 3460:     }
 3461: 
 3462:     /* Computing expectancies */
 3463:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 3464:     for(i=1; i<=nlstate;i++)
 3465:       for(j=1; j<=nlstate;j++)
 3466: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 3467: 	  eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
 3468: 	  
 3469: 	  /* 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]);*/
 3470: 
 3471: 	}
 3472: 
 3473:     fprintf(ficresstdeij,"%3.0f",age );
 3474:     for(i=1; i<=nlstate;i++){
 3475:       eip=0.;
 3476:       vip=0.;
 3477:       for(j=1; j<=nlstate;j++){
 3478: 	eip += eij[i][j][(int)age];
 3479: 	for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
 3480: 	  vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
 3481: 	fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
 3482:       }
 3483:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
 3484:     }
 3485:     fprintf(ficresstdeij,"\n");
 3486: 
 3487:     fprintf(ficrescveij,"%3.0f",age );
 3488:     for(i=1; i<=nlstate;i++)
 3489:       for(j=1; j<=nlstate;j++){
 3490: 	cptj= (j-1)*nlstate+i;
 3491: 	for(i2=1; i2<=nlstate;i2++)
 3492: 	  for(j2=1; j2<=nlstate;j2++){
 3493: 	    cptj2= (j2-1)*nlstate+i2;
 3494: 	    if(cptj2 <= cptj)
 3495: 	      fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
 3496: 	  }
 3497:       }
 3498:     fprintf(ficrescveij,"\n");
 3499:    
 3500:   }
 3501:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
 3502:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
 3503:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
 3504:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
 3505:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3506:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3507:   printf("\n");
 3508:   fprintf(ficlog,"\n");
 3509: 
 3510:   free_vector(xm,1,npar);
 3511:   free_vector(xp,1,npar);
 3512:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
 3513:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
 3514:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
 3515: }
 3516: 
 3517: /************ Variance ******************/
 3518: 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 ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[])
 3519: {
 3520:   /* Variance of health expectancies */
 3521:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
 3522:   /* double **newm;*/
 3523:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
 3524:   
 3525:   int movingaverage();
 3526:   double **dnewm,**doldm;
 3527:   double **dnewmp,**doldmp;
 3528:   int i, j, nhstepm, hstepm, h, nstepm ;
 3529:   int k;
 3530:   double *xp;
 3531:   double **gp, **gm;  /* for var eij */
 3532:   double ***gradg, ***trgradg; /*for var eij */
 3533:   double **gradgp, **trgradgp; /* for var p point j */
 3534:   double *gpp, *gmp; /* for var p point j */
 3535:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
 3536:   double ***p3mat;
 3537:   double age,agelim, hf;
 3538:   double ***mobaverage;
 3539:   int theta;
 3540:   char digit[4];
 3541:   char digitp[25];
 3542: 
 3543:   char fileresprobmorprev[FILENAMELENGTH];
 3544: 
 3545:   if(popbased==1){
 3546:     if(mobilav!=0)
 3547:       strcpy(digitp,"-populbased-mobilav-");
 3548:     else strcpy(digitp,"-populbased-nomobil-");
 3549:   }
 3550:   else 
 3551:     strcpy(digitp,"-stablbased-");
 3552: 
 3553:   if (mobilav!=0) {
 3554:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3555:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 3556:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 3557:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 3558:     }
 3559:   }
 3560: 
 3561:   strcpy(fileresprobmorprev,"prmorprev"); 
 3562:   sprintf(digit,"%-d",ij);
 3563:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
 3564:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
 3565:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
 3566:   strcat(fileresprobmorprev,fileres);
 3567:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
 3568:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
 3569:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
 3570:   }
 3571:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 3572:  
 3573:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 3574:   pstamp(ficresprobmorprev);
 3575:   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);
 3576:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
 3577:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 3578:     fprintf(ficresprobmorprev," p.%-d SE",j);
 3579:     for(i=1; i<=nlstate;i++)
 3580:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 3581:   }  
 3582:   fprintf(ficresprobmorprev,"\n");
 3583:   fprintf(ficgp,"\n# Routine varevsij");
 3584:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
 3585:   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");
 3586:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
 3587: /*   } */
 3588:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3589:   pstamp(ficresvij);
 3590:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
 3591:   if(popbased==1)
 3592:     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);
 3593:   else
 3594:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
 3595:   fprintf(ficresvij,"# Age");
 3596:   for(i=1; i<=nlstate;i++)
 3597:     for(j=1; j<=nlstate;j++)
 3598:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
 3599:   fprintf(ficresvij,"\n");
 3600: 
 3601:   xp=vector(1,npar);
 3602:   dnewm=matrix(1,nlstate,1,npar);
 3603:   doldm=matrix(1,nlstate,1,nlstate);
 3604:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
 3605:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3606: 
 3607:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
 3608:   gpp=vector(nlstate+1,nlstate+ndeath);
 3609:   gmp=vector(nlstate+1,nlstate+ndeath);
 3610:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 3611:   
 3612:   if(estepm < stepm){
 3613:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3614:   }
 3615:   else  hstepm=estepm;   
 3616:   /* For example we decided to compute the life expectancy with the smallest unit */
 3617:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3618:      nhstepm is the number of hstepm from age to agelim 
 3619:      nstepm is the number of stepm from age to agelin. 
 3620:      Look at function hpijx to understand why (it is linked to memory size questions) */
 3621:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3622:      survival function given by stepm (the optimization length). Unfortunately it
 3623:      means that if the survival funtion is printed every two years of age and if
 3624:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3625:      results. So we changed our mind and took the option of the best precision.
 3626:   */
 3627:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3628:   agelim = AGESUP;
 3629:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 3630:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 3631:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3632:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3633:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
 3634:     gp=matrix(0,nhstepm,1,nlstate);
 3635:     gm=matrix(0,nhstepm,1,nlstate);
 3636: 
 3637: 
 3638:     for(theta=1; theta <=npar; theta++){
 3639:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
 3640: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3641:       }
 3642:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 3643:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3644: 
 3645:       if (popbased==1) {
 3646: 	if(mobilav ==0){
 3647: 	  for(i=1; i<=nlstate;i++)
 3648: 	    prlim[i][i]=probs[(int)age][i][ij];
 3649: 	}else{ /* mobilav */ 
 3650: 	  for(i=1; i<=nlstate;i++)
 3651: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 3652: 	}
 3653:       }
 3654:   
 3655:       for(j=1; j<= nlstate; j++){
 3656: 	for(h=0; h<=nhstepm; h++){
 3657: 	  for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 3658: 	    gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 3659: 	}
 3660:       }
 3661:       /* This for computing probability of death (h=1 means
 3662:          computed over hstepm matrices product = hstepm*stepm months) 
 3663:          as a weighted average of prlim.
 3664:       */
 3665:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3666: 	for(i=1,gpp[j]=0.; i<= nlstate; i++)
 3667: 	  gpp[j] += prlim[i][i]*p3mat[i][j][1];
 3668:       }    
 3669:       /* end probability of death */
 3670: 
 3671:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
 3672: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 3673:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 3674:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3675:  
 3676:       if (popbased==1) {
 3677: 	if(mobilav ==0){
 3678: 	  for(i=1; i<=nlstate;i++)
 3679: 	    prlim[i][i]=probs[(int)age][i][ij];
 3680: 	}else{ /* mobilav */ 
 3681: 	  for(i=1; i<=nlstate;i++)
 3682: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 3683: 	}
 3684:       }
 3685: 
 3686:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
 3687: 	for(h=0; h<=nhstepm; h++){
 3688: 	  for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 3689: 	    gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 3690: 	}
 3691:       }
 3692:       /* This for computing probability of death (h=1 means
 3693:          computed over hstepm matrices product = hstepm*stepm months) 
 3694:          as a weighted average of prlim.
 3695:       */
 3696:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3697: 	for(i=1,gmp[j]=0.; i<= nlstate; i++)
 3698:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
 3699:       }    
 3700:       /* end probability of death */
 3701: 
 3702:       for(j=1; j<= nlstate; j++) /* vareij */
 3703: 	for(h=0; h<=nhstepm; h++){
 3704: 	  gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 3705: 	}
 3706: 
 3707:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
 3708: 	gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
 3709:       }
 3710: 
 3711:     } /* End theta */
 3712: 
 3713:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
 3714: 
 3715:     for(h=0; h<=nhstepm; h++) /* veij */
 3716:       for(j=1; j<=nlstate;j++)
 3717: 	for(theta=1; theta <=npar; theta++)
 3718: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 3719: 
 3720:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
 3721:       for(theta=1; theta <=npar; theta++)
 3722: 	trgradgp[j][theta]=gradgp[theta][j];
 3723:   
 3724: 
 3725:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3726:     for(i=1;i<=nlstate;i++)
 3727:       for(j=1;j<=nlstate;j++)
 3728: 	vareij[i][j][(int)age] =0.;
 3729: 
 3730:     for(h=0;h<=nhstepm;h++){
 3731:       for(k=0;k<=nhstepm;k++){
 3732: 	matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 3733: 	matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
 3734: 	for(i=1;i<=nlstate;i++)
 3735: 	  for(j=1;j<=nlstate;j++)
 3736: 	    vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
 3737:       }
 3738:     }
 3739:   
 3740:     /* pptj */
 3741:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
 3742:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
 3743:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
 3744:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
 3745: 	varppt[j][i]=doldmp[j][i];
 3746:     /* end ppptj */
 3747:     /*  x centered again */
 3748:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
 3749:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
 3750:  
 3751:     if (popbased==1) {
 3752:       if(mobilav ==0){
 3753: 	for(i=1; i<=nlstate;i++)
 3754: 	  prlim[i][i]=probs[(int)age][i][ij];
 3755:       }else{ /* mobilav */ 
 3756: 	for(i=1; i<=nlstate;i++)
 3757: 	  prlim[i][i]=mobaverage[(int)age][i][ij];
 3758:       }
 3759:     }
 3760:              
 3761:     /* This for computing probability of death (h=1 means
 3762:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
 3763:        as a weighted average of prlim.
 3764:     */
 3765:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3766:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
 3767: 	gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
 3768:     }    
 3769:     /* end probability of death */
 3770: 
 3771:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
 3772:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 3773:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
 3774:       for(i=1; i<=nlstate;i++){
 3775: 	fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 3776:       }
 3777:     } 
 3778:     fprintf(ficresprobmorprev,"\n");
 3779: 
 3780:     fprintf(ficresvij,"%.0f ",age );
 3781:     for(i=1; i<=nlstate;i++)
 3782:       for(j=1; j<=nlstate;j++){
 3783: 	fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
 3784:       }
 3785:     fprintf(ficresvij,"\n");
 3786:     free_matrix(gp,0,nhstepm,1,nlstate);
 3787:     free_matrix(gm,0,nhstepm,1,nlstate);
 3788:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 3789:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 3790:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3791:   } /* End age */
 3792:   free_vector(gpp,nlstate+1,nlstate+ndeath);
 3793:   free_vector(gmp,nlstate+1,nlstate+ndeath);
 3794:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
 3795:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 3796:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
 3797:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
 3798:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
 3799: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
 3800: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
 3801: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
 3802:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
 3803:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
 3804:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
 3805:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
 3806:   fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"%s%s.png\"> <br>\n", estepm,subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
 3807:   /*  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.png\"> <br>\n", stepm,YEARM,digitp,digit);
 3808: */
 3809: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
 3810:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
 3811: 
 3812:   free_vector(xp,1,npar);
 3813:   free_matrix(doldm,1,nlstate,1,nlstate);
 3814:   free_matrix(dnewm,1,nlstate,1,npar);
 3815:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3816:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
 3817:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3818:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3819:   fclose(ficresprobmorprev);
 3820:   fflush(ficgp);
 3821:   fflush(fichtm); 
 3822: }  /* end varevsij */
 3823: 
 3824: /************ Variance of prevlim ******************/
 3825: 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 ij, char strstart[])
 3826: {
 3827:   /* Variance of prevalence limit */
 3828:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 3829: 
 3830:   double **dnewm,**doldm;
 3831:   int i, j, nhstepm, hstepm;
 3832:   double *xp;
 3833:   double *gp, *gm;
 3834:   double **gradg, **trgradg;
 3835:   double age,agelim;
 3836:   int theta;
 3837:   
 3838:   pstamp(ficresvpl);
 3839:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
 3840:   fprintf(ficresvpl,"# Age");
 3841:   for(i=1; i<=nlstate;i++)
 3842:       fprintf(ficresvpl," %1d-%1d",i,i);
 3843:   fprintf(ficresvpl,"\n");
 3844: 
 3845:   xp=vector(1,npar);
 3846:   dnewm=matrix(1,nlstate,1,npar);
 3847:   doldm=matrix(1,nlstate,1,nlstate);
 3848:   
 3849:   hstepm=1*YEARM; /* Every year of age */
 3850:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 3851:   agelim = AGESUP;
 3852:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 3853:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 3854:     if (stepm >= YEARM) hstepm=1;
 3855:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 3856:     gradg=matrix(1,npar,1,nlstate);
 3857:     gp=vector(1,nlstate);
 3858:     gm=vector(1,nlstate);
 3859: 
 3860:     for(theta=1; theta <=npar; theta++){
 3861:       for(i=1; i<=npar; i++){ /* Computes gradient */
 3862: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3863:       }
 3864:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3865:       for(i=1;i<=nlstate;i++)
 3866: 	gp[i] = prlim[i][i];
 3867:     
 3868:       for(i=1; i<=npar; i++) /* Computes gradient */
 3869: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 3870:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3871:       for(i=1;i<=nlstate;i++)
 3872: 	gm[i] = prlim[i][i];
 3873: 
 3874:       for(i=1;i<=nlstate;i++)
 3875: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 3876:     } /* End theta */
 3877: 
 3878:     trgradg =matrix(1,nlstate,1,npar);
 3879: 
 3880:     for(j=1; j<=nlstate;j++)
 3881:       for(theta=1; theta <=npar; theta++)
 3882: 	trgradg[j][theta]=gradg[theta][j];
 3883: 
 3884:     for(i=1;i<=nlstate;i++)
 3885:       varpl[i][(int)age] =0.;
 3886:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 3887:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 3888:     for(i=1;i<=nlstate;i++)
 3889:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 3890: 
 3891:     fprintf(ficresvpl,"%.0f ",age );
 3892:     for(i=1; i<=nlstate;i++)
 3893:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
 3894:     fprintf(ficresvpl,"\n");
 3895:     free_vector(gp,1,nlstate);
 3896:     free_vector(gm,1,nlstate);
 3897:     free_matrix(gradg,1,npar,1,nlstate);
 3898:     free_matrix(trgradg,1,nlstate,1,npar);
 3899:   } /* End age */
 3900: 
 3901:   free_vector(xp,1,npar);
 3902:   free_matrix(doldm,1,nlstate,1,npar);
 3903:   free_matrix(dnewm,1,nlstate,1,nlstate);
 3904: 
 3905: }
 3906: 
 3907: /************ Variance of one-step probabilities  ******************/
 3908: 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[])
 3909: {
 3910:   int i, j=0,  k1, l1, tj;
 3911:   int k2, l2, j1,  z1;
 3912:   int k=0, l;
 3913:   int first=1, first1, first2;
 3914:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
 3915:   double **dnewm,**doldm;
 3916:   double *xp;
 3917:   double *gp, *gm;
 3918:   double **gradg, **trgradg;
 3919:   double **mu;
 3920:   double age, cov[NCOVMAX+1];
 3921:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
 3922:   int theta;
 3923:   char fileresprob[FILENAMELENGTH];
 3924:   char fileresprobcov[FILENAMELENGTH];
 3925:   char fileresprobcor[FILENAMELENGTH];
 3926:   double ***varpij;
 3927: 
 3928:   strcpy(fileresprob,"prob"); 
 3929:   strcat(fileresprob,fileres);
 3930:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
 3931:     printf("Problem with resultfile: %s\n", fileresprob);
 3932:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
 3933:   }
 3934:   strcpy(fileresprobcov,"probcov"); 
 3935:   strcat(fileresprobcov,fileres);
 3936:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
 3937:     printf("Problem with resultfile: %s\n", fileresprobcov);
 3938:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 3939:   }
 3940:   strcpy(fileresprobcor,"probcor"); 
 3941:   strcat(fileresprobcor,fileres);
 3942:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 3943:     printf("Problem with resultfile: %s\n", fileresprobcor);
 3944:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 3945:   }
 3946:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 3947:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 3948:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 3949:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 3950:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 3951:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 3952:   pstamp(ficresprob);
 3953:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
 3954:   fprintf(ficresprob,"# Age");
 3955:   pstamp(ficresprobcov);
 3956:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
 3957:   fprintf(ficresprobcov,"# Age");
 3958:   pstamp(ficresprobcor);
 3959:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 3960:   fprintf(ficresprobcor,"# Age");
 3961: 
 3962: 
 3963:   for(i=1; i<=nlstate;i++)
 3964:     for(j=1; j<=(nlstate+ndeath);j++){
 3965:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
 3966:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
 3967:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
 3968:     }  
 3969:  /* fprintf(ficresprob,"\n");
 3970:   fprintf(ficresprobcov,"\n");
 3971:   fprintf(ficresprobcor,"\n");
 3972:  */
 3973:   xp=vector(1,npar);
 3974:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 3975:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 3976:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
 3977:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 3978:   first=1;
 3979:   fprintf(ficgp,"\n# Routine varprob");
 3980:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
 3981:   fprintf(fichtm,"\n");
 3982: 
 3983:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
 3984:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
 3985:   file %s<br>\n",optionfilehtmcov);
 3986:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
 3987: and drawn. It helps understanding how is the covariance between two incidences.\
 3988:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
 3989:   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. \
 3990: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
 3991: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
 3992: standard deviations wide on each axis. <br>\
 3993:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
 3994:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 3995: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
 3996: 
 3997:   cov[1]=1;
 3998:   /* tj=cptcoveff; */
 3999:   tj = (int) pow(2,cptcoveff);
 4000:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
 4001:   j1=0;
 4002:   for(j1=1; j1<=tj;j1++){
 4003:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
 4004:     /*j1++;*/
 4005:       if  (cptcovn>0) {
 4006: 	fprintf(ficresprob, "\n#********** Variable "); 
 4007: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 4008: 	fprintf(ficresprob, "**********\n#\n");
 4009: 	fprintf(ficresprobcov, "\n#********** Variable "); 
 4010: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 4011: 	fprintf(ficresprobcov, "**********\n#\n");
 4012: 	
 4013: 	fprintf(ficgp, "\n#********** Variable "); 
 4014: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 4015: 	fprintf(ficgp, "**********\n#\n");
 4016: 	
 4017: 	
 4018: 	fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
 4019: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 4020: 	fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
 4021: 	
 4022: 	fprintf(ficresprobcor, "\n#********** Variable ");    
 4023: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 4024: 	fprintf(ficresprobcor, "**********\n#");    
 4025:       }
 4026:       
 4027:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
 4028:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 4029:       gp=vector(1,(nlstate)*(nlstate+ndeath));
 4030:       gm=vector(1,(nlstate)*(nlstate+ndeath));
 4031:       for (age=bage; age<=fage; age ++){ 
 4032: 	cov[2]=age;
 4033: 	for (k=1; k<=cptcovn;k++) {
 4034: 	  cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
 4035: 							 * 1  1 1 1 1
 4036: 							 * 2  2 1 1 1
 4037: 							 * 3  1 2 1 1
 4038: 							 */
 4039: 	  /* nbcode[1][1]=0 nbcode[1][2]=1;*/
 4040: 	}
 4041: 	for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
 4042: 	for (k=1; k<=cptcovprod;k++)
 4043: 	  cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 4044: 	
 4045:     
 4046: 	for(theta=1; theta <=npar; theta++){
 4047: 	  for(i=1; i<=npar; i++)
 4048: 	    xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
 4049: 	  
 4050: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 4051: 	  
 4052: 	  k=0;
 4053: 	  for(i=1; i<= (nlstate); i++){
 4054: 	    for(j=1; j<=(nlstate+ndeath);j++){
 4055: 	      k=k+1;
 4056: 	      gp[k]=pmmij[i][j];
 4057: 	    }
 4058: 	  }
 4059: 	  
 4060: 	  for(i=1; i<=npar; i++)
 4061: 	    xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
 4062:     
 4063: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 4064: 	  k=0;
 4065: 	  for(i=1; i<=(nlstate); i++){
 4066: 	    for(j=1; j<=(nlstate+ndeath);j++){
 4067: 	      k=k+1;
 4068: 	      gm[k]=pmmij[i][j];
 4069: 	    }
 4070: 	  }
 4071:      
 4072: 	  for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
 4073: 	    gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
 4074: 	}
 4075: 
 4076: 	for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
 4077: 	  for(theta=1; theta <=npar; theta++)
 4078: 	    trgradg[j][theta]=gradg[theta][j];
 4079: 	
 4080: 	matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
 4081: 	matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
 4082: 
 4083: 	pmij(pmmij,cov,ncovmodel,x,nlstate);
 4084: 	
 4085: 	k=0;
 4086: 	for(i=1; i<=(nlstate); i++){
 4087: 	  for(j=1; j<=(nlstate+ndeath);j++){
 4088: 	    k=k+1;
 4089: 	    mu[k][(int) age]=pmmij[i][j];
 4090: 	  }
 4091: 	}
 4092:      	for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 4093: 	  for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 4094: 	    varpij[i][j][(int)age] = doldm[i][j];
 4095: 
 4096: 	/*printf("\n%d ",(int)age);
 4097: 	  for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 4098: 	  printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 4099: 	  fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 4100: 	  }*/
 4101: 
 4102: 	fprintf(ficresprob,"\n%d ",(int)age);
 4103: 	fprintf(ficresprobcov,"\n%d ",(int)age);
 4104: 	fprintf(ficresprobcor,"\n%d ",(int)age);
 4105: 
 4106: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
 4107: 	  fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
 4108: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 4109: 	  fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
 4110: 	  fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
 4111: 	}
 4112: 	i=0;
 4113: 	for (k=1; k<=(nlstate);k++){
 4114:  	  for (l=1; l<=(nlstate+ndeath);l++){ 
 4115:  	    i++;
 4116: 	    fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 4117: 	    fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
 4118: 	    for (j=1; j<=i;j++){
 4119: 	      /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
 4120: 	      fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
 4121: 	      fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
 4122: 	    }
 4123: 	  }
 4124: 	}/* end of loop for state */
 4125:       } /* end of loop for age */
 4126:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
 4127:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 4128:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 4129:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 4130:       
 4131:       /* Confidence intervalle of pij  */
 4132:       /*
 4133: 	fprintf(ficgp,"\nunset parametric;unset label");
 4134: 	fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
 4135: 	fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 4136: 	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);
 4137: 	fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
 4138: 	fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
 4139: 	fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
 4140:       */
 4141: 
 4142:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
 4143:       first1=1;first2=2;
 4144:       for (k2=1; k2<=(nlstate);k2++){
 4145: 	for (l2=1; l2<=(nlstate+ndeath);l2++){ 
 4146: 	  if(l2==k2) continue;
 4147: 	  j=(k2-1)*(nlstate+ndeath)+l2;
 4148: 	  for (k1=1; k1<=(nlstate);k1++){
 4149: 	    for (l1=1; l1<=(nlstate+ndeath);l1++){ 
 4150: 	      if(l1==k1) continue;
 4151: 	      i=(k1-1)*(nlstate+ndeath)+l1;
 4152: 	      if(i<=j) continue;
 4153: 	      for (age=bage; age<=fage; age ++){ 
 4154: 		if ((int)age %5==0){
 4155: 		  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
 4156: 		  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
 4157: 		  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
 4158: 		  mu1=mu[i][(int) age]/stepm*YEARM ;
 4159: 		  mu2=mu[j][(int) age]/stepm*YEARM;
 4160: 		  c12=cv12/sqrt(v1*v2);
 4161: 		  /* Computing eigen value of matrix of covariance */
 4162: 		  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 4163: 		  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 4164: 		  if ((lc2 <0) || (lc1 <0) ){
 4165: 		    if(first2==1){
 4166: 		      first1=0;
 4167: 		    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);
 4168: 		    }
 4169: 		    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);
 4170: 		    /* lc1=fabs(lc1); */ /* If we want to have them positive */
 4171: 		    /* lc2=fabs(lc2); */
 4172: 		  }
 4173: 
 4174: 		  /* Eigen vectors */
 4175: 		  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
 4176: 		  /*v21=sqrt(1.-v11*v11); *//* error */
 4177: 		  v21=(lc1-v1)/cv12*v11;
 4178: 		  v12=-v21;
 4179: 		  v22=v11;
 4180: 		  tnalp=v21/v11;
 4181: 		  if(first1==1){
 4182: 		    first1=0;
 4183: 		    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);
 4184: 		  }
 4185: 		  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);
 4186: 		  /*printf(fignu*/
 4187: 		  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
 4188: 		  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
 4189: 		  if(first==1){
 4190: 		    first=0;
 4191:  		    fprintf(ficgp,"\nset parametric;unset label");
 4192: 		    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);
 4193: 		    fprintf(ficgp,"\nset ter png small size 320, 240");
 4194: 		    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
 4195:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
 4196: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
 4197: 			    subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
 4198: 			    subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4199: 		    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4200: 		    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
 4201: 		    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4202: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 4203: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 4204: 		    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",\
 4205: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 4206: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 4207: 		  }else{
 4208: 		    first=0;
 4209: 		    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
 4210: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 4211: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 4212: 		    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",\
 4213: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 4214: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 4215: 		  }/* if first */
 4216: 		} /* age mod 5 */
 4217: 	      } /* end loop age */
 4218: 	      fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4219: 	      first=1;
 4220: 	    } /*l12 */
 4221: 	  } /* k12 */
 4222: 	} /*l1 */
 4223:       }/* k1 */
 4224:       /* } */ /* loop covariates */
 4225:   }
 4226:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 4227:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
 4228:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 4229:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
 4230:   free_vector(xp,1,npar);
 4231:   fclose(ficresprob);
 4232:   fclose(ficresprobcov);
 4233:   fclose(ficresprobcor);
 4234:   fflush(ficgp);
 4235:   fflush(fichtmcov);
 4236: }
 4237: 
 4238: 
 4239: /******************* Printing html file ***********/
 4240: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
 4241: 		  int lastpass, int stepm, int weightopt, char model[],\
 4242: 		  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 4243: 		  int popforecast, int estepm ,\
 4244: 		  double jprev1, double mprev1,double anprev1, \
 4245: 		  double jprev2, double mprev2,double anprev2){
 4246:   int jj1, k1, i1, cpt;
 4247: 
 4248:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
 4249:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
 4250: </ul>");
 4251:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
 4252:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
 4253: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
 4254:    fprintf(fichtm,"\
 4255:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 4256: 	   stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
 4257:    fprintf(fichtm,"\
 4258:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 4259: 	   subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
 4260:    fprintf(fichtm,"\
 4261:  - (a) Life expectancies by health status at initial age, ei. (b) health expectancies by health status at initial age, eij . 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): \
 4262:    <a href=\"%s\">%s</a> <br>\n",
 4263: 	   estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
 4264:    fprintf(fichtm,"\
 4265:  - Population projections by age and states: \
 4266:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
 4267: 
 4268: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
 4269: 
 4270:  m=pow(2,cptcoveff);
 4271:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 4272: 
 4273:  jj1=0;
 4274:  for(k1=1; k1<=m;k1++){
 4275:    for(i1=1; i1<=ncodemax[k1];i1++){
 4276:      jj1++;
 4277:      if (cptcovn > 0) {
 4278:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 4279:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 4280: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 4281:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 4282:      }
 4283:      /* Pij */
 4284:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s%d_1.png\">%s%d_1.png</a><br> \
 4285: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
 4286:      /* Quasi-incidences */
 4287:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
 4288:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: <a href=\"%s%d_2.png\">%s%d_2.png</a><br> \
 4289: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
 4290:        /* Period (stable) prevalence in each health state */
 4291:        for(cpt=1; cpt<=nlstate;cpt++){
 4292: 	 fprintf(fichtm,"<br>- 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.png\">%s%d_%d.png</a><br> \
 4293: <img src=\"%s%d_%d.png\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
 4294:        }
 4295:      for(cpt=1; cpt<=nlstate;cpt++) {
 4296:         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) : <a href=\"%s%d%d.png\">%s%d%d.png</a> <br> \
 4297: <img src=\"%s%d%d.png\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
 4298:      }
 4299:    } /* end i1 */
 4300:  }/* End k1 */
 4301:  fprintf(fichtm,"</ul>");
 4302: 
 4303: 
 4304:  fprintf(fichtm,"\
 4305: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
 4306:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
 4307: 
 4308:  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4309: 	 subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
 4310:  fprintf(fichtm,"\
 4311:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4312: 	 subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
 4313: 
 4314:  fprintf(fichtm,"\
 4315:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4316: 	 subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
 4317:  fprintf(fichtm,"\
 4318:  - 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): \
 4319:    <a href=\"%s\">%s</a> <br>\n</li>",
 4320: 	   estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
 4321:  fprintf(fichtm,"\
 4322:  - (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): \
 4323:    <a href=\"%s\">%s</a> <br>\n</li>",
 4324: 	   estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
 4325:  fprintf(fichtm,"\
 4326:  - 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",
 4327: 	 estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
 4328:  fprintf(fichtm,"\
 4329:  - 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",
 4330: 	 estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
 4331:  fprintf(fichtm,"\
 4332:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
 4333: 	 subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
 4334: 
 4335: /*  if(popforecast==1) fprintf(fichtm,"\n */
 4336: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
 4337: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
 4338: /* 	<br>",fileres,fileres,fileres,fileres); */
 4339: /*  else  */
 4340: /*    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); */
 4341:  fflush(fichtm);
 4342:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
 4343: 
 4344:  m=pow(2,cptcoveff);
 4345:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 4346: 
 4347:  jj1=0;
 4348:  for(k1=1; k1<=m;k1++){
 4349:    for(i1=1; i1<=ncodemax[k1];i1++){
 4350:      jj1++;
 4351:      if (cptcovn > 0) {
 4352:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 4353:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 4354: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 4355:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 4356:      }
 4357:      for(cpt=1; cpt<=nlstate;cpt++) {
 4358:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
 4359: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
 4360: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
 4361:      }
 4362:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
 4363: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
 4364: true period expectancies (those weighted with period prevalences are also\
 4365:  drawn in addition to the population based expectancies computed using\
 4366:  observed and cahotic prevalences: %s%d.png<br>\
 4367: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
 4368:    } /* end i1 */
 4369:  }/* End k1 */
 4370:  fprintf(fichtm,"</ul>");
 4371:  fflush(fichtm);
 4372: }
 4373: 
 4374: /******************* Gnuplot file **************/
 4375: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 4376: 
 4377:   char dirfileres[132],optfileres[132];
 4378:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
 4379:   int ng=0;
 4380: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
 4381: /*     printf("Problem with file %s",optionfilegnuplot); */
 4382: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
 4383: /*   } */
 4384: 
 4385:   /*#ifdef windows */
 4386:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 4387:     /*#endif */
 4388:   m=pow(2,cptcoveff);
 4389: 
 4390:   strcpy(dirfileres,optionfilefiname);
 4391:   strcpy(optfileres,"vpl");
 4392:  /* 1eme*/
 4393:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
 4394:   for (cpt=1; cpt<= nlstate ; cpt ++) {
 4395:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
 4396:      fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
 4397:      fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
 4398:      fprintf(ficgp,"set xlabel \"Age\" \n\
 4399: set ylabel \"Probability\" \n\
 4400: set ter png small size 320, 240\n\
 4401: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
 4402: 
 4403:      for (i=1; i<= nlstate ; i ++) {
 4404:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 4405:        else        fprintf(ficgp," %%*lf (%%*lf)");
 4406:      }
 4407:      fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);
 4408:      for (i=1; i<= nlstate ; i ++) {
 4409:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 4410:        else fprintf(ficgp," %%*lf (%%*lf)");
 4411:      } 
 4412:      fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1); 
 4413:      for (i=1; i<= nlstate ; i ++) {
 4414:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 4415:        else fprintf(ficgp," %%*lf (%%*lf)");
 4416:      }  
 4417:      fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence \" w l lt 2",subdirf2(fileres,"p"),k1-1,k1-1,2+4*(cpt-1));
 4418:    }
 4419:   }
 4420:   /*2 eme*/
 4421:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
 4422:   for (k1=1; k1<= m ; k1 ++) { 
 4423:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
 4424:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
 4425:     
 4426:     for (i=1; i<= nlstate+1 ; i ++) {
 4427:       k=2*i;
 4428:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4429:       for (j=1; j<= nlstate+1 ; j ++) {
 4430: 	if (j==i) fprintf(ficgp," %%lf (%%lf)");
 4431: 	else fprintf(ficgp," %%*lf (%%*lf)");
 4432:       }   
 4433:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
 4434:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
 4435:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4436:       for (j=1; j<= nlstate+1 ; j ++) {
 4437: 	if (j==i) fprintf(ficgp," %%lf (%%lf)");
 4438: 	else fprintf(ficgp," %%*lf (%%*lf)");
 4439:       }   
 4440:       fprintf(ficgp,"\" t\"\" w l lt 0,");
 4441:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4442:       for (j=1; j<= nlstate+1 ; j ++) {
 4443: 	if (j==i) fprintf(ficgp," %%lf (%%lf)");
 4444: 	else fprintf(ficgp," %%*lf (%%*lf)");
 4445:       }   
 4446:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
 4447:       else fprintf(ficgp,"\" t\"\" w l lt 0,");
 4448:     }
 4449:   }
 4450:   
 4451:   /*3eme*/
 4452:   
 4453:   for (k1=1; k1<= m ; k1 ++) { 
 4454:     for (cpt=1; cpt<= nlstate ; cpt ++) {
 4455:       /*       k=2+nlstate*(2*cpt-2); */
 4456:       k=2+(nlstate+1)*(cpt-1);
 4457:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
 4458:       fprintf(ficgp,"set ter png small size 320, 240\n\
 4459: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileres,"e"),k1-1,k1-1,k,cpt);
 4460:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 4461: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 4462: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 4463: 	fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 4464: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 4465: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 4466: 	
 4467:       */
 4468:       for (i=1; i< nlstate ; i ++) {
 4469: 	fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+i,cpt,i+1);
 4470: 	/*	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);*/
 4471: 	
 4472:       } 
 4473:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
 4474:     }
 4475:   }
 4476:   
 4477:   /* CV preval stable (period) */
 4478:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
 4479:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 4480:       k=3;
 4481:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
 4482:       fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
 4483:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 4484: set ter png small size 320, 240\n\
 4485: unset log y\n\
 4486: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 4487:       for (i=1; i<= nlstate ; i ++){
 4488: 	if(i==1)
 4489: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
 4490: 	else
 4491: 	  fprintf(ficgp,", '' ");
 4492: 	l=(nlstate+ndeath)*(i-1)+1;
 4493: 	fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 4494: 	for (j=1; j<= (nlstate-1) ; j ++)
 4495: 	  fprintf(ficgp,"+$%d",k+l+j);
 4496: 	fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
 4497:       } /* nlstate */
 4498:       fprintf(ficgp,"\n");
 4499:     } /* end cpt state*/ 
 4500:   } /* end covariate */  
 4501:   
 4502:   /* proba elementaires */
 4503:   for(i=1,jk=1; i <=nlstate; i++){
 4504:     for(k=1; k <=(nlstate+ndeath); k++){
 4505:       if (k != i) {
 4506: 	for(j=1; j <=ncovmodel; j++){
 4507: 	  fprintf(ficgp,"p%d=%f ",jk,p[jk]);
 4508: 	  jk++; 
 4509: 	  fprintf(ficgp,"\n");
 4510: 	}
 4511:       }
 4512:     }
 4513:    }
 4514:   /*goto avoid;*/
 4515:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
 4516:      for(jk=1; jk <=m; jk++) {
 4517:        fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
 4518:        if (ng==2)
 4519: 	 fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
 4520:        else
 4521: 	 fprintf(ficgp,"\nset title \"Probability\"\n");
 4522:        fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
 4523:        i=1;
 4524:        for(k2=1; k2<=nlstate; k2++) {
 4525: 	 k3=i;
 4526: 	 for(k=1; k<=(nlstate+ndeath); k++) {
 4527: 	   if (k != k2){
 4528: 	     if(ng==2)
 4529: 	       fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
 4530: 	     else
 4531: 	       fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
 4532: 	     ij=1;/* To be checked else nbcode[0][0] wrong */
 4533: 	     for(j=3; j <=ncovmodel; j++) {
 4534: 	       /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
 4535: 	       /* 	 /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
 4536: 	       /* 	 ij++; */
 4537: 	       /* } */
 4538: 	       /* else */
 4539: 		 fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 4540: 	     }
 4541: 	     fprintf(ficgp,")/(1");
 4542: 	     
 4543: 	     for(k1=1; k1 <=nlstate; k1++){   
 4544: 	       fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
 4545: 	       ij=1;
 4546: 	       for(j=3; j <=ncovmodel; j++){
 4547: 		 /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
 4548: 		 /*   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
 4549: 		 /*   ij++; */
 4550: 		 /* } */
 4551: 		 /* else */
 4552: 		   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 4553: 	       }
 4554: 	       fprintf(ficgp,")");
 4555: 	     }
 4556: 	     fprintf(ficgp,") t \"p%d%d\" ", k2,k);
 4557: 	     if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
 4558: 	     i=i+ncovmodel;
 4559: 	   }
 4560: 	 } /* end k */
 4561:        } /* end k2 */
 4562:      } /* end jk */
 4563:    } /* end ng */
 4564:  /* avoid: */
 4565:    fflush(ficgp); 
 4566: }  /* end gnuplot */
 4567: 
 4568: 
 4569: /*************** Moving average **************/
 4570: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
 4571: 
 4572:   int i, cpt, cptcod;
 4573:   int modcovmax =1;
 4574:   int mobilavrange, mob;
 4575:   double age;
 4576: 
 4577:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
 4578: 			   a covariate has 2 modalities */
 4579:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
 4580: 
 4581:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
 4582:     if(mobilav==1) mobilavrange=5; /* default */
 4583:     else mobilavrange=mobilav;
 4584:     for (age=bage; age<=fage; age++)
 4585:       for (i=1; i<=nlstate;i++)
 4586: 	for (cptcod=1;cptcod<=modcovmax;cptcod++)
 4587: 	  mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 4588:     /* We keep the original values on the extreme ages bage, fage and for 
 4589:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
 4590:        we use a 5 terms etc. until the borders are no more concerned. 
 4591:     */ 
 4592:     for (mob=3;mob <=mobilavrange;mob=mob+2){
 4593:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
 4594: 	for (i=1; i<=nlstate;i++){
 4595: 	  for (cptcod=1;cptcod<=modcovmax;cptcod++){
 4596: 	    mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
 4597: 	      for (cpt=1;cpt<=(mob-1)/2;cpt++){
 4598: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
 4599: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
 4600: 	      }
 4601: 	    mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
 4602: 	  }
 4603: 	}
 4604:       }/* end age */
 4605:     }/* end mob */
 4606:   }else return -1;
 4607:   return 0;
 4608: }/* End movingaverage */
 4609: 
 4610: 
 4611: /************** Forecasting ******************/
 4612: 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){
 4613:   /* proj1, year, month, day of starting projection 
 4614:      agemin, agemax range of age
 4615:      dateprev1 dateprev2 range of dates during which prevalence is computed
 4616:      anproj2 year of en of projection (same day and month as proj1).
 4617:   */
 4618:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
 4619:   double agec; /* generic age */
 4620:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
 4621:   double *popeffectif,*popcount;
 4622:   double ***p3mat;
 4623:   double ***mobaverage;
 4624:   char fileresf[FILENAMELENGTH];
 4625: 
 4626:   agelim=AGESUP;
 4627:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 4628:  
 4629:   strcpy(fileresf,"f"); 
 4630:   strcat(fileresf,fileres);
 4631:   if((ficresf=fopen(fileresf,"w"))==NULL) {
 4632:     printf("Problem with forecast resultfile: %s\n", fileresf);
 4633:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
 4634:   }
 4635:   printf("Computing forecasting: result on file '%s' \n", fileresf);
 4636:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
 4637: 
 4638:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 4639: 
 4640:   if (mobilav!=0) {
 4641:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4642:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 4643:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 4644:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 4645:     }
 4646:   }
 4647: 
 4648:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 4649:   if (stepm<=12) stepsize=1;
 4650:   if(estepm < stepm){
 4651:     printf ("Problem %d lower than %d\n",estepm, stepm);
 4652:   }
 4653:   else  hstepm=estepm;   
 4654: 
 4655:   hstepm=hstepm/stepm; 
 4656:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
 4657:                                fractional in yp1 */
 4658:   anprojmean=yp;
 4659:   yp2=modf((yp1*12),&yp);
 4660:   mprojmean=yp;
 4661:   yp1=modf((yp2*30.5),&yp);
 4662:   jprojmean=yp;
 4663:   if(jprojmean==0) jprojmean=1;
 4664:   if(mprojmean==0) jprojmean=1;
 4665: 
 4666:   i1=cptcoveff;
 4667:   if (cptcovn < 1){i1=1;}
 4668:   
 4669:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
 4670:   
 4671:   fprintf(ficresf,"#****** Routine prevforecast **\n");
 4672: 
 4673: /* 	      if (h==(int)(YEARM*yearp)){ */
 4674:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
 4675:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 4676:       k=k+1;
 4677:       fprintf(ficresf,"\n#******");
 4678:       for(j=1;j<=cptcoveff;j++) {
 4679: 	fprintf(ficresf," V%d=%d, hpijx=probability over h years, hp.jx is weighted by observed prev ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4680:       }
 4681:       fprintf(ficresf,"******\n");
 4682:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
 4683:       for(j=1; j<=nlstate+ndeath;j++){ 
 4684: 	for(i=1; i<=nlstate;i++) 	      
 4685:           fprintf(ficresf," p%d%d",i,j);
 4686: 	fprintf(ficresf," p.%d",j);
 4687:       }
 4688:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
 4689: 	fprintf(ficresf,"\n");
 4690: 	fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
 4691: 
 4692:      	for (agec=fage; agec>=(ageminpar-1); agec--){ 
 4693: 	  nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
 4694: 	  nhstepm = nhstepm/hstepm; 
 4695: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4696: 	  oldm=oldms;savm=savms;
 4697: 	  hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4698: 	
 4699: 	  for (h=0; h<=nhstepm; h++){
 4700: 	    if (h*hstepm/YEARM*stepm ==yearp) {
 4701:               fprintf(ficresf,"\n");
 4702:               for(j=1;j<=cptcoveff;j++) 
 4703:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4704: 	      fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
 4705: 	    } 
 4706: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4707: 	      ppij=0.;
 4708: 	      for(i=1; i<=nlstate;i++) {
 4709: 		if (mobilav==1) 
 4710: 		  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
 4711: 		else {
 4712: 		  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
 4713: 		}
 4714: 		if (h*hstepm/YEARM*stepm== yearp) {
 4715: 		  fprintf(ficresf," %.3f", p3mat[i][j][h]);
 4716: 		}
 4717: 	      } /* end i */
 4718: 	      if (h*hstepm/YEARM*stepm==yearp) {
 4719: 		fprintf(ficresf," %.3f", ppij);
 4720: 	      }
 4721: 	    }/* end j */
 4722: 	  } /* end h */
 4723: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4724: 	} /* end agec */
 4725:       } /* end yearp */
 4726:     } /* end cptcod */
 4727:   } /* end  cptcov */
 4728:        
 4729:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4730: 
 4731:   fclose(ficresf);
 4732: }
 4733: 
 4734: /************** Forecasting *****not tested NB*************/
 4735: 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){
 4736:   
 4737:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
 4738:   int *popage;
 4739:   double calagedatem, agelim, kk1, kk2;
 4740:   double *popeffectif,*popcount;
 4741:   double ***p3mat,***tabpop,***tabpopprev;
 4742:   double ***mobaverage;
 4743:   char filerespop[FILENAMELENGTH];
 4744: 
 4745:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4746:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4747:   agelim=AGESUP;
 4748:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
 4749:   
 4750:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 4751:   
 4752:   
 4753:   strcpy(filerespop,"pop"); 
 4754:   strcat(filerespop,fileres);
 4755:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
 4756:     printf("Problem with forecast resultfile: %s\n", filerespop);
 4757:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
 4758:   }
 4759:   printf("Computing forecasting: result on file '%s' \n", filerespop);
 4760:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
 4761: 
 4762:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 4763: 
 4764:   if (mobilav!=0) {
 4765:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4766:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 4767:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 4768:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 4769:     }
 4770:   }
 4771: 
 4772:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 4773:   if (stepm<=12) stepsize=1;
 4774:   
 4775:   agelim=AGESUP;
 4776:   
 4777:   hstepm=1;
 4778:   hstepm=hstepm/stepm; 
 4779:   
 4780:   if (popforecast==1) {
 4781:     if((ficpop=fopen(popfile,"r"))==NULL) {
 4782:       printf("Problem with population file : %s\n",popfile);exit(0);
 4783:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
 4784:     } 
 4785:     popage=ivector(0,AGESUP);
 4786:     popeffectif=vector(0,AGESUP);
 4787:     popcount=vector(0,AGESUP);
 4788:     
 4789:     i=1;   
 4790:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
 4791:    
 4792:     imx=i;
 4793:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
 4794:   }
 4795: 
 4796:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
 4797:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 4798:       k=k+1;
 4799:       fprintf(ficrespop,"\n#******");
 4800:       for(j=1;j<=cptcoveff;j++) {
 4801: 	fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4802:       }
 4803:       fprintf(ficrespop,"******\n");
 4804:       fprintf(ficrespop,"# Age");
 4805:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
 4806:       if (popforecast==1)  fprintf(ficrespop," [Population]");
 4807:       
 4808:       for (cpt=0; cpt<=0;cpt++) { 
 4809: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 4810: 	
 4811:      	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 4812: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 4813: 	  nhstepm = nhstepm/hstepm; 
 4814: 	  
 4815: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4816: 	  oldm=oldms;savm=savms;
 4817: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4818: 	
 4819: 	  for (h=0; h<=nhstepm; h++){
 4820: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 4821: 	      fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 4822: 	    } 
 4823: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4824: 	      kk1=0.;kk2=0;
 4825: 	      for(i=1; i<=nlstate;i++) {	      
 4826: 		if (mobilav==1) 
 4827: 		  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
 4828: 		else {
 4829: 		  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
 4830: 		}
 4831: 	      }
 4832: 	      if (h==(int)(calagedatem+12*cpt)){
 4833: 		tabpop[(int)(agedeb)][j][cptcod]=kk1;
 4834: 		  /*fprintf(ficrespop," %.3f", kk1);
 4835: 		    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
 4836: 	      }
 4837: 	    }
 4838: 	    for(i=1; i<=nlstate;i++){
 4839: 	      kk1=0.;
 4840: 		for(j=1; j<=nlstate;j++){
 4841: 		  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
 4842: 		}
 4843: 		  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
 4844: 	    }
 4845: 
 4846: 	    if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
 4847: 	      fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
 4848: 	  }
 4849: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4850: 	}
 4851:       }
 4852:  
 4853:   /******/
 4854: 
 4855:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
 4856: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 4857: 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 4858: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 4859: 	  nhstepm = nhstepm/hstepm; 
 4860: 	  
 4861: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4862: 	  oldm=oldms;savm=savms;
 4863: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4864: 	  for (h=0; h<=nhstepm; h++){
 4865: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 4866: 	      fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 4867: 	    } 
 4868: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4869: 	      kk1=0.;kk2=0;
 4870: 	      for(i=1; i<=nlstate;i++) {	      
 4871: 		kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];	
 4872: 	      }
 4873: 	      if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);	
 4874: 	    }
 4875: 	  }
 4876: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4877: 	}
 4878:       }
 4879:    } 
 4880:   }
 4881:  
 4882:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4883: 
 4884:   if (popforecast==1) {
 4885:     free_ivector(popage,0,AGESUP);
 4886:     free_vector(popeffectif,0,AGESUP);
 4887:     free_vector(popcount,0,AGESUP);
 4888:   }
 4889:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4890:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4891:   fclose(ficrespop);
 4892: } /* End of popforecast */
 4893: 
 4894: int fileappend(FILE *fichier, char *optionfich)
 4895: {
 4896:   if((fichier=fopen(optionfich,"a"))==NULL) {
 4897:     printf("Problem with file: %s\n", optionfich);
 4898:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
 4899:     return (0);
 4900:   }
 4901:   fflush(fichier);
 4902:   return (1);
 4903: }
 4904: 
 4905: 
 4906: /**************** function prwizard **********************/
 4907: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
 4908: {
 4909: 
 4910:   /* Wizard to print covariance matrix template */
 4911: 
 4912:   char ca[32], cb[32];
 4913:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
 4914:   int numlinepar;
 4915: 
 4916:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 4917:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 4918:   for(i=1; i <=nlstate; i++){
 4919:     jj=0;
 4920:     for(j=1; j <=nlstate+ndeath; j++){
 4921:       if(j==i) continue;
 4922:       jj++;
 4923:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
 4924:       printf("%1d%1d",i,j);
 4925:       fprintf(ficparo,"%1d%1d",i,j);
 4926:       for(k=1; k<=ncovmodel;k++){
 4927: 	/* 	  printf(" %lf",param[i][j][k]); */
 4928: 	/* 	  fprintf(ficparo," %lf",param[i][j][k]); */
 4929: 	printf(" 0.");
 4930: 	fprintf(ficparo," 0.");
 4931:       }
 4932:       printf("\n");
 4933:       fprintf(ficparo,"\n");
 4934:     }
 4935:   }
 4936:   printf("# Scales (for hessian or gradient estimation)\n");
 4937:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
 4938:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
 4939:   for(i=1; i <=nlstate; i++){
 4940:     jj=0;
 4941:     for(j=1; j <=nlstate+ndeath; j++){
 4942:       if(j==i) continue;
 4943:       jj++;
 4944:       fprintf(ficparo,"%1d%1d",i,j);
 4945:       printf("%1d%1d",i,j);
 4946:       fflush(stdout);
 4947:       for(k=1; k<=ncovmodel;k++){
 4948: 	/* 	printf(" %le",delti3[i][j][k]); */
 4949: 	/* 	fprintf(ficparo," %le",delti3[i][j][k]); */
 4950: 	printf(" 0.");
 4951: 	fprintf(ficparo," 0.");
 4952:       }
 4953:       numlinepar++;
 4954:       printf("\n");
 4955:       fprintf(ficparo,"\n");
 4956:     }
 4957:   }
 4958:   printf("# Covariance matrix\n");
 4959: /* # 121 Var(a12)\n\ */
 4960: /* # 122 Cov(b12,a12) Var(b12)\n\ */
 4961: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 4962: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 4963: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 4964: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 4965: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 4966: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 4967:   fflush(stdout);
 4968:   fprintf(ficparo,"# Covariance matrix\n");
 4969:   /* # 121 Var(a12)\n\ */
 4970:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
 4971:   /* #   ...\n\ */
 4972:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
 4973:   
 4974:   for(itimes=1;itimes<=2;itimes++){
 4975:     jj=0;
 4976:     for(i=1; i <=nlstate; i++){
 4977:       for(j=1; j <=nlstate+ndeath; j++){
 4978: 	if(j==i) continue;
 4979: 	for(k=1; k<=ncovmodel;k++){
 4980: 	  jj++;
 4981: 	  ca[0]= k+'a'-1;ca[1]='\0';
 4982: 	  if(itimes==1){
 4983: 	    printf("#%1d%1d%d",i,j,k);
 4984: 	    fprintf(ficparo,"#%1d%1d%d",i,j,k);
 4985: 	  }else{
 4986: 	    printf("%1d%1d%d",i,j,k);
 4987: 	    fprintf(ficparo,"%1d%1d%d",i,j,k);
 4988: 	    /* 	printf(" %.5le",matcov[i][j]); */
 4989: 	  }
 4990: 	  ll=0;
 4991: 	  for(li=1;li <=nlstate; li++){
 4992: 	    for(lj=1;lj <=nlstate+ndeath; lj++){
 4993: 	      if(lj==li) continue;
 4994: 	      for(lk=1;lk<=ncovmodel;lk++){
 4995: 		ll++;
 4996: 		if(ll<=jj){
 4997: 		  cb[0]= lk +'a'-1;cb[1]='\0';
 4998: 		  if(ll<jj){
 4999: 		    if(itimes==1){
 5000: 		      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 5001: 		      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 5002: 		    }else{
 5003: 		      printf(" 0.");
 5004: 		      fprintf(ficparo," 0.");
 5005: 		    }
 5006: 		  }else{
 5007: 		    if(itimes==1){
 5008: 		      printf(" Var(%s%1d%1d)",ca,i,j);
 5009: 		      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
 5010: 		    }else{
 5011: 		      printf(" 0.");
 5012: 		      fprintf(ficparo," 0.");
 5013: 		    }
 5014: 		  }
 5015: 		}
 5016: 	      } /* end lk */
 5017: 	    } /* end lj */
 5018: 	  } /* end li */
 5019: 	  printf("\n");
 5020: 	  fprintf(ficparo,"\n");
 5021: 	  numlinepar++;
 5022: 	} /* end k*/
 5023:       } /*end j */
 5024:     } /* end i */
 5025:   } /* end itimes */
 5026: 
 5027: } /* end of prwizard */
 5028: /******************* Gompertz Likelihood ******************************/
 5029: double gompertz(double x[])
 5030: { 
 5031:   double A,B,L=0.0,sump=0.,num=0.;
 5032:   int i,n=0; /* n is the size of the sample */
 5033: 
 5034:   for (i=0;i<=imx-1 ; i++) {
 5035:     sump=sump+weight[i];
 5036:     /*    sump=sump+1;*/
 5037:     num=num+1;
 5038:   }
 5039:  
 5040:  
 5041:   /* for (i=0; i<=imx; i++) 
 5042:      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]);*/
 5043: 
 5044:   for (i=1;i<=imx ; i++)
 5045:     {
 5046:       if (cens[i] == 1 && wav[i]>1)
 5047: 	A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
 5048:       
 5049:       if (cens[i] == 0 && wav[i]>1)
 5050: 	A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
 5051: 	     +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
 5052:       
 5053:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 5054:       if (wav[i] > 1 ) { /* ??? */
 5055: 	L=L+A*weight[i];
 5056: 	/* 	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]);*/
 5057:       }
 5058:     }
 5059: 
 5060:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 5061:  
 5062:   return -2*L*num/sump;
 5063: }
 5064: 
 5065: #ifdef GSL
 5066: /******************* Gompertz_f Likelihood ******************************/
 5067: double gompertz_f(const gsl_vector *v, void *params)
 5068: { 
 5069:   double A,B,LL=0.0,sump=0.,num=0.;
 5070:   double *x= (double *) v->data;
 5071:   int i,n=0; /* n is the size of the sample */
 5072: 
 5073:   for (i=0;i<=imx-1 ; i++) {
 5074:     sump=sump+weight[i];
 5075:     /*    sump=sump+1;*/
 5076:     num=num+1;
 5077:   }
 5078:  
 5079:  
 5080:   /* for (i=0; i<=imx; i++) 
 5081:      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]);*/
 5082:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
 5083:   for (i=1;i<=imx ; i++)
 5084:     {
 5085:       if (cens[i] == 1 && wav[i]>1)
 5086: 	A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
 5087:       
 5088:       if (cens[i] == 0 && wav[i]>1)
 5089: 	A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
 5090: 	     +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
 5091:       
 5092:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 5093:       if (wav[i] > 1 ) { /* ??? */
 5094: 	LL=LL+A*weight[i];
 5095: 	/* 	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]);*/
 5096:       }
 5097:     }
 5098: 
 5099:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 5100:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
 5101:  
 5102:   return -2*LL*num/sump;
 5103: }
 5104: #endif
 5105: 
 5106: /******************* Printing html file ***********/
 5107: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
 5108: 		  int lastpass, int stepm, int weightopt, char model[],\
 5109: 		  int imx,  double p[],double **matcov,double agemortsup){
 5110:   int i,k;
 5111: 
 5112:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
 5113:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
 5114:   for (i=1;i<=2;i++) 
 5115:     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]));
 5116:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
 5117:   fprintf(fichtm,"</ul>");
 5118: 
 5119: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
 5120: 
 5121:  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>");
 5122: 
 5123:  for (k=agegomp;k<(agemortsup-2);k++) 
 5124:    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]);
 5125: 
 5126:  
 5127:   fflush(fichtm);
 5128: }
 5129: 
 5130: /******************* Gnuplot file **************/
 5131: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 5132: 
 5133:   char dirfileres[132],optfileres[132];
 5134: 
 5135:   int ng;
 5136: 
 5137: 
 5138:   /*#ifdef windows */
 5139:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 5140:     /*#endif */
 5141: 
 5142: 
 5143:   strcpy(dirfileres,optionfilefiname);
 5144:   strcpy(optfileres,"vpl");
 5145:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
 5146:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
 5147:   fprintf(ficgp, "set ter png small size 320, 240\n set log y\n"); 
 5148:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
 5149:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
 5150: 
 5151: } 
 5152: 
 5153: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
 5154: {
 5155: 
 5156:   /*-------- data file ----------*/
 5157:   FILE *fic;
 5158:   char dummy[]="                         ";
 5159:   int i=0, j=0, n=0;
 5160:   int linei, month, year,iout;
 5161:   char line[MAXLINE], linetmp[MAXLINE];
 5162:   char stra[MAXLINE], strb[MAXLINE];
 5163:   char *stratrunc;
 5164:   int lstra;
 5165: 
 5166: 
 5167:   if((fic=fopen(datafile,"r"))==NULL)    {
 5168:     printf("Problem while opening datafile: %s\n", datafile);return 1;
 5169:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
 5170:   }
 5171: 
 5172:   i=1;
 5173:   linei=0;
 5174:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
 5175:     linei=linei+1;
 5176:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
 5177:       if(line[j] == '\t')
 5178: 	line[j] = ' ';
 5179:     }
 5180:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
 5181:       ;
 5182:     };
 5183:     line[j+1]=0;  /* Trims blanks at end of line */
 5184:     if(line[0]=='#'){
 5185:       fprintf(ficlog,"Comment line\n%s\n",line);
 5186:       printf("Comment line\n%s\n",line);
 5187:       continue;
 5188:     }
 5189:     trimbb(linetmp,line); /* Trims multiple blanks in line */
 5190:     strcpy(line, linetmp);
 5191:   
 5192: 
 5193:     for (j=maxwav;j>=1;j--){
 5194:       cutv(stra, strb, line, ' '); 
 5195:       if(strb[0]=='.') { /* Missing status */
 5196: 	lval=-1;
 5197:       }else{
 5198: 	errno=0;
 5199: 	lval=strtol(strb,&endptr,10); 
 5200:       /*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
 5201: 	if( strb[0]=='\0' || (*endptr != '\0')){
 5202: 	  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);
 5203: 	  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);
 5204: 	  return 1;
 5205: 	}
 5206:       }
 5207:       s[j][i]=lval;
 5208:       
 5209:       strcpy(line,stra);
 5210:       cutv(stra, strb,line,' ');
 5211:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 5212:       }
 5213:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 5214: 	month=99;
 5215: 	year=9999;
 5216:       }else{
 5217: 	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);
 5218: 	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);
 5219: 	return 1;
 5220:       }
 5221:       anint[j][i]= (double) year; 
 5222:       mint[j][i]= (double)month; 
 5223:       strcpy(line,stra);
 5224:     } /* ENd Waves */
 5225:     
 5226:     cutv(stra, strb,line,' '); 
 5227:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 5228:     }
 5229:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 5230:       month=99;
 5231:       year=9999;
 5232:     }else{
 5233:       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);
 5234: 	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);
 5235: 	return 1;
 5236:     }
 5237:     andc[i]=(double) year; 
 5238:     moisdc[i]=(double) month; 
 5239:     strcpy(line,stra);
 5240:     
 5241:     cutv(stra, strb,line,' '); 
 5242:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 5243:     }
 5244:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
 5245:       month=99;
 5246:       year=9999;
 5247:     }else{
 5248:       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);
 5249:       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);
 5250: 	return 1;
 5251:     }
 5252:     if (year==9999) {
 5253:       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);
 5254:       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);
 5255: 	return 1;
 5256: 
 5257:     }
 5258:     annais[i]=(double)(year);
 5259:     moisnais[i]=(double)(month); 
 5260:     strcpy(line,stra);
 5261:     
 5262:     cutv(stra, strb,line,' '); 
 5263:     errno=0;
 5264:     dval=strtod(strb,&endptr); 
 5265:     if( strb[0]=='\0' || (*endptr != '\0')){
 5266:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
 5267:       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);
 5268:       fflush(ficlog);
 5269:       return 1;
 5270:     }
 5271:     weight[i]=dval; 
 5272:     strcpy(line,stra);
 5273:     
 5274:     for (j=ncovcol;j>=1;j--){
 5275:       cutv(stra, strb,line,' '); 
 5276:       if(strb[0]=='.') { /* Missing status */
 5277: 	lval=-1;
 5278:       }else{
 5279: 	errno=0;
 5280: 	lval=strtol(strb,&endptr,10); 
 5281: 	if( strb[0]=='\0' || (*endptr != '\0')){
 5282: 	  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);
 5283: 	  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);
 5284: 	  return 1;
 5285: 	}
 5286:       }
 5287:       if(lval <-1 || lval >1){
 5288: 	printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 5289:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 5290:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 5291:  For example, for multinomial values like 1, 2 and 3,\n \
 5292:  build V1=0 V2=0 for the reference value (1),\n \
 5293:         V1=1 V2=0 for (2) \n \
 5294:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 5295:  output of IMaCh is often meaningless.\n \
 5296:  Exiting.\n",lval,linei, i,line,j);
 5297: 	fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 5298:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 5299:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 5300:  For example, for multinomial values like 1, 2 and 3,\n \
 5301:  build V1=0 V2=0 for the reference value (1),\n \
 5302:         V1=1 V2=0 for (2) \n \
 5303:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 5304:  output of IMaCh is often meaningless.\n \
 5305:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
 5306: 	return 1;
 5307:       }
 5308:       covar[j][i]=(double)(lval);
 5309:       strcpy(line,stra);
 5310:     }  
 5311:     lstra=strlen(stra);
 5312:      
 5313:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
 5314:       stratrunc = &(stra[lstra-9]);
 5315:       num[i]=atol(stratrunc);
 5316:     }
 5317:     else
 5318:       num[i]=atol(stra);
 5319:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
 5320:       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;}*/
 5321:     
 5322:     i=i+1;
 5323:   } /* End loop reading  data */
 5324: 
 5325:   *imax=i-1; /* Number of individuals */
 5326:   fclose(fic);
 5327:  
 5328:   return (0);
 5329:   /* endread: */
 5330:     printf("Exiting readdata: ");
 5331:     fclose(fic);
 5332:     return (1);
 5333: 
 5334: 
 5335: 
 5336: }
 5337: void removespace(char *str) {
 5338:   char *p1 = str, *p2 = str;
 5339:   do
 5340:     while (*p2 == ' ')
 5341:       p2++;
 5342:   while (*p1++ == *p2++);
 5343: }
 5344: 
 5345: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
 5346:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
 5347:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
 5348:    * - cptcovn or number of covariates k of the models excluding age*products =6
 5349:    * - cptcovage number of covariates with age*products =2
 5350:    * - cptcovs number of simple covariates
 5351:    * - 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
 5352:    *     which is a new column after the 9 (ncovcol) variables. 
 5353:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
 5354:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
 5355:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
 5356:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
 5357:  */
 5358: {
 5359:   int i, j, k, ks;
 5360:   int  j1, k1, k2;
 5361:   char modelsav[80];
 5362:   char stra[80], strb[80], strc[80], strd[80],stre[80];
 5363: 
 5364:   /*removespace(model);*/
 5365:   if (strlen(model) >1){ /* If there is at least 1 covariate */
 5366:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
 5367:     j=nbocc(model,'+'); /**< j=Number of '+' */
 5368:     j1=nbocc(model,'*'); /**< j1=Number of '*' */
 5369:     cptcovs=j+1-j1; /**<  Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2  */
 5370:     cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
 5371:                   /* including age products which are counted in cptcovage.
 5372: 		  * but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
 5373:     cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
 5374:     cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
 5375:     strcpy(modelsav,model); 
 5376:     if (strstr(model,"AGE") !=0){
 5377:       printf("Error. AGE must be in lower case 'age' model=%s ",model);
 5378:       fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
 5379:       return 1;
 5380:     }
 5381:     if (strstr(model,"v") !=0){
 5382:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
 5383:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
 5384:       return 1;
 5385:     }
 5386:     
 5387:     /*   Design
 5388:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
 5389:      *  <          ncovcol=8                >
 5390:      * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
 5391:      *   k=  1    2      3       4     5       6      7        8
 5392:      *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
 5393:      *  covar[k,i], value of kth covariate if not including age for individual i:
 5394:      *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
 5395:      *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
 5396:      *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
 5397:      *  Tage[++cptcovage]=k
 5398:      *       if products, new covar are created after ncovcol with k1
 5399:      *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
 5400:      *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
 5401:      *  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
 5402:      *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
 5403:      *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
 5404:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
 5405:      *  <          ncovcol=8                >
 5406:      *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
 5407:      *          k=  1    2      3       4     5       6      7        8    9   10   11  12
 5408:      *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
 5409:      * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 5410:      * p Tprod[1]@2={                         6, 5}
 5411:      *p Tvard[1][1]@4= {7, 8, 5, 6}
 5412:      * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
 5413:      *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 5414:      *How to reorganize?
 5415:      * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
 5416:      * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 5417:      *       {2,   1,     4,      8,    5,      6,     3,       7}
 5418:      * Struct []
 5419:      */
 5420: 
 5421:     /* This loop fills the array Tvar from the string 'model'.*/
 5422:     /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
 5423:     /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
 5424:     /* 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
 5425:     /* 	k=3 V4 Tvar[k=3]= 4 (from V4) */
 5426:     /* 	k=2 V1 Tvar[k=2]= 1 (from V1) */
 5427:     /* 	k=1 Tvar[1]=2 (from V2) */
 5428:     /* 	k=5 Tvar[5] */
 5429:     /* for (k=1; k<=cptcovn;k++) { */
 5430:     /* 	cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
 5431:     /* 	} */
 5432:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 5433:     /*
 5434:      * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
 5435:     for(k=cptcovt; k>=1;k--) /**< Number of covariates */
 5436:         Tvar[k]=0;
 5437:     cptcovage=0;
 5438:     for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
 5439:       cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
 5440: 				     modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
 5441:       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
 5442:       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
 5443:       /*scanf("%d",i);*/
 5444:       if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
 5445: 	cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
 5446: 	if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
 5447: 	  /* covar is not filled and then is empty */
 5448: 	  cptcovprod--;
 5449: 	  cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
 5450: 	  Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
 5451: 	  cptcovage++; /* Sums the number of covariates which include age as a product */
 5452: 	  Tage[cptcovage]=k;  /* Tage[1] = 4 */
 5453: 	  /*printf("stre=%s ", stre);*/
 5454: 	} else if (strcmp(strd,"age")==0) { /* or age*Vn */
 5455: 	  cptcovprod--;
 5456: 	  cutl(stre,strb,strc,'V');
 5457: 	  Tvar[k]=atoi(stre);
 5458: 	  cptcovage++;
 5459: 	  Tage[cptcovage]=k;
 5460: 	} else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
 5461: 	  /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
 5462: 	  cptcovn++;
 5463: 	  cptcovprodnoage++;k1++;
 5464: 	  cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
 5465: 	  Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
 5466: 				  because this model-covariate is a construction we invent a new column
 5467: 				  ncovcol + k1
 5468: 				  If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
 5469: 				  Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
 5470: 	  cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
 5471: 	  Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
 5472: 	  Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
 5473: 	  Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
 5474: 	  k2=k2+2;
 5475: 	  Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
 5476: 	  Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
 5477: 	  for (i=1; i<=lastobs;i++){
 5478: 	    /* Computes the new covariate which is a product of
 5479: 	       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
 5480: 	    covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
 5481: 	  }
 5482: 	} /* End age is not in the model */
 5483:       } /* End if model includes a product */
 5484:       else { /* no more sum */
 5485: 	/*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
 5486:        /*  scanf("%d",i);*/
 5487: 	cutl(strd,strc,strb,'V');
 5488: 	ks++; /**< Number of simple covariates */
 5489: 	cptcovn++;
 5490: 	Tvar[k]=atoi(strd);
 5491:       }
 5492:       strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
 5493:       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
 5494: 	scanf("%d",i);*/
 5495:     } /* end of loop + */
 5496:   } /* end model */
 5497:   
 5498:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
 5499:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
 5500: 
 5501:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
 5502:   printf("cptcovprod=%d ", cptcovprod);
 5503:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
 5504: 
 5505:   scanf("%d ",i);*/
 5506: 
 5507: 
 5508:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
 5509:   /*endread:*/
 5510:     printf("Exiting decodemodel: ");
 5511:     return (1);
 5512: }
 5513: 
 5514: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
 5515: {
 5516:   int i, m;
 5517: 
 5518:   for (i=1; i<=imx; i++) {
 5519:     for(m=2; (m<= maxwav); m++) {
 5520:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
 5521: 	anint[m][i]=9999;
 5522: 	s[m][i]=-1;
 5523:       }
 5524:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
 5525: 	*nberr = *nberr + 1;
 5526: 	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 are biased (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
 5527: 	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 are biased (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
 5528: 	s[m][i]=-1;
 5529:       }
 5530:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
 5531: 	(*nberr)++;
 5532: 	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]); 
 5533: 	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]); 
 5534: 	s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
 5535:       }
 5536:     }
 5537:   }
 5538: 
 5539:   for (i=1; i<=imx; i++)  {
 5540:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
 5541:     for(m=firstpass; (m<= lastpass); m++){
 5542:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
 5543: 	if (s[m][i] >= nlstate+1) {
 5544: 	  if(agedc[i]>0){
 5545: 	    if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
 5546: 	      agev[m][i]=agedc[i];
 5547: 	  /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
 5548: 	    }else {
 5549: 	      if ((int)andc[i]!=9999){
 5550: 		nbwarn++;
 5551: 		printf("Warning negative age at death: %ld line:%d\n",num[i],i);
 5552: 		fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
 5553: 		agev[m][i]=-1;
 5554: 	      }
 5555: 	    }
 5556: 	  } /* agedc > 0 */
 5557: 	}
 5558: 	else if(s[m][i] !=9){ /* Standard case, age in fractional
 5559: 				 years but with the precision of a month */
 5560: 	  agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
 5561: 	  if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
 5562: 	    agev[m][i]=1;
 5563: 	  else if(agev[m][i] < *agemin){ 
 5564: 	    *agemin=agev[m][i];
 5565: 	    printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
 5566: 	  }
 5567: 	  else if(agev[m][i] >*agemax){
 5568: 	    *agemax=agev[m][i];
 5569: 	    /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
 5570: 	  }
 5571: 	  /*agev[m][i]=anint[m][i]-annais[i];*/
 5572: 	  /*	 agev[m][i] = age[i]+2*m;*/
 5573: 	}
 5574: 	else { /* =9 */
 5575: 	  agev[m][i]=1;
 5576: 	  s[m][i]=-1;
 5577: 	}
 5578:       }
 5579:       else /*= 0 Unknown */
 5580: 	agev[m][i]=1;
 5581:     }
 5582:     
 5583:   }
 5584:   for (i=1; i<=imx; i++)  {
 5585:     for(m=firstpass; (m<=lastpass); m++){
 5586:       if (s[m][i] > (nlstate+ndeath)) {
 5587: 	(*nberr)++;
 5588: 	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);	
 5589: 	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);	
 5590: 	return 1;
 5591:       }
 5592:     }
 5593:   }
 5594: 
 5595:   /*for (i=1; i<=imx; i++){
 5596:   for (m=firstpass; (m<lastpass); m++){
 5597:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
 5598: }
 5599: 
 5600: }*/
 5601: 
 5602: 
 5603:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
 5604:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
 5605: 
 5606:   return (0);
 5607:  /* endread:*/
 5608:     printf("Exiting calandcheckages: ");
 5609:     return (1);
 5610: }
 5611: 
 5612: #if defined(_MSC_VER)
 5613: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 5614: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 5615: //#include "stdafx.h"
 5616: //#include <stdio.h>
 5617: //#include <tchar.h>
 5618: //#include <windows.h>
 5619: //#include <iostream>
 5620: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
 5621: 
 5622: LPFN_ISWOW64PROCESS fnIsWow64Process;
 5623: 
 5624: BOOL IsWow64()
 5625: {
 5626: 	BOOL bIsWow64 = FALSE;
 5627: 
 5628: 	//typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
 5629: 	//  (HANDLE, PBOOL);
 5630: 
 5631: 	//LPFN_ISWOW64PROCESS fnIsWow64Process;
 5632: 
 5633: 	HMODULE module = GetModuleHandle(_T("kernel32"));
 5634: 	const char funcName[] = "IsWow64Process";
 5635: 	fnIsWow64Process = (LPFN_ISWOW64PROCESS)
 5636: 		GetProcAddress(module, funcName);
 5637: 
 5638: 	if (NULL != fnIsWow64Process)
 5639: 	{
 5640: 		if (!fnIsWow64Process(GetCurrentProcess(),
 5641: 			&bIsWow64))
 5642: 			//throw std::exception("Unknown error");
 5643: 			printf("Unknown error\n");
 5644: 	}
 5645: 	return bIsWow64 != FALSE;
 5646: }
 5647: #endif
 5648: 
 5649: void syscompilerinfo()
 5650:  {
 5651:    /* #include "syscompilerinfo.h"*/
 5652:    /* command line Intel compiler 32bit windows, XP compatible:*/
 5653:    /* /GS /W3 /Gy
 5654:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
 5655:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
 5656:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
 5657:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch" 
 5658:       /* 64 bits */
 5659:    /*
 5660:      /GS /W3 /Gy
 5661:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
 5662:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
 5663:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
 5664:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
 5665:    /* Optimization are useless and O3 is slower than O2 */
 5666:    /*
 5667:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
 5668:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
 5669:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
 5670:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
 5671:    */
 5672:    /* Link is $/ /* /OUT:"visual studio
 5673:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
 5674:       /PDB:"visual studio
 5675:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
 5676:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
 5677:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
 5678:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
 5679:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
 5680:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
 5681:       uiAccess='false'"
 5682:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
 5683:       /NOLOGO /TLBID:1
 5684:    */
 5685: #if defined __INTEL_COMPILER
 5686: #if defined(__GNUC__)
 5687: 	struct utsname sysInfo;  /* For Intel on Linux and OS/X */
 5688: #endif
 5689: #elif defined(__GNUC__) 
 5690: #ifndef  __APPLE__
 5691: #include <gnu/libc-version.h>  /* Only on gnu */
 5692: #endif
 5693:    struct utsname sysInfo;
 5694:    int cross = CROSS;
 5695:    if (cross){
 5696: 	   printf("Cross-");
 5697: 	   fprintf(ficlog, "Cross-");
 5698:    }
 5699: #endif
 5700: 
 5701: #include <stdint.h>
 5702: 
 5703:    printf("Compiled with:");fprintf(ficlog,"Compiled with:");
 5704: #if defined(__clang__)
 5705:    printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM");	/* Clang/LLVM. ---------------------------------------------- */
 5706: #endif
 5707: #if defined(__ICC) || defined(__INTEL_COMPILER)
 5708:    printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
 5709: #endif
 5710: #if defined(__GNUC__) || defined(__GNUG__)
 5711:    printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
 5712: #endif
 5713: #if defined(__HP_cc) || defined(__HP_aCC)
 5714:    printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
 5715: #endif
 5716: #if defined(__IBMC__) || defined(__IBMCPP__)
 5717:    printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
 5718: #endif
 5719: #if defined(_MSC_VER)
 5720:    printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
 5721: #endif
 5722: #if defined(__PGI)
 5723:    printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
 5724: #endif
 5725: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
 5726:    printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
 5727: #endif
 5728:    printf(" for ");fprintf(ficlog," for ");
 5729:    
 5730: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
 5731: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
 5732:     // Windows (x64 and x86)
 5733:    printf("Windows (x64 and x86) ");fprintf(ficlog,"Windows (x64 and x86) ");
 5734: #elif __unix__ // all unices, not all compilers
 5735:     // Unix
 5736:    printf("Unix ");fprintf(ficlog,"Unix ");
 5737: #elif __linux__
 5738:     // linux
 5739:    printf("linux ");fprintf(ficlog,"linux ");
 5740: #elif __APPLE__
 5741:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
 5742:    printf("Mac OS ");fprintf(ficlog,"Mac OS ");
 5743: #endif
 5744: 
 5745: /*  __MINGW32__	  */
 5746: /*  __CYGWIN__	 */
 5747: /* __MINGW64__  */
 5748: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
 5749: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
 5750: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
 5751: /* _WIN64  // Defined for applications for Win64. */
 5752: /* _M_X64 // Defined for compilations that target x64 processors. */
 5753: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
 5754: 
 5755: #if UINTPTR_MAX == 0xffffffff
 5756:    printf(" 32-bit"); fprintf(ficlog," 32-bit");/* 32-bit */
 5757: #elif UINTPTR_MAX == 0xffffffffffffffff
 5758:    printf(" 64-bit"); fprintf(ficlog," 64-bit");/* 64-bit */
 5759: #else
 5760:    printf(" wtf-bit"); fprintf(ficlog," wtf-bit");/* wtf */
 5761: #endif
 5762: 
 5763: #if defined(__GNUC__)
 5764: # if defined(__GNUC_PATCHLEVEL__)
 5765: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 5766:                             + __GNUC_MINOR__ * 100 \
 5767:                             + __GNUC_PATCHLEVEL__)
 5768: # else
 5769: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 5770:                             + __GNUC_MINOR__ * 100)
 5771: # endif
 5772:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
 5773:    fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
 5774: 
 5775:    if (uname(&sysInfo) != -1) {
 5776:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 5777:      fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 5778:    }
 5779:    else
 5780:       perror("uname() error");
 5781:    //#ifndef __INTEL_COMPILER 
 5782: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
 5783:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
 5784:    fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
 5785: #endif
 5786: #endif
 5787: 
 5788:    //   void main()
 5789:    //   {
 5790: #if defined(_MSC_VER)
 5791:    if (IsWow64()){
 5792: 	   printf("The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 5793: 	   fprintf(ficlog, "The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 5794:    }
 5795:    else{
 5796: 	   printf("The process is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 5797: 	   fprintf(ficlog,"The programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 5798:    }
 5799:    //	   printf("\nPress Enter to continue...");
 5800:    //	   getchar();
 5801:    //   }
 5802: 
 5803: #endif
 5804:    
 5805: 
 5806:  }
 5807: 
 5808: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
 5809:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 5810:   int i, j, k, i1 ;
 5811:   double ftolpl = 1.e-10;
 5812:   double age, agebase, agelim;
 5813: 
 5814:     strcpy(filerespl,"pl");
 5815:     strcat(filerespl,fileres);
 5816:     if((ficrespl=fopen(filerespl,"w"))==NULL) {
 5817:       printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
 5818:       fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
 5819:     }
 5820:     printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
 5821:     fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
 5822:     pstamp(ficrespl);
 5823:     fprintf(ficrespl,"# Period (stable) prevalence \n");
 5824:     fprintf(ficrespl,"#Age ");
 5825:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
 5826:     fprintf(ficrespl,"\n");
 5827:   
 5828:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
 5829: 
 5830:     agebase=ageminpar;
 5831:     agelim=agemaxpar;
 5832: 
 5833:     i1=pow(2,cptcoveff);
 5834:     if (cptcovn < 1){i1=1;}
 5835: 
 5836:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 5837:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
 5838:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 5839: 	k=k+1;
 5840: 	/* to clean */
 5841: 	//printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
 5842: 	fprintf(ficrespl,"\n#******");
 5843: 	printf("\n#******");
 5844: 	fprintf(ficlog,"\n#******");
 5845: 	for(j=1;j<=cptcoveff;j++) {
 5846: 	  fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 5847: 	  printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 5848: 	  fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 5849: 	}
 5850: 	fprintf(ficrespl,"******\n");
 5851: 	printf("******\n");
 5852: 	fprintf(ficlog,"******\n");
 5853: 
 5854: 	fprintf(ficrespl,"#Age ");
 5855: 	for(j=1;j<=cptcoveff;j++) {
 5856: 	  fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 5857: 	}
 5858: 	for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
 5859: 	fprintf(ficrespl,"\n");
 5860: 	
 5861: 	for (age=agebase; age<=agelim; age++){
 5862: 	/* for (age=agebase; age<=agebase; age++){ */
 5863: 	  prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
 5864: 	  fprintf(ficrespl,"%.0f ",age );
 5865: 	  for(j=1;j<=cptcoveff;j++)
 5866: 	    fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 5867: 	  for(i=1; i<=nlstate;i++)
 5868: 	    fprintf(ficrespl," %.5f", prlim[i][i]);
 5869: 	  fprintf(ficrespl,"\n");
 5870: 	} /* Age */
 5871: 	/* was end of cptcod */
 5872:     } /* cptcov */
 5873: 	return 0;
 5874: }
 5875: 
 5876: int hPijx(double *p, int bage, int fage){
 5877:     /*------------- h Pij x at various ages ------------*/
 5878: 
 5879:   int stepsize;
 5880:   int agelim;
 5881:   int hstepm;
 5882:   int nhstepm;
 5883:   int h, i, i1, j, k;
 5884: 
 5885:   double agedeb;
 5886:   double ***p3mat;
 5887: 
 5888:     strcpy(filerespij,"pij");  strcat(filerespij,fileres);
 5889:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
 5890:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
 5891:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
 5892:     }
 5893:     printf("Computing pij: result on file '%s' \n", filerespij);
 5894:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
 5895:   
 5896:     stepsize=(int) (stepm+YEARM-1)/YEARM;
 5897:     /*if (stepm<=24) stepsize=2;*/
 5898: 
 5899:     agelim=AGESUP;
 5900:     hstepm=stepsize*YEARM; /* Every year of age */
 5901:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
 5902: 
 5903:     /* hstepm=1;   aff par mois*/
 5904:     pstamp(ficrespij);
 5905:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
 5906:     i1= pow(2,cptcoveff);
 5907:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 5908:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
 5909:    /*  	k=k+1;  */
 5910:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 5911:       fprintf(ficrespij,"\n#****** ");
 5912:       for(j=1;j<=cptcoveff;j++) 
 5913: 	fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 5914:       fprintf(ficrespij,"******\n");
 5915:       
 5916:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
 5917: 	nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 5918: 	nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 5919: 	
 5920: 	/*	  nhstepm=nhstepm*YEARM; aff par mois*/
 5921: 	
 5922: 	p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5923: 	oldm=oldms;savm=savms;
 5924: 	hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 5925: 	fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
 5926: 	for(i=1; i<=nlstate;i++)
 5927: 	  for(j=1; j<=nlstate+ndeath;j++)
 5928: 	    fprintf(ficrespij," %1d-%1d",i,j);
 5929: 	fprintf(ficrespij,"\n");
 5930: 	for (h=0; h<=nhstepm; h++){
 5931: 	  /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
 5932: 	  fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
 5933: 	  for(i=1; i<=nlstate;i++)
 5934: 	    for(j=1; j<=nlstate+ndeath;j++)
 5935: 	      fprintf(ficrespij," %.5f", p3mat[i][j][h]);
 5936: 	  fprintf(ficrespij,"\n");
 5937: 	}
 5938: 	free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5939: 	fprintf(ficrespij,"\n");
 5940:       }
 5941:       /*}*/
 5942:     }
 5943: 	return 0;
 5944: }
 5945: 
 5946: 
 5947: /***********************************************/
 5948: /**************** Main Program *****************/
 5949: /***********************************************/
 5950: 
 5951: int main(int argc, char *argv[])
 5952: {
 5953: #ifdef GSL
 5954:   const gsl_multimin_fminimizer_type *T;
 5955:   size_t iteri = 0, it;
 5956:   int rval = GSL_CONTINUE;
 5957:   int status = GSL_SUCCESS;
 5958:   double ssval;
 5959: #endif
 5960:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
 5961:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
 5962: 
 5963:   int jj, ll, li, lj, lk;
 5964:   int numlinepar=0; /* Current linenumber of parameter file */
 5965:   int itimes;
 5966:   int NDIM=2;
 5967:   int vpopbased=0;
 5968: 
 5969:   char ca[32], cb[32];
 5970:   /*  FILE *fichtm; *//* Html File */
 5971:   /* FILE *ficgp;*/ /*Gnuplot File */
 5972:   struct stat info;
 5973:   double agedeb;
 5974:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
 5975: 
 5976:   double fret;
 5977:   double dum; /* Dummy variable */
 5978:   double ***p3mat;
 5979:   double ***mobaverage;
 5980: 
 5981:   char line[MAXLINE];
 5982:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
 5983:   char pathr[MAXLINE], pathimach[MAXLINE]; 
 5984:   char *tok, *val; /* pathtot */
 5985:   int firstobs=1, lastobs=10;
 5986:   int c,  h , cpt;
 5987:   int jl;
 5988:   int i1, j1, jk, stepsize;
 5989:   int *tab; 
 5990:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
 5991:   int mobilav=0,popforecast=0;
 5992:   int hstepm, nhstepm;
 5993:   int agemortsup;
 5994:   float  sumlpop=0.;
 5995:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
 5996:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
 5997: 
 5998:   double bage=0, fage=110, age, agelim, agebase;
 5999:   double ftolpl=FTOL;
 6000:   double **prlim;
 6001:   double ***param; /* Matrix of parameters */
 6002:   double  *p;
 6003:   double **matcov; /* Matrix of covariance */
 6004:   double ***delti3; /* Scale */
 6005:   double *delti; /* Scale */
 6006:   double ***eij, ***vareij;
 6007:   double **varpl; /* Variances of prevalence limits by age */
 6008:   double *epj, vepp;
 6009: 
 6010:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
 6011:   double **ximort;
 6012:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
 6013:   int *dcwave;
 6014: 
 6015:   char z[1]="c";
 6016: 
 6017:   /*char  *strt;*/
 6018:   char strtend[80];
 6019: 
 6020: 
 6021: /*   setlocale (LC_ALL, ""); */
 6022: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
 6023: /*   textdomain (PACKAGE); */
 6024: /*   setlocale (LC_CTYPE, ""); */
 6025: /*   setlocale (LC_MESSAGES, ""); */
 6026: 
 6027:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
 6028:   rstart_time = time(NULL);  
 6029:   /*  (void) gettimeofday(&start_time,&tzp);*/
 6030:   start_time = *localtime(&rstart_time);
 6031:   curr_time=start_time;
 6032:   /*tml = *localtime(&start_time.tm_sec);*/
 6033:   /* strcpy(strstart,asctime(&tml)); */
 6034:   strcpy(strstart,asctime(&start_time));
 6035: 
 6036: /*  printf("Localtime (at start)=%s",strstart); */
 6037: /*  tp.tm_sec = tp.tm_sec +86400; */
 6038: /*  tm = *localtime(&start_time.tm_sec); */
 6039: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
 6040: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
 6041: /*   tmg.tm_hour=tmg.tm_hour + 1; */
 6042: /*   tp.tm_sec = mktime(&tmg); */
 6043: /*   strt=asctime(&tmg); */
 6044: /*   printf("Time(after) =%s",strstart);  */
 6045: /*  (void) time (&time_value);
 6046: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
 6047: *  tm = *localtime(&time_value);
 6048: *  strstart=asctime(&tm);
 6049: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
 6050: */
 6051: 
 6052:   nberr=0; /* Number of errors and warnings */
 6053:   nbwarn=0;
 6054: #ifdef WIN32
 6055:   _getcwd(pathcd, size);
 6056: #else
 6057:   getcwd(pathcd, size);
 6058: #endif
 6059: 
 6060:   printf("\n%s\n%s",version,fullversion);
 6061:   if(argc <=1){
 6062:     printf("\nEnter the parameter file name: ");
 6063:     fgets(pathr,FILENAMELENGTH,stdin);
 6064:     i=strlen(pathr);
 6065:     if(pathr[i-1]=='\n')
 6066:       pathr[i-1]='\0';
 6067:     i=strlen(pathr);
 6068:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
 6069:       pathr[i-1]='\0';
 6070:    for (tok = pathr; tok != NULL; ){
 6071:       printf("Pathr |%s|\n",pathr);
 6072:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
 6073:       printf("val= |%s| pathr=%s\n",val,pathr);
 6074:       strcpy (pathtot, val);
 6075:       if(pathr[0] == '\0') break; /* Dirty */
 6076:     }
 6077:   }
 6078:   else{
 6079:     strcpy(pathtot,argv[1]);
 6080:   }
 6081:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
 6082:   /*cygwin_split_path(pathtot,path,optionfile);
 6083:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
 6084:   /* cutv(path,optionfile,pathtot,'\\');*/
 6085: 
 6086:   /* Split argv[0], imach program to get pathimach */
 6087:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
 6088:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 6089:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 6090:  /*   strcpy(pathimach,argv[0]); */
 6091:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
 6092:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
 6093:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
 6094: #ifdef WIN32
 6095:   _chdir(path); /* Can be a relative path */
 6096:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
 6097: #else
 6098:   chdir(path); /* Can be a relative path */
 6099:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
 6100: #endif
 6101:   printf("Current directory %s!\n",pathcd);
 6102:   strcpy(command,"mkdir ");
 6103:   strcat(command,optionfilefiname);
 6104:   if((outcmd=system(command)) != 0){
 6105:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
 6106:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
 6107:     /* fclose(ficlog); */
 6108: /*     exit(1); */
 6109:   }
 6110: /*   if((imk=mkdir(optionfilefiname))<0){ */
 6111: /*     perror("mkdir"); */
 6112: /*   } */
 6113: 
 6114:   /*-------- arguments in the command line --------*/
 6115: 
 6116:   /* Log file */
 6117:   strcat(filelog, optionfilefiname);
 6118:   strcat(filelog,".log");    /* */
 6119:   if((ficlog=fopen(filelog,"w"))==NULL)    {
 6120:     printf("Problem with logfile %s\n",filelog);
 6121:     goto end;
 6122:   }
 6123:   fprintf(ficlog,"Log filename:%s\n",filelog);
 6124:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
 6125:   fprintf(ficlog,"\nEnter the parameter file name: \n");
 6126:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
 6127:  path=%s \n\
 6128:  optionfile=%s\n\
 6129:  optionfilext=%s\n\
 6130:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
 6131: 
 6132:   syscompilerinfo();
 6133: 
 6134:   printf("Local time (at start):%s",strstart);
 6135:   fprintf(ficlog,"Local time (at start): %s",strstart);
 6136:   fflush(ficlog);
 6137: /*   (void) gettimeofday(&curr_time,&tzp); */
 6138: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
 6139: 
 6140:   /* */
 6141:   strcpy(fileres,"r");
 6142:   strcat(fileres, optionfilefiname);
 6143:   strcat(fileres,".txt");    /* Other files have txt extension */
 6144: 
 6145:   /*---------arguments file --------*/
 6146: 
 6147:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
 6148:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 6149:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 6150:     fflush(ficlog);
 6151:     /* goto end; */
 6152:     exit(70); 
 6153:   }
 6154: 
 6155: 
 6156: 
 6157:   strcpy(filereso,"o");
 6158:   strcat(filereso,fileres);
 6159:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
 6160:     printf("Problem with Output resultfile: %s\n", filereso);
 6161:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
 6162:     fflush(ficlog);
 6163:     goto end;
 6164:   }
 6165: 
 6166:   /* Reads comments: lines beginning with '#' */
 6167:   numlinepar=0;
 6168:   while((c=getc(ficpar))=='#' && c!= EOF){
 6169:     ungetc(c,ficpar);
 6170:     fgets(line, MAXLINE, ficpar);
 6171:     numlinepar++;
 6172:     fputs(line,stdout);
 6173:     fputs(line,ficparo);
 6174:     fputs(line,ficlog);
 6175:   }
 6176:   ungetc(c,ficpar);
 6177: 
 6178:   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=%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model);
 6179:   numlinepar++;
 6180:   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=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model);
 6181:   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=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
 6182:   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=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
 6183:   fflush(ficlog);
 6184:   while((c=getc(ficpar))=='#' && c!= EOF){
 6185:     ungetc(c,ficpar);
 6186:     fgets(line, MAXLINE, ficpar);
 6187:     numlinepar++;
 6188:     fputs(line, stdout);
 6189:     //puts(line);
 6190:     fputs(line,ficparo);
 6191:     fputs(line,ficlog);
 6192:   }
 6193:   ungetc(c,ficpar);
 6194: 
 6195:    
 6196:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
 6197:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
 6198:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
 6199:      v1+v2*age+v2*v3 makes cptcovn = 3
 6200:   */
 6201:   if (strlen(model)>1) 
 6202:     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*/
 6203:   else
 6204:     ncovmodel=2;
 6205:   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
 6206:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
 6207:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
 6208:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
 6209:     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);
 6210:     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);
 6211:     fflush(stdout);
 6212:     fclose (ficlog);
 6213:     goto end;
 6214:   }
 6215:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 6216:   delti=delti3[1][1];
 6217:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
 6218:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
 6219:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 6220:     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 6221:     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 6222:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 6223:     fclose (ficparo);
 6224:     fclose (ficlog);
 6225:     goto end;
 6226:     exit(0);
 6227:   }
 6228:   else if(mle==-3) {
 6229:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 6230:     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 6231:     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 6232:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 6233:     matcov=matrix(1,npar,1,npar);
 6234:   }
 6235:   else{
 6236:     /* Read guessed parameters */
 6237:     /* Reads comments: lines beginning with '#' */
 6238:     while((c=getc(ficpar))=='#' && c!= EOF){
 6239:       ungetc(c,ficpar);
 6240:       fgets(line, MAXLINE, ficpar);
 6241:       numlinepar++;
 6242:       fputs(line,stdout);
 6243:       fputs(line,ficparo);
 6244:       fputs(line,ficlog);
 6245:     }
 6246:     ungetc(c,ficpar);
 6247:     
 6248:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 6249:     for(i=1; i <=nlstate; i++){
 6250:       j=0;
 6251:       for(jj=1; jj <=nlstate+ndeath; jj++){
 6252: 	if(jj==i) continue;
 6253: 	j++;
 6254: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 6255: 	if ((i1 != i) && (j1 != j)){
 6256: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
 6257: It might be a problem of design; if ncovcol and the model are correct\n \
 6258: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
 6259: 	  exit(1);
 6260: 	}
 6261: 	fprintf(ficparo,"%1d%1d",i1,j1);
 6262: 	if(mle==1)
 6263: 	  printf("%1d%1d",i,j);
 6264: 	fprintf(ficlog,"%1d%1d",i,j);
 6265: 	for(k=1; k<=ncovmodel;k++){
 6266: 	  fscanf(ficpar," %lf",&param[i][j][k]);
 6267: 	  if(mle==1){
 6268: 	    printf(" %lf",param[i][j][k]);
 6269: 	    fprintf(ficlog," %lf",param[i][j][k]);
 6270: 	  }
 6271: 	  else
 6272: 	    fprintf(ficlog," %lf",param[i][j][k]);
 6273: 	  fprintf(ficparo," %lf",param[i][j][k]);
 6274: 	}
 6275: 	fscanf(ficpar,"\n");
 6276: 	numlinepar++;
 6277: 	if(mle==1)
 6278: 	  printf("\n");
 6279: 	fprintf(ficlog,"\n");
 6280: 	fprintf(ficparo,"\n");
 6281:       }
 6282:     }  
 6283:     fflush(ficlog);
 6284: 
 6285:     /* Reads scales values */
 6286:     p=param[1][1];
 6287:     
 6288:     /* Reads comments: lines beginning with '#' */
 6289:     while((c=getc(ficpar))=='#' && c!= EOF){
 6290:       ungetc(c,ficpar);
 6291:       fgets(line, MAXLINE, ficpar);
 6292:       numlinepar++;
 6293:       fputs(line,stdout);
 6294:       fputs(line,ficparo);
 6295:       fputs(line,ficlog);
 6296:     }
 6297:     ungetc(c,ficpar);
 6298: 
 6299:     for(i=1; i <=nlstate; i++){
 6300:       for(j=1; j <=nlstate+ndeath-1; j++){
 6301: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 6302: 	if ( (i1-i) * (j1-j) != 0){
 6303: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
 6304: 	  exit(1);
 6305: 	}
 6306: 	printf("%1d%1d",i,j);
 6307: 	fprintf(ficparo,"%1d%1d",i1,j1);
 6308: 	fprintf(ficlog,"%1d%1d",i1,j1);
 6309: 	for(k=1; k<=ncovmodel;k++){
 6310: 	  fscanf(ficpar,"%le",&delti3[i][j][k]);
 6311: 	  printf(" %le",delti3[i][j][k]);
 6312: 	  fprintf(ficparo," %le",delti3[i][j][k]);
 6313: 	  fprintf(ficlog," %le",delti3[i][j][k]);
 6314: 	}
 6315: 	fscanf(ficpar,"\n");
 6316: 	numlinepar++;
 6317: 	printf("\n");
 6318: 	fprintf(ficparo,"\n");
 6319: 	fprintf(ficlog,"\n");
 6320:       }
 6321:     }
 6322:     fflush(ficlog);
 6323: 
 6324:     /* Reads covariance matrix */
 6325:     delti=delti3[1][1];
 6326: 
 6327: 
 6328:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
 6329:   
 6330:     /* Reads comments: lines beginning with '#' */
 6331:     while((c=getc(ficpar))=='#' && c!= EOF){
 6332:       ungetc(c,ficpar);
 6333:       fgets(line, MAXLINE, ficpar);
 6334:       numlinepar++;
 6335:       fputs(line,stdout);
 6336:       fputs(line,ficparo);
 6337:       fputs(line,ficlog);
 6338:     }
 6339:     ungetc(c,ficpar);
 6340:   
 6341:     matcov=matrix(1,npar,1,npar);
 6342:     for(i=1; i <=npar; i++)
 6343:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
 6344:       
 6345:     for(i=1; i <=npar; i++){
 6346:       fscanf(ficpar,"%s",str);
 6347:       if(mle==1)
 6348: 	printf("%s",str);
 6349:       fprintf(ficlog,"%s",str);
 6350:       fprintf(ficparo,"%s",str);
 6351:       for(j=1; j <=i; j++){
 6352: 	fscanf(ficpar," %le",&matcov[i][j]);
 6353: 	if(mle==1){
 6354: 	  printf(" %.5le",matcov[i][j]);
 6355: 	}
 6356: 	fprintf(ficlog," %.5le",matcov[i][j]);
 6357: 	fprintf(ficparo," %.5le",matcov[i][j]);
 6358:       }
 6359:       fscanf(ficpar,"\n");
 6360:       numlinepar++;
 6361:       if(mle==1)
 6362: 	printf("\n");
 6363:       fprintf(ficlog,"\n");
 6364:       fprintf(ficparo,"\n");
 6365:     }
 6366:     for(i=1; i <=npar; i++)
 6367:       for(j=i+1;j<=npar;j++)
 6368: 	matcov[i][j]=matcov[j][i];
 6369:     
 6370:     if(mle==1)
 6371:       printf("\n");
 6372:     fprintf(ficlog,"\n");
 6373:     
 6374:     fflush(ficlog);
 6375:     
 6376:     /*-------- Rewriting parameter file ----------*/
 6377:     strcpy(rfileres,"r");    /* "Rparameterfile */
 6378:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
 6379:     strcat(rfileres,".");    /* */
 6380:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
 6381:     if((ficres =fopen(rfileres,"w"))==NULL) {
 6382:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
 6383:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
 6384:     }
 6385:     fprintf(ficres,"#%s\n",version);
 6386:   }    /* End of mle != -3 */
 6387: 
 6388: 
 6389:   n= lastobs;
 6390:   num=lvector(1,n);
 6391:   moisnais=vector(1,n);
 6392:   annais=vector(1,n);
 6393:   moisdc=vector(1,n);
 6394:   andc=vector(1,n);
 6395:   agedc=vector(1,n);
 6396:   cod=ivector(1,n);
 6397:   weight=vector(1,n);
 6398:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
 6399:   mint=matrix(1,maxwav,1,n);
 6400:   anint=matrix(1,maxwav,1,n);
 6401:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
 6402:   tab=ivector(1,NCOVMAX);
 6403:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
 6404: 
 6405:   /* Reads data from file datafile */
 6406:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
 6407:     goto end;
 6408: 
 6409:   /* Calculation of the number of parameters from char model */
 6410:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
 6411: 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
 6412: 	k=3 V4 Tvar[k=3]= 4 (from V4)
 6413: 	k=2 V1 Tvar[k=2]= 1 (from V1)
 6414: 	k=1 Tvar[1]=2 (from V2)
 6415:     */
 6416:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
 6417:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
 6418:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
 6419:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
 6420:   */
 6421:   /* For model-covariate k tells which data-covariate to use but
 6422:     because this model-covariate is a construction we invent a new column
 6423:     ncovcol + k1
 6424:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
 6425:     Tvar[3=V1*V4]=4+1 etc */
 6426:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
 6427:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
 6428:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
 6429:   */
 6430:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
 6431:   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
 6432: 			    * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
 6433: 			    * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
 6434:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
 6435: 			 4 covariates (3 plus signs)
 6436: 			 Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
 6437: 		      */  
 6438: 
 6439:   if(decodemodel(model, lastobs) == 1)
 6440:     goto end;
 6441: 
 6442:   if((double)(lastobs-imx)/(double)imx > 1.10){
 6443:     nbwarn++;
 6444:     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); 
 6445:     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); 
 6446:   }
 6447:     /*  if(mle==1){*/
 6448:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
 6449:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
 6450:   }
 6451: 
 6452:     /*-calculation of age at interview from date of interview and age at death -*/
 6453:   agev=matrix(1,maxwav,1,imx);
 6454: 
 6455:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
 6456:     goto end;
 6457: 
 6458: 
 6459:   agegomp=(int)agemin;
 6460:   free_vector(moisnais,1,n);
 6461:   free_vector(annais,1,n);
 6462:   /* free_matrix(mint,1,maxwav,1,n);
 6463:      free_matrix(anint,1,maxwav,1,n);*/
 6464:   free_vector(moisdc,1,n);
 6465:   free_vector(andc,1,n);
 6466:   /* */
 6467:   
 6468:   wav=ivector(1,imx);
 6469:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
 6470:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
 6471:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
 6472:    
 6473:   /* Concatenates waves */
 6474:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
 6475:   /* */
 6476:  
 6477:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
 6478: 
 6479:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
 6480:   ncodemax[1]=1;
 6481:   Ndum =ivector(-1,NCOVMAX);  
 6482:   if (ncovmodel > 2)
 6483:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
 6484: 
 6485:   codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
 6486:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
 6487:   h=0;
 6488: 
 6489: 
 6490:   /*if (cptcovn > 0) */
 6491:       
 6492:  
 6493:   m=pow(2,cptcoveff);
 6494:  
 6495:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
 6496:     for(i=1; i <=pow(2,cptcoveff-k);i++){ /* i=1 to 8/1=8; i=1 to 8/2=4; i=1 to 8/8=1 */ 
 6497:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
 6498: 	for(cpt=1; cpt <=pow(2,k-1); cpt++){  /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */ 
 6499: 	  h++;
 6500: 	  if (h>m) 
 6501: 	    h=1;
 6502: 	  /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
 6503: 	   *     h     1     2     3     4
 6504: 	   *______________________________  
 6505: 	   *     1 i=1 1 i=1 1 i=1 1 i=1 1
 6506: 	   *     2     2     1     1     1
 6507: 	   *     3 i=2 1     2     1     1
 6508: 	   *     4     2     2     1     1
 6509: 	   *     5 i=3 1 i=2 1     2     1
 6510: 	   *     6     2     1     2     1
 6511: 	   *     7 i=4 1     2     2     1
 6512: 	   *     8     2     2     2     1
 6513: 	   *     9 i=5 1 i=3 1 i=2 1     1
 6514: 	   *    10     2     1     1     1
 6515: 	   *    11 i=6 1     2     1     1
 6516: 	   *    12     2     2     1     1
 6517: 	   *    13 i=7 1 i=4 1     2     1    
 6518: 	   *    14     2     1     2     1
 6519: 	   *    15 i=8 1     2     2     1
 6520: 	   *    16     2     2     2     1
 6521: 	   */
 6522: 	  codtab[h][k]=j;
 6523: 	  /*codtab[h][Tvar[k]]=j;*/
 6524: 	  printf("h=%d k=%d j=%d codtab[h][k]=%d Tvar[k]=%d codtab[h][Tvar[k]]=%d \n",h, k,j,codtab[h][k],Tvar[k],codtab[h][Tvar[k]]);
 6525: 	} 
 6526:       }
 6527:     }
 6528:   } 
 6529:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
 6530:      codtab[1][2]=1;codtab[2][2]=2; */
 6531:   /* for(i=1; i <=m ;i++){ 
 6532:      for(k=1; k <=cptcovn; k++){
 6533:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
 6534:      }
 6535:      printf("\n");
 6536:      }
 6537:      scanf("%d",i);*/
 6538: 
 6539:  free_ivector(Ndum,-1,NCOVMAX);
 6540: 
 6541: 
 6542:     
 6543:   /*------------ gnuplot -------------*/
 6544:   strcpy(optionfilegnuplot,optionfilefiname);
 6545:   if(mle==-3)
 6546:     strcat(optionfilegnuplot,"-mort");
 6547:   strcat(optionfilegnuplot,".gp");
 6548: 
 6549:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
 6550:     printf("Problem with file %s",optionfilegnuplot);
 6551:   }
 6552:   else{
 6553:     fprintf(ficgp,"\n# %s\n", version); 
 6554:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
 6555:     //fprintf(ficgp,"set missing 'NaNq'\n");
 6556:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
 6557:   }
 6558:   /*  fclose(ficgp);*/
 6559:   /*--------- index.htm --------*/
 6560: 
 6561:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
 6562:   if(mle==-3)
 6563:     strcat(optionfilehtm,"-mort");
 6564:   strcat(optionfilehtm,".htm");
 6565:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
 6566:     printf("Problem with %s \n",optionfilehtm);
 6567:     exit(0);
 6568:   }
 6569: 
 6570:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
 6571:   strcat(optionfilehtmcov,"-cov.htm");
 6572:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
 6573:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
 6574:   }
 6575:   else{
 6576:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 6577: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 6578: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
 6579: 	  optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 6580:   }
 6581: 
 6582:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 6583: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 6584: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
 6585: \n\
 6586: <hr  size=\"2\" color=\"#EC5E5E\">\
 6587:  <ul><li><h4>Parameter files</h4>\n\
 6588:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
 6589:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
 6590:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
 6591:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
 6592:  - Date and time at start: %s</ul>\n",\
 6593: 	  optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
 6594: 	  optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
 6595: 	  fileres,fileres,\
 6596: 	  filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
 6597:   fflush(fichtm);
 6598: 
 6599:   strcpy(pathr,path);
 6600:   strcat(pathr,optionfilefiname);
 6601: #ifdef WIN32
 6602:   _chdir(optionfilefiname); /* Move to directory named optionfile */
 6603: #else
 6604:   chdir(optionfilefiname); /* Move to directory named optionfile */
 6605: #endif
 6606: 	  
 6607:   
 6608:   /* Calculates basic frequencies. Computes observed prevalence at single age
 6609:      and prints on file fileres'p'. */
 6610:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
 6611: 
 6612:   fprintf(fichtm,"\n");
 6613:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
 6614: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
 6615: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
 6616: 	  imx,agemin,agemax,jmin,jmax,jmean);
 6617:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6618:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6619:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6620:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6621:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
 6622:     
 6623:    
 6624:   /* For Powell, parameters are in a vector p[] starting at p[1]
 6625:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
 6626:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
 6627: 
 6628:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
 6629: 
 6630:   if (mle==-3){
 6631:     ximort=matrix(1,NDIM,1,NDIM); 
 6632: /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
 6633:     cens=ivector(1,n);
 6634:     ageexmed=vector(1,n);
 6635:     agecens=vector(1,n);
 6636:     dcwave=ivector(1,n);
 6637:  
 6638:     for (i=1; i<=imx; i++){
 6639:       dcwave[i]=-1;
 6640:       for (m=firstpass; m<=lastpass; m++)
 6641: 	if (s[m][i]>nlstate) {
 6642: 	  dcwave[i]=m;
 6643: 	  /*	printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
 6644: 	  break;
 6645: 	}
 6646:     }
 6647: 
 6648:     for (i=1; i<=imx; i++) {
 6649:       if (wav[i]>0){
 6650: 	ageexmed[i]=agev[mw[1][i]][i];
 6651: 	j=wav[i];
 6652: 	agecens[i]=1.; 
 6653: 
 6654: 	if (ageexmed[i]> 1 && wav[i] > 0){
 6655: 	  agecens[i]=agev[mw[j][i]][i];
 6656: 	  cens[i]= 1;
 6657: 	}else if (ageexmed[i]< 1) 
 6658: 	  cens[i]= -1;
 6659: 	if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
 6660: 	  cens[i]=0 ;
 6661:       }
 6662:       else cens[i]=-1;
 6663:     }
 6664:     
 6665:     for (i=1;i<=NDIM;i++) {
 6666:       for (j=1;j<=NDIM;j++)
 6667: 	ximort[i][j]=(i == j ? 1.0 : 0.0);
 6668:     }
 6669:     
 6670:     /*p[1]=0.0268; p[NDIM]=0.083;*/
 6671:     /*printf("%lf %lf", p[1], p[2]);*/
 6672:     
 6673:     
 6674: #ifdef GSL
 6675:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
 6676: #else
 6677:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
 6678: #endif
 6679:     strcpy(filerespow,"pow-mort"); 
 6680:     strcat(filerespow,fileres);
 6681:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
 6682:       printf("Problem with resultfile: %s\n", filerespow);
 6683:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 6684:     }
 6685: #ifdef GSL
 6686:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
 6687: #else
 6688:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
 6689: #endif
 6690:     /*  for (i=1;i<=nlstate;i++)
 6691: 	for(j=1;j<=nlstate+ndeath;j++)
 6692: 	if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 6693:     */
 6694:     fprintf(ficrespow,"\n");
 6695: #ifdef GSL
 6696:     /* gsl starts here */ 
 6697:     T = gsl_multimin_fminimizer_nmsimplex;
 6698:     gsl_multimin_fminimizer *sfm = NULL;
 6699:     gsl_vector *ss, *x;
 6700:     gsl_multimin_function minex_func;
 6701: 
 6702:     /* Initial vertex size vector */
 6703:     ss = gsl_vector_alloc (NDIM);
 6704:     
 6705:     if (ss == NULL){
 6706:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
 6707:     }
 6708:     /* Set all step sizes to 1 */
 6709:     gsl_vector_set_all (ss, 0.001);
 6710: 
 6711:     /* Starting point */
 6712:     
 6713:     x = gsl_vector_alloc (NDIM);
 6714:     
 6715:     if (x == NULL){
 6716:       gsl_vector_free(ss);
 6717:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
 6718:     }
 6719:   
 6720:     /* Initialize method and iterate */
 6721:     /*     p[1]=0.0268; p[NDIM]=0.083; */
 6722: /*     gsl_vector_set(x, 0, 0.0268); */
 6723: /*     gsl_vector_set(x, 1, 0.083); */
 6724:     gsl_vector_set(x, 0, p[1]);
 6725:     gsl_vector_set(x, 1, p[2]);
 6726: 
 6727:     minex_func.f = &gompertz_f;
 6728:     minex_func.n = NDIM;
 6729:     minex_func.params = (void *)&p; /* ??? */
 6730:     
 6731:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
 6732:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
 6733:     
 6734:     printf("Iterations beginning .....\n\n");
 6735:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
 6736: 
 6737:     iteri=0;
 6738:     while (rval == GSL_CONTINUE){
 6739:       iteri++;
 6740:       status = gsl_multimin_fminimizer_iterate(sfm);
 6741:       
 6742:       if (status) printf("error: %s\n", gsl_strerror (status));
 6743:       fflush(0);
 6744:       
 6745:       if (status) 
 6746:         break;
 6747:       
 6748:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
 6749:       ssval = gsl_multimin_fminimizer_size (sfm);
 6750:       
 6751:       if (rval == GSL_SUCCESS)
 6752:         printf ("converged to a local maximum at\n");
 6753:       
 6754:       printf("%5d ", iteri);
 6755:       for (it = 0; it < NDIM; it++){
 6756: 	printf ("%10.5f ", gsl_vector_get (sfm->x, it));
 6757:       }
 6758:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
 6759:     }
 6760:     
 6761:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
 6762:     
 6763:     gsl_vector_free(x); /* initial values */
 6764:     gsl_vector_free(ss); /* inital step size */
 6765:     for (it=0; it<NDIM; it++){
 6766:       p[it+1]=gsl_vector_get(sfm->x,it);
 6767:       fprintf(ficrespow," %.12lf", p[it]);
 6768:     }
 6769:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
 6770: #endif
 6771: #ifdef POWELL
 6772:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
 6773: #endif  
 6774:     fclose(ficrespow);
 6775:     
 6776:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
 6777: 
 6778:     for(i=1; i <=NDIM; i++)
 6779:       for(j=i+1;j<=NDIM;j++)
 6780: 	matcov[i][j]=matcov[j][i];
 6781:     
 6782:     printf("\nCovariance matrix\n ");
 6783:     for(i=1; i <=NDIM; i++) {
 6784:       for(j=1;j<=NDIM;j++){ 
 6785: 	printf("%f ",matcov[i][j]);
 6786:       }
 6787:       printf("\n ");
 6788:     }
 6789:     
 6790:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
 6791:     for (i=1;i<=NDIM;i++) 
 6792:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
 6793: 
 6794:     lsurv=vector(1,AGESUP);
 6795:     lpop=vector(1,AGESUP);
 6796:     tpop=vector(1,AGESUP);
 6797:     lsurv[agegomp]=100000;
 6798:     
 6799:     for (k=agegomp;k<=AGESUP;k++) {
 6800:       agemortsup=k;
 6801:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
 6802:     }
 6803:     
 6804:     for (k=agegomp;k<agemortsup;k++)
 6805:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
 6806:     
 6807:     for (k=agegomp;k<agemortsup;k++){
 6808:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
 6809:       sumlpop=sumlpop+lpop[k];
 6810:     }
 6811:     
 6812:     tpop[agegomp]=sumlpop;
 6813:     for (k=agegomp;k<(agemortsup-3);k++){
 6814:       /*  tpop[k+1]=2;*/
 6815:       tpop[k+1]=tpop[k]-lpop[k];
 6816:     }
 6817:     
 6818:     
 6819:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
 6820:     for (k=agegomp;k<(agemortsup-2);k++) 
 6821:       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]);
 6822:     
 6823:     
 6824:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 6825:     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 6826:     
 6827:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
 6828: 		     stepm, weightopt,\
 6829: 		     model,imx,p,matcov,agemortsup);
 6830:     
 6831:     free_vector(lsurv,1,AGESUP);
 6832:     free_vector(lpop,1,AGESUP);
 6833:     free_vector(tpop,1,AGESUP);
 6834: #ifdef GSL
 6835:     free_ivector(cens,1,n);
 6836:     free_vector(agecens,1,n);
 6837:     free_ivector(dcwave,1,n);
 6838:     free_matrix(ximort,1,NDIM,1,NDIM);
 6839: #endif
 6840:   } /* Endof if mle==-3 */
 6841:   
 6842:   else{ /* For mle >=1 */
 6843:     globpr=0;/* debug */
 6844:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 6845:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 6846:     for (k=1; k<=npar;k++)
 6847:       printf(" %d %8.5f",k,p[k]);
 6848:     printf("\n");
 6849:     globpr=1; /* to print the contributions */
 6850:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 6851:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 6852:     for (k=1; k<=npar;k++)
 6853:       printf(" %d %8.5f",k,p[k]);
 6854:     printf("\n");
 6855:     if(mle>=1){ /* Could be 1 or 2 */
 6856:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
 6857:     }
 6858:     
 6859:     /*--------- results files --------------*/
 6860:     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=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate, ndeath, maxwav, weightopt,model);
 6861:     
 6862:     
 6863:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 6864:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 6865:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 6866:     for(i=1,jk=1; i <=nlstate; i++){
 6867:       for(k=1; k <=(nlstate+ndeath); k++){
 6868: 	if (k != i) {
 6869: 	  printf("%d%d ",i,k);
 6870: 	  fprintf(ficlog,"%d%d ",i,k);
 6871: 	  fprintf(ficres,"%1d%1d ",i,k);
 6872: 	  for(j=1; j <=ncovmodel; j++){
 6873: 	    printf("%lf ",p[jk]);
 6874: 	    fprintf(ficlog,"%lf ",p[jk]);
 6875: 	    fprintf(ficres,"%lf ",p[jk]);
 6876: 	    jk++; 
 6877: 	  }
 6878: 	  printf("\n");
 6879: 	  fprintf(ficlog,"\n");
 6880: 	  fprintf(ficres,"\n");
 6881: 	}
 6882:       }
 6883:     }
 6884:     if(mle!=0){
 6885:       /* Computing hessian and covariance matrix */
 6886:       ftolhess=ftol; /* Usually correct */
 6887:       hesscov(matcov, p, npar, delti, ftolhess, func);
 6888:     }
 6889:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
 6890:     printf("# Scales (for hessian or gradient estimation)\n");
 6891:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
 6892:     for(i=1,jk=1; i <=nlstate; i++){
 6893:       for(j=1; j <=nlstate+ndeath; j++){
 6894: 	if (j!=i) {
 6895: 	  fprintf(ficres,"%1d%1d",i,j);
 6896: 	  printf("%1d%1d",i,j);
 6897: 	  fprintf(ficlog,"%1d%1d",i,j);
 6898: 	  for(k=1; k<=ncovmodel;k++){
 6899: 	    printf(" %.5e",delti[jk]);
 6900: 	    fprintf(ficlog," %.5e",delti[jk]);
 6901: 	    fprintf(ficres," %.5e",delti[jk]);
 6902: 	    jk++;
 6903: 	  }
 6904: 	  printf("\n");
 6905: 	  fprintf(ficlog,"\n");
 6906: 	  fprintf(ficres,"\n");
 6907: 	}
 6908:       }
 6909:     }
 6910:     
 6911:     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");
 6912:     if(mle>=1)
 6913:       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");
 6914:     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");
 6915:     /* # 121 Var(a12)\n\ */
 6916:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
 6917:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 6918:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 6919:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 6920:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 6921:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 6922:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 6923:     
 6924:     
 6925:     /* Just to have a covariance matrix which will be more understandable
 6926:        even is we still don't want to manage dictionary of variables
 6927:     */
 6928:     for(itimes=1;itimes<=2;itimes++){
 6929:       jj=0;
 6930:       for(i=1; i <=nlstate; i++){
 6931: 	for(j=1; j <=nlstate+ndeath; j++){
 6932: 	  if(j==i) continue;
 6933: 	  for(k=1; k<=ncovmodel;k++){
 6934: 	    jj++;
 6935: 	    ca[0]= k+'a'-1;ca[1]='\0';
 6936: 	    if(itimes==1){
 6937: 	      if(mle>=1)
 6938: 		printf("#%1d%1d%d",i,j,k);
 6939: 	      fprintf(ficlog,"#%1d%1d%d",i,j,k);
 6940: 	      fprintf(ficres,"#%1d%1d%d",i,j,k);
 6941: 	    }else{
 6942: 	      if(mle>=1)
 6943: 		printf("%1d%1d%d",i,j,k);
 6944: 	      fprintf(ficlog,"%1d%1d%d",i,j,k);
 6945: 	      fprintf(ficres,"%1d%1d%d",i,j,k);
 6946: 	    }
 6947: 	    ll=0;
 6948: 	    for(li=1;li <=nlstate; li++){
 6949: 	      for(lj=1;lj <=nlstate+ndeath; lj++){
 6950: 		if(lj==li) continue;
 6951: 		for(lk=1;lk<=ncovmodel;lk++){
 6952: 		  ll++;
 6953: 		  if(ll<=jj){
 6954: 		    cb[0]= lk +'a'-1;cb[1]='\0';
 6955: 		    if(ll<jj){
 6956: 		      if(itimes==1){
 6957: 			if(mle>=1)
 6958: 			  printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 6959: 			fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 6960: 			fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 6961: 		      }else{
 6962: 			if(mle>=1)
 6963: 			  printf(" %.5e",matcov[jj][ll]); 
 6964: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 6965: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 6966: 		      }
 6967: 		    }else{
 6968: 		      if(itimes==1){
 6969: 			if(mle>=1)
 6970: 			  printf(" Var(%s%1d%1d)",ca,i,j);
 6971: 			fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
 6972: 			fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
 6973: 		      }else{
 6974: 			if(mle>=1)
 6975: 			  printf(" %.5e",matcov[jj][ll]); 
 6976: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 6977: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 6978: 		      }
 6979: 		    }
 6980: 		  }
 6981: 		} /* end lk */
 6982: 	      } /* end lj */
 6983: 	    } /* end li */
 6984: 	    if(mle>=1)
 6985: 	      printf("\n");
 6986: 	    fprintf(ficlog,"\n");
 6987: 	    fprintf(ficres,"\n");
 6988: 	    numlinepar++;
 6989: 	  } /* end k*/
 6990: 	} /*end j */
 6991:       } /* end i */
 6992:     } /* end itimes */
 6993:     
 6994:     fflush(ficlog);
 6995:     fflush(ficres);
 6996:     
 6997:     while((c=getc(ficpar))=='#' && c!= EOF){
 6998:       ungetc(c,ficpar);
 6999:       fgets(line, MAXLINE, ficpar);
 7000:       fputs(line,stdout);
 7001:       fputs(line,ficparo);
 7002:     }
 7003:     ungetc(c,ficpar);
 7004:     
 7005:     estepm=0;
 7006:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
 7007:     if (estepm==0 || estepm < stepm) estepm=stepm;
 7008:     if (fage <= 2) {
 7009:       bage = ageminpar;
 7010:       fage = agemaxpar;
 7011:     }
 7012:     
 7013:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
 7014:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 7015:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 7016:     
 7017:     while((c=getc(ficpar))=='#' && c!= EOF){
 7018:       ungetc(c,ficpar);
 7019:       fgets(line, MAXLINE, ficpar);
 7020:       fputs(line,stdout);
 7021:       fputs(line,ficparo);
 7022:     }
 7023:     ungetc(c,ficpar);
 7024:     
 7025:     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);
 7026:     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);
 7027:     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);
 7028:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
 7029:     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);
 7030:     
 7031:     while((c=getc(ficpar))=='#' && c!= EOF){
 7032:       ungetc(c,ficpar);
 7033:       fgets(line, MAXLINE, ficpar);
 7034:       fputs(line,stdout);
 7035:       fputs(line,ficparo);
 7036:     }
 7037:     ungetc(c,ficpar);
 7038:     
 7039:     
 7040:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
 7041:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
 7042:     
 7043:     fscanf(ficpar,"pop_based=%d\n",&popbased);
 7044:     fprintf(ficparo,"pop_based=%d\n",popbased);   
 7045:     fprintf(ficres,"pop_based=%d\n",popbased);   
 7046:     
 7047:     while((c=getc(ficpar))=='#' && c!= EOF){
 7048:       ungetc(c,ficpar);
 7049:       fgets(line, MAXLINE, ficpar);
 7050:       fputs(line,stdout);
 7051:       fputs(line,ficparo);
 7052:     }
 7053:     ungetc(c,ficpar);
 7054:     
 7055:     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);
 7056:     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);
 7057:     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);
 7058:     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);
 7059:     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);
 7060:     /* day and month of proj2 are not used but only year anproj2.*/
 7061:     
 7062:     
 7063:     
 7064:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
 7065:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
 7066:     
 7067:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 7068:     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 7069:     
 7070:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
 7071: 		 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
 7072: 		 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
 7073:       
 7074:    /*------------ free_vector  -------------*/
 7075:    /*  chdir(path); */
 7076:  
 7077:     free_ivector(wav,1,imx);
 7078:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
 7079:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
 7080:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
 7081:     free_lvector(num,1,n);
 7082:     free_vector(agedc,1,n);
 7083:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
 7084:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
 7085:     fclose(ficparo);
 7086:     fclose(ficres);
 7087: 
 7088: 
 7089:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 7090:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
 7091:     prlim=matrix(1,nlstate,1,nlstate);
 7092:     prevalence_limit(p, prlim,  ageminpar, agemaxpar);
 7093:     fclose(ficrespl);
 7094: 
 7095: #ifdef FREEEXIT2
 7096: #include "freeexit2.h"
 7097: #endif
 7098: 
 7099:     /*------------- h Pij x at various ages ------------*/
 7100:     /*#include "hpijx.h"*/
 7101:     hPijx(p, bage, fage);
 7102:     fclose(ficrespij);
 7103: 
 7104:   /*-------------- Variance of one-step probabilities---*/
 7105:     k=1;
 7106:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
 7107: 
 7108: 
 7109:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 7110:     for(i=1;i<=AGESUP;i++)
 7111:       for(j=1;j<=NCOVMAX;j++)
 7112: 	for(k=1;k<=NCOVMAX;k++)
 7113: 	  probs[i][j][k]=0.;
 7114: 
 7115:     /*---------- Forecasting ------------------*/
 7116:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
 7117:     if(prevfcast==1){
 7118:       /*    if(stepm ==1){*/
 7119:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
 7120:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
 7121:       /*      }  */
 7122:       /*      else{ */
 7123:       /*        erreur=108; */
 7124:       /*        printf("Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
 7125:       /*        fprintf(ficlog,"Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
 7126:       /*      } */
 7127:     }
 7128:   
 7129: 
 7130:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
 7131: 
 7132:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 7133:     /*  printf("ageminpar=%f, agemax=%f, s[lastpass][imx]=%d, agev[lastpass][imx]=%f, nlstate=%d, imx=%d,  mint[lastpass][imx]=%f, anint[lastpass][imx]=%f,dateprev1=%f, dateprev2=%f, firstpass=%d, lastpass=%d\n",\
 7134: 	ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
 7135:     */
 7136: 
 7137:     if (mobilav!=0) {
 7138:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 7139:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 7140: 	fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 7141: 	printf(" Error in movingaverage mobilav=%d\n",mobilav);
 7142:       }
 7143:     }
 7144: 
 7145: 
 7146:     /*---------- Health expectancies, no variances ------------*/
 7147: 
 7148:     strcpy(filerese,"e");
 7149:     strcat(filerese,fileres);
 7150:     if((ficreseij=fopen(filerese,"w"))==NULL) {
 7151:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 7152:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 7153:     }
 7154:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
 7155:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
 7156:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 7157:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 7158:           
 7159:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 7160: 	fprintf(ficreseij,"\n#****** ");
 7161: 	for(j=1;j<=cptcoveff;j++) {
 7162: 	  fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7163: 	}
 7164: 	fprintf(ficreseij,"******\n");
 7165: 
 7166: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 7167: 	oldm=oldms;savm=savms;
 7168: 	evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
 7169:       
 7170: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 7171:       /*}*/
 7172:     }
 7173:     fclose(ficreseij);
 7174: 
 7175: 
 7176:     /*---------- Health expectancies and variances ------------*/
 7177: 
 7178: 
 7179:     strcpy(filerest,"t");
 7180:     strcat(filerest,fileres);
 7181:     if((ficrest=fopen(filerest,"w"))==NULL) {
 7182:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
 7183:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
 7184:     }
 7185:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
 7186:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
 7187: 
 7188: 
 7189:     strcpy(fileresstde,"stde");
 7190:     strcat(fileresstde,fileres);
 7191:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
 7192:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 7193:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 7194:     }
 7195:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 7196:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 7197: 
 7198:     strcpy(filerescve,"cve");
 7199:     strcat(filerescve,fileres);
 7200:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
 7201:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 7202:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 7203:     }
 7204:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 7205:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 7206: 
 7207:     strcpy(fileresv,"v");
 7208:     strcat(fileresv,fileres);
 7209:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
 7210:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
 7211:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
 7212:     }
 7213:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 7214:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 7215: 
 7216:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 7217:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 7218:           
 7219:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 7220:     	fprintf(ficrest,"\n#****** ");
 7221: 	for(j=1;j<=cptcoveff;j++) 
 7222: 	  fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7223: 	fprintf(ficrest,"******\n");
 7224: 
 7225: 	fprintf(ficresstdeij,"\n#****** ");
 7226: 	fprintf(ficrescveij,"\n#****** ");
 7227: 	for(j=1;j<=cptcoveff;j++) {
 7228: 	  fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7229: 	  fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7230: 	}
 7231: 	fprintf(ficresstdeij,"******\n");
 7232: 	fprintf(ficrescveij,"******\n");
 7233: 
 7234: 	fprintf(ficresvij,"\n#****** ");
 7235: 	for(j=1;j<=cptcoveff;j++) 
 7236: 	  fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7237: 	fprintf(ficresvij,"******\n");
 7238: 
 7239: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 7240: 	oldm=oldms;savm=savms;
 7241: 	cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
 7242: 	/*
 7243: 	 */
 7244: 	/* goto endfree; */
 7245:  
 7246: 	vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 7247: 	pstamp(ficrest);
 7248: 
 7249: 
 7250: 	for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 7251: 	  oldm=oldms;savm=savms; /* Segmentation fault */
 7252: 	  cptcod= 0; /* To be deleted */
 7253: 	  varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); /* cptcod not initialized Intel */
 7254: 	  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 ");
 7255: 	  if(vpopbased==1)
 7256: 	    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);
 7257: 	  else
 7258: 	    fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
 7259: 	  fprintf(ficrest,"# Age e.. (std) ");
 7260: 	  for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
 7261: 	  fprintf(ficrest,"\n");
 7262: 
 7263: 	  epj=vector(1,nlstate+1);
 7264: 	  for(age=bage; age <=fage ;age++){
 7265: 	    prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
 7266: 	    if (vpopbased==1) {
 7267: 	      if(mobilav ==0){
 7268: 		for(i=1; i<=nlstate;i++)
 7269: 		  prlim[i][i]=probs[(int)age][i][k];
 7270: 	      }else{ /* mobilav */ 
 7271: 		for(i=1; i<=nlstate;i++)
 7272: 		  prlim[i][i]=mobaverage[(int)age][i][k];
 7273: 	      }
 7274: 	    }
 7275: 	
 7276: 	    fprintf(ficrest," %4.0f",age);
 7277: 	    for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
 7278: 	      for(i=1, epj[j]=0.;i <=nlstate;i++) {
 7279: 		epj[j] += prlim[i][i]*eij[i][j][(int)age];
 7280: 		/*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
 7281: 	      }
 7282: 	      epj[nlstate+1] +=epj[j];
 7283: 	    }
 7284: 
 7285: 	    for(i=1, vepp=0.;i <=nlstate;i++)
 7286: 	      for(j=1;j <=nlstate;j++)
 7287: 		vepp += vareij[i][j][(int)age];
 7288: 	    fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
 7289: 	    for(j=1;j <=nlstate;j++){
 7290: 	      fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
 7291: 	    }
 7292: 	    fprintf(ficrest,"\n");
 7293: 	  }
 7294: 	}
 7295: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 7296: 	free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 7297: 	free_vector(epj,1,nlstate+1);
 7298:       /*}*/
 7299:     }
 7300:     free_vector(weight,1,n);
 7301:     free_imatrix(Tvard,1,NCOVMAX,1,2);
 7302:     free_imatrix(s,1,maxwav+1,1,n);
 7303:     free_matrix(anint,1,maxwav,1,n); 
 7304:     free_matrix(mint,1,maxwav,1,n);
 7305:     free_ivector(cod,1,n);
 7306:     free_ivector(tab,1,NCOVMAX);
 7307:     fclose(ficresstdeij);
 7308:     fclose(ficrescveij);
 7309:     fclose(ficresvij);
 7310:     fclose(ficrest);
 7311:     fclose(ficpar);
 7312:   
 7313:     /*------- Variance of period (stable) prevalence------*/   
 7314: 
 7315:     strcpy(fileresvpl,"vpl");
 7316:     strcat(fileresvpl,fileres);
 7317:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
 7318:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
 7319:       exit(0);
 7320:     }
 7321:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
 7322: 
 7323:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 7324:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 7325:           
 7326:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 7327:     	fprintf(ficresvpl,"\n#****** ");
 7328: 	for(j=1;j<=cptcoveff;j++) 
 7329: 	  fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7330: 	fprintf(ficresvpl,"******\n");
 7331:       
 7332: 	varpl=matrix(1,nlstate,(int) bage, (int) fage);
 7333: 	oldm=oldms;savm=savms;
 7334: 	varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
 7335: 	free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
 7336:       /*}*/
 7337:     }
 7338: 
 7339:     fclose(ficresvpl);
 7340: 
 7341:     /*---------- End : free ----------------*/
 7342:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 7343:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 7344:   }  /* mle==-3 arrives here for freeing */
 7345:  /* endfree:*/
 7346:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
 7347:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
 7348:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
 7349:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
 7350:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
 7351:     free_matrix(covar,0,NCOVMAX,1,n);
 7352:     free_matrix(matcov,1,npar,1,npar);
 7353:     /*free_vector(delti,1,npar);*/
 7354:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 7355:     free_matrix(agev,1,maxwav,1,imx);
 7356:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
 7357: 
 7358:     free_ivector(ncodemax,1,NCOVMAX);
 7359:     free_ivector(Tvar,1,NCOVMAX);
 7360:     free_ivector(Tprod,1,NCOVMAX);
 7361:     free_ivector(Tvaraff,1,NCOVMAX);
 7362:     free_ivector(Tage,1,NCOVMAX);
 7363: 
 7364:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
 7365:     free_imatrix(codtab,1,100,1,10);
 7366:   fflush(fichtm);
 7367:   fflush(ficgp);
 7368:   
 7369: 
 7370:   if((nberr >0) || (nbwarn>0)){
 7371:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
 7372:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
 7373:   }else{
 7374:     printf("End of Imach\n");
 7375:     fprintf(ficlog,"End of Imach\n");
 7376:   }
 7377:   printf("See log file on %s\n",filelog);
 7378:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
 7379:   /*(void) gettimeofday(&end_time,&tzp);*/
 7380:   rend_time = time(NULL);  
 7381:   end_time = *localtime(&rend_time);
 7382:   /* tml = *localtime(&end_time.tm_sec); */
 7383:   strcpy(strtend,asctime(&end_time));
 7384:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
 7385:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
 7386:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 7387: 
 7388:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 7389:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 7390:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 7391:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
 7392: /*   if(fileappend(fichtm,optionfilehtm)){ */
 7393:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 7394:   fclose(fichtm);
 7395:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 7396:   fclose(fichtmcov);
 7397:   fclose(ficgp);
 7398:   fclose(ficlog);
 7399:   /*------ End -----------*/
 7400: 
 7401: 
 7402:    printf("Before Current directory %s!\n",pathcd);
 7403: #ifdef WIN32
 7404:    if (_chdir(pathcd) != 0)
 7405: 	   printf("Can't move to directory %s!\n",path);
 7406:    if(_getcwd(pathcd,MAXLINE) > 0)
 7407: #else
 7408:    if(chdir(pathcd) != 0)
 7409: 	   printf("Can't move to directory %s!\n", path);
 7410:    if (getcwd(pathcd, MAXLINE) > 0)
 7411: #endif 
 7412:     printf("Current directory %s!\n",pathcd);
 7413:   /*strcat(plotcmd,CHARSEPARATOR);*/
 7414:   sprintf(plotcmd,"gnuplot");
 7415: #ifdef _WIN32
 7416:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
 7417: #endif
 7418:   if(!stat(plotcmd,&info)){
 7419:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 7420:     if(!stat(getenv("GNUPLOTBIN"),&info)){
 7421:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
 7422:     }else
 7423:       strcpy(pplotcmd,plotcmd);
 7424: #ifdef __unix
 7425:     strcpy(plotcmd,GNUPLOTPROGRAM);
 7426:     if(!stat(plotcmd,&info)){
 7427:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 7428:     }else
 7429:       strcpy(pplotcmd,plotcmd);
 7430: #endif
 7431:   }else
 7432:     strcpy(pplotcmd,plotcmd);
 7433:   
 7434:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
 7435:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
 7436: 
 7437:   if((outcmd=system(plotcmd)) != 0){
 7438:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
 7439:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
 7440:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
 7441:     if((outcmd=system(plotcmd)) != 0)
 7442:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
 7443:   }
 7444:   printf(" Successful, please wait...");
 7445:   while (z[0] != 'q') {
 7446:     /* chdir(path); */
 7447:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
 7448:     scanf("%s",z);
 7449: /*     if (z[0] == 'c') system("./imach"); */
 7450:     if (z[0] == 'e') {
 7451: #ifdef __APPLE__
 7452:       sprintf(pplotcmd, "open %s", optionfilehtm);
 7453: #elif __linux
 7454:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
 7455: #else
 7456:       sprintf(pplotcmd, "%s", optionfilehtm);
 7457: #endif
 7458:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
 7459:       system(pplotcmd);
 7460:     }
 7461:     else if (z[0] == 'g') system(plotcmd);
 7462:     else if (z[0] == 'q') exit(0);
 7463:   }
 7464:   end:
 7465:   while (z[0] != 'q') {
 7466:     printf("\nType  q for exiting: ");
 7467:     scanf("%s",z);
 7468:   }
 7469: }

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