File:  [Local Repository] / imach / src / imach.c
Revision 1.189: download - view: text, annotated - select for diffs
Thu Apr 30 14:45:16 2015 UTC (9 years, 1 month ago) by brouard
Branches: MAIN
CVS tags: HEAD
Summary: 0.98q2

    1: /* $Id: imach.c,v 1.189 2015/04/30 14:45:16 brouard Exp $
    2:   $State: Exp $
    3:   $Log: imach.c,v $
    4:   Revision 1.189  2015/04/30 14:45:16  brouard
    5:   Summary: 0.98q2
    6: 
    7:   Revision 1.188  2015/04/30 08:27:53  brouard
    8:   *** empty log message ***
    9: 
   10:   Revision 1.187  2015/04/29 09:11:15  brouard
   11:   *** empty log message ***
   12: 
   13:   Revision 1.186  2015/04/23 12:01:52  brouard
   14:   Summary: V1*age is working now, version 0.98q1
   15: 
   16:   Some codes had been disabled in order to simplify and Vn*age was
   17:   working in the optimization phase, ie, giving correct MLE parameters,
   18:   but, as usual, outputs were not correct and program core dumped.
   19: 
   20:   Revision 1.185  2015/03/11 13:26:42  brouard
   21:   Summary: Inclusion of compile and links command line for Intel Compiler
   22: 
   23:   Revision 1.184  2015/03/11 11:52:39  brouard
   24:   Summary: Back from Windows 8. Intel Compiler
   25: 
   26:   Revision 1.183  2015/03/10 20:34:32  brouard
   27:   Summary: 0.98q0, trying with directest, mnbrak fixed
   28: 
   29:   We use directest instead of original Powell test; probably no
   30:   incidence on the results, but better justifications;
   31:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
   32:   wrong results.
   33: 
   34:   Revision 1.182  2015/02/12 08:19:57  brouard
   35:   Summary: Trying to keep directest which seems simpler and more general
   36:   Author: Nicolas Brouard
   37: 
   38:   Revision 1.181  2015/02/11 23:22:24  brouard
   39:   Summary: Comments on Powell added
   40: 
   41:   Author:
   42: 
   43:   Revision 1.180  2015/02/11 17:33:45  brouard
   44:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
   45: 
   46:   Revision 1.179  2015/01/04 09:57:06  brouard
   47:   Summary: back to OS/X
   48: 
   49:   Revision 1.178  2015/01/04 09:35:48  brouard
   50:   *** empty log message ***
   51: 
   52:   Revision 1.177  2015/01/03 18:40:56  brouard
   53:   Summary: Still testing ilc32 on OSX
   54: 
   55:   Revision 1.176  2015/01/03 16:45:04  brouard
   56:   *** empty log message ***
   57: 
   58:   Revision 1.175  2015/01/03 16:33:42  brouard
   59:   *** empty log message ***
   60: 
   61:   Revision 1.174  2015/01/03 16:15:49  brouard
   62:   Summary: Still in cross-compilation
   63: 
   64:   Revision 1.173  2015/01/03 12:06:26  brouard
   65:   Summary: trying to detect cross-compilation
   66: 
   67:   Revision 1.172  2014/12/27 12:07:47  brouard
   68:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
   69: 
   70:   Revision 1.171  2014/12/23 13:26:59  brouard
   71:   Summary: Back from Visual C
   72: 
   73:   Still problem with utsname.h on Windows
   74: 
   75:   Revision 1.170  2014/12/23 11:17:12  brouard
   76:   Summary: Cleaning some \%% back to %%
   77: 
   78:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
   79: 
   80:   Revision 1.169  2014/12/22 23:08:31  brouard
   81:   Summary: 0.98p
   82: 
   83:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
   84: 
   85:   Revision 1.168  2014/12/22 15:17:42  brouard
   86:   Summary: update
   87: 
   88:   Revision 1.167  2014/12/22 13:50:56  brouard
   89:   Summary: Testing uname and compiler version and if compiled 32 or 64
   90: 
   91:   Testing on Linux 64
   92: 
   93:   Revision 1.166  2014/12/22 11:40:47  brouard
   94:   *** empty log message ***
   95: 
   96:   Revision 1.165  2014/12/16 11:20:36  brouard
   97:   Summary: After compiling on Visual C
   98: 
   99:   * imach.c (Module): Merging 1.61 to 1.162
  100: 
  101:   Revision 1.164  2014/12/16 10:52:11  brouard
  102:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
  103: 
  104:   * imach.c (Module): Merging 1.61 to 1.162
  105: 
  106:   Revision 1.163  2014/12/16 10:30:11  brouard
  107:   * imach.c (Module): Merging 1.61 to 1.162
  108: 
  109:   Revision 1.162  2014/09/25 11:43:39  brouard
  110:   Summary: temporary backup 0.99!
  111: 
  112:   Revision 1.1  2014/09/16 11:06:58  brouard
  113:   Summary: With some code (wrong) for nlopt
  114: 
  115:   Author:
  116: 
  117:   Revision 1.161  2014/09/15 20:41:41  brouard
  118:   Summary: Problem with macro SQR on Intel compiler
  119: 
  120:   Revision 1.160  2014/09/02 09:24:05  brouard
  121:   *** empty log message ***
  122: 
  123:   Revision 1.159  2014/09/01 10:34:10  brouard
  124:   Summary: WIN32
  125:   Author: Brouard
  126: 
  127:   Revision 1.158  2014/08/27 17:11:51  brouard
  128:   *** empty log message ***
  129: 
  130:   Revision 1.157  2014/08/27 16:26:55  brouard
  131:   Summary: Preparing windows Visual studio version
  132:   Author: Brouard
  133: 
  134:   In order to compile on Visual studio, time.h is now correct and time_t
  135:   and tm struct should be used. difftime should be used but sometimes I
  136:   just make the differences in raw time format (time(&now).
  137:   Trying to suppress #ifdef LINUX
  138:   Add xdg-open for __linux in order to open default browser.
  139: 
  140:   Revision 1.156  2014/08/25 20:10:10  brouard
  141:   *** empty log message ***
  142: 
  143:   Revision 1.155  2014/08/25 18:32:34  brouard
  144:   Summary: New compile, minor changes
  145:   Author: Brouard
  146: 
  147:   Revision 1.154  2014/06/20 17:32:08  brouard
  148:   Summary: Outputs now all graphs of convergence to period prevalence
  149: 
  150:   Revision 1.153  2014/06/20 16:45:46  brouard
  151:   Summary: If 3 live state, convergence to period prevalence on same graph
  152:   Author: Brouard
  153: 
  154:   Revision 1.152  2014/06/18 17:54:09  brouard
  155:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
  156: 
  157:   Revision 1.151  2014/06/18 16:43:30  brouard
  158:   *** empty log message ***
  159: 
  160:   Revision 1.150  2014/06/18 16:42:35  brouard
  161:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
  162:   Author: brouard
  163: 
  164:   Revision 1.149  2014/06/18 15:51:14  brouard
  165:   Summary: Some fixes in parameter files errors
  166:   Author: Nicolas Brouard
  167: 
  168:   Revision 1.148  2014/06/17 17:38:48  brouard
  169:   Summary: Nothing new
  170:   Author: Brouard
  171: 
  172:   Just a new packaging for OS/X version 0.98nS
  173: 
  174:   Revision 1.147  2014/06/16 10:33:11  brouard
  175:   *** empty log message ***
  176: 
  177:   Revision 1.146  2014/06/16 10:20:28  brouard
  178:   Summary: Merge
  179:   Author: Brouard
  180: 
  181:   Merge, before building revised version.
  182: 
  183:   Revision 1.145  2014/06/10 21:23:15  brouard
  184:   Summary: Debugging with valgrind
  185:   Author: Nicolas Brouard
  186: 
  187:   Lot of changes in order to output the results with some covariates
  188:   After the Edimburgh REVES conference 2014, it seems mandatory to
  189:   improve the code.
  190:   No more memory valgrind error but a lot has to be done in order to
  191:   continue the work of splitting the code into subroutines.
  192:   Also, decodemodel has been improved. Tricode is still not
  193:   optimal. nbcode should be improved. Documentation has been added in
  194:   the source code.
  195: 
  196:   Revision 1.143  2014/01/26 09:45:38  brouard
  197:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
  198: 
  199:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  200:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
  201: 
  202:   Revision 1.142  2014/01/26 03:57:36  brouard
  203:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
  204: 
  205:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  206: 
  207:   Revision 1.141  2014/01/26 02:42:01  brouard
  208:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  209: 
  210:   Revision 1.140  2011/09/02 10:37:54  brouard
  211:   Summary: times.h is ok with mingw32 now.
  212: 
  213:   Revision 1.139  2010/06/14 07:50:17  brouard
  214:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
  215:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
  216: 
  217:   Revision 1.138  2010/04/30 18:19:40  brouard
  218:   *** empty log message ***
  219: 
  220:   Revision 1.137  2010/04/29 18:11:38  brouard
  221:   (Module): Checking covariates for more complex models
  222:   than V1+V2. A lot of change to be done. Unstable.
  223: 
  224:   Revision 1.136  2010/04/26 20:30:53  brouard
  225:   (Module): merging some libgsl code. Fixing computation
  226:   of likelione (using inter/intrapolation if mle = 0) in order to
  227:   get same likelihood as if mle=1.
  228:   Some cleaning of code and comments added.
  229: 
  230:   Revision 1.135  2009/10/29 15:33:14  brouard
  231:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  232: 
  233:   Revision 1.134  2009/10/29 13:18:53  brouard
  234:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  235: 
  236:   Revision 1.133  2009/07/06 10:21:25  brouard
  237:   just nforces
  238: 
  239:   Revision 1.132  2009/07/06 08:22:05  brouard
  240:   Many tings
  241: 
  242:   Revision 1.131  2009/06/20 16:22:47  brouard
  243:   Some dimensions resccaled
  244: 
  245:   Revision 1.130  2009/05/26 06:44:34  brouard
  246:   (Module): Max Covariate is now set to 20 instead of 8. A
  247:   lot of cleaning with variables initialized to 0. Trying to make
  248:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
  249: 
  250:   Revision 1.129  2007/08/31 13:49:27  lievre
  251:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
  252: 
  253:   Revision 1.128  2006/06/30 13:02:05  brouard
  254:   (Module): Clarifications on computing e.j
  255: 
  256:   Revision 1.127  2006/04/28 18:11:50  brouard
  257:   (Module): Yes the sum of survivors was wrong since
  258:   imach-114 because nhstepm was no more computed in the age
  259:   loop. Now we define nhstepma in the age loop.
  260:   (Module): In order to speed up (in case of numerous covariates) we
  261:   compute health expectancies (without variances) in a first step
  262:   and then all the health expectancies with variances or standard
  263:   deviation (needs data from the Hessian matrices) which slows the
  264:   computation.
  265:   In the future we should be able to stop the program is only health
  266:   expectancies and graph are needed without standard deviations.
  267: 
  268:   Revision 1.126  2006/04/28 17:23:28  brouard
  269:   (Module): Yes the sum of survivors was wrong since
  270:   imach-114 because nhstepm was no more computed in the age
  271:   loop. Now we define nhstepma in the age loop.
  272:   Version 0.98h
  273: 
  274:   Revision 1.125  2006/04/04 15:20:31  lievre
  275:   Errors in calculation of health expectancies. Age was not initialized.
  276:   Forecasting file added.
  277: 
  278:   Revision 1.124  2006/03/22 17:13:53  lievre
  279:   Parameters are printed with %lf instead of %f (more numbers after the comma).
  280:   The log-likelihood is printed in the log file
  281: 
  282:   Revision 1.123  2006/03/20 10:52:43  brouard
  283:   * imach.c (Module): <title> changed, corresponds to .htm file
  284:   name. <head> headers where missing.
  285: 
  286:   * imach.c (Module): Weights can have a decimal point as for
  287:   English (a comma might work with a correct LC_NUMERIC environment,
  288:   otherwise the weight is truncated).
  289:   Modification of warning when the covariates values are not 0 or
  290:   1.
  291:   Version 0.98g
  292: 
  293:   Revision 1.122  2006/03/20 09:45:41  brouard
  294:   (Module): Weights can have a decimal point as for
  295:   English (a comma might work with a correct LC_NUMERIC environment,
  296:   otherwise the weight is truncated).
  297:   Modification of warning when the covariates values are not 0 or
  298:   1.
  299:   Version 0.98g
  300: 
  301:   Revision 1.121  2006/03/16 17:45:01  lievre
  302:   * imach.c (Module): Comments concerning covariates added
  303: 
  304:   * imach.c (Module): refinements in the computation of lli if
  305:   status=-2 in order to have more reliable computation if stepm is
  306:   not 1 month. Version 0.98f
  307: 
  308:   Revision 1.120  2006/03/16 15:10:38  lievre
  309:   (Module): refinements in the computation of lli if
  310:   status=-2 in order to have more reliable computation if stepm is
  311:   not 1 month. Version 0.98f
  312: 
  313:   Revision 1.119  2006/03/15 17:42:26  brouard
  314:   (Module): Bug if status = -2, the loglikelihood was
  315:   computed as likelihood omitting the logarithm. Version O.98e
  316: 
  317:   Revision 1.118  2006/03/14 18:20:07  brouard
  318:   (Module): varevsij Comments added explaining the second
  319:   table of variances if popbased=1 .
  320:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  321:   (Module): Function pstamp added
  322:   (Module): Version 0.98d
  323: 
  324:   Revision 1.117  2006/03/14 17:16:22  brouard
  325:   (Module): varevsij Comments added explaining the second
  326:   table of variances if popbased=1 .
  327:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  328:   (Module): Function pstamp added
  329:   (Module): Version 0.98d
  330: 
  331:   Revision 1.116  2006/03/06 10:29:27  brouard
  332:   (Module): Variance-covariance wrong links and
  333:   varian-covariance of ej. is needed (Saito).
  334: 
  335:   Revision 1.115  2006/02/27 12:17:45  brouard
  336:   (Module): One freematrix added in mlikeli! 0.98c
  337: 
  338:   Revision 1.114  2006/02/26 12:57:58  brouard
  339:   (Module): Some improvements in processing parameter
  340:   filename with strsep.
  341: 
  342:   Revision 1.113  2006/02/24 14:20:24  brouard
  343:   (Module): Memory leaks checks with valgrind and:
  344:   datafile was not closed, some imatrix were not freed and on matrix
  345:   allocation too.
  346: 
  347:   Revision 1.112  2006/01/30 09:55:26  brouard
  348:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
  349: 
  350:   Revision 1.111  2006/01/25 20:38:18  brouard
  351:   (Module): Lots of cleaning and bugs added (Gompertz)
  352:   (Module): Comments can be added in data file. Missing date values
  353:   can be a simple dot '.'.
  354: 
  355:   Revision 1.110  2006/01/25 00:51:50  brouard
  356:   (Module): Lots of cleaning and bugs added (Gompertz)
  357: 
  358:   Revision 1.109  2006/01/24 19:37:15  brouard
  359:   (Module): Comments (lines starting with a #) are allowed in data.
  360: 
  361:   Revision 1.108  2006/01/19 18:05:42  lievre
  362:   Gnuplot problem appeared...
  363:   To be fixed
  364: 
  365:   Revision 1.107  2006/01/19 16:20:37  brouard
  366:   Test existence of gnuplot in imach path
  367: 
  368:   Revision 1.106  2006/01/19 13:24:36  brouard
  369:   Some cleaning and links added in html output
  370: 
  371:   Revision 1.105  2006/01/05 20:23:19  lievre
  372:   *** empty log message ***
  373: 
  374:   Revision 1.104  2005/09/30 16:11:43  lievre
  375:   (Module): sump fixed, loop imx fixed, and simplifications.
  376:   (Module): If the status is missing at the last wave but we know
  377:   that the person is alive, then we can code his/her status as -2
  378:   (instead of missing=-1 in earlier versions) and his/her
  379:   contributions to the likelihood is 1 - Prob of dying from last
  380:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
  381:   the healthy state at last known wave). Version is 0.98
  382: 
  383:   Revision 1.103  2005/09/30 15:54:49  lievre
  384:   (Module): sump fixed, loop imx fixed, and simplifications.
  385: 
  386:   Revision 1.102  2004/09/15 17:31:30  brouard
  387:   Add the possibility to read data file including tab characters.
  388: 
  389:   Revision 1.101  2004/09/15 10:38:38  brouard
  390:   Fix on curr_time
  391: 
  392:   Revision 1.100  2004/07/12 18:29:06  brouard
  393:   Add version for Mac OS X. Just define UNIX in Makefile
  394: 
  395:   Revision 1.99  2004/06/05 08:57:40  brouard
  396:   *** empty log message ***
  397: 
  398:   Revision 1.98  2004/05/16 15:05:56  brouard
  399:   New version 0.97 . First attempt to estimate force of mortality
  400:   directly from the data i.e. without the need of knowing the health
  401:   state at each age, but using a Gompertz model: log u =a + b*age .
  402:   This is the basic analysis of mortality and should be done before any
  403:   other analysis, in order to test if the mortality estimated from the
  404:   cross-longitudinal survey is different from the mortality estimated
  405:   from other sources like vital statistic data.
  406: 
  407:   The same imach parameter file can be used but the option for mle should be -3.
  408: 
  409:   Agnès, who wrote this part of the code, tried to keep most of the
  410:   former routines in order to include the new code within the former code.
  411: 
  412:   The output is very simple: only an estimate of the intercept and of
  413:   the slope with 95% confident intervals.
  414: 
  415:   Current limitations:
  416:   A) Even if you enter covariates, i.e. with the
  417:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
  418:   B) There is no computation of Life Expectancy nor Life Table.
  419: 
  420:   Revision 1.97  2004/02/20 13:25:42  lievre
  421:   Version 0.96d. Population forecasting command line is (temporarily)
  422:   suppressed.
  423: 
  424:   Revision 1.96  2003/07/15 15:38:55  brouard
  425:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
  426:   rewritten within the same printf. Workaround: many printfs.
  427: 
  428:   Revision 1.95  2003/07/08 07:54:34  brouard
  429:   * imach.c (Repository):
  430:   (Repository): Using imachwizard code to output a more meaningful covariance
  431:   matrix (cov(a12,c31) instead of numbers.
  432: 
  433:   Revision 1.94  2003/06/27 13:00:02  brouard
  434:   Just cleaning
  435: 
  436:   Revision 1.93  2003/06/25 16:33:55  brouard
  437:   (Module): On windows (cygwin) function asctime_r doesn't
  438:   exist so I changed back to asctime which exists.
  439:   (Module): Version 0.96b
  440: 
  441:   Revision 1.92  2003/06/25 16:30:45  brouard
  442:   (Module): On windows (cygwin) function asctime_r doesn't
  443:   exist so I changed back to asctime which exists.
  444: 
  445:   Revision 1.91  2003/06/25 15:30:29  brouard
  446:   * imach.c (Repository): Duplicated warning errors corrected.
  447:   (Repository): Elapsed time after each iteration is now output. It
  448:   helps to forecast when convergence will be reached. Elapsed time
  449:   is stamped in powell.  We created a new html file for the graphs
  450:   concerning matrix of covariance. It has extension -cov.htm.
  451: 
  452:   Revision 1.90  2003/06/24 12:34:15  brouard
  453:   (Module): Some bugs corrected for windows. Also, when
  454:   mle=-1 a template is output in file "or"mypar.txt with the design
  455:   of the covariance matrix to be input.
  456: 
  457:   Revision 1.89  2003/06/24 12:30:52  brouard
  458:   (Module): Some bugs corrected for windows. Also, when
  459:   mle=-1 a template is output in file "or"mypar.txt with the design
  460:   of the covariance matrix to be input.
  461: 
  462:   Revision 1.88  2003/06/23 17:54:56  brouard
  463:   * 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.
  464: 
  465:   Revision 1.87  2003/06/18 12:26:01  brouard
  466:   Version 0.96
  467: 
  468:   Revision 1.86  2003/06/17 20:04:08  brouard
  469:   (Module): Change position of html and gnuplot routines and added
  470:   routine fileappend.
  471: 
  472:   Revision 1.85  2003/06/17 13:12:43  brouard
  473:   * imach.c (Repository): Check when date of death was earlier that
  474:   current date of interview. It may happen when the death was just
  475:   prior to the death. In this case, dh was negative and likelihood
  476:   was wrong (infinity). We still send an "Error" but patch by
  477:   assuming that the date of death was just one stepm after the
  478:   interview.
  479:   (Repository): Because some people have very long ID (first column)
  480:   we changed int to long in num[] and we added a new lvector for
  481:   memory allocation. But we also truncated to 8 characters (left
  482:   truncation)
  483:   (Repository): No more line truncation errors.
  484: 
  485:   Revision 1.84  2003/06/13 21:44:43  brouard
  486:   * imach.c (Repository): Replace "freqsummary" at a correct
  487:   place. It differs from routine "prevalence" which may be called
  488:   many times. Probs is memory consuming and must be used with
  489:   parcimony.
  490:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
  491: 
  492:   Revision 1.83  2003/06/10 13:39:11  lievre
  493:   *** empty log message ***
  494: 
  495:   Revision 1.82  2003/06/05 15:57:20  brouard
  496:   Add log in  imach.c and  fullversion number is now printed.
  497: 
  498: */
  499: /*
  500:    Interpolated Markov Chain
  501: 
  502:   Short summary of the programme:
  503:   
  504:   This program computes Healthy Life Expectancies from
  505:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
  506:   first survey ("cross") where individuals from different ages are
  507:   interviewed on their health status or degree of disability (in the
  508:   case of a health survey which is our main interest) -2- at least a
  509:   second wave of interviews ("longitudinal") which measure each change
  510:   (if any) in individual health status.  Health expectancies are
  511:   computed from the time spent in each health state according to a
  512:   model. More health states you consider, more time is necessary to reach the
  513:   Maximum Likelihood of the parameters involved in the model.  The
  514:   simplest model is the multinomial logistic model where pij is the
  515:   probability to be observed in state j at the second wave
  516:   conditional to be observed in state i at the first wave. Therefore
  517:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
  518:   'age' is age and 'sex' is a covariate. If you want to have a more
  519:   complex model than "constant and age", you should modify the program
  520:   where the markup *Covariates have to be included here again* invites
  521:   you to do it.  More covariates you add, slower the
  522:   convergence.
  523: 
  524:   The advantage of this computer programme, compared to a simple
  525:   multinomial logistic model, is clear when the delay between waves is not
  526:   identical for each individual. Also, if a individual missed an
  527:   intermediate interview, the information is lost, but taken into
  528:   account using an interpolation or extrapolation.  
  529: 
  530:   hPijx is the probability to be observed in state i at age x+h
  531:   conditional to the observed state i at age x. The delay 'h' can be
  532:   split into an exact number (nh*stepm) of unobserved intermediate
  533:   states. This elementary transition (by month, quarter,
  534:   semester or year) is modelled as a multinomial logistic.  The hPx
  535:   matrix is simply the matrix product of nh*stepm elementary matrices
  536:   and the contribution of each individual to the likelihood is simply
  537:   hPijx.
  538: 
  539:   Also this programme outputs the covariance matrix of the parameters but also
  540:   of the life expectancies. It also computes the period (stable) prevalence. 
  541:   
  542:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
  543:            Institut national d'études démographiques, Paris.
  544:   This software have been partly granted by Euro-REVES, a concerted action
  545:   from the European Union.
  546:   It is copyrighted identically to a GNU software product, ie programme and
  547:   software can be distributed freely for non commercial use. Latest version
  548:   can be accessed at http://euroreves.ined.fr/imach .
  549: 
  550:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
  551:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
  552:   
  553:   **********************************************************************/
  554: /*
  555:   main
  556:   read parameterfile
  557:   read datafile
  558:   concatwav
  559:   freqsummary
  560:   if (mle >= 1)
  561:     mlikeli
  562:   print results files
  563:   if mle==1 
  564:      computes hessian
  565:   read end of parameter file: agemin, agemax, bage, fage, estepm
  566:       begin-prev-date,...
  567:   open gnuplot file
  568:   open html file
  569:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
  570:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
  571:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
  572:     freexexit2 possible for memory heap.
  573: 
  574:   h Pij x                         | pij_nom  ficrestpij
  575:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
  576:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
  577:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
  578: 
  579:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
  580:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
  581:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
  582:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
  583:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
  584: 
  585:   forecasting if prevfcast==1 prevforecast call prevalence()
  586:   health expectancies
  587:   Variance-covariance of DFLE
  588:   prevalence()
  589:    movingaverage()
  590:   varevsij() 
  591:   if popbased==1 varevsij(,popbased)
  592:   total life expectancies
  593:   Variance of period (stable) prevalence
  594:  end
  595: */
  596: 
  597: /* #define DEBUG */
  598: /* #define DEBUGBRENT */
  599: #define POWELL /* Instead of NLOPT */
  600: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
  601: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
  602: 
  603: #include <math.h>
  604: #include <stdio.h>
  605: #include <stdlib.h>
  606: #include <string.h>
  607: 
  608: #ifdef _WIN32
  609: #include <io.h>
  610: #include <windows.h>
  611: #include <tchar.h>
  612: #else
  613: #include <unistd.h>
  614: #endif
  615: 
  616: #include <limits.h>
  617: #include <sys/types.h>
  618: 
  619: #if defined(__GNUC__)
  620: #include <sys/utsname.h> /* Doesn't work on Windows */
  621: #endif
  622: 
  623: #include <sys/stat.h>
  624: #include <errno.h>
  625: /* extern int errno; */
  626: 
  627: /* #ifdef LINUX */
  628: /* #include <time.h> */
  629: /* #include "timeval.h" */
  630: /* #else */
  631: /* #include <sys/time.h> */
  632: /* #endif */
  633: 
  634: #include <time.h>
  635: 
  636: #ifdef GSL
  637: #include <gsl/gsl_errno.h>
  638: #include <gsl/gsl_multimin.h>
  639: #endif
  640: 
  641: 
  642: #ifdef NLOPT
  643: #include <nlopt.h>
  644: typedef struct {
  645:   double (* function)(double [] );
  646: } myfunc_data ;
  647: #endif
  648: 
  649: /* #include <libintl.h> */
  650: /* #define _(String) gettext (String) */
  651: 
  652: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
  653: 
  654: #define GNUPLOTPROGRAM "gnuplot"
  655: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
  656: #define FILENAMELENGTH 132
  657: 
  658: #define	GLOCK_ERROR_NOPATH		-1	/* empty path */
  659: #define	GLOCK_ERROR_GETCWD		-2	/* cannot get cwd */
  660: 
  661: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
  662: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
  663: 
  664: #define NINTERVMAX 8
  665: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
  666: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
  667: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
  668: #define codtabm(h,k)  1 & (h-1) >> (k-1) ;
  669: #define MAXN 20000
  670: #define YEARM 12. /**< Number of months per year */
  671: #define AGESUP 130
  672: #define AGEBASE 40
  673: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
  674: #ifdef _WIN32
  675: #define DIRSEPARATOR '\\'
  676: #define CHARSEPARATOR "\\"
  677: #define ODIRSEPARATOR '/'
  678: #else
  679: #define DIRSEPARATOR '/'
  680: #define CHARSEPARATOR "/"
  681: #define ODIRSEPARATOR '\\'
  682: #endif
  683: 
  684: /* $Id: imach.c,v 1.189 2015/04/30 14:45:16 brouard Exp $ */
  685: /* $State: Exp $ */
  686: 
  687: char version[]="Imach version 0.98q2, April 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
  688: char fullversion[]="$Revision: 1.189 $ $Date: 2015/04/30 14:45:16 $"; 
  689: char strstart[80];
  690: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
  691: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
  692: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
  693: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
  694: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
  695: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
  696: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
  697: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
  698: int cptcovprodnoage=0; /**< Number of covariate products without age */   
  699: int cptcoveff=0; /* Total number of covariates to vary for printing results */
  700: int cptcov=0; /* Working variable */
  701: int npar=NPARMAX;
  702: int nlstate=2; /* Number of live states */
  703: int ndeath=1; /* Number of dead states */
  704: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
  705: int popbased=0;
  706: 
  707: int *wav; /* Number of waves for this individuual 0 is possible */
  708: int maxwav=0; /* Maxim number of waves */
  709: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
  710: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
  711: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
  712: 		   to the likelihood and the sum of weights (done by funcone)*/
  713: int mle=1, weightopt=0;
  714: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
  715: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
  716: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
  717: 	   * wave mi and wave mi+1 is not an exact multiple of stepm. */
  718: int countcallfunc=0;  /* Count the number of calls to func */
  719: double jmean=1; /* Mean space between 2 waves */
  720: double **matprod2(); /* test */
  721: double **oldm, **newm, **savm; /* Working pointers to matrices */
  722: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
  723: /*FILE *fic ; */ /* Used in readdata only */
  724: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
  725: FILE *ficlog, *ficrespow;
  726: int globpr=0; /* Global variable for printing or not */
  727: double fretone; /* Only one call to likelihood */
  728: long ipmx=0; /* Number of contributions */
  729: double sw; /* Sum of weights */
  730: char filerespow[FILENAMELENGTH];
  731: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
  732: FILE *ficresilk;
  733: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
  734: FILE *ficresprobmorprev;
  735: FILE *fichtm, *fichtmcov; /* Html File */
  736: FILE *ficreseij;
  737: char filerese[FILENAMELENGTH];
  738: FILE *ficresstdeij;
  739: char fileresstde[FILENAMELENGTH];
  740: FILE *ficrescveij;
  741: char filerescve[FILENAMELENGTH];
  742: FILE  *ficresvij;
  743: char fileresv[FILENAMELENGTH];
  744: FILE  *ficresvpl;
  745: char fileresvpl[FILENAMELENGTH];
  746: char title[MAXLINE];
  747: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
  748: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
  749: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
  750: char command[FILENAMELENGTH];
  751: int  outcmd=0;
  752: 
  753: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
  754: 
  755: char filelog[FILENAMELENGTH]; /* Log file */
  756: char filerest[FILENAMELENGTH];
  757: char fileregp[FILENAMELENGTH];
  758: char popfile[FILENAMELENGTH];
  759: 
  760: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
  761: 
  762: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
  763: /* struct timezone tzp; */
  764: /* extern int gettimeofday(); */
  765: struct tm tml, *gmtime(), *localtime();
  766: 
  767: extern time_t time();
  768: 
  769: struct tm start_time, end_time, curr_time, last_time, forecast_time;
  770: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
  771: struct tm tm;
  772: 
  773: char strcurr[80], strfor[80];
  774: 
  775: char *endptr;
  776: long lval;
  777: double dval;
  778: 
  779: #define NR_END 1
  780: #define FREE_ARG char*
  781: #define FTOL 1.0e-10
  782: 
  783: #define NRANSI 
  784: #define ITMAX 200 
  785: 
  786: #define TOL 2.0e-4 
  787: 
  788: #define CGOLD 0.3819660 
  789: #define ZEPS 1.0e-10 
  790: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
  791: 
  792: #define GOLD 1.618034 
  793: #define GLIMIT 100.0 
  794: #define TINY 1.0e-20 
  795: 
  796: static double maxarg1,maxarg2;
  797: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
  798: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
  799:   
  800: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
  801: #define rint(a) floor(a+0.5)
  802: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
  803: #define mytinydouble 1.0e-16
  804: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
  805: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
  806: /* static double dsqrarg; */
  807: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
  808: static double sqrarg;
  809: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
  810: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
  811: int agegomp= AGEGOMP;
  812: 
  813: int imx; 
  814: int stepm=1;
  815: /* Stepm, step in month: minimum step interpolation*/
  816: 
  817: int estepm;
  818: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
  819: 
  820: int m,nb;
  821: long *num;
  822: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
  823: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
  824: double **pmmij, ***probs;
  825: double *ageexmed,*agecens;
  826: double dateintmean=0;
  827: 
  828: double *weight;
  829: int **s; /* Status */
  830: double *agedc;
  831: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
  832: 		  * covar=matrix(0,NCOVMAX,1,n); 
  833: 		  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
  834: double  idx; 
  835: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
  836: int *Ndum; /** Freq of modality (tricode */
  837: int **codtab; /**< codtab=imatrix(1,100,1,10); */
  838: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
  839: double *lsurv, *lpop, *tpop;
  840: 
  841: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
  842: double ftolhess; /**< Tolerance for computing hessian */
  843: 
  844: /**************** split *************************/
  845: static	int split( char *path, char *dirc, char *name, char *ext, char *finame )
  846: {
  847:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
  848:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
  849:   */ 
  850:   char	*ss;				/* pointer */
  851:   int	l1=0, l2=0;				/* length counters */
  852: 
  853:   l1 = strlen(path );			/* length of path */
  854:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
  855:   ss= strrchr( path, DIRSEPARATOR );		/* find last / */
  856:   if ( ss == NULL ) {			/* no directory, so determine current directory */
  857:     strcpy( name, path );		/* we got the fullname name because no directory */
  858:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
  859:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
  860:     /* get current working directory */
  861:     /*    extern  char* getcwd ( char *buf , int len);*/
  862: #ifdef WIN32
  863:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
  864: #else
  865: 	if (getcwd(dirc, FILENAME_MAX) == NULL) {
  866: #endif
  867:       return( GLOCK_ERROR_GETCWD );
  868:     }
  869:     /* got dirc from getcwd*/
  870:     printf(" DIRC = %s \n",dirc);
  871:   } else {				/* strip direcotry from path */
  872:     ss++;				/* after this, the filename */
  873:     l2 = strlen( ss );			/* length of filename */
  874:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
  875:     strcpy( name, ss );		/* save file name */
  876:     strncpy( dirc, path, l1 - l2 );	/* now the directory */
  877:     dirc[l1-l2] = '\0';			/* add zero */
  878:     printf(" DIRC2 = %s \n",dirc);
  879:   }
  880:   /* We add a separator at the end of dirc if not exists */
  881:   l1 = strlen( dirc );			/* length of directory */
  882:   if( dirc[l1-1] != DIRSEPARATOR ){
  883:     dirc[l1] =  DIRSEPARATOR;
  884:     dirc[l1+1] = 0; 
  885:     printf(" DIRC3 = %s \n",dirc);
  886:   }
  887:   ss = strrchr( name, '.' );		/* find last / */
  888:   if (ss >0){
  889:     ss++;
  890:     strcpy(ext,ss);			/* save extension */
  891:     l1= strlen( name);
  892:     l2= strlen(ss)+1;
  893:     strncpy( finame, name, l1-l2);
  894:     finame[l1-l2]= 0;
  895:   }
  896: 
  897:   return( 0 );				/* we're done */
  898: }
  899: 
  900: 
  901: /******************************************/
  902: 
  903: void replace_back_to_slash(char *s, char*t)
  904: {
  905:   int i;
  906:   int lg=0;
  907:   i=0;
  908:   lg=strlen(t);
  909:   for(i=0; i<= lg; i++) {
  910:     (s[i] = t[i]);
  911:     if (t[i]== '\\') s[i]='/';
  912:   }
  913: }
  914: 
  915: char *trimbb(char *out, char *in)
  916: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
  917:   char *s;
  918:   s=out;
  919:   while (*in != '\0'){
  920:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
  921:       in++;
  922:     }
  923:     *out++ = *in++;
  924:   }
  925:   *out='\0';
  926:   return s;
  927: }
  928: 
  929: /* char *substrchaine(char *out, char *in, char *chain) */
  930: /* { */
  931: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
  932: /*   char *s, *t; */
  933: /*   t=in;s=out; */
  934: /*   while ((*in != *chain) && (*in != '\0')){ */
  935: /*     *out++ = *in++; */
  936: /*   } */
  937: 
  938: /*   /\* *in matches *chain *\/ */
  939: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
  940: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
  941: /*   } */
  942: /*   in--; chain--; */
  943: /*   while ( (*in != '\0')){ */
  944: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
  945: /*     *out++ = *in++; */
  946: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
  947: /*   } */
  948: /*   *out='\0'; */
  949: /*   out=s; */
  950: /*   return out; */
  951: /* } */
  952: char *substrchaine(char *out, char *in, char *chain)
  953: {
  954:   /* Substract chain 'chain' from 'in', return and output 'out' */
  955:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
  956: 
  957:   char *strloc;
  958: 
  959:   strcpy (out, in); 
  960:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
  961:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
  962:   if(strloc != NULL){ 
  963:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
  964:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
  965:     /* strcpy (strloc, strloc +strlen(chain));*/
  966:   }
  967:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
  968:   return out;
  969: }
  970: 
  971: 
  972: char *cutl(char *blocc, char *alocc, char *in, char occ)
  973: {
  974:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
  975:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
  976:      gives blocc="abcdef" and alocc="ghi2j".
  977:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
  978:   */
  979:   char *s, *t;
  980:   t=in;s=in;
  981:   while ((*in != occ) && (*in != '\0')){
  982:     *alocc++ = *in++;
  983:   }
  984:   if( *in == occ){
  985:     *(alocc)='\0';
  986:     s=++in;
  987:   }
  988:  
  989:   if (s == t) {/* occ not found */
  990:     *(alocc-(in-s))='\0';
  991:     in=s;
  992:   }
  993:   while ( *in != '\0'){
  994:     *blocc++ = *in++;
  995:   }
  996: 
  997:   *blocc='\0';
  998:   return t;
  999: }
 1000: char *cutv(char *blocc, char *alocc, char *in, char occ)
 1001: {
 1002:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
 1003:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
 1004:      gives blocc="abcdef2ghi" and alocc="j".
 1005:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
 1006:   */
 1007:   char *s, *t;
 1008:   t=in;s=in;
 1009:   while (*in != '\0'){
 1010:     while( *in == occ){
 1011:       *blocc++ = *in++;
 1012:       s=in;
 1013:     }
 1014:     *blocc++ = *in++;
 1015:   }
 1016:   if (s == t) /* occ not found */
 1017:     *(blocc-(in-s))='\0';
 1018:   else
 1019:     *(blocc-(in-s)-1)='\0';
 1020:   in=s;
 1021:   while ( *in != '\0'){
 1022:     *alocc++ = *in++;
 1023:   }
 1024: 
 1025:   *alocc='\0';
 1026:   return s;
 1027: }
 1028: 
 1029: int nbocc(char *s, char occ)
 1030: {
 1031:   int i,j=0;
 1032:   int lg=20;
 1033:   i=0;
 1034:   lg=strlen(s);
 1035:   for(i=0; i<= lg; i++) {
 1036:   if  (s[i] == occ ) j++;
 1037:   }
 1038:   return j;
 1039: }
 1040: 
 1041: /* void cutv(char *u,char *v, char*t, char occ) */
 1042: /* { */
 1043: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
 1044: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
 1045: /*      gives u="abcdef2ghi" and v="j" *\/ */
 1046: /*   int i,lg,j,p=0; */
 1047: /*   i=0; */
 1048: /*   lg=strlen(t); */
 1049: /*   for(j=0; j<=lg-1; j++) { */
 1050: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
 1051: /*   } */
 1052: 
 1053: /*   for(j=0; j<p; j++) { */
 1054: /*     (u[j] = t[j]); */
 1055: /*   } */
 1056: /*      u[p]='\0'; */
 1057: 
 1058: /*    for(j=0; j<= lg; j++) { */
 1059: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
 1060: /*   } */
 1061: /* } */
 1062: 
 1063: #ifdef _WIN32
 1064: char * strsep(char **pp, const char *delim)
 1065: {
 1066:   char *p, *q;
 1067:          
 1068:   if ((p = *pp) == NULL)
 1069:     return 0;
 1070:   if ((q = strpbrk (p, delim)) != NULL)
 1071:   {
 1072:     *pp = q + 1;
 1073:     *q = '\0';
 1074:   }
 1075:   else
 1076:     *pp = 0;
 1077:   return p;
 1078: }
 1079: #endif
 1080: 
 1081: /********************** nrerror ********************/
 1082: 
 1083: void nrerror(char error_text[])
 1084: {
 1085:   fprintf(stderr,"ERREUR ...\n");
 1086:   fprintf(stderr,"%s\n",error_text);
 1087:   exit(EXIT_FAILURE);
 1088: }
 1089: /*********************** vector *******************/
 1090: double *vector(int nl, int nh)
 1091: {
 1092:   double *v;
 1093:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
 1094:   if (!v) nrerror("allocation failure in vector");
 1095:   return v-nl+NR_END;
 1096: }
 1097: 
 1098: /************************ free vector ******************/
 1099: void free_vector(double*v, int nl, int nh)
 1100: {
 1101:   free((FREE_ARG)(v+nl-NR_END));
 1102: }
 1103: 
 1104: /************************ivector *******************************/
 1105: int *ivector(long nl,long nh)
 1106: {
 1107:   int *v;
 1108:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
 1109:   if (!v) nrerror("allocation failure in ivector");
 1110:   return v-nl+NR_END;
 1111: }
 1112: 
 1113: /******************free ivector **************************/
 1114: void free_ivector(int *v, long nl, long nh)
 1115: {
 1116:   free((FREE_ARG)(v+nl-NR_END));
 1117: }
 1118: 
 1119: /************************lvector *******************************/
 1120: long *lvector(long nl,long nh)
 1121: {
 1122:   long *v;
 1123:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
 1124:   if (!v) nrerror("allocation failure in ivector");
 1125:   return v-nl+NR_END;
 1126: }
 1127: 
 1128: /******************free lvector **************************/
 1129: void free_lvector(long *v, long nl, long nh)
 1130: {
 1131:   free((FREE_ARG)(v+nl-NR_END));
 1132: }
 1133: 
 1134: /******************* imatrix *******************************/
 1135: int **imatrix(long nrl, long nrh, long ncl, long nch) 
 1136:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
 1137: { 
 1138:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
 1139:   int **m; 
 1140:   
 1141:   /* allocate pointers to rows */ 
 1142:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
 1143:   if (!m) nrerror("allocation failure 1 in matrix()"); 
 1144:   m += NR_END; 
 1145:   m -= nrl; 
 1146:   
 1147:   
 1148:   /* allocate rows and set pointers to them */ 
 1149:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
 1150:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
 1151:   m[nrl] += NR_END; 
 1152:   m[nrl] -= ncl; 
 1153:   
 1154:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
 1155:   
 1156:   /* return pointer to array of pointers to rows */ 
 1157:   return m; 
 1158: } 
 1159: 
 1160: /****************** free_imatrix *************************/
 1161: void free_imatrix(m,nrl,nrh,ncl,nch)
 1162:       int **m;
 1163:       long nch,ncl,nrh,nrl; 
 1164:      /* free an int matrix allocated by imatrix() */ 
 1165: { 
 1166:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
 1167:   free((FREE_ARG) (m+nrl-NR_END)); 
 1168: } 
 1169: 
 1170: /******************* matrix *******************************/
 1171: double **matrix(long nrl, long nrh, long ncl, long nch)
 1172: {
 1173:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
 1174:   double **m;
 1175: 
 1176:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1177:   if (!m) nrerror("allocation failure 1 in matrix()");
 1178:   m += NR_END;
 1179:   m -= nrl;
 1180: 
 1181:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1182:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1183:   m[nrl] += NR_END;
 1184:   m[nrl] -= ncl;
 1185: 
 1186:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1187:   return m;
 1188:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
 1189: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
 1190: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
 1191:    */
 1192: }
 1193: 
 1194: /*************************free matrix ************************/
 1195: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
 1196: {
 1197:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1198:   free((FREE_ARG)(m+nrl-NR_END));
 1199: }
 1200: 
 1201: /******************* ma3x *******************************/
 1202: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
 1203: {
 1204:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
 1205:   double ***m;
 1206: 
 1207:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1208:   if (!m) nrerror("allocation failure 1 in matrix()");
 1209:   m += NR_END;
 1210:   m -= nrl;
 1211: 
 1212:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1213:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1214:   m[nrl] += NR_END;
 1215:   m[nrl] -= ncl;
 1216: 
 1217:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1218: 
 1219:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
 1220:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
 1221:   m[nrl][ncl] += NR_END;
 1222:   m[nrl][ncl] -= nll;
 1223:   for (j=ncl+1; j<=nch; j++) 
 1224:     m[nrl][j]=m[nrl][j-1]+nlay;
 1225:   
 1226:   for (i=nrl+1; i<=nrh; i++) {
 1227:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
 1228:     for (j=ncl+1; j<=nch; j++) 
 1229:       m[i][j]=m[i][j-1]+nlay;
 1230:   }
 1231:   return m; 
 1232:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
 1233:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
 1234:   */
 1235: }
 1236: 
 1237: /*************************free ma3x ************************/
 1238: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
 1239: {
 1240:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
 1241:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1242:   free((FREE_ARG)(m+nrl-NR_END));
 1243: }
 1244: 
 1245: /*************** function subdirf ***********/
 1246: char *subdirf(char fileres[])
 1247: {
 1248:   /* Caution optionfilefiname is hidden */
 1249:   strcpy(tmpout,optionfilefiname);
 1250:   strcat(tmpout,"/"); /* Add to the right */
 1251:   strcat(tmpout,fileres);
 1252:   return tmpout;
 1253: }
 1254: 
 1255: /*************** function subdirf2 ***********/
 1256: char *subdirf2(char fileres[], char *preop)
 1257: {
 1258:   
 1259:   /* Caution optionfilefiname is hidden */
 1260:   strcpy(tmpout,optionfilefiname);
 1261:   strcat(tmpout,"/");
 1262:   strcat(tmpout,preop);
 1263:   strcat(tmpout,fileres);
 1264:   return tmpout;
 1265: }
 1266: 
 1267: /*************** function subdirf3 ***********/
 1268: char *subdirf3(char fileres[], char *preop, char *preop2)
 1269: {
 1270:   
 1271:   /* Caution optionfilefiname is hidden */
 1272:   strcpy(tmpout,optionfilefiname);
 1273:   strcat(tmpout,"/");
 1274:   strcat(tmpout,preop);
 1275:   strcat(tmpout,preop2);
 1276:   strcat(tmpout,fileres);
 1277:   return tmpout;
 1278: }
 1279: 
 1280: char *asc_diff_time(long time_sec, char ascdiff[])
 1281: {
 1282:   long sec_left, days, hours, minutes;
 1283:   days = (time_sec) / (60*60*24);
 1284:   sec_left = (time_sec) % (60*60*24);
 1285:   hours = (sec_left) / (60*60) ;
 1286:   sec_left = (sec_left) %(60*60);
 1287:   minutes = (sec_left) /60;
 1288:   sec_left = (sec_left) % (60);
 1289:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
 1290:   return ascdiff;
 1291: }
 1292: 
 1293: /***************** f1dim *************************/
 1294: extern int ncom; 
 1295: extern double *pcom,*xicom;
 1296: extern double (*nrfunc)(double []); 
 1297:  
 1298: double f1dim(double x) 
 1299: { 
 1300:   int j; 
 1301:   double f;
 1302:   double *xt; 
 1303:  
 1304:   xt=vector(1,ncom); 
 1305:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
 1306:   f=(*nrfunc)(xt); 
 1307:   free_vector(xt,1,ncom); 
 1308:   return f; 
 1309: } 
 1310: 
 1311: /*****************brent *************************/
 1312: double brent(double ax, double bx, double cx, double (*f)(double), double tol, 	double *xmin) 
 1313: {
 1314:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
 1315:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
 1316:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
 1317:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
 1318:    * returned function value. 
 1319:   */
 1320:   int iter; 
 1321:   double a,b,d,etemp;
 1322:   double fu=0,fv,fw,fx;
 1323:   double ftemp=0.;
 1324:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
 1325:   double e=0.0; 
 1326:  
 1327:   a=(ax < cx ? ax : cx); 
 1328:   b=(ax > cx ? ax : cx); 
 1329:   x=w=v=bx; 
 1330:   fw=fv=fx=(*f)(x); 
 1331:   for (iter=1;iter<=ITMAX;iter++) { 
 1332:     xm=0.5*(a+b); 
 1333:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
 1334:     /*		if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
 1335:     printf(".");fflush(stdout);
 1336:     fprintf(ficlog,".");fflush(ficlog);
 1337: #ifdef DEBUGBRENT
 1338:     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);
 1339:     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);
 1340:     /*		if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
 1341: #endif
 1342:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
 1343:       *xmin=x; 
 1344:       return fx; 
 1345:     } 
 1346:     ftemp=fu;
 1347:     if (fabs(e) > tol1) { 
 1348:       r=(x-w)*(fx-fv); 
 1349:       q=(x-v)*(fx-fw); 
 1350:       p=(x-v)*q-(x-w)*r; 
 1351:       q=2.0*(q-r); 
 1352:       if (q > 0.0) p = -p; 
 1353:       q=fabs(q); 
 1354:       etemp=e; 
 1355:       e=d; 
 1356:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
 1357: 	d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1358:       else { 
 1359: 	d=p/q; 
 1360: 	u=x+d; 
 1361: 	if (u-a < tol2 || b-u < tol2) 
 1362: 	  d=SIGN(tol1,xm-x); 
 1363:       } 
 1364:     } else { 
 1365:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1366:     } 
 1367:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
 1368:     fu=(*f)(u); 
 1369:     if (fu <= fx) { 
 1370:       if (u >= x) a=x; else b=x; 
 1371:       SHFT(v,w,x,u) 
 1372:       SHFT(fv,fw,fx,fu) 
 1373:     } else { 
 1374:       if (u < x) a=u; else b=u; 
 1375:       if (fu <= fw || w == x) { 
 1376: 	v=w; 
 1377: 	w=u; 
 1378: 	fv=fw; 
 1379: 	fw=fu; 
 1380:       } else if (fu <= fv || v == x || v == w) { 
 1381: 	v=u; 
 1382: 	fv=fu; 
 1383:       } 
 1384:     } 
 1385:   } 
 1386:   nrerror("Too many iterations in brent"); 
 1387:   *xmin=x; 
 1388:   return fx; 
 1389: } 
 1390: 
 1391: /****************** mnbrak ***********************/
 1392: 
 1393: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
 1394: 	    double (*func)(double)) 
 1395: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
 1396: the downhill direction (defined by the function as evaluated at the initial points) and returns
 1397: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
 1398: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
 1399:    */
 1400:   double ulim,u,r,q, dum;
 1401:   double fu; 
 1402: 
 1403:   double scale=10.;
 1404:   int iterscale=0;
 1405: 
 1406:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
 1407:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
 1408: 
 1409: 
 1410:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
 1411:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
 1412:   /*   *bx = *ax - (*ax - *bx)/scale; */
 1413:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
 1414:   /* } */
 1415: 
 1416:   if (*fb > *fa) { 
 1417:     SHFT(dum,*ax,*bx,dum) 
 1418:     SHFT(dum,*fb,*fa,dum) 
 1419:   } 
 1420:   *cx=(*bx)+GOLD*(*bx-*ax); 
 1421:   *fc=(*func)(*cx); 
 1422: #ifdef DEBUG
 1423:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
 1424:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
 1425: #endif
 1426:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
 1427:     r=(*bx-*ax)*(*fb-*fc); 
 1428:     q=(*bx-*cx)*(*fb-*fa); 
 1429:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
 1430:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
 1431:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
 1432:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
 1433:       fu=(*func)(u); 
 1434: #ifdef DEBUG
 1435:       /* f(x)=A(x-u)**2+f(u) */
 1436:       double A, fparabu; 
 1437:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 1438:       fparabu= *fa - A*(*ax-u)*(*ax-u);
 1439:       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);
 1440:       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);
 1441:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
 1442:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
 1443:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
 1444:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
 1445: #endif 
 1446: #ifdef MNBRAKORIGINAL
 1447: #else
 1448:       if (fu > *fc) {
 1449: #ifdef DEBUG
 1450:       printf("mnbrak4  fu > fc \n");
 1451:       fprintf(ficlog, "mnbrak4 fu > fc\n");
 1452: #endif
 1453: 	/* 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 *\/  */
 1454: 	/* SHFT(*fa,*fc,fu,*fc) /\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\/ */
 1455: 	dum=u; /* Shifting c and u */
 1456: 	u = *cx;
 1457: 	*cx = dum;
 1458: 	dum = fu;
 1459: 	fu = *fc;
 1460: 	*fc =dum;
 1461:       } else { /* end */
 1462: #ifdef DEBUG
 1463:       printf("mnbrak3  fu < fc \n");
 1464:       fprintf(ficlog, "mnbrak3 fu < fc\n");
 1465: #endif
 1466: 	dum=u; /* Shifting c and u */
 1467: 	u = *cx;
 1468: 	*cx = dum;
 1469: 	dum = fu;
 1470: 	fu = *fc;
 1471: 	*fc =dum;
 1472:       }
 1473: #endif
 1474:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
 1475: #ifdef DEBUG
 1476:       printf("mnbrak2  u after c but before ulim\n");
 1477:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
 1478: #endif
 1479:       fu=(*func)(u); 
 1480:       if (fu < *fc) { 
 1481: #ifdef DEBUG
 1482:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
 1483:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
 1484: #endif
 1485: 	SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
 1486: 	SHFT(*fb,*fc,fu,(*func)(u)) 
 1487:       } 
 1488:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
 1489: #ifdef DEBUG
 1490:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
 1491:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
 1492: #endif
 1493:       u=ulim; 
 1494:       fu=(*func)(u); 
 1495:     } else { /* u could be left to b (if r > q parabola has a maximum) */
 1496: #ifdef DEBUG
 1497:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
 1498:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
 1499: #endif
 1500:       u=(*cx)+GOLD*(*cx-*bx); 
 1501:       fu=(*func)(u); 
 1502:     } /* end tests */
 1503:     SHFT(*ax,*bx,*cx,u) 
 1504:     SHFT(*fa,*fb,*fc,fu) 
 1505: #ifdef DEBUG
 1506:       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);
 1507:       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);
 1508: #endif
 1509:   } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
 1510: } 
 1511: 
 1512: /*************** linmin ************************/
 1513: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
 1514: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
 1515: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
 1516: the value of func at the returned location p . This is actually all accomplished by calling the
 1517: routines mnbrak and brent .*/
 1518: int ncom; 
 1519: double *pcom,*xicom;
 1520: double (*nrfunc)(double []); 
 1521:  
 1522: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
 1523: { 
 1524:   double brent(double ax, double bx, double cx, 
 1525: 	       double (*f)(double), double tol, double *xmin); 
 1526:   double f1dim(double x); 
 1527:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
 1528: 	      double *fc, double (*func)(double)); 
 1529:   int j; 
 1530:   double xx,xmin,bx,ax; 
 1531:   double fx,fb,fa;
 1532: 
 1533:   double scale=10., axs, xxs, xxss; /* Scale added for infinity */
 1534:  
 1535:   ncom=n; 
 1536:   pcom=vector(1,n); 
 1537:   xicom=vector(1,n); 
 1538:   nrfunc=func; 
 1539:   for (j=1;j<=n;j++) { 
 1540:     pcom[j]=p[j]; 
 1541:     xicom[j]=xi[j]; 
 1542:   } 
 1543: 
 1544:   axs=0.0;
 1545:   xxss=1; /* 1 and using scale */
 1546:   xxs=1;
 1547:   do{
 1548:     ax=0.;
 1549:     xx= xxs;
 1550:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
 1551:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
 1552:     /* xt[x,j]=pcom[j]+x*xicom[j]  f(ax) = f(xt(a,j=1,n)) = f(p(j) + 0 * xi(j)) and  f(xx) = f(xt(x, j=1,n)) = f(p(j) + 1 * xi(j))   */
 1553:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
 1554:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
 1555:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
 1556:     /* Find a bracket a,x,b in direction n=xi ie xicom, order may change. Scale is [0:xxs*xi[j]] et non plus  [0:xi[j]]*/
 1557:     if (fx != fx){
 1558: 	xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
 1559: 	printf("\nLinmin NAN : input [axs=%lf:xxs=%lf], mnbrak outputs fx=%lf <(fb=%lf and fa=%lf) with xx=%lf in [ax=%lf:bx=%lf] \n",  axs, xxs, fx,fb, fa, xx, ax, bx);
 1560:     }
 1561:   }while(fx != fx);
 1562: 
 1563:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
 1564:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
 1565:   /* fmin = f(p[j] + xmin * xi[j]) */
 1566:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
 1567:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
 1568: #ifdef DEBUG
 1569:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1570:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1571: #endif
 1572:   /* printf("linmin end "); */
 1573:   for (j=1;j<=n;j++) { 
 1574:     /* printf(" before xi[%d]=%12.8f", j,xi[j]); */
 1575:     xi[j] *= xmin; /* xi rescaled by xmin: if xmin=-1.237 and xi=(1,0,...,0) xi=(-1.237,0,...,0) */
 1576:     /* if(xxs <1.0) */
 1577:     /*   printf(" after xi[%d]=%12.8f, xmin=%12.8f, ax=%12.8f, xx=%12.8f, bx=%12.8f, xxs=%12.8f", j,xi[j], xmin, ax, xx, bx,xxs ); */
 1578:     p[j] += xi[j]; /* Parameters values are updated accordingly */
 1579:   } 
 1580:   /* printf("\n"); */
 1581:   /* printf("Comparing last *frec(xmin)=%12.8f from Brent and frec(0.)=%12.8f \n", *fret, (*func)(p)); */
 1582:   free_vector(xicom,1,n); 
 1583:   free_vector(pcom,1,n); 
 1584: } 
 1585: 
 1586: 
 1587: /*************** powell ************************/
 1588: /*
 1589: Minimization of a function func of n variables. Input consists of an initial starting point
 1590: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
 1591: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
 1592: such that failure to decrease by more than this amount on one iteration signals doneness. On
 1593: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
 1594: function value at p , and iter is the number of iterations taken. The routine linmin is used.
 1595:  */
 1596: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
 1597: 	    double (*func)(double [])) 
 1598: { 
 1599:   void linmin(double p[], double xi[], int n, double *fret, 
 1600: 	      double (*func)(double [])); 
 1601:   int i,ibig,j; 
 1602:   double del,t,*pt,*ptt,*xit;
 1603:   double directest;
 1604:   double fp,fptt;
 1605:   double *xits;
 1606:   int niterf, itmp;
 1607: 
 1608:   pt=vector(1,n); 
 1609:   ptt=vector(1,n); 
 1610:   xit=vector(1,n); 
 1611:   xits=vector(1,n); 
 1612:   *fret=(*func)(p); 
 1613:   for (j=1;j<=n;j++) pt[j]=p[j]; 
 1614:     rcurr_time = time(NULL);  
 1615:   for (*iter=1;;++(*iter)) { 
 1616:     fp=(*fret); /* From former iteration or initial value */
 1617:     ibig=0; 
 1618:     del=0.0; 
 1619:     rlast_time=rcurr_time;
 1620:     /* (void) gettimeofday(&curr_time,&tzp); */
 1621:     rcurr_time = time(NULL);  
 1622:     curr_time = *localtime(&rcurr_time);
 1623:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
 1624:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
 1625: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
 1626:    for (i=1;i<=n;i++) {
 1627:       printf(" %d %.12f",i, p[i]);
 1628:       fprintf(ficlog," %d %.12lf",i, p[i]);
 1629:       fprintf(ficrespow," %.12lf", p[i]);
 1630:     }
 1631:     printf("\n");
 1632:     fprintf(ficlog,"\n");
 1633:     fprintf(ficrespow,"\n");fflush(ficrespow);
 1634:     if(*iter <=3){
 1635:       tml = *localtime(&rcurr_time);
 1636:       strcpy(strcurr,asctime(&tml));
 1637:       rforecast_time=rcurr_time; 
 1638:       itmp = strlen(strcurr);
 1639:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
 1640: 	strcurr[itmp-1]='\0';
 1641:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1642:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1643:       for(niterf=10;niterf<=30;niterf+=10){
 1644: 	rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
 1645: 	forecast_time = *localtime(&rforecast_time);
 1646: 	strcpy(strfor,asctime(&forecast_time));
 1647: 	itmp = strlen(strfor);
 1648: 	if(strfor[itmp-1]=='\n')
 1649: 	strfor[itmp-1]='\0';
 1650: 	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);
 1651: 	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);
 1652:       }
 1653:     }
 1654:     for (i=1;i<=n;i++) { /* For each direction i */
 1655:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
 1656:       fptt=(*fret); 
 1657: #ifdef DEBUG
 1658: 	  printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1659: 	  fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1660: #endif
 1661: 	  printf("%d",i);fflush(stdout); /* print direction (parameter) i */
 1662:       fprintf(ficlog,"%d",i);fflush(ficlog);
 1663:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
 1664: 				    /* Outputs are fret(new point p) p is updated and xit rescaled */
 1665:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
 1666: 	/* because that direction will be replaced unless the gain del is small */
 1667: 	/* in comparison with the 'probable' gain, mu^2, with the last average direction. */
 1668: 	/* Unless the n directions are conjugate some gain in the determinant may be obtained */
 1669: 	/* with the new direction. */
 1670: 	del=fabs(fptt-(*fret)); 
 1671: 	ibig=i; 
 1672:       } 
 1673: #ifdef DEBUG
 1674:       printf("%d %.12e",i,(*fret));
 1675:       fprintf(ficlog,"%d %.12e",i,(*fret));
 1676:       for (j=1;j<=n;j++) {
 1677: 	xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
 1678: 	printf(" x(%d)=%.12e",j,xit[j]);
 1679: 	fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
 1680:       }
 1681:       for(j=1;j<=n;j++) {
 1682: 	printf(" p(%d)=%.12e",j,p[j]);
 1683: 	fprintf(ficlog," p(%d)=%.12e",j,p[j]);
 1684:       }
 1685:       printf("\n");
 1686:       fprintf(ficlog,"\n");
 1687: #endif
 1688:     } /* end loop on each direction i */
 1689:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
 1690:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
 1691:     /* New value of last point Pn is not computed, P(n-1) */
 1692:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
 1693:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
 1694:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
 1695:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
 1696:       /* decreased of more than 3.84  */
 1697:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
 1698:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
 1699:       /* By adding 10 parameters more the gain should be 18.31 */
 1700: 
 1701:       /* Starting the program with initial values given by a former maximization will simply change */
 1702:       /* the scales of the directions and the directions, because the are reset to canonical directions */
 1703:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
 1704:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
 1705: #ifdef DEBUG
 1706:       int k[2],l;
 1707:       k[0]=1;
 1708:       k[1]=-1;
 1709:       printf("Max: %.12e",(*func)(p));
 1710:       fprintf(ficlog,"Max: %.12e",(*func)(p));
 1711:       for (j=1;j<=n;j++) {
 1712: 	printf(" %.12e",p[j]);
 1713: 	fprintf(ficlog," %.12e",p[j]);
 1714:       }
 1715:       printf("\n");
 1716:       fprintf(ficlog,"\n");
 1717:       for(l=0;l<=1;l++) {
 1718: 	for (j=1;j<=n;j++) {
 1719: 	  ptt[j]=p[j]+(p[j]-pt[j])*k[l];
 1720: 	  printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1721: 	  fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1722: 	}
 1723: 	printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1724: 	fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1725:       }
 1726: #endif
 1727: 
 1728: 
 1729:       free_vector(xit,1,n); 
 1730:       free_vector(xits,1,n); 
 1731:       free_vector(ptt,1,n); 
 1732:       free_vector(pt,1,n); 
 1733:       return; 
 1734:     } 
 1735:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
 1736:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
 1737:       ptt[j]=2.0*p[j]-pt[j]; 
 1738:       xit[j]=p[j]-pt[j]; 
 1739:       pt[j]=p[j]; 
 1740:     } 
 1741:     fptt=(*func)(ptt); /* f_3 */
 1742:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
 1743:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
 1744:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
 1745:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
 1746:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
 1747:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
 1748:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
 1749:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
 1750: #ifdef NRCORIGINAL
 1751:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
 1752: #else
 1753:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
 1754:       t= t- del*SQR(fp-fptt);
 1755: #endif
 1756:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If del was big enough we change it for a new direction */
 1757: #ifdef DEBUG
 1758:       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);
 1759:       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);
 1760:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 1761: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 1762:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 1763: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 1764:       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);
 1765:       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);
 1766: #endif
 1767: #ifdef POWELLORIGINAL
 1768:       if (t < 0.0) { /* Then we use it for new direction */
 1769: #else
 1770:       if (directest*t < 0.0) { /* Contradiction between both tests */
 1771:       printf("directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
 1772:       printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 1773:       fprintf(ficlog,"directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
 1774:       fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
 1775:     } 
 1776:       if (directest < 0.0) { /* Then we use it for new direction */
 1777: #endif
 1778: 	linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
 1779: 	for (j=1;j<=n;j++) { 
 1780: 	  xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
 1781: 	  xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
 1782: 	}
 1783: 	printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 1784: 	fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 1785: 
 1786: #ifdef DEBUG
 1787: 	printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1788: 	fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1789: 	for(j=1;j<=n;j++){
 1790: 	  printf(" %.12e",xit[j]);
 1791: 	  fprintf(ficlog," %.12e",xit[j]);
 1792: 	}
 1793: 	printf("\n");
 1794: 	fprintf(ficlog,"\n");
 1795: #endif
 1796:       } /* end of t negative */
 1797:     } /* end if (fptt < fp)  */
 1798:   } 
 1799: } 
 1800: 
 1801: /**** Prevalence limit (stable or period prevalence)  ****************/
 1802: 
 1803: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
 1804: {
 1805:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
 1806:      matrix by transitions matrix until convergence is reached */
 1807:   
 1808:   int i, ii,j,k;
 1809:   double min, max, maxmin, maxmax,sumnew=0.;
 1810:   /* double **matprod2(); */ /* test */
 1811:   double **out, cov[NCOVMAX+1], **pmij();
 1812:   double **newm;
 1813:   double agefin, delaymax=50 ; /* Max number of years to converge */
 1814:   
 1815:   for (ii=1;ii<=nlstate+ndeath;ii++)
 1816:     for (j=1;j<=nlstate+ndeath;j++){
 1817:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1818:     }
 1819:   
 1820:   cov[1]=1.;
 1821:   
 1822:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 1823:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
 1824:     newm=savm;
 1825:     /* Covariates have to be included here again */
 1826:     cov[2]=agefin;
 1827:     if(nagesqr==1)
 1828:       cov[3]= agefin*agefin;;
 1829:     for (k=1; k<=cptcovn;k++) {
 1830:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 1831:       /*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]]);*/
 1832:     }
 1833:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 1834:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]*cov[2];
 1835:     for (k=1; k<=cptcovprod;k++) /* Useless */
 1836:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 1837:     
 1838:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 1839:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 1840:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 1841:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 1842:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 1843:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
 1844:     
 1845:     savm=oldm;
 1846:     oldm=newm;
 1847:     maxmax=0.;
 1848:     for(j=1;j<=nlstate;j++){
 1849:       min=1.;
 1850:       max=0.;
 1851:       for(i=1; i<=nlstate; i++) {
 1852: 	sumnew=0;
 1853: 	for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
 1854: 	prlim[i][j]= newm[i][j]/(1-sumnew);
 1855:         /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
 1856: 	max=FMAX(max,prlim[i][j]);
 1857: 	min=FMIN(min,prlim[i][j]);
 1858:       }
 1859:       maxmin=max-min;
 1860:       maxmax=FMAX(maxmax,maxmin);
 1861:     } /* j loop */
 1862:     if(maxmax < ftolpl){
 1863:       return prlim;
 1864:     }
 1865:   } /* age loop */
 1866:   return prlim; /* should not reach here */
 1867: }
 1868: 
 1869: /*************** transition probabilities ***************/ 
 1870: 
 1871: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 1872: {
 1873:   /* According to parameters values stored in x and the covariate's values stored in cov,
 1874:      computes the probability to be observed in state j being in state i by appying the
 1875:      model to the ncovmodel covariates (including constant and age).
 1876:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 1877:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 1878:      ncth covariate in the global vector x is given by the formula:
 1879:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 1880:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 1881:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 1882:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 1883:      Outputs ps[i][j] the probability to be observed in j being in j according to
 1884:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 1885:   */
 1886:   double s1, lnpijopii;
 1887:   /*double t34;*/
 1888:   int i,j, nc, ii, jj;
 1889: 
 1890:     for(i=1; i<= nlstate; i++){
 1891:       for(j=1; j<i;j++){
 1892: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 1893: 	  /*lnpijopii += param[i][j][nc]*cov[nc];*/
 1894: 	  lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 1895: /* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 1896: 	}
 1897: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 1898: /* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 1899:       }
 1900:       for(j=i+1; j<=nlstate+ndeath;j++){
 1901: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 1902: 	  /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 1903: 	  lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 1904: /* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 1905: 	}
 1906: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 1907:       }
 1908:     }
 1909:     
 1910:     for(i=1; i<= nlstate; i++){
 1911:       s1=0;
 1912:       for(j=1; j<i; j++){
 1913: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 1914: 	/*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 1915:       }
 1916:       for(j=i+1; j<=nlstate+ndeath; j++){
 1917: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 1918: 	/*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 1919:       }
 1920:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 1921:       ps[i][i]=1./(s1+1.);
 1922:       /* Computing other pijs */
 1923:       for(j=1; j<i; j++)
 1924: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 1925:       for(j=i+1; j<=nlstate+ndeath; j++)
 1926: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 1927:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 1928:     } /* end i */
 1929:     
 1930:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 1931:       for(jj=1; jj<= nlstate+ndeath; jj++){
 1932: 	ps[ii][jj]=0;
 1933: 	ps[ii][ii]=1;
 1934:       }
 1935:     }
 1936:     
 1937:     
 1938:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 1939:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 1940:     /* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 1941:     /*   } */
 1942:     /*   printf("\n "); */
 1943:     /* } */
 1944:     /* printf("\n ");printf("%lf ",cov[2]);*/
 1945:     /*
 1946:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
 1947:       goto end;*/
 1948:     return ps;
 1949: }
 1950: 
 1951: /**************** Product of 2 matrices ******************/
 1952: 
 1953: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
 1954: {
 1955:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
 1956:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
 1957:   /* in, b, out are matrice of pointers which should have been initialized 
 1958:      before: only the contents of out is modified. The function returns
 1959:      a pointer to pointers identical to out */
 1960:   int i, j, k;
 1961:   for(i=nrl; i<= nrh; i++)
 1962:     for(k=ncolol; k<=ncoloh; k++){
 1963:       out[i][k]=0.;
 1964:       for(j=ncl; j<=nch; j++)
 1965:   	out[i][k] +=in[i][j]*b[j][k];
 1966:     }
 1967:   return out;
 1968: }
 1969: 
 1970: 
 1971: /************* Higher Matrix Product ***************/
 1972: 
 1973: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
 1974: {
 1975:   /* Computes the transition matrix starting at age 'age' over 
 1976:      'nhstepm*hstepm*stepm' months (i.e. until
 1977:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
 1978:      nhstepm*hstepm matrices. 
 1979:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
 1980:      (typically every 2 years instead of every month which is too big 
 1981:      for the memory).
 1982:      Model is determined by parameters x and covariates have to be 
 1983:      included manually here. 
 1984: 
 1985:      */
 1986: 
 1987:   int i, j, d, h, k;
 1988:   double **out, cov[NCOVMAX+1];
 1989:   double **newm;
 1990:   double agexact;
 1991: 
 1992:   /* Hstepm could be zero and should return the unit matrix */
 1993:   for (i=1;i<=nlstate+ndeath;i++)
 1994:     for (j=1;j<=nlstate+ndeath;j++){
 1995:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 1996:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 1997:     }
 1998:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 1999:   for(h=1; h <=nhstepm; h++){
 2000:     for(d=1; d <=hstepm; d++){
 2001:       newm=savm;
 2002:       /* Covariates have to be included here again */
 2003:       cov[1]=1.;
 2004:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
 2005:       cov[2]=agexact;
 2006:       if(nagesqr==1)
 2007: 	cov[3]= agexact*agexact;
 2008:       for (k=1; k<=cptcovn;k++) 
 2009: 	cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 2010:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
 2011: 	/* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 2012: 	cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
 2013:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
 2014: 	cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 2015: 
 2016: 
 2017:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 2018:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 2019:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
 2020: 		   pmij(pmmij,cov,ncovmodel,x,nlstate));
 2021:       savm=oldm;
 2022:       oldm=newm;
 2023:     }
 2024:     for(i=1; i<=nlstate+ndeath; i++)
 2025:       for(j=1;j<=nlstate+ndeath;j++) {
 2026: 	po[i][j][h]=newm[i][j];
 2027: 	/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 2028:       }
 2029:     /*printf("h=%d ",h);*/
 2030:   } /* end h */
 2031: /*     printf("\n H=%d \n",h); */
 2032:   return po;
 2033: }
 2034: 
 2035: #ifdef NLOPT
 2036:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
 2037:   double fret;
 2038:   double *xt;
 2039:   int j;
 2040:   myfunc_data *d2 = (myfunc_data *) pd;
 2041: /* xt = (p1-1); */
 2042:   xt=vector(1,n); 
 2043:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
 2044: 
 2045:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
 2046:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
 2047:   printf("Function = %.12lf ",fret);
 2048:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
 2049:   printf("\n");
 2050:  free_vector(xt,1,n);
 2051:   return fret;
 2052: }
 2053: #endif
 2054: 
 2055: /*************** log-likelihood *************/
 2056: double func( double *x)
 2057: {
 2058:   int i, ii, j, k, mi, d, kk;
 2059:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 2060:   double **out;
 2061:   double sw; /* Sum of weights */
 2062:   double lli; /* Individual log likelihood */
 2063:   int s1, s2;
 2064:   double bbh, survp;
 2065:   long ipmx;
 2066:   double agexact;
 2067:   /*extern weight */
 2068:   /* We are differentiating ll according to initial status */
 2069:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 2070:   /*for(i=1;i<imx;i++) 
 2071:     printf(" %d\n",s[4][i]);
 2072:   */
 2073: 
 2074:   ++countcallfunc;
 2075: 
 2076:   cov[1]=1.;
 2077: 
 2078:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 2079: 
 2080:   if(mle==1){
 2081:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2082:       /* Computes the values of the ncovmodel covariates of the model
 2083: 	 depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
 2084: 	 Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
 2085: 	 to be observed in j being in i according to the model.
 2086:        */
 2087:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
 2088: 	  cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2089:       }
 2090:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
 2091: 	 is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
 2092: 	 has been calculated etc */
 2093:       for(mi=1; mi<= wav[i]-1; mi++){
 2094: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2095: 	  for (j=1;j<=nlstate+ndeath;j++){
 2096: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2097: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2098: 	  }
 2099: 	for(d=0; d<dh[mi][i]; d++){
 2100: 	  newm=savm;
 2101: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2102: 	  cov[2]=agexact;
 2103: 	  if(nagesqr==1)
 2104: 	    cov[3]= agexact*agexact;
 2105: 	  for (kk=1; kk<=cptcovage;kk++) {
 2106: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
 2107: 	  }
 2108: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2109: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2110: 	  savm=oldm;
 2111: 	  oldm=newm;
 2112: 	} /* end mult */
 2113:       
 2114: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 2115: 	/* But now since version 0.9 we anticipate for bias at large stepm.
 2116: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 2117: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
 2118: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
 2119: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 2120: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
 2121: 	 * probability in order to take into account the bias as a fraction of the way
 2122: 	 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
 2123: 	 * -stepm/2 to stepm/2 .
 2124: 	 * For stepm=1 the results are the same as for previous versions of Imach.
 2125: 	 * For stepm > 1 the results are less biased than in previous versions. 
 2126: 	 */
 2127: 	s1=s[mw[mi][i]][i];
 2128: 	s2=s[mw[mi+1][i]][i];
 2129: 	bbh=(double)bh[mi][i]/(double)stepm; 
 2130: 	/* bias bh is positive if real duration
 2131: 	 * is higher than the multiple of stepm and negative otherwise.
 2132: 	 */
 2133: 	/* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
 2134: 	if( s2 > nlstate){ 
 2135: 	  /* i.e. if s2 is a death state and if the date of death is known 
 2136: 	     then the contribution to the likelihood is the probability to 
 2137: 	     die between last step unit time and current  step unit time, 
 2138: 	     which is also equal to probability to die before dh 
 2139: 	     minus probability to die before dh-stepm . 
 2140: 	     In version up to 0.92 likelihood was computed
 2141: 	as if date of death was unknown. Death was treated as any other
 2142: 	health state: the date of the interview describes the actual state
 2143: 	and not the date of a change in health state. The former idea was
 2144: 	to consider that at each interview the state was recorded
 2145: 	(healthy, disable or death) and IMaCh was corrected; but when we
 2146: 	introduced the exact date of death then we should have modified
 2147: 	the contribution of an exact death to the likelihood. This new
 2148: 	contribution is smaller and very dependent of the step unit
 2149: 	stepm. It is no more the probability to die between last interview
 2150: 	and month of death but the probability to survive from last
 2151: 	interview up to one month before death multiplied by the
 2152: 	probability to die within a month. Thanks to Chris
 2153: 	Jackson for correcting this bug.  Former versions increased
 2154: 	mortality artificially. The bad side is that we add another loop
 2155: 	which slows down the processing. The difference can be up to 10%
 2156: 	lower mortality.
 2157: 	  */
 2158: 	/* If, at the beginning of the maximization mostly, the
 2159: 	   cumulative probability or probability to be dead is
 2160: 	   constant (ie = 1) over time d, the difference is equal to
 2161: 	   0.  out[s1][3] = savm[s1][3]: probability, being at state
 2162: 	   s1 at precedent wave, to be dead a month before current
 2163: 	   wave is equal to probability, being at state s1 at
 2164: 	   precedent wave, to be dead at mont of the current
 2165: 	   wave. Then the observed probability (that this person died)
 2166: 	   is null according to current estimated parameter. In fact,
 2167: 	   it should be very low but not zero otherwise the log go to
 2168: 	   infinity.
 2169: 	*/
 2170: /* #ifdef INFINITYORIGINAL */
 2171: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 2172: /* #else */
 2173: /* 	  if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
 2174: /* 	    lli=log(mytinydouble); */
 2175: /* 	  else */
 2176: /* 	    lli=log(out[s1][s2] - savm[s1][s2]); */
 2177: /* #endif */
 2178: 	    lli=log(out[s1][s2] - savm[s1][s2]);
 2179: 
 2180: 	} else if  (s2==-2) {
 2181: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 2182: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2183: 	  /*survp += out[s1][j]; */
 2184: 	  lli= log(survp);
 2185: 	}
 2186: 	
 2187:  	else if  (s2==-4) { 
 2188: 	  for (j=3,survp=0. ; j<=nlstate; j++)  
 2189: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2190:  	  lli= log(survp); 
 2191:  	} 
 2192: 
 2193:  	else if  (s2==-5) { 
 2194:  	  for (j=1,survp=0. ; j<=2; j++)  
 2195: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2196:  	  lli= log(survp); 
 2197:  	} 
 2198: 	
 2199: 	else{
 2200: 	  lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2201: 	  /*  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 */
 2202: 	} 
 2203: 	/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 2204: 	/*if(lli ==000.0)*/
 2205: 	/*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); */
 2206:   	ipmx +=1;
 2207: 	sw += weight[i];
 2208: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2209: 	/* if (lli < log(mytinydouble)){ */
 2210: 	/*   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); */
 2211: 	/*   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]); */
 2212: 	/* } */
 2213:       } /* end of wave */
 2214:     } /* end of individual */
 2215:   }  else if(mle==2){
 2216:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2217:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2218:       for(mi=1; mi<= wav[i]-1; mi++){
 2219: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2220: 	  for (j=1;j<=nlstate+ndeath;j++){
 2221: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2222: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2223: 	  }
 2224: 	for(d=0; d<=dh[mi][i]; d++){
 2225: 	  newm=savm;
 2226: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2227: 	  cov[2]=agexact;
 2228: 	  if(nagesqr==1)
 2229: 	    cov[3]= agexact*agexact;
 2230: 	  for (kk=1; kk<=cptcovage;kk++) {
 2231: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2232: 	  }
 2233: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2234: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2235: 	  savm=oldm;
 2236: 	  oldm=newm;
 2237: 	} /* end mult */
 2238:       
 2239: 	s1=s[mw[mi][i]][i];
 2240: 	s2=s[mw[mi+1][i]][i];
 2241: 	bbh=(double)bh[mi][i]/(double)stepm; 
 2242: 	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 */
 2243: 	ipmx +=1;
 2244: 	sw += weight[i];
 2245: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2246:       } /* end of wave */
 2247:     } /* end of individual */
 2248:   }  else if(mle==3){  /* exponential inter-extrapolation */
 2249:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2250:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2251:       for(mi=1; mi<= wav[i]-1; mi++){
 2252: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2253: 	  for (j=1;j<=nlstate+ndeath;j++){
 2254: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2255: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2256: 	  }
 2257: 	for(d=0; d<dh[mi][i]; d++){
 2258: 	  newm=savm;
 2259: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2260: 	  cov[2]=agexact;
 2261: 	  if(nagesqr==1)
 2262: 	    cov[3]= agexact*agexact;
 2263: 	  for (kk=1; kk<=cptcovage;kk++) {
 2264: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2265: 	  }
 2266: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2267: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2268: 	  savm=oldm;
 2269: 	  oldm=newm;
 2270: 	} /* end mult */
 2271:       
 2272: 	s1=s[mw[mi][i]][i];
 2273: 	s2=s[mw[mi+1][i]][i];
 2274: 	bbh=(double)bh[mi][i]/(double)stepm; 
 2275: 	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 */
 2276: 	ipmx +=1;
 2277: 	sw += weight[i];
 2278: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2279:       } /* end of wave */
 2280:     } /* end of individual */
 2281:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
 2282:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2283:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2284:       for(mi=1; mi<= wav[i]-1; mi++){
 2285: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2286: 	  for (j=1;j<=nlstate+ndeath;j++){
 2287: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2288: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2289: 	  }
 2290: 	for(d=0; d<dh[mi][i]; d++){
 2291: 	  newm=savm;
 2292: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2293: 	  cov[2]=agexact;
 2294: 	  if(nagesqr==1)
 2295: 	    cov[3]= agexact*agexact;
 2296: 	  for (kk=1; kk<=cptcovage;kk++) {
 2297: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2298: 	  }
 2299: 	
 2300: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2301: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2302: 	  savm=oldm;
 2303: 	  oldm=newm;
 2304: 	} /* end mult */
 2305:       
 2306: 	s1=s[mw[mi][i]][i];
 2307: 	s2=s[mw[mi+1][i]][i];
 2308: 	if( s2 > nlstate){ 
 2309: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 2310: 	}else{
 2311: 	  lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 2312: 	}
 2313: 	ipmx +=1;
 2314: 	sw += weight[i];
 2315: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2316: /* 	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]); */
 2317:       } /* end of wave */
 2318:     } /* end of individual */
 2319:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
 2320:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2321:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2322:       for(mi=1; mi<= wav[i]-1; mi++){
 2323: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2324: 	  for (j=1;j<=nlstate+ndeath;j++){
 2325: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2326: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2327: 	  }
 2328: 	for(d=0; d<dh[mi][i]; d++){
 2329: 	  newm=savm;
 2330: 	  agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2331: 	  cov[2]=agexact;
 2332: 	  if(nagesqr==1)
 2333: 	    cov[3]= agexact*agexact;
 2334: 	  for (kk=1; kk<=cptcovage;kk++) {
 2335: 	    cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2336: 	  }
 2337: 	
 2338: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2339: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2340: 	  savm=oldm;
 2341: 	  oldm=newm;
 2342: 	} /* end mult */
 2343:       
 2344: 	s1=s[mw[mi][i]][i];
 2345: 	s2=s[mw[mi+1][i]][i];
 2346: 	lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 2347: 	ipmx +=1;
 2348: 	sw += weight[i];
 2349: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2350: 	/*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]);*/
 2351:       } /* end of wave */
 2352:     } /* end of individual */
 2353:   } /* End of if */
 2354:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 2355:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 2356:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 2357:   return -l;
 2358: }
 2359: 
 2360: /*************** log-likelihood *************/
 2361: double funcone( double *x)
 2362: {
 2363:   /* Same as likeli but slower because of a lot of printf and if */
 2364:   int i, ii, j, k, mi, d, kk;
 2365:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 2366:   double **out;
 2367:   double lli; /* Individual log likelihood */
 2368:   double llt;
 2369:   int s1, s2;
 2370:   double bbh, survp;
 2371:   double agexact;
 2372:   /*extern weight */
 2373:   /* We are differentiating ll according to initial status */
 2374:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 2375:   /*for(i=1;i<imx;i++) 
 2376:     printf(" %d\n",s[4][i]);
 2377:   */
 2378:   cov[1]=1.;
 2379: 
 2380:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 2381: 
 2382:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2383:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
 2384:     for(mi=1; mi<= wav[i]-1; mi++){
 2385:       for (ii=1;ii<=nlstate+ndeath;ii++)
 2386: 	for (j=1;j<=nlstate+ndeath;j++){
 2387: 	  oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2388: 	  savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2389: 	}
 2390:       for(d=0; d<dh[mi][i]; d++){
 2391: 	newm=savm;
 2392: 	agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2393: 	cov[2]=agexact;
 2394: 	if(nagesqr==1)
 2395: 	  cov[3]= agexact*agexact;
 2396: 	for (kk=1; kk<=cptcovage;kk++) {
 2397: 	  cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
 2398: 	}
 2399: 
 2400: 	/* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2401: 	out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2402: 		     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2403: 	/* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
 2404: 	/* 	     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
 2405: 	savm=oldm;
 2406: 	oldm=newm;
 2407:       } /* end mult */
 2408:       
 2409:       s1=s[mw[mi][i]][i];
 2410:       s2=s[mw[mi+1][i]][i];
 2411:       bbh=(double)bh[mi][i]/(double)stepm; 
 2412:       /* bias is positive if real duration
 2413:        * is higher than the multiple of stepm and negative otherwise.
 2414:        */
 2415:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
 2416: 	lli=log(out[s1][s2] - savm[s1][s2]);
 2417:       } else if  (s2==-2) {
 2418: 	for (j=1,survp=0. ; j<=nlstate; j++) 
 2419: 	  survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2420: 	lli= log(survp);
 2421:       }else if (mle==1){
 2422: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2423:       } else if(mle==2){
 2424: 	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 */
 2425:       } else if(mle==3){  /* exponential inter-extrapolation */
 2426: 	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 */
 2427:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
 2428: 	lli=log(out[s1][s2]); /* Original formula */
 2429:       } else{  /* mle=0 back to 1 */
 2430: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2431: 	/*lli=log(out[s1][s2]); */ /* Original formula */
 2432:       } /* End of if */
 2433:       ipmx +=1;
 2434:       sw += weight[i];
 2435:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2436:       /*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]); */
 2437:       if(globpr){
 2438: 	fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
 2439:  %11.6f %11.6f %11.6f ", \
 2440: 		num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
 2441: 		2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
 2442: 	for(k=1,llt=0.,l=0.; k<=nlstate; k++){
 2443: 	  llt +=ll[k]*gipmx/gsw;
 2444: 	  fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
 2445: 	}
 2446: 	fprintf(ficresilk," %10.6f\n", -llt);
 2447:       }
 2448:     } /* end of wave */
 2449:   } /* end of individual */
 2450:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 2451:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 2452:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 2453:   if(globpr==0){ /* First time we count the contributions and weights */
 2454:     gipmx=ipmx;
 2455:     gsw=sw;
 2456:   }
 2457:   return -l;
 2458: }
 2459: 
 2460: 
 2461: /*************** function likelione ***********/
 2462: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
 2463: {
 2464:   /* This routine should help understanding what is done with 
 2465:      the selection of individuals/waves and
 2466:      to check the exact contribution to the likelihood.
 2467:      Plotting could be done.
 2468:    */
 2469:   int k;
 2470: 
 2471:   if(*globpri !=0){ /* Just counts and sums, no printings */
 2472:     strcpy(fileresilk,"ilk"); 
 2473:     strcat(fileresilk,fileres);
 2474:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
 2475:       printf("Problem with resultfile: %s\n", fileresilk);
 2476:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
 2477:     }
 2478:     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");
 2479:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
 2480:     /* 	i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
 2481:     for(k=1; k<=nlstate; k++) 
 2482:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
 2483:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
 2484:   }
 2485: 
 2486:   *fretone=(*funcone)(p);
 2487:   if(*globpri !=0){
 2488:     fclose(ficresilk);
 2489:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
 2490:     fflush(fichtm); 
 2491:   } 
 2492:   return;
 2493: }
 2494: 
 2495: 
 2496: /*********** Maximum Likelihood Estimation ***************/
 2497: 
 2498: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
 2499: {
 2500:   int i,j, iter=0;
 2501:   double **xi;
 2502:   double fret;
 2503:   double fretone; /* Only one call to likelihood */
 2504:   /*  char filerespow[FILENAMELENGTH];*/
 2505: 
 2506: #ifdef NLOPT
 2507:   int creturn;
 2508:   nlopt_opt opt;
 2509:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
 2510:   double *lb;
 2511:   double minf; /* the minimum objective value, upon return */
 2512:   double * p1; /* Shifted parameters from 0 instead of 1 */
 2513:   myfunc_data dinst, *d = &dinst;
 2514: #endif
 2515: 
 2516: 
 2517:   xi=matrix(1,npar,1,npar);
 2518:   for (i=1;i<=npar;i++)
 2519:     for (j=1;j<=npar;j++)
 2520:       xi[i][j]=(i==j ? 1.0 : 0.0);
 2521:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
 2522:   strcpy(filerespow,"pow"); 
 2523:   strcat(filerespow,fileres);
 2524:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
 2525:     printf("Problem with resultfile: %s\n", filerespow);
 2526:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 2527:   }
 2528:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
 2529:   for (i=1;i<=nlstate;i++)
 2530:     for(j=1;j<=nlstate+ndeath;j++)
 2531:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 2532:   fprintf(ficrespow,"\n");
 2533: #ifdef POWELL
 2534:   powell(p,xi,npar,ftol,&iter,&fret,func);
 2535: #endif
 2536: 
 2537: #ifdef NLOPT
 2538: #ifdef NEWUOA
 2539:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
 2540: #else
 2541:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
 2542: #endif
 2543:   lb=vector(0,npar-1);
 2544:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
 2545:   nlopt_set_lower_bounds(opt, lb);
 2546:   nlopt_set_initial_step1(opt, 0.1);
 2547:   
 2548:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
 2549:   d->function = func;
 2550:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
 2551:   nlopt_set_min_objective(opt, myfunc, d);
 2552:   nlopt_set_xtol_rel(opt, ftol);
 2553:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
 2554:     printf("nlopt failed! %d\n",creturn); 
 2555:   }
 2556:   else {
 2557:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
 2558:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
 2559:     iter=1; /* not equal */
 2560:   }
 2561:   nlopt_destroy(opt);
 2562: #endif
 2563:   free_matrix(xi,1,npar,1,npar);
 2564:   fclose(ficrespow);
 2565:   printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2566:   fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2567:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2568: 
 2569: }
 2570: 
 2571: /**** Computes Hessian and covariance matrix ***/
 2572: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
 2573: {
 2574:   double  **a,**y,*x,pd;
 2575:   double **hess;
 2576:   int i, j;
 2577:   int *indx;
 2578: 
 2579:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
 2580:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
 2581:   void lubksb(double **a, int npar, int *indx, double b[]) ;
 2582:   void ludcmp(double **a, int npar, int *indx, double *d) ;
 2583:   double gompertz(double p[]);
 2584:   hess=matrix(1,npar,1,npar);
 2585: 
 2586:   printf("\nCalculation of the hessian matrix. Wait...\n");
 2587:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
 2588:   for (i=1;i<=npar;i++){
 2589:     printf("%d",i);fflush(stdout);
 2590:     fprintf(ficlog,"%d",i);fflush(ficlog);
 2591:    
 2592:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
 2593:     
 2594:     /*  printf(" %f ",p[i]);
 2595: 	printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
 2596:   }
 2597:   
 2598:   for (i=1;i<=npar;i++) {
 2599:     for (j=1;j<=npar;j++)  {
 2600:       if (j>i) { 
 2601: 	printf(".%d%d",i,j);fflush(stdout);
 2602: 	fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
 2603: 	hess[i][j]=hessij(p,delti,i,j,func,npar);
 2604: 	
 2605: 	hess[j][i]=hess[i][j];    
 2606: 	/*printf(" %lf ",hess[i][j]);*/
 2607:       }
 2608:     }
 2609:   }
 2610:   printf("\n");
 2611:   fprintf(ficlog,"\n");
 2612: 
 2613:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
 2614:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
 2615:   
 2616:   a=matrix(1,npar,1,npar);
 2617:   y=matrix(1,npar,1,npar);
 2618:   x=vector(1,npar);
 2619:   indx=ivector(1,npar);
 2620:   for (i=1;i<=npar;i++)
 2621:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
 2622:   ludcmp(a,npar,indx,&pd);
 2623: 
 2624:   for (j=1;j<=npar;j++) {
 2625:     for (i=1;i<=npar;i++) x[i]=0;
 2626:     x[j]=1;
 2627:     lubksb(a,npar,indx,x);
 2628:     for (i=1;i<=npar;i++){ 
 2629:       matcov[i][j]=x[i];
 2630:     }
 2631:   }
 2632: 
 2633:   printf("\n#Hessian matrix#\n");
 2634:   fprintf(ficlog,"\n#Hessian matrix#\n");
 2635:   for (i=1;i<=npar;i++) { 
 2636:     for (j=1;j<=npar;j++) { 
 2637:       printf("%.3e ",hess[i][j]);
 2638:       fprintf(ficlog,"%.3e ",hess[i][j]);
 2639:     }
 2640:     printf("\n");
 2641:     fprintf(ficlog,"\n");
 2642:   }
 2643: 
 2644:   /* Recompute Inverse */
 2645:   for (i=1;i<=npar;i++)
 2646:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
 2647:   ludcmp(a,npar,indx,&pd);
 2648: 
 2649:   /*  printf("\n#Hessian matrix recomputed#\n");
 2650: 
 2651:   for (j=1;j<=npar;j++) {
 2652:     for (i=1;i<=npar;i++) x[i]=0;
 2653:     x[j]=1;
 2654:     lubksb(a,npar,indx,x);
 2655:     for (i=1;i<=npar;i++){ 
 2656:       y[i][j]=x[i];
 2657:       printf("%.3e ",y[i][j]);
 2658:       fprintf(ficlog,"%.3e ",y[i][j]);
 2659:     }
 2660:     printf("\n");
 2661:     fprintf(ficlog,"\n");
 2662:   }
 2663:   */
 2664: 
 2665:   free_matrix(a,1,npar,1,npar);
 2666:   free_matrix(y,1,npar,1,npar);
 2667:   free_vector(x,1,npar);
 2668:   free_ivector(indx,1,npar);
 2669:   free_matrix(hess,1,npar,1,npar);
 2670: 
 2671: 
 2672: }
 2673: 
 2674: /*************** hessian matrix ****************/
 2675: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
 2676: {
 2677:   int i;
 2678:   int l=1, lmax=20;
 2679:   double k1,k2;
 2680:   double p2[MAXPARM+1]; /* identical to x */
 2681:   double res;
 2682:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 2683:   double fx;
 2684:   int k=0,kmax=10;
 2685:   double l1;
 2686: 
 2687:   fx=func(x);
 2688:   for (i=1;i<=npar;i++) p2[i]=x[i];
 2689:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
 2690:     l1=pow(10,l);
 2691:     delts=delt;
 2692:     for(k=1 ; k <kmax; k=k+1){
 2693:       delt = delta*(l1*k);
 2694:       p2[theta]=x[theta] +delt;
 2695:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
 2696:       p2[theta]=x[theta]-delt;
 2697:       k2=func(p2)-fx;
 2698:       /*res= (k1-2.0*fx+k2)/delt/delt; */
 2699:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
 2700:       
 2701: #ifdef DEBUGHESS
 2702:       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);
 2703:       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);
 2704: #endif
 2705:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
 2706:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 2707: 	k=kmax;
 2708:       }
 2709:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
 2710: 	k=kmax; l=lmax*10;
 2711:       }
 2712:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
 2713: 	delts=delt;
 2714:       }
 2715:     }
 2716:   }
 2717:   delti[theta]=delts;
 2718:   return res; 
 2719:   
 2720: }
 2721: 
 2722: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
 2723: {
 2724:   int i;
 2725:   int l=1, lmax=20;
 2726:   double k1,k2,k3,k4,res,fx;
 2727:   double p2[MAXPARM+1];
 2728:   int k;
 2729: 
 2730:   fx=func(x);
 2731:   for (k=1; k<=2; k++) {
 2732:     for (i=1;i<=npar;i++) p2[i]=x[i];
 2733:     p2[thetai]=x[thetai]+delti[thetai]/k;
 2734:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 2735:     k1=func(p2)-fx;
 2736:   
 2737:     p2[thetai]=x[thetai]+delti[thetai]/k;
 2738:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 2739:     k2=func(p2)-fx;
 2740:   
 2741:     p2[thetai]=x[thetai]-delti[thetai]/k;
 2742:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 2743:     k3=func(p2)-fx;
 2744:   
 2745:     p2[thetai]=x[thetai]-delti[thetai]/k;
 2746:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 2747:     k4=func(p2)-fx;
 2748:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
 2749: #ifdef DEBUG
 2750:     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);
 2751:     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);
 2752: #endif
 2753:   }
 2754:   return res;
 2755: }
 2756: 
 2757: /************** Inverse of matrix **************/
 2758: void ludcmp(double **a, int n, int *indx, double *d) 
 2759: { 
 2760:   int i,imax,j,k; 
 2761:   double big,dum,sum,temp; 
 2762:   double *vv; 
 2763:  
 2764:   vv=vector(1,n); 
 2765:   *d=1.0; 
 2766:   for (i=1;i<=n;i++) { 
 2767:     big=0.0; 
 2768:     for (j=1;j<=n;j++) 
 2769:       if ((temp=fabs(a[i][j])) > big) big=temp; 
 2770:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
 2771:     vv[i]=1.0/big; 
 2772:   } 
 2773:   for (j=1;j<=n;j++) { 
 2774:     for (i=1;i<j;i++) { 
 2775:       sum=a[i][j]; 
 2776:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
 2777:       a[i][j]=sum; 
 2778:     } 
 2779:     big=0.0; 
 2780:     for (i=j;i<=n;i++) { 
 2781:       sum=a[i][j]; 
 2782:       for (k=1;k<j;k++) 
 2783: 	sum -= a[i][k]*a[k][j]; 
 2784:       a[i][j]=sum; 
 2785:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
 2786: 	big=dum; 
 2787: 	imax=i; 
 2788:       } 
 2789:     } 
 2790:     if (j != imax) { 
 2791:       for (k=1;k<=n;k++) { 
 2792: 	dum=a[imax][k]; 
 2793: 	a[imax][k]=a[j][k]; 
 2794: 	a[j][k]=dum; 
 2795:       } 
 2796:       *d = -(*d); 
 2797:       vv[imax]=vv[j]; 
 2798:     } 
 2799:     indx[j]=imax; 
 2800:     if (a[j][j] == 0.0) a[j][j]=TINY; 
 2801:     if (j != n) { 
 2802:       dum=1.0/(a[j][j]); 
 2803:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
 2804:     } 
 2805:   } 
 2806:   free_vector(vv,1,n);  /* Doesn't work */
 2807: ;
 2808: } 
 2809: 
 2810: void lubksb(double **a, int n, int *indx, double b[]) 
 2811: { 
 2812:   int i,ii=0,ip,j; 
 2813:   double sum; 
 2814:  
 2815:   for (i=1;i<=n;i++) { 
 2816:     ip=indx[i]; 
 2817:     sum=b[ip]; 
 2818:     b[ip]=b[i]; 
 2819:     if (ii) 
 2820:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
 2821:     else if (sum) ii=i; 
 2822:     b[i]=sum; 
 2823:   } 
 2824:   for (i=n;i>=1;i--) { 
 2825:     sum=b[i]; 
 2826:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
 2827:     b[i]=sum/a[i][i]; 
 2828:   } 
 2829: } 
 2830: 
 2831: void pstamp(FILE *fichier)
 2832: {
 2833:   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
 2834: }
 2835: 
 2836: /************ Frequencies ********************/
 2837: 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[])
 2838: {  /* Some frequencies */
 2839:   
 2840:   int i, m, jk, j1, bool, z1,j;
 2841:   int first;
 2842:   double ***freq; /* Frequencies */
 2843:   double *pp, **prop;
 2844:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
 2845:   char fileresp[FILENAMELENGTH];
 2846:   
 2847:   pp=vector(1,nlstate);
 2848:   prop=matrix(1,nlstate,iagemin,iagemax+3);
 2849:   strcpy(fileresp,"p");
 2850:   strcat(fileresp,fileres);
 2851:   if((ficresp=fopen(fileresp,"w"))==NULL) {
 2852:     printf("Problem with prevalence resultfile: %s\n", fileresp);
 2853:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
 2854:     exit(0);
 2855:   }
 2856:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
 2857:   j1=0;
 2858:   
 2859:   j=cptcoveff;
 2860:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 2861: 
 2862:   first=1;
 2863: 
 2864:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
 2865:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
 2866:   /*    j1++; */
 2867:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
 2868:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
 2869: 	scanf("%d", i);*/
 2870:       for (i=-5; i<=nlstate+ndeath; i++)  
 2871: 	for (jk=-5; jk<=nlstate+ndeath; jk++)  
 2872: 	  for(m=iagemin; m <= iagemax+3; m++)
 2873: 	    freq[i][jk][m]=0;
 2874:       
 2875:       for (i=1; i<=nlstate; i++)  
 2876: 	for(m=iagemin; m <= iagemax+3; m++)
 2877: 	  prop[i][m]=0;
 2878:       
 2879:       dateintsum=0;
 2880:       k2cpt=0;
 2881:       for (i=1; i<=imx; i++) {
 2882: 	bool=1;
 2883: 	if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
 2884: 	  for (z1=1; z1<=cptcoveff; z1++)       
 2885:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
 2886:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
 2887:               bool=0;
 2888:               /* 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", 
 2889:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
 2890:                 j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
 2891:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
 2892:             } 
 2893: 	}
 2894:  
 2895: 	if (bool==1){
 2896: 	  for(m=firstpass; m<=lastpass; m++){
 2897: 	    k2=anint[m][i]+(mint[m][i]/12.);
 2898: 	    /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
 2899: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 2900: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 2901: 	      if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
 2902: 	      if (m<lastpass) {
 2903: 		freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
 2904: 		freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
 2905: 	      }
 2906: 	      
 2907: 	      if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
 2908: 		dateintsum=dateintsum+k2;
 2909: 		k2cpt++;
 2910: 	      }
 2911: 	      /*}*/
 2912: 	  }
 2913: 	}
 2914:       } /* end i */
 2915:        
 2916:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 2917:       pstamp(ficresp);
 2918:       if  (cptcovn>0) {
 2919: 	fprintf(ficresp, "\n#********** Variable "); 
 2920: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2921: 	fprintf(ficresp, "**********\n#");
 2922: 	fprintf(ficlog, "\n#********** Variable "); 
 2923: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2924: 	fprintf(ficlog, "**********\n#");
 2925:       }
 2926:       for(i=1; i<=nlstate;i++) 
 2927: 	fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
 2928:       fprintf(ficresp, "\n");
 2929:       
 2930:       for(i=iagemin; i <= iagemax+3; i++){
 2931: 	if(i==iagemax+3){
 2932: 	  fprintf(ficlog,"Total");
 2933: 	}else{
 2934: 	  if(first==1){
 2935: 	    first=0;
 2936: 	    printf("See log file for details...\n");
 2937: 	  }
 2938: 	  fprintf(ficlog,"Age %d", i);
 2939: 	}
 2940: 	for(jk=1; jk <=nlstate ; jk++){
 2941: 	  for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
 2942: 	    pp[jk] += freq[jk][m][i]; 
 2943: 	}
 2944: 	for(jk=1; jk <=nlstate ; jk++){
 2945: 	  for(m=-1, pos=0; m <=0 ; m++)
 2946: 	    pos += freq[jk][m][i];
 2947: 	  if(pp[jk]>=1.e-10){
 2948: 	    if(first==1){
 2949: 	      printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 2950: 	    }
 2951: 	    fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 2952: 	  }else{
 2953: 	    if(first==1)
 2954: 	      printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 2955: 	    fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 2956: 	  }
 2957: 	}
 2958: 
 2959: 	for(jk=1; jk <=nlstate ; jk++){
 2960: 	  for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
 2961: 	    pp[jk] += freq[jk][m][i];
 2962: 	}	
 2963: 	for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
 2964: 	  pos += pp[jk];
 2965: 	  posprop += prop[jk][i];
 2966: 	}
 2967: 	for(jk=1; jk <=nlstate ; jk++){
 2968: 	  if(pos>=1.e-5){
 2969: 	    if(first==1)
 2970: 	      printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 2971: 	    fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 2972: 	  }else{
 2973: 	    if(first==1)
 2974: 	      printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 2975: 	    fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 2976: 	  }
 2977: 	  if( i <= iagemax){
 2978: 	    if(pos>=1.e-5){
 2979: 	      fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
 2980: 	      /*probs[i][jk][j1]= pp[jk]/pos;*/
 2981: 	      /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
 2982: 	    }
 2983: 	    else
 2984: 	      fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
 2985: 	  }
 2986: 	}
 2987: 	
 2988: 	for(jk=-1; jk <=nlstate+ndeath; jk++)
 2989: 	  for(m=-1; m <=nlstate+ndeath; m++)
 2990: 	    if(freq[jk][m][i] !=0 ) {
 2991: 	    if(first==1)
 2992: 	      printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
 2993: 	      fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
 2994: 	    }
 2995: 	if(i <= iagemax)
 2996: 	  fprintf(ficresp,"\n");
 2997: 	if(first==1)
 2998: 	  printf("Others in log...\n");
 2999: 	fprintf(ficlog,"\n");
 3000:       }
 3001:       /*}*/
 3002:   }
 3003:   dateintmean=dateintsum/k2cpt; 
 3004:  
 3005:   fclose(ficresp);
 3006:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
 3007:   free_vector(pp,1,nlstate);
 3008:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
 3009:   /* End of Freq */
 3010: }
 3011: 
 3012: /************ Prevalence ********************/
 3013: 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)
 3014: {  
 3015:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 3016:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 3017:      We still use firstpass and lastpass as another selection.
 3018:   */
 3019:  
 3020:   int i, m, jk, j1, bool, z1,j;
 3021: 
 3022:   double **prop;
 3023:   double posprop; 
 3024:   double  y2; /* in fractional years */
 3025:   int iagemin, iagemax;
 3026:   int first; /** to stop verbosity which is redirected to log file */
 3027: 
 3028:   iagemin= (int) agemin;
 3029:   iagemax= (int) agemax;
 3030:   /*pp=vector(1,nlstate);*/
 3031:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
 3032:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
 3033:   j1=0;
 3034:   
 3035:   /*j=cptcoveff;*/
 3036:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 3037:   
 3038:   first=1;
 3039:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
 3040:     /*for(i1=1; i1<=ncodemax[k1];i1++){
 3041:       j1++;*/
 3042:       
 3043:       for (i=1; i<=nlstate; i++)  
 3044: 	for(m=iagemin; m <= iagemax+3; m++)
 3045: 	  prop[i][m]=0.0;
 3046:      
 3047:       for (i=1; i<=imx; i++) { /* Each individual */
 3048: 	bool=1;
 3049: 	if  (cptcovn>0) {
 3050: 	  for (z1=1; z1<=cptcoveff; z1++) 
 3051: 	    if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
 3052: 	      bool=0;
 3053: 	} 
 3054: 	if (bool==1) { 
 3055: 	  for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
 3056: 	    y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
 3057: 	    if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
 3058: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 3059: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 3060: 	      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); 
 3061:  	      if (s[m][i]>0 && s[m][i]<=nlstate) { 
 3062: 		/*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]]);*/
 3063:  		prop[s[m][i]][(int)agev[m][i]] += weight[i];
 3064:  		prop[s[m][i]][iagemax+3] += weight[i]; 
 3065:  	      } 
 3066: 	    }
 3067: 	  } /* end selection of waves */
 3068: 	}
 3069:       }
 3070:       for(i=iagemin; i <= iagemax+3; i++){  
 3071:  	for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
 3072:  	  posprop += prop[jk][i]; 
 3073:  	} 
 3074: 	
 3075:  	for(jk=1; jk <=nlstate ; jk++){	    
 3076:  	  if( i <=  iagemax){ 
 3077:  	    if(posprop>=1.e-5){ 
 3078:  	      probs[i][jk][j1]= prop[jk][i]/posprop;
 3079:  	    } else{
 3080: 	      if(first==1){
 3081: 		first=0;
 3082: 		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]);
 3083: 	      }
 3084: 	    }
 3085:  	  } 
 3086:  	}/* end jk */ 
 3087:       }/* end i */ 
 3088:     /*} *//* end i1 */
 3089:   } /* end j1 */
 3090:   
 3091:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
 3092:   /*free_vector(pp,1,nlstate);*/
 3093:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
 3094: }  /* End of prevalence */
 3095: 
 3096: /************* Waves Concatenation ***************/
 3097: 
 3098: 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)
 3099: {
 3100:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 3101:      Death is a valid wave (if date is known).
 3102:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
 3103:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 3104:      and mw[mi+1][i]. dh depends on stepm.
 3105:      */
 3106: 
 3107:   int i, mi, m;
 3108:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
 3109:      double sum=0., jmean=0.;*/
 3110:   int first;
 3111:   int j, k=0,jk, ju, jl;
 3112:   double sum=0.;
 3113:   first=0;
 3114:   jmin=100000;
 3115:   jmax=-1;
 3116:   jmean=0.;
 3117:   for(i=1; i<=imx; i++){
 3118:     mi=0;
 3119:     m=firstpass;
 3120:     while(s[m][i] <= nlstate){
 3121:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
 3122: 	mw[++mi][i]=m;
 3123:       if(m >=lastpass)
 3124: 	break;
 3125:       else
 3126: 	m++;
 3127:     }/* end while */
 3128:     if (s[m][i] > nlstate){
 3129:       mi++;	/* Death is another wave */
 3130:       /* if(mi==0)  never been interviewed correctly before death */
 3131: 	 /* Only death is a correct wave */
 3132:       mw[mi][i]=m;
 3133:     }
 3134: 
 3135:     wav[i]=mi;
 3136:     if(mi==0){
 3137:       nbwarn++;
 3138:       if(first==0){
 3139: 	printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
 3140: 	first=1;
 3141:       }
 3142:       if(first==1){
 3143: 	fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
 3144:       }
 3145:     } /* end mi==0 */
 3146:   } /* End individuals */
 3147: 
 3148:   for(i=1; i<=imx; i++){
 3149:     for(mi=1; mi<wav[i];mi++){
 3150:       if (stepm <=0)
 3151: 	dh[mi][i]=1;
 3152:       else{
 3153: 	if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
 3154: 	  if (agedc[i] < 2*AGESUP) {
 3155: 	    j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
 3156: 	    if(j==0) j=1;  /* Survives at least one month after exam */
 3157: 	    else if(j<0){
 3158: 	      nberr++;
 3159: 	      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]);
 3160: 	      j=1; /* Temporary Dangerous patch */
 3161: 	      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);
 3162: 	      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]);
 3163: 	      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);
 3164: 	    }
 3165: 	    k=k+1;
 3166: 	    if (j >= jmax){
 3167: 	      jmax=j;
 3168: 	      ijmax=i;
 3169: 	    }
 3170: 	    if (j <= jmin){
 3171: 	      jmin=j;
 3172: 	      ijmin=i;
 3173: 	    }
 3174: 	    sum=sum+j;
 3175: 	    /*if (j<0) printf("j=%d num=%d \n",j,i);*/
 3176: 	    /*	  printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
 3177: 	  }
 3178: 	}
 3179: 	else{
 3180: 	  j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 3181: /* 	  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]); */
 3182: 
 3183: 	  k=k+1;
 3184: 	  if (j >= jmax) {
 3185: 	    jmax=j;
 3186: 	    ijmax=i;
 3187: 	  }
 3188: 	  else if (j <= jmin){
 3189: 	    jmin=j;
 3190: 	    ijmin=i;
 3191: 	  }
 3192: 	  /*	    if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
 3193: 	  /*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]);*/
 3194: 	  if(j<0){
 3195: 	    nberr++;
 3196: 	    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]);
 3197: 	    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]);
 3198: 	  }
 3199: 	  sum=sum+j;
 3200: 	}
 3201: 	jk= j/stepm;
 3202: 	jl= j -jk*stepm;
 3203: 	ju= j -(jk+1)*stepm;
 3204: 	if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
 3205: 	  if(jl==0){
 3206: 	    dh[mi][i]=jk;
 3207: 	    bh[mi][i]=0;
 3208: 	  }else{ /* We want a negative bias in order to only have interpolation ie
 3209: 		  * to avoid the price of an extra matrix product in likelihood */
 3210: 	    dh[mi][i]=jk+1;
 3211: 	    bh[mi][i]=ju;
 3212: 	  }
 3213: 	}else{
 3214: 	  if(jl <= -ju){
 3215: 	    dh[mi][i]=jk;
 3216: 	    bh[mi][i]=jl;	/* bias is positive if real duration
 3217: 				 * is higher than the multiple of stepm and negative otherwise.
 3218: 				 */
 3219: 	  }
 3220: 	  else{
 3221: 	    dh[mi][i]=jk+1;
 3222: 	    bh[mi][i]=ju;
 3223: 	  }
 3224: 	  if(dh[mi][i]==0){
 3225: 	    dh[mi][i]=1; /* At least one step */
 3226: 	    bh[mi][i]=ju; /* At least one step */
 3227: 	    /*  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);*/
 3228: 	  }
 3229: 	} /* end if mle */
 3230:       }
 3231:     } /* end wave */
 3232:   }
 3233:   jmean=sum/k;
 3234:   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);
 3235:   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);
 3236:  }
 3237: 
 3238: /*********** Tricode ****************************/
 3239: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
 3240: {
 3241:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
 3242:   /*	  Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
 3243:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
 3244:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
 3245:    * nbcode[Tvar[j]][1]= 
 3246:   */
 3247: 
 3248:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
 3249:   int modmaxcovj=0; /* Modality max of covariates j */
 3250:   int cptcode=0; /* Modality max of covariates j */
 3251:   int modmincovj=0; /* Modality min of covariates j */
 3252: 
 3253: 
 3254:   cptcoveff=0; 
 3255:  
 3256:   for (k=-1; k < maxncov; k++) Ndum[k]=0;
 3257:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
 3258: 
 3259:   /* Loop on covariates without age and products */
 3260:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
 3261:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
 3262: 			       modality of this covariate Vj*/ 
 3263:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
 3264: 				    * If product of Vn*Vm, still boolean *:
 3265: 				    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
 3266: 				    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
 3267:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
 3268: 				      modality of the nth covariate of individual i. */
 3269:       if (ij > modmaxcovj)
 3270:         modmaxcovj=ij; 
 3271:       else if (ij < modmincovj) 
 3272: 	modmincovj=ij; 
 3273:       if ((ij < -1) && (ij > NCOVMAX)){
 3274: 	printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
 3275: 	exit(1);
 3276:       }else
 3277:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
 3278:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
 3279:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
 3280:       /* getting the maximum value of the modality of the covariate
 3281: 	 (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
 3282: 	 female is 1, then modmaxcovj=1.*/
 3283:     } /* end for loop on individuals */
 3284:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
 3285:     cptcode=modmaxcovj;
 3286:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
 3287:    /*for (i=0; i<=cptcode; i++) {*/
 3288:     for (i=modmincovj;  i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
 3289:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], i, Ndum[i]);
 3290:       if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
 3291: 	ncodemax[j]++;  /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
 3292:       }
 3293:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
 3294: 	 historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
 3295:     } /* Ndum[-1] number of undefined modalities */
 3296: 
 3297:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
 3298:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
 3299:        If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
 3300:        modmincovj=3; modmaxcovj = 7;
 3301:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
 3302:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
 3303:        defining two dummy variables: variables V1_1 and V1_2.
 3304:        nbcode[Tvar[j]][ij]=k;
 3305:        nbcode[Tvar[j]][1]=0;
 3306:        nbcode[Tvar[j]][2]=1;
 3307:        nbcode[Tvar[j]][3]=2;
 3308:     */
 3309:     ij=1; /* ij is similar to i but can jumps over null modalities */
 3310:     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
 3311:       for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
 3312: 	/*recode from 0 */
 3313: 	if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
 3314: 	  nbcode[Tvar[j]][ij]=k;  /* stores the modality k in an array nbcode. 
 3315: 				     k is a modality. If we have model=V1+V1*sex 
 3316: 				     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
 3317: 	  ij++;
 3318: 	}
 3319: 	if (ij > ncodemax[j]) break; 
 3320:       }  /* end of loop on */
 3321:     } /* end of loop on modality */ 
 3322:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
 3323:   
 3324:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
 3325:   
 3326:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
 3327:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
 3328:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
 3329:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
 3330:  } 
 3331: 
 3332:  ij=1;
 3333:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
 3334:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
 3335:    if((Ndum[i]!=0) && (i<=ncovcol)){
 3336:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
 3337:      Tvaraff[ij]=i; /*For printing (unclear) */
 3338:      ij++;
 3339:    }else
 3340:        Tvaraff[ij]=0;
 3341:  }
 3342:  ij--;
 3343:  cptcoveff=ij; /*Number of total covariates*/
 3344: 
 3345: }
 3346: 
 3347: 
 3348: /*********** Health Expectancies ****************/
 3349: 
 3350: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
 3351: 
 3352: {
 3353:   /* Health expectancies, no variances */
 3354:   int i, j, nhstepm, hstepm, h, nstepm;
 3355:   int nhstepma, nstepma; /* Decreasing with age */
 3356:   double age, agelim, hf;
 3357:   double ***p3mat;
 3358:   double eip;
 3359: 
 3360:   pstamp(ficreseij);
 3361:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
 3362:   fprintf(ficreseij,"# Age");
 3363:   for(i=1; i<=nlstate;i++){
 3364:     for(j=1; j<=nlstate;j++){
 3365:       fprintf(ficreseij," e%1d%1d ",i,j);
 3366:     }
 3367:     fprintf(ficreseij," e%1d. ",i);
 3368:   }
 3369:   fprintf(ficreseij,"\n");
 3370: 
 3371:   
 3372:   if(estepm < stepm){
 3373:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3374:   }
 3375:   else  hstepm=estepm;   
 3376:   /* We compute the life expectancy from trapezoids spaced every estepm months
 3377:    * This is mainly to measure the difference between two models: for example
 3378:    * if stepm=24 months pijx are given only every 2 years and by summing them
 3379:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 3380:    * progression in between and thus overestimating or underestimating according
 3381:    * to the curvature of the survival function. If, for the same date, we 
 3382:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 3383:    * to compare the new estimate of Life expectancy with the same linear 
 3384:    * hypothesis. A more precise result, taking into account a more precise
 3385:    * curvature will be obtained if estepm is as small as stepm. */
 3386: 
 3387:   /* For example we decided to compute the life expectancy with the smallest unit */
 3388:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3389:      nhstepm is the number of hstepm from age to agelim 
 3390:      nstepm is the number of stepm from age to agelin. 
 3391:      Look at hpijx to understand the reason of that which relies in memory size
 3392:      and note for a fixed period like estepm months */
 3393:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3394:      survival function given by stepm (the optimization length). Unfortunately it
 3395:      means that if the survival funtion is printed only each two years of age and if
 3396:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3397:      results. So we changed our mind and took the option of the best precision.
 3398:   */
 3399:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3400: 
 3401:   agelim=AGESUP;
 3402:   /* If stepm=6 months */
 3403:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
 3404:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 3405:     
 3406: /* nhstepm age range expressed in number of stepm */
 3407:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3408:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3409:   /* if (stepm >= YEARM) hstepm=1;*/
 3410:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3411:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3412: 
 3413:   for (age=bage; age<=fage; age ++){ 
 3414:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3415:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3416:     /* if (stepm >= YEARM) hstepm=1;*/
 3417:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 3418: 
 3419:     /* If stepm=6 months */
 3420:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 3421:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 3422:     
 3423:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 3424:     
 3425:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3426:     
 3427:     printf("%d|",(int)age);fflush(stdout);
 3428:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 3429:     
 3430:     /* Computing expectancies */
 3431:     for(i=1; i<=nlstate;i++)
 3432:       for(j=1; j<=nlstate;j++)
 3433: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 3434: 	  eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
 3435: 	  
 3436: 	  /* 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]);*/
 3437: 
 3438: 	}
 3439: 
 3440:     fprintf(ficreseij,"%3.0f",age );
 3441:     for(i=1; i<=nlstate;i++){
 3442:       eip=0;
 3443:       for(j=1; j<=nlstate;j++){
 3444: 	eip +=eij[i][j][(int)age];
 3445: 	fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
 3446:       }
 3447:       fprintf(ficreseij,"%9.4f", eip );
 3448:     }
 3449:     fprintf(ficreseij,"\n");
 3450:     
 3451:   }
 3452:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3453:   printf("\n");
 3454:   fprintf(ficlog,"\n");
 3455:   
 3456: }
 3457: 
 3458: 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[] )
 3459: 
 3460: {
 3461:   /* Covariances of health expectancies eij and of total life expectancies according
 3462:    to initial status i, ei. .
 3463:   */
 3464:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
 3465:   int nhstepma, nstepma; /* Decreasing with age */
 3466:   double age, agelim, hf;
 3467:   double ***p3matp, ***p3matm, ***varhe;
 3468:   double **dnewm,**doldm;
 3469:   double *xp, *xm;
 3470:   double **gp, **gm;
 3471:   double ***gradg, ***trgradg;
 3472:   int theta;
 3473: 
 3474:   double eip, vip;
 3475: 
 3476:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
 3477:   xp=vector(1,npar);
 3478:   xm=vector(1,npar);
 3479:   dnewm=matrix(1,nlstate*nlstate,1,npar);
 3480:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
 3481:   
 3482:   pstamp(ficresstdeij);
 3483:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
 3484:   fprintf(ficresstdeij,"# Age");
 3485:   for(i=1; i<=nlstate;i++){
 3486:     for(j=1; j<=nlstate;j++)
 3487:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
 3488:     fprintf(ficresstdeij," e%1d. ",i);
 3489:   }
 3490:   fprintf(ficresstdeij,"\n");
 3491: 
 3492:   pstamp(ficrescveij);
 3493:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
 3494:   fprintf(ficrescveij,"# Age");
 3495:   for(i=1; i<=nlstate;i++)
 3496:     for(j=1; j<=nlstate;j++){
 3497:       cptj= (j-1)*nlstate+i;
 3498:       for(i2=1; i2<=nlstate;i2++)
 3499: 	for(j2=1; j2<=nlstate;j2++){
 3500: 	  cptj2= (j2-1)*nlstate+i2;
 3501: 	  if(cptj2 <= cptj)
 3502: 	    fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
 3503: 	}
 3504:     }
 3505:   fprintf(ficrescveij,"\n");
 3506:   
 3507:   if(estepm < stepm){
 3508:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3509:   }
 3510:   else  hstepm=estepm;   
 3511:   /* We compute the life expectancy from trapezoids spaced every estepm months
 3512:    * This is mainly to measure the difference between two models: for example
 3513:    * if stepm=24 months pijx are given only every 2 years and by summing them
 3514:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 3515:    * progression in between and thus overestimating or underestimating according
 3516:    * to the curvature of the survival function. If, for the same date, we 
 3517:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 3518:    * to compare the new estimate of Life expectancy with the same linear 
 3519:    * hypothesis. A more precise result, taking into account a more precise
 3520:    * curvature will be obtained if estepm is as small as stepm. */
 3521: 
 3522:   /* For example we decided to compute the life expectancy with the smallest unit */
 3523:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3524:      nhstepm is the number of hstepm from age to agelim 
 3525:      nstepm is the number of stepm from age to agelin. 
 3526:      Look at hpijx to understand the reason of that which relies in memory size
 3527:      and note for a fixed period like estepm months */
 3528:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3529:      survival function given by stepm (the optimization length). Unfortunately it
 3530:      means that if the survival funtion is printed only each two years of age and if
 3531:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3532:      results. So we changed our mind and took the option of the best precision.
 3533:   */
 3534:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3535: 
 3536:   /* If stepm=6 months */
 3537:   /* nhstepm age range expressed in number of stepm */
 3538:   agelim=AGESUP;
 3539:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
 3540:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3541:   /* if (stepm >= YEARM) hstepm=1;*/
 3542:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3543:   
 3544:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3545:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3546:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
 3547:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
 3548:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
 3549:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
 3550: 
 3551:   for (age=bage; age<=fage; age ++){ 
 3552:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3553:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3554:     /* if (stepm >= YEARM) hstepm=1;*/
 3555:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 3556: 
 3557:     /* If stepm=6 months */
 3558:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 3559:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 3560:     
 3561:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3562: 
 3563:     /* Computing  Variances of health expectancies */
 3564:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
 3565:        decrease memory allocation */
 3566:     for(theta=1; theta <=npar; theta++){
 3567:       for(i=1; i<=npar; i++){ 
 3568: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3569: 	xm[i] = x[i] - (i==theta ?delti[theta]:0);
 3570:       }
 3571:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
 3572:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
 3573:   
 3574:       for(j=1; j<= nlstate; j++){
 3575: 	for(i=1; i<=nlstate; i++){
 3576: 	  for(h=0; h<=nhstepm-1; h++){
 3577: 	    gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
 3578: 	    gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
 3579: 	  }
 3580: 	}
 3581:       }
 3582:      
 3583:       for(ij=1; ij<= nlstate*nlstate; ij++)
 3584: 	for(h=0; h<=nhstepm-1; h++){
 3585: 	  gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
 3586: 	}
 3587:     }/* End theta */
 3588:     
 3589:     
 3590:     for(h=0; h<=nhstepm-1; h++)
 3591:       for(j=1; j<=nlstate*nlstate;j++)
 3592: 	for(theta=1; theta <=npar; theta++)
 3593: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 3594:     
 3595: 
 3596:      for(ij=1;ij<=nlstate*nlstate;ij++)
 3597:       for(ji=1;ji<=nlstate*nlstate;ji++)
 3598: 	varhe[ij][ji][(int)age] =0.;
 3599: 
 3600:      printf("%d|",(int)age);fflush(stdout);
 3601:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 3602:      for(h=0;h<=nhstepm-1;h++){
 3603:       for(k=0;k<=nhstepm-1;k++){
 3604: 	matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
 3605: 	matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
 3606: 	for(ij=1;ij<=nlstate*nlstate;ij++)
 3607: 	  for(ji=1;ji<=nlstate*nlstate;ji++)
 3608: 	    varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
 3609:       }
 3610:     }
 3611: 
 3612:     /* Computing expectancies */
 3613:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 3614:     for(i=1; i<=nlstate;i++)
 3615:       for(j=1; j<=nlstate;j++)
 3616: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 3617: 	  eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
 3618: 	  
 3619: 	  /* 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]);*/
 3620: 
 3621: 	}
 3622: 
 3623:     fprintf(ficresstdeij,"%3.0f",age );
 3624:     for(i=1; i<=nlstate;i++){
 3625:       eip=0.;
 3626:       vip=0.;
 3627:       for(j=1; j<=nlstate;j++){
 3628: 	eip += eij[i][j][(int)age];
 3629: 	for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
 3630: 	  vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
 3631: 	fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
 3632:       }
 3633:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
 3634:     }
 3635:     fprintf(ficresstdeij,"\n");
 3636: 
 3637:     fprintf(ficrescveij,"%3.0f",age );
 3638:     for(i=1; i<=nlstate;i++)
 3639:       for(j=1; j<=nlstate;j++){
 3640: 	cptj= (j-1)*nlstate+i;
 3641: 	for(i2=1; i2<=nlstate;i2++)
 3642: 	  for(j2=1; j2<=nlstate;j2++){
 3643: 	    cptj2= (j2-1)*nlstate+i2;
 3644: 	    if(cptj2 <= cptj)
 3645: 	      fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
 3646: 	  }
 3647:       }
 3648:     fprintf(ficrescveij,"\n");
 3649:    
 3650:   }
 3651:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
 3652:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
 3653:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
 3654:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
 3655:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3656:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3657:   printf("\n");
 3658:   fprintf(ficlog,"\n");
 3659: 
 3660:   free_vector(xm,1,npar);
 3661:   free_vector(xp,1,npar);
 3662:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
 3663:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
 3664:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
 3665: }
 3666: 
 3667: /************ Variance ******************/
 3668: 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[])
 3669: {
 3670:   /* Variance of health expectancies */
 3671:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
 3672:   /* double **newm;*/
 3673:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
 3674:   
 3675:   int movingaverage();
 3676:   double **dnewm,**doldm;
 3677:   double **dnewmp,**doldmp;
 3678:   int i, j, nhstepm, hstepm, h, nstepm ;
 3679:   int k;
 3680:   double *xp;
 3681:   double **gp, **gm;  /* for var eij */
 3682:   double ***gradg, ***trgradg; /*for var eij */
 3683:   double **gradgp, **trgradgp; /* for var p point j */
 3684:   double *gpp, *gmp; /* for var p point j */
 3685:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
 3686:   double ***p3mat;
 3687:   double age,agelim, hf;
 3688:   double ***mobaverage;
 3689:   int theta;
 3690:   char digit[4];
 3691:   char digitp[25];
 3692: 
 3693:   char fileresprobmorprev[FILENAMELENGTH];
 3694: 
 3695:   if(popbased==1){
 3696:     if(mobilav!=0)
 3697:       strcpy(digitp,"-populbased-mobilav-");
 3698:     else strcpy(digitp,"-populbased-nomobil-");
 3699:   }
 3700:   else 
 3701:     strcpy(digitp,"-stablbased-");
 3702: 
 3703:   if (mobilav!=0) {
 3704:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3705:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 3706:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 3707:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 3708:     }
 3709:   }
 3710: 
 3711:   strcpy(fileresprobmorprev,"prmorprev"); 
 3712:   sprintf(digit,"%-d",ij);
 3713:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
 3714:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
 3715:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
 3716:   strcat(fileresprobmorprev,fileres);
 3717:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
 3718:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
 3719:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
 3720:   }
 3721:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 3722:  
 3723:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 3724:   pstamp(ficresprobmorprev);
 3725:   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);
 3726:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
 3727:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 3728:     fprintf(ficresprobmorprev," p.%-d SE",j);
 3729:     for(i=1; i<=nlstate;i++)
 3730:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 3731:   }  
 3732:   fprintf(ficresprobmorprev,"\n");
 3733:   fprintf(ficgp,"\n# Routine varevsij");
 3734:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
 3735:   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");
 3736:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
 3737: /*   } */
 3738:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3739:   pstamp(ficresvij);
 3740:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
 3741:   if(popbased==1)
 3742:     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);
 3743:   else
 3744:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
 3745:   fprintf(ficresvij,"# Age");
 3746:   for(i=1; i<=nlstate;i++)
 3747:     for(j=1; j<=nlstate;j++)
 3748:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
 3749:   fprintf(ficresvij,"\n");
 3750: 
 3751:   xp=vector(1,npar);
 3752:   dnewm=matrix(1,nlstate,1,npar);
 3753:   doldm=matrix(1,nlstate,1,nlstate);
 3754:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
 3755:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3756: 
 3757:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
 3758:   gpp=vector(nlstate+1,nlstate+ndeath);
 3759:   gmp=vector(nlstate+1,nlstate+ndeath);
 3760:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 3761:   
 3762:   if(estepm < stepm){
 3763:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3764:   }
 3765:   else  hstepm=estepm;   
 3766:   /* For example we decided to compute the life expectancy with the smallest unit */
 3767:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3768:      nhstepm is the number of hstepm from age to agelim 
 3769:      nstepm is the number of stepm from age to agelin. 
 3770:      Look at function hpijx to understand why (it is linked to memory size questions) */
 3771:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3772:      survival function given by stepm (the optimization length). Unfortunately it
 3773:      means that if the survival funtion is printed every two years of age and if
 3774:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3775:      results. So we changed our mind and took the option of the best precision.
 3776:   */
 3777:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3778:   agelim = AGESUP;
 3779:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 3780:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 3781:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3782:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3783:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
 3784:     gp=matrix(0,nhstepm,1,nlstate);
 3785:     gm=matrix(0,nhstepm,1,nlstate);
 3786: 
 3787: 
 3788:     for(theta=1; theta <=npar; theta++){
 3789:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
 3790: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3791:       }
 3792:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 3793:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3794: 
 3795:       if (popbased==1) {
 3796: 	if(mobilav ==0){
 3797: 	  for(i=1; i<=nlstate;i++)
 3798: 	    prlim[i][i]=probs[(int)age][i][ij];
 3799: 	}else{ /* mobilav */ 
 3800: 	  for(i=1; i<=nlstate;i++)
 3801: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 3802: 	}
 3803:       }
 3804:   
 3805:       for(j=1; j<= nlstate; j++){
 3806: 	for(h=0; h<=nhstepm; h++){
 3807: 	  for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 3808: 	    gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 3809: 	}
 3810:       }
 3811:       /* This for computing probability of death (h=1 means
 3812:          computed over hstepm matrices product = hstepm*stepm months) 
 3813:          as a weighted average of prlim.
 3814:       */
 3815:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3816: 	for(i=1,gpp[j]=0.; i<= nlstate; i++)
 3817: 	  gpp[j] += prlim[i][i]*p3mat[i][j][1];
 3818:       }    
 3819:       /* end probability of death */
 3820: 
 3821:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
 3822: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 3823:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 3824:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3825:  
 3826:       if (popbased==1) {
 3827: 	if(mobilav ==0){
 3828: 	  for(i=1; i<=nlstate;i++)
 3829: 	    prlim[i][i]=probs[(int)age][i][ij];
 3830: 	}else{ /* mobilav */ 
 3831: 	  for(i=1; i<=nlstate;i++)
 3832: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 3833: 	}
 3834:       }
 3835: 
 3836:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
 3837: 	for(h=0; h<=nhstepm; h++){
 3838: 	  for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 3839: 	    gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 3840: 	}
 3841:       }
 3842:       /* This for computing probability of death (h=1 means
 3843:          computed over hstepm matrices product = hstepm*stepm months) 
 3844:          as a weighted average of prlim.
 3845:       */
 3846:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3847: 	for(i=1,gmp[j]=0.; i<= nlstate; i++)
 3848:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
 3849:       }    
 3850:       /* end probability of death */
 3851: 
 3852:       for(j=1; j<= nlstate; j++) /* vareij */
 3853: 	for(h=0; h<=nhstepm; h++){
 3854: 	  gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 3855: 	}
 3856: 
 3857:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
 3858: 	gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
 3859:       }
 3860: 
 3861:     } /* End theta */
 3862: 
 3863:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
 3864: 
 3865:     for(h=0; h<=nhstepm; h++) /* veij */
 3866:       for(j=1; j<=nlstate;j++)
 3867: 	for(theta=1; theta <=npar; theta++)
 3868: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 3869: 
 3870:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
 3871:       for(theta=1; theta <=npar; theta++)
 3872: 	trgradgp[j][theta]=gradgp[theta][j];
 3873:   
 3874: 
 3875:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3876:     for(i=1;i<=nlstate;i++)
 3877:       for(j=1;j<=nlstate;j++)
 3878: 	vareij[i][j][(int)age] =0.;
 3879: 
 3880:     for(h=0;h<=nhstepm;h++){
 3881:       for(k=0;k<=nhstepm;k++){
 3882: 	matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 3883: 	matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
 3884: 	for(i=1;i<=nlstate;i++)
 3885: 	  for(j=1;j<=nlstate;j++)
 3886: 	    vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
 3887:       }
 3888:     }
 3889:   
 3890:     /* pptj */
 3891:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
 3892:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
 3893:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
 3894:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
 3895: 	varppt[j][i]=doldmp[j][i];
 3896:     /* end ppptj */
 3897:     /*  x centered again */
 3898:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
 3899:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
 3900:  
 3901:     if (popbased==1) {
 3902:       if(mobilav ==0){
 3903: 	for(i=1; i<=nlstate;i++)
 3904: 	  prlim[i][i]=probs[(int)age][i][ij];
 3905:       }else{ /* mobilav */ 
 3906: 	for(i=1; i<=nlstate;i++)
 3907: 	  prlim[i][i]=mobaverage[(int)age][i][ij];
 3908:       }
 3909:     }
 3910:              
 3911:     /* This for computing probability of death (h=1 means
 3912:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
 3913:        as a weighted average of prlim.
 3914:     */
 3915:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3916:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
 3917: 	gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
 3918:     }    
 3919:     /* end probability of death */
 3920: 
 3921:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
 3922:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 3923:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
 3924:       for(i=1; i<=nlstate;i++){
 3925: 	fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 3926:       }
 3927:     } 
 3928:     fprintf(ficresprobmorprev,"\n");
 3929: 
 3930:     fprintf(ficresvij,"%.0f ",age );
 3931:     for(i=1; i<=nlstate;i++)
 3932:       for(j=1; j<=nlstate;j++){
 3933: 	fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
 3934:       }
 3935:     fprintf(ficresvij,"\n");
 3936:     free_matrix(gp,0,nhstepm,1,nlstate);
 3937:     free_matrix(gm,0,nhstepm,1,nlstate);
 3938:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 3939:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 3940:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3941:   } /* End age */
 3942:   free_vector(gpp,nlstate+1,nlstate+ndeath);
 3943:   free_vector(gmp,nlstate+1,nlstate+ndeath);
 3944:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
 3945:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 3946:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
 3947:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
 3948:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
 3949: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
 3950: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
 3951: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
 3952:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
 3953:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
 3954:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
 3955:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
 3956:   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);
 3957:   /*  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);
 3958: */
 3959: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
 3960:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
 3961: 
 3962:   free_vector(xp,1,npar);
 3963:   free_matrix(doldm,1,nlstate,1,nlstate);
 3964:   free_matrix(dnewm,1,nlstate,1,npar);
 3965:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3966:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
 3967:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3968:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3969:   fclose(ficresprobmorprev);
 3970:   fflush(ficgp);
 3971:   fflush(fichtm); 
 3972: }  /* end varevsij */
 3973: 
 3974: /************ Variance of prevlim ******************/
 3975: 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[])
 3976: {
 3977:   /* Variance of prevalence limit */
 3978:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 3979: 
 3980:   double **dnewm,**doldm;
 3981:   int i, j, nhstepm, hstepm;
 3982:   double *xp;
 3983:   double *gp, *gm;
 3984:   double **gradg, **trgradg;
 3985:   double age,agelim;
 3986:   int theta;
 3987:   
 3988:   pstamp(ficresvpl);
 3989:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
 3990:   fprintf(ficresvpl,"# Age");
 3991:   for(i=1; i<=nlstate;i++)
 3992:       fprintf(ficresvpl," %1d-%1d",i,i);
 3993:   fprintf(ficresvpl,"\n");
 3994: 
 3995:   xp=vector(1,npar);
 3996:   dnewm=matrix(1,nlstate,1,npar);
 3997:   doldm=matrix(1,nlstate,1,nlstate);
 3998:   
 3999:   hstepm=1*YEARM; /* Every year of age */
 4000:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 4001:   agelim = AGESUP;
 4002:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 4003:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 4004:     if (stepm >= YEARM) hstepm=1;
 4005:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 4006:     gradg=matrix(1,npar,1,nlstate);
 4007:     gp=vector(1,nlstate);
 4008:     gm=vector(1,nlstate);
 4009: 
 4010:     for(theta=1; theta <=npar; theta++){
 4011:       for(i=1; i<=npar; i++){ /* Computes gradient */
 4012: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 4013:       }
 4014:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 4015:       for(i=1;i<=nlstate;i++)
 4016: 	gp[i] = prlim[i][i];
 4017:     
 4018:       for(i=1; i<=npar; i++) /* Computes gradient */
 4019: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 4020:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 4021:       for(i=1;i<=nlstate;i++)
 4022: 	gm[i] = prlim[i][i];
 4023: 
 4024:       for(i=1;i<=nlstate;i++)
 4025: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 4026:     } /* End theta */
 4027: 
 4028:     trgradg =matrix(1,nlstate,1,npar);
 4029: 
 4030:     for(j=1; j<=nlstate;j++)
 4031:       for(theta=1; theta <=npar; theta++)
 4032: 	trgradg[j][theta]=gradg[theta][j];
 4033: 
 4034:     for(i=1;i<=nlstate;i++)
 4035:       varpl[i][(int)age] =0.;
 4036:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 4037:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 4038:     for(i=1;i<=nlstate;i++)
 4039:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 4040: 
 4041:     fprintf(ficresvpl,"%.0f ",age );
 4042:     for(i=1; i<=nlstate;i++)
 4043:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
 4044:     fprintf(ficresvpl,"\n");
 4045:     free_vector(gp,1,nlstate);
 4046:     free_vector(gm,1,nlstate);
 4047:     free_matrix(gradg,1,npar,1,nlstate);
 4048:     free_matrix(trgradg,1,nlstate,1,npar);
 4049:   } /* End age */
 4050: 
 4051:   free_vector(xp,1,npar);
 4052:   free_matrix(doldm,1,nlstate,1,npar);
 4053:   free_matrix(dnewm,1,nlstate,1,nlstate);
 4054: 
 4055: }
 4056: 
 4057: /************ Variance of one-step probabilities  ******************/
 4058: 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[])
 4059: {
 4060:   int i, j=0,  k1, l1, tj;
 4061:   int k2, l2, j1,  z1;
 4062:   int k=0, l;
 4063:   int first=1, first1, first2;
 4064:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
 4065:   double **dnewm,**doldm;
 4066:   double *xp;
 4067:   double *gp, *gm;
 4068:   double **gradg, **trgradg;
 4069:   double **mu;
 4070:   double age, cov[NCOVMAX+1];
 4071:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
 4072:   int theta;
 4073:   char fileresprob[FILENAMELENGTH];
 4074:   char fileresprobcov[FILENAMELENGTH];
 4075:   char fileresprobcor[FILENAMELENGTH];
 4076:   double ***varpij;
 4077: 
 4078:   strcpy(fileresprob,"prob"); 
 4079:   strcat(fileresprob,fileres);
 4080:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
 4081:     printf("Problem with resultfile: %s\n", fileresprob);
 4082:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
 4083:   }
 4084:   strcpy(fileresprobcov,"probcov"); 
 4085:   strcat(fileresprobcov,fileres);
 4086:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
 4087:     printf("Problem with resultfile: %s\n", fileresprobcov);
 4088:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 4089:   }
 4090:   strcpy(fileresprobcor,"probcor"); 
 4091:   strcat(fileresprobcor,fileres);
 4092:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 4093:     printf("Problem with resultfile: %s\n", fileresprobcor);
 4094:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 4095:   }
 4096:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 4097:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 4098:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 4099:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 4100:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 4101:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 4102:   pstamp(ficresprob);
 4103:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
 4104:   fprintf(ficresprob,"# Age");
 4105:   pstamp(ficresprobcov);
 4106:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
 4107:   fprintf(ficresprobcov,"# Age");
 4108:   pstamp(ficresprobcor);
 4109:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 4110:   fprintf(ficresprobcor,"# Age");
 4111: 
 4112: 
 4113:   for(i=1; i<=nlstate;i++)
 4114:     for(j=1; j<=(nlstate+ndeath);j++){
 4115:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
 4116:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
 4117:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
 4118:     }  
 4119:  /* fprintf(ficresprob,"\n");
 4120:   fprintf(ficresprobcov,"\n");
 4121:   fprintf(ficresprobcor,"\n");
 4122:  */
 4123:   xp=vector(1,npar);
 4124:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 4125:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 4126:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
 4127:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 4128:   first=1;
 4129:   fprintf(ficgp,"\n# Routine varprob");
 4130:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
 4131:   fprintf(fichtm,"\n");
 4132: 
 4133:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
 4134:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
 4135:   file %s<br>\n",optionfilehtmcov);
 4136:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
 4137: and drawn. It helps understanding how is the covariance between two incidences.\
 4138:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
 4139:   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. \
 4140: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
 4141: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
 4142: standard deviations wide on each axis. <br>\
 4143:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
 4144:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 4145: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
 4146: 
 4147:   cov[1]=1;
 4148:   /* tj=cptcoveff; */
 4149:   tj = (int) pow(2,cptcoveff);
 4150:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
 4151:   j1=0;
 4152:   for(j1=1; j1<=tj;j1++){
 4153:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
 4154:     /*j1++;*/
 4155:       if  (cptcovn>0) {
 4156: 	fprintf(ficresprob, "\n#********** Variable "); 
 4157: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 4158: 	fprintf(ficresprob, "**********\n#\n");
 4159: 	fprintf(ficresprobcov, "\n#********** Variable "); 
 4160: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 4161: 	fprintf(ficresprobcov, "**********\n#\n");
 4162: 	
 4163: 	fprintf(ficgp, "\n#********** Variable "); 
 4164: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 4165: 	fprintf(ficgp, "**********\n#\n");
 4166: 	
 4167: 	
 4168: 	fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
 4169: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 4170: 	fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
 4171: 	
 4172: 	fprintf(ficresprobcor, "\n#********** Variable ");    
 4173: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 4174: 	fprintf(ficresprobcor, "**********\n#");    
 4175:       }
 4176:       
 4177:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
 4178:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 4179:       gp=vector(1,(nlstate)*(nlstate+ndeath));
 4180:       gm=vector(1,(nlstate)*(nlstate+ndeath));
 4181:       for (age=bage; age<=fage; age ++){ 
 4182: 	cov[2]=age;
 4183: 	if(nagesqr==1)
 4184: 	  cov[3]= age*age;
 4185: 	for (k=1; k<=cptcovn;k++) {
 4186: 	  cov[2+nagesqr+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
 4187: 							 * 1  1 1 1 1
 4188: 							 * 2  2 1 1 1
 4189: 							 * 3  1 2 1 1
 4190: 							 */
 4191: 	  /* nbcode[1][1]=0 nbcode[1][2]=1;*/
 4192: 	}
 4193: 	/* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 4194: 	for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2];
 4195: 	for (k=1; k<=cptcovprod;k++)
 4196: 	  cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 4197: 	
 4198:     
 4199: 	for(theta=1; theta <=npar; theta++){
 4200: 	  for(i=1; i<=npar; i++)
 4201: 	    xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
 4202: 	  
 4203: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 4204: 	  
 4205: 	  k=0;
 4206: 	  for(i=1; i<= (nlstate); i++){
 4207: 	    for(j=1; j<=(nlstate+ndeath);j++){
 4208: 	      k=k+1;
 4209: 	      gp[k]=pmmij[i][j];
 4210: 	    }
 4211: 	  }
 4212: 	  
 4213: 	  for(i=1; i<=npar; i++)
 4214: 	    xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
 4215:     
 4216: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 4217: 	  k=0;
 4218: 	  for(i=1; i<=(nlstate); i++){
 4219: 	    for(j=1; j<=(nlstate+ndeath);j++){
 4220: 	      k=k+1;
 4221: 	      gm[k]=pmmij[i][j];
 4222: 	    }
 4223: 	  }
 4224:      
 4225: 	  for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
 4226: 	    gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
 4227: 	}
 4228: 
 4229: 	for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
 4230: 	  for(theta=1; theta <=npar; theta++)
 4231: 	    trgradg[j][theta]=gradg[theta][j];
 4232: 	
 4233: 	matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
 4234: 	matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
 4235: 
 4236: 	pmij(pmmij,cov,ncovmodel,x,nlstate);
 4237: 	
 4238: 	k=0;
 4239: 	for(i=1; i<=(nlstate); i++){
 4240: 	  for(j=1; j<=(nlstate+ndeath);j++){
 4241: 	    k=k+1;
 4242: 	    mu[k][(int) age]=pmmij[i][j];
 4243: 	  }
 4244: 	}
 4245:      	for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 4246: 	  for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 4247: 	    varpij[i][j][(int)age] = doldm[i][j];
 4248: 
 4249: 	/*printf("\n%d ",(int)age);
 4250: 	  for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 4251: 	  printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 4252: 	  fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 4253: 	  }*/
 4254: 
 4255: 	fprintf(ficresprob,"\n%d ",(int)age);
 4256: 	fprintf(ficresprobcov,"\n%d ",(int)age);
 4257: 	fprintf(ficresprobcor,"\n%d ",(int)age);
 4258: 
 4259: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
 4260: 	  fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
 4261: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 4262: 	  fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
 4263: 	  fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
 4264: 	}
 4265: 	i=0;
 4266: 	for (k=1; k<=(nlstate);k++){
 4267:  	  for (l=1; l<=(nlstate+ndeath);l++){ 
 4268:  	    i++;
 4269: 	    fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 4270: 	    fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
 4271: 	    for (j=1; j<=i;j++){
 4272: 	      /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
 4273: 	      fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
 4274: 	      fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
 4275: 	    }
 4276: 	  }
 4277: 	}/* end of loop for state */
 4278:       } /* end of loop for age */
 4279:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
 4280:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 4281:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 4282:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 4283:       
 4284:       /* Confidence intervalle of pij  */
 4285:       /*
 4286: 	fprintf(ficgp,"\nunset parametric;unset label");
 4287: 	fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
 4288: 	fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 4289: 	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);
 4290: 	fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
 4291: 	fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
 4292: 	fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
 4293:       */
 4294: 
 4295:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
 4296:       first1=1;first2=2;
 4297:       for (k2=1; k2<=(nlstate);k2++){
 4298: 	for (l2=1; l2<=(nlstate+ndeath);l2++){ 
 4299: 	  if(l2==k2) continue;
 4300: 	  j=(k2-1)*(nlstate+ndeath)+l2;
 4301: 	  for (k1=1; k1<=(nlstate);k1++){
 4302: 	    for (l1=1; l1<=(nlstate+ndeath);l1++){ 
 4303: 	      if(l1==k1) continue;
 4304: 	      i=(k1-1)*(nlstate+ndeath)+l1;
 4305: 	      if(i<=j) continue;
 4306: 	      for (age=bage; age<=fage; age ++){ 
 4307: 		if ((int)age %5==0){
 4308: 		  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
 4309: 		  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
 4310: 		  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
 4311: 		  mu1=mu[i][(int) age]/stepm*YEARM ;
 4312: 		  mu2=mu[j][(int) age]/stepm*YEARM;
 4313: 		  c12=cv12/sqrt(v1*v2);
 4314: 		  /* Computing eigen value of matrix of covariance */
 4315: 		  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 4316: 		  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 4317: 		  if ((lc2 <0) || (lc1 <0) ){
 4318: 		    if(first2==1){
 4319: 		      first1=0;
 4320: 		    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);
 4321: 		    }
 4322: 		    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);
 4323: 		    /* lc1=fabs(lc1); */ /* If we want to have them positive */
 4324: 		    /* lc2=fabs(lc2); */
 4325: 		  }
 4326: 
 4327: 		  /* Eigen vectors */
 4328: 		  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
 4329: 		  /*v21=sqrt(1.-v11*v11); *//* error */
 4330: 		  v21=(lc1-v1)/cv12*v11;
 4331: 		  v12=-v21;
 4332: 		  v22=v11;
 4333: 		  tnalp=v21/v11;
 4334: 		  if(first1==1){
 4335: 		    first1=0;
 4336: 		    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);
 4337: 		  }
 4338: 		  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);
 4339: 		  /*printf(fignu*/
 4340: 		  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
 4341: 		  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
 4342: 		  if(first==1){
 4343: 		    first=0;
 4344:  		    fprintf(ficgp,"\nset parametric;unset label");
 4345: 		    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);
 4346: 		    fprintf(ficgp,"\nset ter png small size 320, 240");
 4347: 		    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
 4348:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
 4349: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
 4350: 			    subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
 4351: 			    subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4352: 		    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4353: 		    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
 4354: 		    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4355: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 4356: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 4357: 		    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",\
 4358: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 4359: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 4360: 		  }else{
 4361: 		    first=0;
 4362: 		    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
 4363: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 4364: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 4365: 		    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",\
 4366: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 4367: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 4368: 		  }/* if first */
 4369: 		} /* age mod 5 */
 4370: 	      } /* end loop age */
 4371: 	      fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4372: 	      first=1;
 4373: 	    } /*l12 */
 4374: 	  } /* k12 */
 4375: 	} /*l1 */
 4376:       }/* k1 */
 4377:       /* } */ /* loop covariates */
 4378:   }
 4379:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 4380:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
 4381:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 4382:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
 4383:   free_vector(xp,1,npar);
 4384:   fclose(ficresprob);
 4385:   fclose(ficresprobcov);
 4386:   fclose(ficresprobcor);
 4387:   fflush(ficgp);
 4388:   fflush(fichtmcov);
 4389: }
 4390: 
 4391: 
 4392: /******************* Printing html file ***********/
 4393: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
 4394: 		  int lastpass, int stepm, int weightopt, char model[],\
 4395: 		  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 4396: 		  int popforecast, int estepm ,\
 4397: 		  double jprev1, double mprev1,double anprev1, \
 4398: 		  double jprev2, double mprev2,double anprev2){
 4399:   int jj1, k1, i1, cpt;
 4400: 
 4401:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
 4402:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
 4403: </ul>");
 4404:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
 4405:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
 4406: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
 4407:    fprintf(fichtm,"\
 4408:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 4409: 	   stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
 4410:    fprintf(fichtm,"\
 4411:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 4412: 	   subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
 4413:    fprintf(fichtm,"\
 4414:  - (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): \
 4415:    <a href=\"%s\">%s</a> <br>\n",
 4416: 	   estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
 4417:    fprintf(fichtm,"\
 4418:  - Population projections by age and states: \
 4419:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
 4420: 
 4421: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
 4422: 
 4423:  m=pow(2,cptcoveff);
 4424:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 4425: 
 4426:  jj1=0;
 4427:  for(k1=1; k1<=m;k1++){
 4428:    for(i1=1; i1<=ncodemax[k1];i1++){
 4429:      jj1++;
 4430:      if (cptcovn > 0) {
 4431:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 4432:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 4433: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 4434:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 4435:      }
 4436:      /* Pij */
 4437:      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> \
 4438: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
 4439:      /* Quasi-incidences */
 4440:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
 4441:  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> \
 4442: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
 4443:        /* Period (stable) prevalence in each health state */
 4444:        for(cpt=1; cpt<=nlstate;cpt++){
 4445: 	 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> \
 4446: <img src=\"%s%d_%d.png\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
 4447:        }
 4448:      for(cpt=1; cpt<=nlstate;cpt++) {
 4449:         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> \
 4450: <img src=\"%s%d%d.png\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
 4451:      }
 4452:    } /* end i1 */
 4453:  }/* End k1 */
 4454:  fprintf(fichtm,"</ul>");
 4455: 
 4456: 
 4457:  fprintf(fichtm,"\
 4458: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
 4459:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
 4460: 
 4461:  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4462: 	 subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
 4463:  fprintf(fichtm,"\
 4464:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4465: 	 subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
 4466: 
 4467:  fprintf(fichtm,"\
 4468:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4469: 	 subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
 4470:  fprintf(fichtm,"\
 4471:  - 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): \
 4472:    <a href=\"%s\">%s</a> <br>\n</li>",
 4473: 	   estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
 4474:  fprintf(fichtm,"\
 4475:  - (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): \
 4476:    <a href=\"%s\">%s</a> <br>\n</li>",
 4477: 	   estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
 4478:  fprintf(fichtm,"\
 4479:  - 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",
 4480: 	 estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
 4481:  fprintf(fichtm,"\
 4482:  - 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",
 4483: 	 estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
 4484:  fprintf(fichtm,"\
 4485:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
 4486: 	 subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
 4487: 
 4488: /*  if(popforecast==1) fprintf(fichtm,"\n */
 4489: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
 4490: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
 4491: /* 	<br>",fileres,fileres,fileres,fileres); */
 4492: /*  else  */
 4493: /*    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); */
 4494:  fflush(fichtm);
 4495:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
 4496: 
 4497:  m=pow(2,cptcoveff);
 4498:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 4499: 
 4500:  jj1=0;
 4501:  for(k1=1; k1<=m;k1++){
 4502:    for(i1=1; i1<=ncodemax[k1];i1++){
 4503:      jj1++;
 4504:      if (cptcovn > 0) {
 4505:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 4506:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 4507: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 4508:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 4509:      }
 4510:      for(cpt=1; cpt<=nlstate;cpt++) {
 4511:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
 4512: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
 4513: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
 4514:      }
 4515:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
 4516: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
 4517: true period expectancies (those weighted with period prevalences are also\
 4518:  drawn in addition to the population based expectancies computed using\
 4519:  observed and cahotic prevalences: %s%d.png<br>\
 4520: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
 4521:    } /* end i1 */
 4522:  }/* End k1 */
 4523:  fprintf(fichtm,"</ul>");
 4524:  fflush(fichtm);
 4525: }
 4526: 
 4527: /******************* Gnuplot file **************/
 4528: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 4529: 
 4530:   char dirfileres[132],optfileres[132];
 4531:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
 4532:   int ng=0;
 4533: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
 4534: /*     printf("Problem with file %s",optionfilegnuplot); */
 4535: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
 4536: /*   } */
 4537: 
 4538:   /*#ifdef windows */
 4539:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 4540:     /*#endif */
 4541:   m=pow(2,cptcoveff);
 4542: 
 4543:   strcpy(dirfileres,optionfilefiname);
 4544:   strcpy(optfileres,"vpl");
 4545:  /* 1eme*/
 4546:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
 4547:   for (cpt=1; cpt<= nlstate ; cpt ++) {
 4548:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
 4549:      fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
 4550:      fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
 4551:      fprintf(ficgp,"set xlabel \"Age\" \n\
 4552: set ylabel \"Probability\" \n\
 4553: set ter png small size 320, 240\n\
 4554: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
 4555: 
 4556:      for (i=1; i<= nlstate ; i ++) {
 4557:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 4558:        else        fprintf(ficgp," %%*lf (%%*lf)");
 4559:      }
 4560:      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);
 4561:      for (i=1; i<= nlstate ; i ++) {
 4562:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 4563:        else fprintf(ficgp," %%*lf (%%*lf)");
 4564:      } 
 4565:      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); 
 4566:      for (i=1; i<= nlstate ; i ++) {
 4567:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 4568:        else fprintf(ficgp," %%*lf (%%*lf)");
 4569:      }  
 4570:      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));
 4571:    }
 4572:   }
 4573:   /*2 eme*/
 4574:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
 4575:   for (k1=1; k1<= m ; k1 ++) { 
 4576:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
 4577:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
 4578:     
 4579:     for (i=1; i<= nlstate+1 ; i ++) {
 4580:       k=2*i;
 4581:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4582:       for (j=1; j<= nlstate+1 ; j ++) {
 4583: 	if (j==i) fprintf(ficgp," %%lf (%%lf)");
 4584: 	else fprintf(ficgp," %%*lf (%%*lf)");
 4585:       }   
 4586:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
 4587:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
 4588:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4589:       for (j=1; j<= nlstate+1 ; j ++) {
 4590: 	if (j==i) fprintf(ficgp," %%lf (%%lf)");
 4591: 	else fprintf(ficgp," %%*lf (%%*lf)");
 4592:       }   
 4593:       fprintf(ficgp,"\" t\"\" w l lt 0,");
 4594:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4595:       for (j=1; j<= nlstate+1 ; j ++) {
 4596: 	if (j==i) fprintf(ficgp," %%lf (%%lf)");
 4597: 	else fprintf(ficgp," %%*lf (%%*lf)");
 4598:       }   
 4599:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
 4600:       else fprintf(ficgp,"\" t\"\" w l lt 0,");
 4601:     }
 4602:   }
 4603:   
 4604:   /*3eme*/
 4605:   
 4606:   for (k1=1; k1<= m ; k1 ++) { 
 4607:     for (cpt=1; cpt<= nlstate ; cpt ++) {
 4608:       /*       k=2+nlstate*(2*cpt-2); */
 4609:       k=2+(nlstate+1)*(cpt-1);
 4610:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
 4611:       fprintf(ficgp,"set ter png small size 320, 240\n\
 4612: 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);
 4613:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 4614: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 4615: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 4616: 	fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 4617: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 4618: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 4619: 	
 4620:       */
 4621:       for (i=1; i< nlstate ; i ++) {
 4622: 	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);
 4623: 	/*	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);*/
 4624: 	
 4625:       } 
 4626:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
 4627:     }
 4628:   }
 4629:   
 4630:   /* CV preval stable (period) */
 4631:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
 4632:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 4633:       k=3;
 4634:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
 4635:       fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
 4636:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 4637: set ter png small size 320, 240\n\
 4638: unset log y\n\
 4639: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 4640:       for (i=1; i<= nlstate ; i ++){
 4641: 	if(i==1)
 4642: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
 4643: 	else
 4644: 	  fprintf(ficgp,", '' ");
 4645: 	l=(nlstate+ndeath)*(i-1)+1;
 4646: 	fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 4647: 	for (j=1; j<= (nlstate-1) ; j ++)
 4648: 	  fprintf(ficgp,"+$%d",k+l+j);
 4649: 	fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
 4650:       } /* nlstate */
 4651:       fprintf(ficgp,"\n");
 4652:     } /* end cpt state*/ 
 4653:   } /* end covariate */  
 4654:   
 4655:   /* proba elementaires */
 4656:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
 4657:   for(i=1,jk=1; i <=nlstate; i++){
 4658:     fprintf(ficgp,"# initial state %d\n",i);
 4659:     for(k=1; k <=(nlstate+ndeath); k++){
 4660:       if (k != i) {
 4661: 	fprintf(ficgp,"#   current state %d\n",k);
 4662: 	for(j=1; j <=ncovmodel; j++){
 4663: 	  fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
 4664: 	  jk++; 
 4665: 	}
 4666: 	fprintf(ficgp,"\n");
 4667:       }
 4668:     }
 4669:    }
 4670:   fprintf(ficgp,"##############\n#\n");
 4671: 
 4672:   /*goto avoid;*/
 4673:   fprintf(ficgp,"\n##############\n#Graphics of of probabilities or incidences\n#############\n");
 4674:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
 4675:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
 4676:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
 4677:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
 4678:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 4679:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 4680:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 4681:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
 4682:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
 4683:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
 4684:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
 4685:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
 4686:   fprintf(ficgp,"#\n");
 4687:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
 4688:      fprintf(ficgp,"# ng=%d\n",ng);
 4689:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
 4690:      for(jk=1; jk <=m; jk++) {
 4691:        fprintf(ficgp,"#    jk=%d\n",jk);
 4692:        fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
 4693:        if (ng==2)
 4694: 	 fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
 4695:        else
 4696: 	 fprintf(ficgp,"\nset title \"Probability\"\n");
 4697:        fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
 4698:        i=1;
 4699:        for(k2=1; k2<=nlstate; k2++) {
 4700: 	 k3=i;
 4701: 	 for(k=1; k<=(nlstate+ndeath); k++) {
 4702: 	   if (k != k2){
 4703: 	     if(ng==2)
 4704: 	       if(nagesqr==0)
 4705: 		 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
 4706: 	       else /* nagesqr =1 */
 4707: 		 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
 4708: 	     else
 4709: 	       if(nagesqr==0)
 4710: 		 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
 4711: 	       else /* nagesqr =1 */
 4712: 		 fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
 4713: 	     ij=1;/* To be checked else nbcode[0][0] wrong */
 4714: 	     for(j=3; j <=ncovmodel-nagesqr; j++) {
 4715: 	       if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /* Bug valgrind */
 4716: 	       	 fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
 4717: 	       	 ij++;
 4718: 	       }
 4719: 	       else
 4720: 		 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 4721: 	     }
 4722: 	     fprintf(ficgp,")/(1");
 4723: 	     
 4724: 	     for(k1=1; k1 <=nlstate; k1++){ 
 4725: 	       if(nagesqr==0)
 4726: 		 fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
 4727: 	       else /* nagesqr =1 */
 4728: 		 fprintf(ficgp,"+exp(p%d+p%d*x+p%d*x*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1,k3+(k1-1)*ncovmodel+1+nagesqr);
 4729:   
 4730: 	       ij=1;
 4731: 	       for(j=3; j <=ncovmodel-nagesqr; j++){
 4732: 		 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
 4733: 		   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
 4734: 		   ij++;
 4735: 		 }
 4736: 		 else
 4737: 		   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 4738: 	       }
 4739: 	       fprintf(ficgp,")");
 4740: 	     }
 4741: 	     fprintf(ficgp,") t \"p%d%d\" ", k2,k);
 4742: 	     if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
 4743: 	     i=i+ncovmodel;
 4744: 	   }
 4745: 	 } /* end k */
 4746:        } /* end k2 */
 4747:      } /* end jk */
 4748:    } /* end ng */
 4749:  /* avoid: */
 4750:    fflush(ficgp); 
 4751: }  /* end gnuplot */
 4752: 
 4753: 
 4754: /*************** Moving average **************/
 4755: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
 4756: 
 4757:   int i, cpt, cptcod;
 4758:   int modcovmax =1;
 4759:   int mobilavrange, mob;
 4760:   double age;
 4761: 
 4762:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
 4763: 			   a covariate has 2 modalities */
 4764:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
 4765: 
 4766:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
 4767:     if(mobilav==1) mobilavrange=5; /* default */
 4768:     else mobilavrange=mobilav;
 4769:     for (age=bage; age<=fage; age++)
 4770:       for (i=1; i<=nlstate;i++)
 4771: 	for (cptcod=1;cptcod<=modcovmax;cptcod++)
 4772: 	  mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 4773:     /* We keep the original values on the extreme ages bage, fage and for 
 4774:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
 4775:        we use a 5 terms etc. until the borders are no more concerned. 
 4776:     */ 
 4777:     for (mob=3;mob <=mobilavrange;mob=mob+2){
 4778:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
 4779: 	for (i=1; i<=nlstate;i++){
 4780: 	  for (cptcod=1;cptcod<=modcovmax;cptcod++){
 4781: 	    mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
 4782: 	      for (cpt=1;cpt<=(mob-1)/2;cpt++){
 4783: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
 4784: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
 4785: 	      }
 4786: 	    mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
 4787: 	  }
 4788: 	}
 4789:       }/* end age */
 4790:     }/* end mob */
 4791:   }else return -1;
 4792:   return 0;
 4793: }/* End movingaverage */
 4794: 
 4795: 
 4796: /************** Forecasting ******************/
 4797: 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){
 4798:   /* proj1, year, month, day of starting projection 
 4799:      agemin, agemax range of age
 4800:      dateprev1 dateprev2 range of dates during which prevalence is computed
 4801:      anproj2 year of en of projection (same day and month as proj1).
 4802:   */
 4803:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
 4804:   double agec; /* generic age */
 4805:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
 4806:   double *popeffectif,*popcount;
 4807:   double ***p3mat;
 4808:   double ***mobaverage;
 4809:   char fileresf[FILENAMELENGTH];
 4810: 
 4811:   agelim=AGESUP;
 4812:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 4813:  
 4814:   strcpy(fileresf,"f"); 
 4815:   strcat(fileresf,fileres);
 4816:   if((ficresf=fopen(fileresf,"w"))==NULL) {
 4817:     printf("Problem with forecast resultfile: %s\n", fileresf);
 4818:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
 4819:   }
 4820:   printf("Computing forecasting: result on file '%s' \n", fileresf);
 4821:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
 4822: 
 4823:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 4824: 
 4825:   if (mobilav!=0) {
 4826:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4827:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 4828:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 4829:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 4830:     }
 4831:   }
 4832: 
 4833:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 4834:   if (stepm<=12) stepsize=1;
 4835:   if(estepm < stepm){
 4836:     printf ("Problem %d lower than %d\n",estepm, stepm);
 4837:   }
 4838:   else  hstepm=estepm;   
 4839: 
 4840:   hstepm=hstepm/stepm; 
 4841:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
 4842:                                fractional in yp1 */
 4843:   anprojmean=yp;
 4844:   yp2=modf((yp1*12),&yp);
 4845:   mprojmean=yp;
 4846:   yp1=modf((yp2*30.5),&yp);
 4847:   jprojmean=yp;
 4848:   if(jprojmean==0) jprojmean=1;
 4849:   if(mprojmean==0) jprojmean=1;
 4850: 
 4851:   i1=cptcoveff;
 4852:   if (cptcovn < 1){i1=1;}
 4853:   
 4854:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
 4855:   
 4856:   fprintf(ficresf,"#****** Routine prevforecast **\n");
 4857: 
 4858: /* 	      if (h==(int)(YEARM*yearp)){ */
 4859:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
 4860:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 4861:       k=k+1;
 4862:       fprintf(ficresf,"\n#******");
 4863:       for(j=1;j<=cptcoveff;j++) {
 4864: 	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]]);
 4865:       }
 4866:       fprintf(ficresf,"******\n");
 4867:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
 4868:       for(j=1; j<=nlstate+ndeath;j++){ 
 4869: 	for(i=1; i<=nlstate;i++) 	      
 4870:           fprintf(ficresf," p%d%d",i,j);
 4871: 	fprintf(ficresf," p.%d",j);
 4872:       }
 4873:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
 4874: 	fprintf(ficresf,"\n");
 4875: 	fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
 4876: 
 4877:      	for (agec=fage; agec>=(ageminpar-1); agec--){ 
 4878: 	  nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
 4879: 	  nhstepm = nhstepm/hstepm; 
 4880: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4881: 	  oldm=oldms;savm=savms;
 4882: 	  hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4883: 	
 4884: 	  for (h=0; h<=nhstepm; h++){
 4885: 	    if (h*hstepm/YEARM*stepm ==yearp) {
 4886:               fprintf(ficresf,"\n");
 4887:               for(j=1;j<=cptcoveff;j++) 
 4888:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4889: 	      fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
 4890: 	    } 
 4891: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4892: 	      ppij=0.;
 4893: 	      for(i=1; i<=nlstate;i++) {
 4894: 		if (mobilav==1) 
 4895: 		  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
 4896: 		else {
 4897: 		  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
 4898: 		}
 4899: 		if (h*hstepm/YEARM*stepm== yearp) {
 4900: 		  fprintf(ficresf," %.3f", p3mat[i][j][h]);
 4901: 		}
 4902: 	      } /* end i */
 4903: 	      if (h*hstepm/YEARM*stepm==yearp) {
 4904: 		fprintf(ficresf," %.3f", ppij);
 4905: 	      }
 4906: 	    }/* end j */
 4907: 	  } /* end h */
 4908: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4909: 	} /* end agec */
 4910:       } /* end yearp */
 4911:     } /* end cptcod */
 4912:   } /* end  cptcov */
 4913:        
 4914:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4915: 
 4916:   fclose(ficresf);
 4917: }
 4918: 
 4919: /************** Forecasting *****not tested NB*************/
 4920: 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){
 4921:   
 4922:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
 4923:   int *popage;
 4924:   double calagedatem, agelim, kk1, kk2;
 4925:   double *popeffectif,*popcount;
 4926:   double ***p3mat,***tabpop,***tabpopprev;
 4927:   double ***mobaverage;
 4928:   char filerespop[FILENAMELENGTH];
 4929: 
 4930:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4931:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4932:   agelim=AGESUP;
 4933:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
 4934:   
 4935:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 4936:   
 4937:   
 4938:   strcpy(filerespop,"pop"); 
 4939:   strcat(filerespop,fileres);
 4940:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
 4941:     printf("Problem with forecast resultfile: %s\n", filerespop);
 4942:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
 4943:   }
 4944:   printf("Computing forecasting: result on file '%s' \n", filerespop);
 4945:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
 4946: 
 4947:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 4948: 
 4949:   if (mobilav!=0) {
 4950:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4951:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 4952:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 4953:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 4954:     }
 4955:   }
 4956: 
 4957:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 4958:   if (stepm<=12) stepsize=1;
 4959:   
 4960:   agelim=AGESUP;
 4961:   
 4962:   hstepm=1;
 4963:   hstepm=hstepm/stepm; 
 4964:   
 4965:   if (popforecast==1) {
 4966:     if((ficpop=fopen(popfile,"r"))==NULL) {
 4967:       printf("Problem with population file : %s\n",popfile);exit(0);
 4968:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
 4969:     } 
 4970:     popage=ivector(0,AGESUP);
 4971:     popeffectif=vector(0,AGESUP);
 4972:     popcount=vector(0,AGESUP);
 4973:     
 4974:     i=1;   
 4975:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
 4976:    
 4977:     imx=i;
 4978:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
 4979:   }
 4980: 
 4981:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
 4982:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 4983:       k=k+1;
 4984:       fprintf(ficrespop,"\n#******");
 4985:       for(j=1;j<=cptcoveff;j++) {
 4986: 	fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4987:       }
 4988:       fprintf(ficrespop,"******\n");
 4989:       fprintf(ficrespop,"# Age");
 4990:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
 4991:       if (popforecast==1)  fprintf(ficrespop," [Population]");
 4992:       
 4993:       for (cpt=0; cpt<=0;cpt++) { 
 4994: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 4995: 	
 4996:      	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 4997: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 4998: 	  nhstepm = nhstepm/hstepm; 
 4999: 	  
 5000: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5001: 	  oldm=oldms;savm=savms;
 5002: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 5003: 	
 5004: 	  for (h=0; h<=nhstepm; h++){
 5005: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 5006: 	      fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 5007: 	    } 
 5008: 	    for(j=1; j<=nlstate+ndeath;j++) {
 5009: 	      kk1=0.;kk2=0;
 5010: 	      for(i=1; i<=nlstate;i++) {	      
 5011: 		if (mobilav==1) 
 5012: 		  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
 5013: 		else {
 5014: 		  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
 5015: 		}
 5016: 	      }
 5017: 	      if (h==(int)(calagedatem+12*cpt)){
 5018: 		tabpop[(int)(agedeb)][j][cptcod]=kk1;
 5019: 		  /*fprintf(ficrespop," %.3f", kk1);
 5020: 		    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
 5021: 	      }
 5022: 	    }
 5023: 	    for(i=1; i<=nlstate;i++){
 5024: 	      kk1=0.;
 5025: 		for(j=1; j<=nlstate;j++){
 5026: 		  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
 5027: 		}
 5028: 		  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
 5029: 	    }
 5030: 
 5031: 	    if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
 5032: 	      fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
 5033: 	  }
 5034: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5035: 	}
 5036:       }
 5037:  
 5038:   /******/
 5039: 
 5040:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
 5041: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 5042: 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 5043: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 5044: 	  nhstepm = nhstepm/hstepm; 
 5045: 	  
 5046: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5047: 	  oldm=oldms;savm=savms;
 5048: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 5049: 	  for (h=0; h<=nhstepm; h++){
 5050: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 5051: 	      fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 5052: 	    } 
 5053: 	    for(j=1; j<=nlstate+ndeath;j++) {
 5054: 	      kk1=0.;kk2=0;
 5055: 	      for(i=1; i<=nlstate;i++) {	      
 5056: 		kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];	
 5057: 	      }
 5058: 	      if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);	
 5059: 	    }
 5060: 	  }
 5061: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 5062: 	}
 5063:       }
 5064:    } 
 5065:   }
 5066:  
 5067:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 5068: 
 5069:   if (popforecast==1) {
 5070:     free_ivector(popage,0,AGESUP);
 5071:     free_vector(popeffectif,0,AGESUP);
 5072:     free_vector(popcount,0,AGESUP);
 5073:   }
 5074:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 5075:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 5076:   fclose(ficrespop);
 5077: } /* End of popforecast */
 5078: 
 5079: int fileappend(FILE *fichier, char *optionfich)
 5080: {
 5081:   if((fichier=fopen(optionfich,"a"))==NULL) {
 5082:     printf("Problem with file: %s\n", optionfich);
 5083:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
 5084:     return (0);
 5085:   }
 5086:   fflush(fichier);
 5087:   return (1);
 5088: }
 5089: 
 5090: 
 5091: /**************** function prwizard **********************/
 5092: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
 5093: {
 5094: 
 5095:   /* Wizard to print covariance matrix template */
 5096: 
 5097:   char ca[32], cb[32];
 5098:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
 5099:   int numlinepar;
 5100: 
 5101:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 5102:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 5103:   for(i=1; i <=nlstate; i++){
 5104:     jj=0;
 5105:     for(j=1; j <=nlstate+ndeath; j++){
 5106:       if(j==i) continue;
 5107:       jj++;
 5108:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
 5109:       printf("%1d%1d",i,j);
 5110:       fprintf(ficparo,"%1d%1d",i,j);
 5111:       for(k=1; k<=ncovmodel;k++){
 5112: 	/* 	  printf(" %lf",param[i][j][k]); */
 5113: 	/* 	  fprintf(ficparo," %lf",param[i][j][k]); */
 5114: 	printf(" 0.");
 5115: 	fprintf(ficparo," 0.");
 5116:       }
 5117:       printf("\n");
 5118:       fprintf(ficparo,"\n");
 5119:     }
 5120:   }
 5121:   printf("# Scales (for hessian or gradient estimation)\n");
 5122:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
 5123:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
 5124:   for(i=1; i <=nlstate; i++){
 5125:     jj=0;
 5126:     for(j=1; j <=nlstate+ndeath; j++){
 5127:       if(j==i) continue;
 5128:       jj++;
 5129:       fprintf(ficparo,"%1d%1d",i,j);
 5130:       printf("%1d%1d",i,j);
 5131:       fflush(stdout);
 5132:       for(k=1; k<=ncovmodel;k++){
 5133: 	/* 	printf(" %le",delti3[i][j][k]); */
 5134: 	/* 	fprintf(ficparo," %le",delti3[i][j][k]); */
 5135: 	printf(" 0.");
 5136: 	fprintf(ficparo," 0.");
 5137:       }
 5138:       numlinepar++;
 5139:       printf("\n");
 5140:       fprintf(ficparo,"\n");
 5141:     }
 5142:   }
 5143:   printf("# Covariance matrix\n");
 5144: /* # 121 Var(a12)\n\ */
 5145: /* # 122 Cov(b12,a12) Var(b12)\n\ */
 5146: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 5147: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 5148: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 5149: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 5150: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 5151: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 5152:   fflush(stdout);
 5153:   fprintf(ficparo,"# Covariance matrix\n");
 5154:   /* # 121 Var(a12)\n\ */
 5155:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
 5156:   /* #   ...\n\ */
 5157:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
 5158:   
 5159:   for(itimes=1;itimes<=2;itimes++){
 5160:     jj=0;
 5161:     for(i=1; i <=nlstate; i++){
 5162:       for(j=1; j <=nlstate+ndeath; j++){
 5163: 	if(j==i) continue;
 5164: 	for(k=1; k<=ncovmodel;k++){
 5165: 	  jj++;
 5166: 	  ca[0]= k+'a'-1;ca[1]='\0';
 5167: 	  if(itimes==1){
 5168: 	    printf("#%1d%1d%d",i,j,k);
 5169: 	    fprintf(ficparo,"#%1d%1d%d",i,j,k);
 5170: 	  }else{
 5171: 	    printf("%1d%1d%d",i,j,k);
 5172: 	    fprintf(ficparo,"%1d%1d%d",i,j,k);
 5173: 	    /* 	printf(" %.5le",matcov[i][j]); */
 5174: 	  }
 5175: 	  ll=0;
 5176: 	  for(li=1;li <=nlstate; li++){
 5177: 	    for(lj=1;lj <=nlstate+ndeath; lj++){
 5178: 	      if(lj==li) continue;
 5179: 	      for(lk=1;lk<=ncovmodel;lk++){
 5180: 		ll++;
 5181: 		if(ll<=jj){
 5182: 		  cb[0]= lk +'a'-1;cb[1]='\0';
 5183: 		  if(ll<jj){
 5184: 		    if(itimes==1){
 5185: 		      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 5186: 		      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 5187: 		    }else{
 5188: 		      printf(" 0.");
 5189: 		      fprintf(ficparo," 0.");
 5190: 		    }
 5191: 		  }else{
 5192: 		    if(itimes==1){
 5193: 		      printf(" Var(%s%1d%1d)",ca,i,j);
 5194: 		      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
 5195: 		    }else{
 5196: 		      printf(" 0.");
 5197: 		      fprintf(ficparo," 0.");
 5198: 		    }
 5199: 		  }
 5200: 		}
 5201: 	      } /* end lk */
 5202: 	    } /* end lj */
 5203: 	  } /* end li */
 5204: 	  printf("\n");
 5205: 	  fprintf(ficparo,"\n");
 5206: 	  numlinepar++;
 5207: 	} /* end k*/
 5208:       } /*end j */
 5209:     } /* end i */
 5210:   } /* end itimes */
 5211: 
 5212: } /* end of prwizard */
 5213: /******************* Gompertz Likelihood ******************************/
 5214: double gompertz(double x[])
 5215: { 
 5216:   double A,B,L=0.0,sump=0.,num=0.;
 5217:   int i,n=0; /* n is the size of the sample */
 5218: 
 5219:   for (i=0;i<=imx-1 ; i++) {
 5220:     sump=sump+weight[i];
 5221:     /*    sump=sump+1;*/
 5222:     num=num+1;
 5223:   }
 5224:  
 5225:  
 5226:   /* for (i=0; i<=imx; i++) 
 5227:      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]);*/
 5228: 
 5229:   for (i=1;i<=imx ; i++)
 5230:     {
 5231:       if (cens[i] == 1 && wav[i]>1)
 5232: 	A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
 5233:       
 5234:       if (cens[i] == 0 && wav[i]>1)
 5235: 	A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
 5236: 	     +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
 5237:       
 5238:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 5239:       if (wav[i] > 1 ) { /* ??? */
 5240: 	L=L+A*weight[i];
 5241: 	/* 	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]);*/
 5242:       }
 5243:     }
 5244: 
 5245:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 5246:  
 5247:   return -2*L*num/sump;
 5248: }
 5249: 
 5250: #ifdef GSL
 5251: /******************* Gompertz_f Likelihood ******************************/
 5252: double gompertz_f(const gsl_vector *v, void *params)
 5253: { 
 5254:   double A,B,LL=0.0,sump=0.,num=0.;
 5255:   double *x= (double *) v->data;
 5256:   int i,n=0; /* n is the size of the sample */
 5257: 
 5258:   for (i=0;i<=imx-1 ; i++) {
 5259:     sump=sump+weight[i];
 5260:     /*    sump=sump+1;*/
 5261:     num=num+1;
 5262:   }
 5263:  
 5264:  
 5265:   /* for (i=0; i<=imx; i++) 
 5266:      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]);*/
 5267:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
 5268:   for (i=1;i<=imx ; i++)
 5269:     {
 5270:       if (cens[i] == 1 && wav[i]>1)
 5271: 	A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
 5272:       
 5273:       if (cens[i] == 0 && wav[i]>1)
 5274: 	A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
 5275: 	     +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
 5276:       
 5277:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 5278:       if (wav[i] > 1 ) { /* ??? */
 5279: 	LL=LL+A*weight[i];
 5280: 	/* 	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]);*/
 5281:       }
 5282:     }
 5283: 
 5284:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 5285:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
 5286:  
 5287:   return -2*LL*num/sump;
 5288: }
 5289: #endif
 5290: 
 5291: /******************* Printing html file ***********/
 5292: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
 5293: 		  int lastpass, int stepm, int weightopt, char model[],\
 5294: 		  int imx,  double p[],double **matcov,double agemortsup){
 5295:   int i,k;
 5296: 
 5297:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
 5298:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
 5299:   for (i=1;i<=2;i++) 
 5300:     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]));
 5301:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
 5302:   fprintf(fichtm,"</ul>");
 5303: 
 5304: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
 5305: 
 5306:  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>");
 5307: 
 5308:  for (k=agegomp;k<(agemortsup-2);k++) 
 5309:    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]);
 5310: 
 5311:  
 5312:   fflush(fichtm);
 5313: }
 5314: 
 5315: /******************* Gnuplot file **************/
 5316: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 5317: 
 5318:   char dirfileres[132],optfileres[132];
 5319: 
 5320:   int ng;
 5321: 
 5322: 
 5323:   /*#ifdef windows */
 5324:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 5325:     /*#endif */
 5326: 
 5327: 
 5328:   strcpy(dirfileres,optionfilefiname);
 5329:   strcpy(optfileres,"vpl");
 5330:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
 5331:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
 5332:   fprintf(ficgp, "set ter png small size 320, 240\n set log y\n"); 
 5333:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
 5334:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
 5335: 
 5336: } 
 5337: 
 5338: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
 5339: {
 5340: 
 5341:   /*-------- data file ----------*/
 5342:   FILE *fic;
 5343:   char dummy[]="                         ";
 5344:   int i=0, j=0, n=0;
 5345:   int linei, month, year,iout;
 5346:   char line[MAXLINE], linetmp[MAXLINE];
 5347:   char stra[MAXLINE], strb[MAXLINE];
 5348:   char *stratrunc;
 5349:   int lstra;
 5350: 
 5351: 
 5352:   if((fic=fopen(datafile,"r"))==NULL)    {
 5353:     printf("Problem while opening datafile: %s\n", datafile);return 1;
 5354:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
 5355:   }
 5356: 
 5357:   i=1;
 5358:   linei=0;
 5359:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
 5360:     linei=linei+1;
 5361:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
 5362:       if(line[j] == '\t')
 5363: 	line[j] = ' ';
 5364:     }
 5365:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
 5366:       ;
 5367:     };
 5368:     line[j+1]=0;  /* Trims blanks at end of line */
 5369:     if(line[0]=='#'){
 5370:       fprintf(ficlog,"Comment line\n%s\n",line);
 5371:       printf("Comment line\n%s\n",line);
 5372:       continue;
 5373:     }
 5374:     trimbb(linetmp,line); /* Trims multiple blanks in line */
 5375:     strcpy(line, linetmp);
 5376:   
 5377: 
 5378:     for (j=maxwav;j>=1;j--){
 5379:       cutv(stra, strb, line, ' '); 
 5380:       if(strb[0]=='.') { /* Missing status */
 5381: 	lval=-1;
 5382:       }else{
 5383: 	errno=0;
 5384: 	lval=strtol(strb,&endptr,10); 
 5385:       /*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
 5386: 	if( strb[0]=='\0' || (*endptr != '\0')){
 5387: 	  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);
 5388: 	  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);
 5389: 	  return 1;
 5390: 	}
 5391:       }
 5392:       s[j][i]=lval;
 5393:       
 5394:       strcpy(line,stra);
 5395:       cutv(stra, strb,line,' ');
 5396:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 5397:       }
 5398:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 5399: 	month=99;
 5400: 	year=9999;
 5401:       }else{
 5402: 	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);
 5403: 	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);
 5404: 	return 1;
 5405:       }
 5406:       anint[j][i]= (double) year; 
 5407:       mint[j][i]= (double)month; 
 5408:       strcpy(line,stra);
 5409:     } /* ENd Waves */
 5410:     
 5411:     cutv(stra, strb,line,' '); 
 5412:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 5413:     }
 5414:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 5415:       month=99;
 5416:       year=9999;
 5417:     }else{
 5418:       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);
 5419: 	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);
 5420: 	return 1;
 5421:     }
 5422:     andc[i]=(double) year; 
 5423:     moisdc[i]=(double) month; 
 5424:     strcpy(line,stra);
 5425:     
 5426:     cutv(stra, strb,line,' '); 
 5427:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 5428:     }
 5429:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
 5430:       month=99;
 5431:       year=9999;
 5432:     }else{
 5433:       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);
 5434:       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);
 5435: 	return 1;
 5436:     }
 5437:     if (year==9999) {
 5438:       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);
 5439:       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);
 5440: 	return 1;
 5441: 
 5442:     }
 5443:     annais[i]=(double)(year);
 5444:     moisnais[i]=(double)(month); 
 5445:     strcpy(line,stra);
 5446:     
 5447:     cutv(stra, strb,line,' '); 
 5448:     errno=0;
 5449:     dval=strtod(strb,&endptr); 
 5450:     if( strb[0]=='\0' || (*endptr != '\0')){
 5451:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
 5452:       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);
 5453:       fflush(ficlog);
 5454:       return 1;
 5455:     }
 5456:     weight[i]=dval; 
 5457:     strcpy(line,stra);
 5458:     
 5459:     for (j=ncovcol;j>=1;j--){
 5460:       cutv(stra, strb,line,' '); 
 5461:       if(strb[0]=='.') { /* Missing status */
 5462: 	lval=-1;
 5463:       }else{
 5464: 	errno=0;
 5465: 	lval=strtol(strb,&endptr,10); 
 5466: 	if( strb[0]=='\0' || (*endptr != '\0')){
 5467: 	  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);
 5468: 	  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);
 5469: 	  return 1;
 5470: 	}
 5471:       }
 5472:       if(lval <-1 || lval >1){
 5473: 	printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 5474:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 5475:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 5476:  For example, for multinomial values like 1, 2 and 3,\n \
 5477:  build V1=0 V2=0 for the reference value (1),\n \
 5478:         V1=1 V2=0 for (2) \n \
 5479:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 5480:  output of IMaCh is often meaningless.\n \
 5481:  Exiting.\n",lval,linei, i,line,j);
 5482: 	fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 5483:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 5484:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 5485:  For example, for multinomial values like 1, 2 and 3,\n \
 5486:  build V1=0 V2=0 for the reference value (1),\n \
 5487:         V1=1 V2=0 for (2) \n \
 5488:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 5489:  output of IMaCh is often meaningless.\n \
 5490:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
 5491: 	return 1;
 5492:       }
 5493:       covar[j][i]=(double)(lval);
 5494:       strcpy(line,stra);
 5495:     }  
 5496:     lstra=strlen(stra);
 5497:      
 5498:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
 5499:       stratrunc = &(stra[lstra-9]);
 5500:       num[i]=atol(stratrunc);
 5501:     }
 5502:     else
 5503:       num[i]=atol(stra);
 5504:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
 5505:       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;}*/
 5506:     
 5507:     i=i+1;
 5508:   } /* End loop reading  data */
 5509: 
 5510:   *imax=i-1; /* Number of individuals */
 5511:   fclose(fic);
 5512:  
 5513:   return (0);
 5514:   /* endread: */
 5515:     printf("Exiting readdata: ");
 5516:     fclose(fic);
 5517:     return (1);
 5518: 
 5519: 
 5520: 
 5521: }
 5522: void removespace(char *str) {
 5523:   char *p1 = str, *p2 = str;
 5524:   do
 5525:     while (*p2 == ' ')
 5526:       p2++;
 5527:   while (*p1++ == *p2++);
 5528: }
 5529: 
 5530: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
 5531:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
 5532:    * - nagesqr = 1 if age*age in the model, otherwise 0.
 5533:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
 5534:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
 5535:    * - cptcovage number of covariates with age*products =2
 5536:    * - cptcovs number of simple covariates
 5537:    * - 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
 5538:    *     which is a new column after the 9 (ncovcol) variables. 
 5539:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
 5540:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
 5541:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
 5542:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
 5543:  */
 5544: {
 5545:   int i, j, k, ks;
 5546:   int  j1, k1, k2;
 5547:   char modelsav[80];
 5548:   char stra[80], strb[80], strc[80], strd[80],stre[80];
 5549:   char *strpt;
 5550: 
 5551:   /*removespace(model);*/
 5552:   if (strlen(model) >1){ /* If there is at least 1 covariate */
 5553:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
 5554:     if (strstr(model,"AGE") !=0){
 5555:       printf("Error. AGE must be in lower case 'age' model=1+age+%s ",model);
 5556:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s ",model);fflush(ficlog);
 5557:       return 1;
 5558:     }
 5559:     if (strstr(model,"v") !=0){
 5560:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
 5561:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
 5562:       return 1;
 5563:     }
 5564:     strcpy(modelsav,model); 
 5565:     if ((strpt=strstr(model,"age*age")) !=0){
 5566:       printf(" strpt=%s, model=%s\n",strpt, model);
 5567:       if(strpt != model){
 5568:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
 5569:  'model=1+age+age*age+V1' or 'model=1+age+age*age+V1+V1*age', please swap as well as \n \
 5570:  corresponding column of parameters.\n",model);
 5571:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
 5572:  'model=1+age+age*age+V1' or 'model=1+age+age*age+V1+V1*age', please swap as well as \n \
 5573:  corresponding column of parameters.\n",model); fflush(ficlog);
 5574:       return 1;
 5575:     }
 5576: 
 5577:       nagesqr=1;
 5578:       if (strstr(model,"+age*age") !=0)
 5579: 	substrchaine(modelsav, model, "+age*age");
 5580:       else if (strstr(model,"age*age+") !=0)
 5581: 	substrchaine(modelsav, model, "age*age+");
 5582:       else 
 5583: 	substrchaine(modelsav, model, "age*age");
 5584:     }else
 5585:       nagesqr=0;
 5586:     if (strlen(modelsav) >1){
 5587:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
 5588:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
 5589:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
 5590:       cptcovt= j+1; /* Number of total covariates in the model, not including
 5591: 		   * cst, age and age*age 
 5592: 		   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
 5593:                   /* including age products which are counted in cptcovage.
 5594: 		  * but the covariates which are products must be treated 
 5595: 		  * separately: ncovn=4- 2=2 (V1+V3). */
 5596:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
 5597:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
 5598: 
 5599:     
 5600:       /*   Design
 5601:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
 5602:        *  <          ncovcol=8                >
 5603:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
 5604:        *   k=  1    2      3       4     5       6      7        8
 5605:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
 5606:        *  covar[k,i], value of kth covariate if not including age for individual i:
 5607:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
 5608:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
 5609:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
 5610:        *  Tage[++cptcovage]=k
 5611:        *       if products, new covar are created after ncovcol with k1
 5612:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
 5613:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
 5614:        *  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
 5615:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
 5616:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
 5617:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
 5618:        *  <          ncovcol=8                >
 5619:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
 5620:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
 5621:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
 5622:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 5623:        * p Tprod[1]@2={                         6, 5}
 5624:        *p Tvard[1][1]@4= {7, 8, 5, 6}
 5625:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
 5626:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 5627:        *How to reorganize?
 5628:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
 5629:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 5630:        *       {2,   1,     4,      8,    5,      6,     3,       7}
 5631:        * Struct []
 5632:        */
 5633: 
 5634:       /* This loop fills the array Tvar from the string 'model'.*/
 5635:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
 5636:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
 5637:       /* 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
 5638:       /* 	k=3 V4 Tvar[k=3]= 4 (from V4) */
 5639:       /* 	k=2 V1 Tvar[k=2]= 1 (from V1) */
 5640:       /* 	k=1 Tvar[1]=2 (from V2) */
 5641:       /* 	k=5 Tvar[5] */
 5642:       /* for (k=1; k<=cptcovn;k++) { */
 5643:       /* 	cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
 5644:       /* 	} */
 5645:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtab[ij][Tvar[Tage[k]]]]*cov[2]; */
 5646:       /*
 5647:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
 5648:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
 5649:         Tvar[k]=0;
 5650:       cptcovage=0;
 5651:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
 5652: 	cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
 5653: 					 modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
 5654: 	if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
 5655: 	/*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
 5656: 	/*scanf("%d",i);*/
 5657: 	if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
 5658: 	  cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
 5659: 	  if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
 5660: 	    /* covar is not filled and then is empty */
 5661: 	    cptcovprod--;
 5662: 	    cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
 5663: 	    Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
 5664: 	    cptcovage++; /* Sums the number of covariates which include age as a product */
 5665: 	    Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
 5666: 	    /*printf("stre=%s ", stre);*/
 5667: 	  } else if (strcmp(strd,"age")==0) { /* or age*Vn */
 5668: 	    cptcovprod--;
 5669: 	    cutl(stre,strb,strc,'V');
 5670: 	    Tvar[k]=atoi(stre);
 5671: 	    cptcovage++;
 5672: 	    Tage[cptcovage]=k;
 5673: 	  } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
 5674: 	    /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
 5675: 	    cptcovn++;
 5676: 	    cptcovprodnoage++;k1++;
 5677: 	    cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
 5678: 	    Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
 5679: 				   because this model-covariate is a construction we invent a new column
 5680: 				   ncovcol + k1
 5681: 				   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
 5682: 				   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
 5683: 	    cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
 5684: 	    Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
 5685: 	    Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
 5686: 	    Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
 5687: 	    k2=k2+2;
 5688: 	    Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
 5689: 	    Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
 5690: 	    for (i=1; i<=lastobs;i++){
 5691: 	      /* Computes the new covariate which is a product of
 5692: 		 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
 5693: 	      covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
 5694: 	    }
 5695: 	  } /* End age is not in the model */
 5696: 	} /* End if model includes a product */
 5697: 	else { /* no more sum */
 5698: 	  /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
 5699: 	  /*  scanf("%d",i);*/
 5700: 	  cutl(strd,strc,strb,'V');
 5701: 	  ks++; /**< Number of simple covariates */
 5702: 	  cptcovn++;
 5703: 	  Tvar[k]=atoi(strd);
 5704: 	}
 5705: 	strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
 5706: 	/*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
 5707: 	  scanf("%d",i);*/
 5708:       } /* end of loop + on total covariates */
 5709:     } /* end if strlen(modelsave == 0) age*age might exist */
 5710:   } /* end if strlen(model == 0) */
 5711:   
 5712:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
 5713:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
 5714: 
 5715:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
 5716:   printf("cptcovprod=%d ", cptcovprod);
 5717:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
 5718: 
 5719:   scanf("%d ",i);*/
 5720: 
 5721: 
 5722:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
 5723:   /*endread:*/
 5724:     printf("Exiting decodemodel: ");
 5725:     return (1);
 5726: }
 5727: 
 5728: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
 5729: {
 5730:   int i, m;
 5731: 
 5732:   for (i=1; i<=imx; i++) {
 5733:     for(m=2; (m<= maxwav); m++) {
 5734:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
 5735: 	anint[m][i]=9999;
 5736: 	s[m][i]=-1;
 5737:       }
 5738:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
 5739: 	*nberr = *nberr + 1;
 5740: 	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);
 5741: 	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);
 5742: 	s[m][i]=-1;
 5743:       }
 5744:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
 5745: 	(*nberr)++;
 5746: 	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]); 
 5747: 	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]); 
 5748: 	s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
 5749:       }
 5750:     }
 5751:   }
 5752: 
 5753:   for (i=1; i<=imx; i++)  {
 5754:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
 5755:     for(m=firstpass; (m<= lastpass); m++){
 5756:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
 5757: 	if (s[m][i] >= nlstate+1) {
 5758: 	  if(agedc[i]>0){
 5759: 	    if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
 5760: 	      agev[m][i]=agedc[i];
 5761: 	  /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
 5762: 	    }else {
 5763: 	      if ((int)andc[i]!=9999){
 5764: 		nbwarn++;
 5765: 		printf("Warning negative age at death: %ld line:%d\n",num[i],i);
 5766: 		fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
 5767: 		agev[m][i]=-1;
 5768: 	      }
 5769: 	    }
 5770: 	  } /* agedc > 0 */
 5771: 	}
 5772: 	else if(s[m][i] !=9){ /* Standard case, age in fractional
 5773: 				 years but with the precision of a month */
 5774: 	  agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
 5775: 	  if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
 5776: 	    agev[m][i]=1;
 5777: 	  else if(agev[m][i] < *agemin){ 
 5778: 	    *agemin=agev[m][i];
 5779: 	    printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
 5780: 	  }
 5781: 	  else if(agev[m][i] >*agemax){
 5782: 	    *agemax=agev[m][i];
 5783: 	    /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
 5784: 	  }
 5785: 	  /*agev[m][i]=anint[m][i]-annais[i];*/
 5786: 	  /*	 agev[m][i] = age[i]+2*m;*/
 5787: 	}
 5788: 	else { /* =9 */
 5789: 	  agev[m][i]=1;
 5790: 	  s[m][i]=-1;
 5791: 	}
 5792:       }
 5793:       else /*= 0 Unknown */
 5794: 	agev[m][i]=1;
 5795:     }
 5796:     
 5797:   }
 5798:   for (i=1; i<=imx; i++)  {
 5799:     for(m=firstpass; (m<=lastpass); m++){
 5800:       if (s[m][i] > (nlstate+ndeath)) {
 5801: 	(*nberr)++;
 5802: 	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);	
 5803: 	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);	
 5804: 	return 1;
 5805:       }
 5806:     }
 5807:   }
 5808: 
 5809:   /*for (i=1; i<=imx; i++){
 5810:   for (m=firstpass; (m<lastpass); m++){
 5811:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
 5812: }
 5813: 
 5814: }*/
 5815: 
 5816: 
 5817:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
 5818:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
 5819: 
 5820:   return (0);
 5821:  /* endread:*/
 5822:     printf("Exiting calandcheckages: ");
 5823:     return (1);
 5824: }
 5825: 
 5826: #if defined(_MSC_VER)
 5827: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 5828: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 5829: //#include "stdafx.h"
 5830: //#include <stdio.h>
 5831: //#include <tchar.h>
 5832: //#include <windows.h>
 5833: //#include <iostream>
 5834: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
 5835: 
 5836: LPFN_ISWOW64PROCESS fnIsWow64Process;
 5837: 
 5838: BOOL IsWow64()
 5839: {
 5840: 	BOOL bIsWow64 = FALSE;
 5841: 
 5842: 	//typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
 5843: 	//  (HANDLE, PBOOL);
 5844: 
 5845: 	//LPFN_ISWOW64PROCESS fnIsWow64Process;
 5846: 
 5847: 	HMODULE module = GetModuleHandle(_T("kernel32"));
 5848: 	const char funcName[] = "IsWow64Process";
 5849: 	fnIsWow64Process = (LPFN_ISWOW64PROCESS)
 5850: 		GetProcAddress(module, funcName);
 5851: 
 5852: 	if (NULL != fnIsWow64Process)
 5853: 	{
 5854: 		if (!fnIsWow64Process(GetCurrentProcess(),
 5855: 			&bIsWow64))
 5856: 			//throw std::exception("Unknown error");
 5857: 			printf("Unknown error\n");
 5858: 	}
 5859: 	return bIsWow64 != FALSE;
 5860: }
 5861: #endif
 5862: 
 5863: void syscompilerinfo()
 5864:  {
 5865:    /* #include "syscompilerinfo.h"*/
 5866:    /* command line Intel compiler 32bit windows, XP compatible:*/
 5867:    /* /GS /W3 /Gy
 5868:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
 5869:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
 5870:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
 5871:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
 5872:    */ 
 5873:    /* 64 bits */
 5874:    /*
 5875:      /GS /W3 /Gy
 5876:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
 5877:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
 5878:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
 5879:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
 5880:    /* Optimization are useless and O3 is slower than O2 */
 5881:    /*
 5882:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
 5883:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
 5884:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
 5885:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
 5886:    */
 5887:    /* Link is */ /* /OUT:"visual studio
 5888:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
 5889:       /PDB:"visual studio
 5890:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
 5891:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
 5892:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
 5893:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
 5894:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
 5895:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
 5896:       uiAccess='false'"
 5897:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
 5898:       /NOLOGO /TLBID:1
 5899:    */
 5900: #if defined __INTEL_COMPILER
 5901: #if defined(__GNUC__)
 5902: 	struct utsname sysInfo;  /* For Intel on Linux and OS/X */
 5903: #endif
 5904: #elif defined(__GNUC__) 
 5905: #ifndef  __APPLE__
 5906: #include <gnu/libc-version.h>  /* Only on gnu */
 5907: #endif
 5908:    struct utsname sysInfo;
 5909:    int cross = CROSS;
 5910:    if (cross){
 5911: 	   printf("Cross-");
 5912: 	   fprintf(ficlog, "Cross-");
 5913:    }
 5914: #endif
 5915: 
 5916: #include <stdint.h>
 5917: 
 5918:    printf("Compiled with:");fprintf(ficlog,"Compiled with:");
 5919: #if defined(__clang__)
 5920:    printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM");	/* Clang/LLVM. ---------------------------------------------- */
 5921: #endif
 5922: #if defined(__ICC) || defined(__INTEL_COMPILER)
 5923:    printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
 5924: #endif
 5925: #if defined(__GNUC__) || defined(__GNUG__)
 5926:    printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
 5927: #endif
 5928: #if defined(__HP_cc) || defined(__HP_aCC)
 5929:    printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
 5930: #endif
 5931: #if defined(__IBMC__) || defined(__IBMCPP__)
 5932:    printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
 5933: #endif
 5934: #if defined(_MSC_VER)
 5935:    printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
 5936: #endif
 5937: #if defined(__PGI)
 5938:    printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
 5939: #endif
 5940: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
 5941:    printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
 5942: #endif
 5943:    printf(" for ");fprintf(ficlog," for ");
 5944:    
 5945: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
 5946: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
 5947:     // Windows (x64 and x86)
 5948:    printf("Windows (x64 and x86) ");fprintf(ficlog,"Windows (x64 and x86) ");
 5949: #elif __unix__ // all unices, not all compilers
 5950:     // Unix
 5951:    printf("Unix ");fprintf(ficlog,"Unix ");
 5952: #elif __linux__
 5953:     // linux
 5954:    printf("linux ");fprintf(ficlog,"linux ");
 5955: #elif __APPLE__
 5956:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
 5957:    printf("Mac OS ");fprintf(ficlog,"Mac OS ");
 5958: #endif
 5959: 
 5960: /*  __MINGW32__	  */
 5961: /*  __CYGWIN__	 */
 5962: /* __MINGW64__  */
 5963: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
 5964: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
 5965: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
 5966: /* _WIN64  // Defined for applications for Win64. */
 5967: /* _M_X64 // Defined for compilations that target x64 processors. */
 5968: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
 5969: 
 5970: #if UINTPTR_MAX == 0xffffffff
 5971:    printf(" 32-bit"); fprintf(ficlog," 32-bit");/* 32-bit */
 5972: #elif UINTPTR_MAX == 0xffffffffffffffff
 5973:    printf(" 64-bit"); fprintf(ficlog," 64-bit");/* 64-bit */
 5974: #else
 5975:    printf(" wtf-bit"); fprintf(ficlog," wtf-bit");/* wtf */
 5976: #endif
 5977: 
 5978: #if defined(__GNUC__)
 5979: # if defined(__GNUC_PATCHLEVEL__)
 5980: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 5981:                             + __GNUC_MINOR__ * 100 \
 5982:                             + __GNUC_PATCHLEVEL__)
 5983: # else
 5984: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 5985:                             + __GNUC_MINOR__ * 100)
 5986: # endif
 5987:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
 5988:    fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
 5989: 
 5990:    if (uname(&sysInfo) != -1) {
 5991:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 5992:      fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 5993:    }
 5994:    else
 5995:       perror("uname() error");
 5996:    //#ifndef __INTEL_COMPILER 
 5997: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
 5998:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
 5999:    fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
 6000: #endif
 6001: #endif
 6002: 
 6003:    //   void main()
 6004:    //   {
 6005: #if defined(_MSC_VER)
 6006:    if (IsWow64()){
 6007: 	   printf("The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 6008: 	   fprintf(ficlog, "The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 6009:    }
 6010:    else{
 6011: 	   printf("The process is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 6012: 	   fprintf(ficlog,"The programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 6013:    }
 6014:    //	   printf("\nPress Enter to continue...");
 6015:    //	   getchar();
 6016:    //   }
 6017: 
 6018: #endif
 6019:    
 6020: 
 6021:  }
 6022: 
 6023: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
 6024:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 6025:   int i, j, k, i1 ;
 6026:   double ftolpl = 1.e-10;
 6027:   double age, agebase, agelim;
 6028: 
 6029:     strcpy(filerespl,"pl");
 6030:     strcat(filerespl,fileres);
 6031:     if((ficrespl=fopen(filerespl,"w"))==NULL) {
 6032:       printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
 6033:       fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
 6034:     }
 6035:     printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
 6036:     fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
 6037:     pstamp(ficrespl);
 6038:     fprintf(ficrespl,"# Period (stable) prevalence \n");
 6039:     fprintf(ficrespl,"#Age ");
 6040:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
 6041:     fprintf(ficrespl,"\n");
 6042:   
 6043:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
 6044: 
 6045:     agebase=ageminpar;
 6046:     agelim=agemaxpar;
 6047: 
 6048:     i1=pow(2,cptcoveff);
 6049:     if (cptcovn < 1){i1=1;}
 6050: 
 6051:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6052:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
 6053:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
 6054: 	k=k+1;
 6055: 	/* to clean */
 6056: 	//printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
 6057: 	fprintf(ficrespl,"\n#******");
 6058: 	printf("\n#******");
 6059: 	fprintf(ficlog,"\n#******");
 6060: 	for(j=1;j<=cptcoveff;j++) {
 6061: 	  fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6062: 	  printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6063: 	  fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6064: 	}
 6065: 	fprintf(ficrespl,"******\n");
 6066: 	printf("******\n");
 6067: 	fprintf(ficlog,"******\n");
 6068: 
 6069: 	fprintf(ficrespl,"#Age ");
 6070: 	for(j=1;j<=cptcoveff;j++) {
 6071: 	  fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6072: 	}
 6073: 	for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
 6074: 	fprintf(ficrespl,"\n");
 6075: 	
 6076: 	for (age=agebase; age<=agelim; age++){
 6077: 	/* for (age=agebase; age<=agebase; age++){ */
 6078: 	  prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
 6079: 	  fprintf(ficrespl,"%.0f ",age );
 6080: 	  for(j=1;j<=cptcoveff;j++)
 6081: 	    fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6082: 	  for(i=1; i<=nlstate;i++)
 6083: 	    fprintf(ficrespl," %.5f", prlim[i][i]);
 6084: 	  fprintf(ficrespl,"\n");
 6085: 	} /* Age */
 6086: 	/* was end of cptcod */
 6087:     } /* cptcov */
 6088: 	return 0;
 6089: }
 6090: 
 6091: int hPijx(double *p, int bage, int fage){
 6092:     /*------------- h Pij x at various ages ------------*/
 6093: 
 6094:   int stepsize;
 6095:   int agelim;
 6096:   int hstepm;
 6097:   int nhstepm;
 6098:   int h, i, i1, j, k;
 6099: 
 6100:   double agedeb;
 6101:   double ***p3mat;
 6102: 
 6103:     strcpy(filerespij,"pij");  strcat(filerespij,fileres);
 6104:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
 6105:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
 6106:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
 6107:     }
 6108:     printf("Computing pij: result on file '%s' \n", filerespij);
 6109:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
 6110:   
 6111:     stepsize=(int) (stepm+YEARM-1)/YEARM;
 6112:     /*if (stepm<=24) stepsize=2;*/
 6113: 
 6114:     agelim=AGESUP;
 6115:     hstepm=stepsize*YEARM; /* Every year of age */
 6116:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
 6117: 
 6118:     /* hstepm=1;   aff par mois*/
 6119:     pstamp(ficrespij);
 6120:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
 6121:     i1= pow(2,cptcoveff);
 6122:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
 6123:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
 6124:    /*  	k=k+1;  */
 6125:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 6126:       fprintf(ficrespij,"\n#****** ");
 6127:       for(j=1;j<=cptcoveff;j++) 
 6128: 	fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6129:       fprintf(ficrespij,"******\n");
 6130:       
 6131:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
 6132: 	nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 6133: 	nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 6134: 	
 6135: 	/*	  nhstepm=nhstepm*YEARM; aff par mois*/
 6136: 	
 6137: 	p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6138: 	oldm=oldms;savm=savms;
 6139: 	hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 6140: 	fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
 6141: 	for(i=1; i<=nlstate;i++)
 6142: 	  for(j=1; j<=nlstate+ndeath;j++)
 6143: 	    fprintf(ficrespij," %1d-%1d",i,j);
 6144: 	fprintf(ficrespij,"\n");
 6145: 	for (h=0; h<=nhstepm; h++){
 6146: 	  /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
 6147: 	  fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
 6148: 	  for(i=1; i<=nlstate;i++)
 6149: 	    for(j=1; j<=nlstate+ndeath;j++)
 6150: 	      fprintf(ficrespij," %.5f", p3mat[i][j][h]);
 6151: 	  fprintf(ficrespij,"\n");
 6152: 	}
 6153: 	free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 6154: 	fprintf(ficrespij,"\n");
 6155:       }
 6156:       /*}*/
 6157:     }
 6158: 	return 0;
 6159: }
 6160: 
 6161: 
 6162: /***********************************************/
 6163: /**************** Main Program *****************/
 6164: /***********************************************/
 6165: 
 6166: int main(int argc, char *argv[])
 6167: {
 6168: #ifdef GSL
 6169:   const gsl_multimin_fminimizer_type *T;
 6170:   size_t iteri = 0, it;
 6171:   int rval = GSL_CONTINUE;
 6172:   int status = GSL_SUCCESS;
 6173:   double ssval;
 6174: #endif
 6175:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
 6176:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
 6177: 
 6178:   int jj, ll, li, lj, lk;
 6179:   int numlinepar=0; /* Current linenumber of parameter file */
 6180:   int itimes;
 6181:   int NDIM=2;
 6182:   int vpopbased=0;
 6183: 
 6184:   char ca[32], cb[32];
 6185:   /*  FILE *fichtm; *//* Html File */
 6186:   /* FILE *ficgp;*/ /*Gnuplot File */
 6187:   struct stat info;
 6188:   double agedeb;
 6189:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
 6190: 
 6191:   double fret;
 6192:   double dum; /* Dummy variable */
 6193:   double ***p3mat;
 6194:   double ***mobaverage;
 6195: 
 6196:   char line[MAXLINE];
 6197:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
 6198:   char pathr[MAXLINE], pathimach[MAXLINE]; 
 6199:   char *tok, *val; /* pathtot */
 6200:   int firstobs=1, lastobs=10;
 6201:   int c,  h , cpt;
 6202:   int jl;
 6203:   int i1, j1, jk, stepsize;
 6204:   int *tab; 
 6205:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
 6206:   int mobilav=0,popforecast=0;
 6207:   int hstepm, nhstepm;
 6208:   int agemortsup;
 6209:   float  sumlpop=0.;
 6210:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
 6211:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
 6212: 
 6213:   double bage=0, fage=110, age, agelim, agebase;
 6214:   double ftolpl=FTOL;
 6215:   double **prlim;
 6216:   double ***param; /* Matrix of parameters */
 6217:   double  *p;
 6218:   double **matcov; /* Matrix of covariance */
 6219:   double ***delti3; /* Scale */
 6220:   double *delti; /* Scale */
 6221:   double ***eij, ***vareij;
 6222:   double **varpl; /* Variances of prevalence limits by age */
 6223:   double *epj, vepp;
 6224: 
 6225:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
 6226:   double **ximort;
 6227:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
 6228:   int *dcwave;
 6229: 
 6230:   char z[1]="c";
 6231: 
 6232:   /*char  *strt;*/
 6233:   char strtend[80];
 6234: 
 6235: 
 6236: /*   setlocale (LC_ALL, ""); */
 6237: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
 6238: /*   textdomain (PACKAGE); */
 6239: /*   setlocale (LC_CTYPE, ""); */
 6240: /*   setlocale (LC_MESSAGES, ""); */
 6241: 
 6242:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
 6243:   rstart_time = time(NULL);  
 6244:   /*  (void) gettimeofday(&start_time,&tzp);*/
 6245:   start_time = *localtime(&rstart_time);
 6246:   curr_time=start_time;
 6247:   /*tml = *localtime(&start_time.tm_sec);*/
 6248:   /* strcpy(strstart,asctime(&tml)); */
 6249:   strcpy(strstart,asctime(&start_time));
 6250: 
 6251: /*  printf("Localtime (at start)=%s",strstart); */
 6252: /*  tp.tm_sec = tp.tm_sec +86400; */
 6253: /*  tm = *localtime(&start_time.tm_sec); */
 6254: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
 6255: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
 6256: /*   tmg.tm_hour=tmg.tm_hour + 1; */
 6257: /*   tp.tm_sec = mktime(&tmg); */
 6258: /*   strt=asctime(&tmg); */
 6259: /*   printf("Time(after) =%s",strstart);  */
 6260: /*  (void) time (&time_value);
 6261: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
 6262: *  tm = *localtime(&time_value);
 6263: *  strstart=asctime(&tm);
 6264: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
 6265: */
 6266: 
 6267:   nberr=0; /* Number of errors and warnings */
 6268:   nbwarn=0;
 6269: #ifdef WIN32
 6270:   _getcwd(pathcd, size);
 6271: #else
 6272:   getcwd(pathcd, size);
 6273: #endif
 6274: 
 6275:   printf("\n%s\n%s",version,fullversion);
 6276:   if(argc <=1){
 6277:     printf("\nEnter the parameter file name: ");
 6278:     fgets(pathr,FILENAMELENGTH,stdin);
 6279:     i=strlen(pathr);
 6280:     if(pathr[i-1]=='\n')
 6281:       pathr[i-1]='\0';
 6282:     i=strlen(pathr);
 6283:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
 6284:       pathr[i-1]='\0';
 6285:    for (tok = pathr; tok != NULL; ){
 6286:       printf("Pathr |%s|\n",pathr);
 6287:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
 6288:       printf("val= |%s| pathr=%s\n",val,pathr);
 6289:       strcpy (pathtot, val);
 6290:       if(pathr[0] == '\0') break; /* Dirty */
 6291:     }
 6292:   }
 6293:   else{
 6294:     strcpy(pathtot,argv[1]);
 6295:   }
 6296:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
 6297:   /*cygwin_split_path(pathtot,path,optionfile);
 6298:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
 6299:   /* cutv(path,optionfile,pathtot,'\\');*/
 6300: 
 6301:   /* Split argv[0], imach program to get pathimach */
 6302:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
 6303:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 6304:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 6305:  /*   strcpy(pathimach,argv[0]); */
 6306:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
 6307:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
 6308:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
 6309: #ifdef WIN32
 6310:   _chdir(path); /* Can be a relative path */
 6311:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
 6312: #else
 6313:   chdir(path); /* Can be a relative path */
 6314:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
 6315: #endif
 6316:   printf("Current directory %s!\n",pathcd);
 6317:   strcpy(command,"mkdir ");
 6318:   strcat(command,optionfilefiname);
 6319:   if((outcmd=system(command)) != 0){
 6320:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
 6321:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
 6322:     /* fclose(ficlog); */
 6323: /*     exit(1); */
 6324:   }
 6325: /*   if((imk=mkdir(optionfilefiname))<0){ */
 6326: /*     perror("mkdir"); */
 6327: /*   } */
 6328: 
 6329:   /*-------- arguments in the command line --------*/
 6330: 
 6331:   /* Main Log file */
 6332:   strcat(filelog, optionfilefiname);
 6333:   strcat(filelog,".log");    /* */
 6334:   if((ficlog=fopen(filelog,"w"))==NULL)    {
 6335:     printf("Problem with logfile %s\n",filelog);
 6336:     goto end;
 6337:   }
 6338:   fprintf(ficlog,"Log filename:%s\n",filelog);
 6339:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
 6340:   fprintf(ficlog,"\nEnter the parameter file name: \n");
 6341:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
 6342:  path=%s \n\
 6343:  optionfile=%s\n\
 6344:  optionfilext=%s\n\
 6345:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
 6346: 
 6347:   syscompilerinfo();
 6348: 
 6349:   printf("Local time (at start):%s",strstart);
 6350:   fprintf(ficlog,"Local time (at start): %s",strstart);
 6351:   fflush(ficlog);
 6352: /*   (void) gettimeofday(&curr_time,&tzp); */
 6353: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
 6354: 
 6355:   /* */
 6356:   strcpy(fileres,"r");
 6357:   strcat(fileres, optionfilefiname);
 6358:   strcat(fileres,".txt");    /* Other files have txt extension */
 6359: 
 6360:   /* Main ---------arguments file --------*/
 6361: 
 6362:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
 6363:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 6364:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 6365:     fflush(ficlog);
 6366:     /* goto end; */
 6367:     exit(70); 
 6368:   }
 6369: 
 6370: 
 6371: 
 6372:   strcpy(filereso,"o");
 6373:   strcat(filereso,fileres);
 6374:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
 6375:     printf("Problem with Output resultfile: %s\n", filereso);
 6376:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
 6377:     fflush(ficlog);
 6378:     goto end;
 6379:   }
 6380: 
 6381:   /* Reads comments: lines beginning with '#' */
 6382:   numlinepar=0;
 6383:   while((c=getc(ficpar))=='#' && c!= EOF){
 6384:     ungetc(c,ficpar);
 6385:     fgets(line, MAXLINE, ficpar);
 6386:     numlinepar++;
 6387:     fputs(line,stdout);
 6388:     fputs(line,ficparo);
 6389:     fputs(line,ficlog);
 6390:   }
 6391:   ungetc(c,ficpar);
 6392: 
 6393:   fscanf(ficpar,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d model=1+age+%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model);
 6394:   numlinepar++;
 6395:   printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model);
 6396:   if(model[strlen(model)-1]=='.') /* Suppressing leading dot in the model */
 6397:     model[strlen(model)-1]='\0';
 6398:   fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
 6399:   fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
 6400:   fflush(ficlog);
 6401:   if(model[0]=='#'|| model[0]== '\0'){
 6402:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
 6403:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
 6404:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");		\
 6405:     if(mle != -1){
 6406:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
 6407:       exit(1);
 6408:     }
 6409:   }
 6410:   while((c=getc(ficpar))=='#' && c!= EOF){
 6411:     ungetc(c,ficpar);
 6412:     fgets(line, MAXLINE, ficpar);
 6413:     numlinepar++;
 6414:     fputs(line, stdout);
 6415:     //puts(line);
 6416:     fputs(line,ficparo);
 6417:     fputs(line,ficlog);
 6418:   }
 6419:   ungetc(c,ficpar);
 6420: 
 6421:    
 6422:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
 6423:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
 6424:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
 6425:      v1+v2*age+v2*v3 makes cptcovn = 3
 6426:   */
 6427:   if (strlen(model)>1) 
 6428:     ncovmodel=2+nbocc(model,'+')+1; /*Number of variables including intercept and age = cptcovn + intercept + age : v1+v2+v3+v2*v4+v5*age makes 5+2=7,age*age makes 3*/
 6429:   else
 6430:     ncovmodel=2; /* Constant and age */
 6431:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
 6432:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
 6433:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
 6434:     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);
 6435:     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);
 6436:     fflush(stdout);
 6437:     fclose (ficlog);
 6438:     goto end;
 6439:   }
 6440:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 6441:   delti=delti3[1][1];
 6442:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
 6443:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
 6444:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 6445:     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 6446:     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 6447:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 6448:     fclose (ficparo);
 6449:     fclose (ficlog);
 6450:     goto end;
 6451:     exit(0);
 6452:   }
 6453:   else if(mle==-3) { /* Main Wizard */
 6454:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 6455:     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 6456:     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 6457:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 6458:     matcov=matrix(1,npar,1,npar);
 6459:   }
 6460:   else{
 6461:     /* Read guessed parameters */
 6462:     /* Reads comments: lines beginning with '#' */
 6463:     while((c=getc(ficpar))=='#' && c!= EOF){
 6464:       ungetc(c,ficpar);
 6465:       fgets(line, MAXLINE, ficpar);
 6466:       numlinepar++;
 6467:       fputs(line,stdout);
 6468:       fputs(line,ficparo);
 6469:       fputs(line,ficlog);
 6470:     }
 6471:     ungetc(c,ficpar);
 6472:     
 6473:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 6474:     for(i=1; i <=nlstate; i++){
 6475:       j=0;
 6476:       for(jj=1; jj <=nlstate+ndeath; jj++){
 6477: 	if(jj==i) continue;
 6478: 	j++;
 6479: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 6480: 	if ((i1 != i) && (j1 != j)){
 6481: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
 6482: It might be a problem of design; if ncovcol and the model are correct\n \
 6483: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
 6484: 	  exit(1);
 6485: 	}
 6486: 	fprintf(ficparo,"%1d%1d",i1,j1);
 6487: 	if(mle==1)
 6488: 	  printf("%1d%1d",i,j);
 6489: 	fprintf(ficlog,"%1d%1d",i,j);
 6490: 	for(k=1; k<=ncovmodel;k++){
 6491: 	  fscanf(ficpar," %lf",&param[i][j][k]);
 6492: 	  if(mle==1){
 6493: 	    printf(" %lf",param[i][j][k]);
 6494: 	    fprintf(ficlog," %lf",param[i][j][k]);
 6495: 	  }
 6496: 	  else
 6497: 	    fprintf(ficlog," %lf",param[i][j][k]);
 6498: 	  fprintf(ficparo," %lf",param[i][j][k]);
 6499: 	}
 6500: 	fscanf(ficpar,"\n");
 6501: 	numlinepar++;
 6502: 	if(mle==1)
 6503: 	  printf("\n");
 6504: 	fprintf(ficlog,"\n");
 6505: 	fprintf(ficparo,"\n");
 6506:       }
 6507:     }  
 6508:     fflush(ficlog);
 6509: 
 6510:     /* Reads scales values */
 6511:     p=param[1][1];
 6512:     
 6513:     /* Reads comments: lines beginning with '#' */
 6514:     while((c=getc(ficpar))=='#' && c!= EOF){
 6515:       ungetc(c,ficpar);
 6516:       fgets(line, MAXLINE, ficpar);
 6517:       numlinepar++;
 6518:       fputs(line,stdout);
 6519:       fputs(line,ficparo);
 6520:       fputs(line,ficlog);
 6521:     }
 6522:     ungetc(c,ficpar);
 6523: 
 6524:     for(i=1; i <=nlstate; i++){
 6525:       for(j=1; j <=nlstate+ndeath-1; j++){
 6526: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 6527: 	if ( (i1-i) * (j1-j) != 0){
 6528: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
 6529: 	  exit(1);
 6530: 	}
 6531: 	printf("%1d%1d",i,j);
 6532: 	fprintf(ficparo,"%1d%1d",i1,j1);
 6533: 	fprintf(ficlog,"%1d%1d",i1,j1);
 6534: 	for(k=1; k<=ncovmodel;k++){
 6535: 	  fscanf(ficpar,"%le",&delti3[i][j][k]);
 6536: 	  printf(" %le",delti3[i][j][k]);
 6537: 	  fprintf(ficparo," %le",delti3[i][j][k]);
 6538: 	  fprintf(ficlog," %le",delti3[i][j][k]);
 6539: 	}
 6540: 	fscanf(ficpar,"\n");
 6541: 	numlinepar++;
 6542: 	printf("\n");
 6543: 	fprintf(ficparo,"\n");
 6544: 	fprintf(ficlog,"\n");
 6545:       }
 6546:     }
 6547:     fflush(ficlog);
 6548: 
 6549:     /* Reads covariance matrix */
 6550:     delti=delti3[1][1];
 6551: 
 6552: 
 6553:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
 6554:   
 6555:     /* Reads comments: lines beginning with '#' */
 6556:     while((c=getc(ficpar))=='#' && c!= EOF){
 6557:       ungetc(c,ficpar);
 6558:       fgets(line, MAXLINE, ficpar);
 6559:       numlinepar++;
 6560:       fputs(line,stdout);
 6561:       fputs(line,ficparo);
 6562:       fputs(line,ficlog);
 6563:     }
 6564:     ungetc(c,ficpar);
 6565:   
 6566:     matcov=matrix(1,npar,1,npar);
 6567:     for(i=1; i <=npar; i++)
 6568:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
 6569:       
 6570:     for(i=1; i <=npar; i++){
 6571:       fscanf(ficpar,"%s",str);
 6572:       if(mle==1)
 6573: 	printf("%s",str);
 6574:       fprintf(ficlog,"%s",str);
 6575:       fprintf(ficparo,"%s",str);
 6576:       for(j=1; j <=i; j++){
 6577: 	fscanf(ficpar," %le",&matcov[i][j]);
 6578: 	if(mle==1){
 6579: 	  printf(" %.5le",matcov[i][j]);
 6580: 	}
 6581: 	fprintf(ficlog," %.5le",matcov[i][j]);
 6582: 	fprintf(ficparo," %.5le",matcov[i][j]);
 6583:       }
 6584:       fscanf(ficpar,"\n");
 6585:       numlinepar++;
 6586:       if(mle==1)
 6587: 	printf("\n");
 6588:       fprintf(ficlog,"\n");
 6589:       fprintf(ficparo,"\n");
 6590:     }
 6591:     for(i=1; i <=npar; i++)
 6592:       for(j=i+1;j<=npar;j++)
 6593: 	matcov[i][j]=matcov[j][i];
 6594:     
 6595:     if(mle==1)
 6596:       printf("\n");
 6597:     fprintf(ficlog,"\n");
 6598:     
 6599:     fflush(ficlog);
 6600:     
 6601:     /*-------- Rewriting parameter file ----------*/
 6602:     strcpy(rfileres,"r");    /* "Rparameterfile */
 6603:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
 6604:     strcat(rfileres,".");    /* */
 6605:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
 6606:     if((ficres =fopen(rfileres,"w"))==NULL) {
 6607:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
 6608:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
 6609:     }
 6610:     fprintf(ficres,"#%s\n",version);
 6611:   }    /* End of mle != -3 */
 6612: 
 6613:   /*  Main data
 6614:    */
 6615:   n= lastobs;
 6616:   num=lvector(1,n);
 6617:   moisnais=vector(1,n);
 6618:   annais=vector(1,n);
 6619:   moisdc=vector(1,n);
 6620:   andc=vector(1,n);
 6621:   agedc=vector(1,n);
 6622:   cod=ivector(1,n);
 6623:   weight=vector(1,n);
 6624:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
 6625:   mint=matrix(1,maxwav,1,n);
 6626:   anint=matrix(1,maxwav,1,n);
 6627:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
 6628:   tab=ivector(1,NCOVMAX);
 6629:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
 6630: 
 6631:   /* Reads data from file datafile */
 6632:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
 6633:     goto end;
 6634: 
 6635:   /* Calculation of the number of parameters from char model */
 6636:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
 6637: 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
 6638: 	k=3 V4 Tvar[k=3]= 4 (from V4)
 6639: 	k=2 V1 Tvar[k=2]= 1 (from V1)
 6640: 	k=1 Tvar[1]=2 (from V2)
 6641:     */
 6642:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
 6643:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
 6644:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
 6645:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
 6646:   */
 6647:   /* For model-covariate k tells which data-covariate to use but
 6648:     because this model-covariate is a construction we invent a new column
 6649:     ncovcol + k1
 6650:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
 6651:     Tvar[3=V1*V4]=4+1 etc */
 6652:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
 6653:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
 6654:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
 6655:   */
 6656:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
 6657:   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
 6658: 			    * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
 6659: 			    * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
 6660:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
 6661: 			 4 covariates (3 plus signs)
 6662: 			 Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
 6663: 		      */  
 6664: 
 6665: /* Main decodemodel */
 6666: 
 6667: 
 6668:   if(decodemodel(model, lastobs) == 1)
 6669:     goto end;
 6670: 
 6671:   if((double)(lastobs-imx)/(double)imx > 1.10){
 6672:     nbwarn++;
 6673:     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); 
 6674:     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); 
 6675:   }
 6676:     /*  if(mle==1){*/
 6677:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
 6678:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
 6679:   }
 6680: 
 6681:     /*-calculation of age at interview from date of interview and age at death -*/
 6682:   agev=matrix(1,maxwav,1,imx);
 6683: 
 6684:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
 6685:     goto end;
 6686: 
 6687: 
 6688:   agegomp=(int)agemin;
 6689:   free_vector(moisnais,1,n);
 6690:   free_vector(annais,1,n);
 6691:   /* free_matrix(mint,1,maxwav,1,n);
 6692:      free_matrix(anint,1,maxwav,1,n);*/
 6693:   free_vector(moisdc,1,n);
 6694:   free_vector(andc,1,n);
 6695:   /* */
 6696:   
 6697:   wav=ivector(1,imx);
 6698:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
 6699:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
 6700:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
 6701:    
 6702:   /* Concatenates waves */
 6703:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
 6704:   /* */
 6705:  
 6706:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
 6707: 
 6708:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
 6709:   ncodemax[1]=1;
 6710:   Ndum =ivector(-1,NCOVMAX);  
 6711:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
 6712:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
 6713:   /* Nbcode gives the value of the lth modality of jth covariate, in
 6714:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
 6715:   /* 1 to ncodemax[j] is the maximum value of this jth covariate */
 6716: 
 6717:   codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
 6718:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
 6719:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
 6720:   h=0;
 6721: 
 6722: 
 6723:   /*if (cptcovn > 0) */
 6724:       
 6725:  
 6726:   m=pow(2,cptcoveff);
 6727:  
 6728:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
 6729:     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 */ 
 6730:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
 6731: 	for(cpt=1; cpt <=pow(2,k-1); cpt++){  /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */ 
 6732: 	  h++;
 6733: 	  if (h>m) 
 6734: 	    h=1;
 6735: 	  /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
 6736: 	   * For k=4 covariates, h goes from 1 to 2**k
 6737: 	   * codtabm(h,k)=  1 & (h-1) >> (k-1) ;
 6738: 	   *     h\k   1     2     3     4
 6739: 	   *______________________________  
 6740: 	   *     1 i=1 1 i=1 1 i=1 1 i=1 1
 6741: 	   *     2     2     1     1     1
 6742: 	   *     3 i=2 1     2     1     1
 6743: 	   *     4     2     2     1     1
 6744: 	   *     5 i=3 1 i=2 1     2     1
 6745: 	   *     6     2     1     2     1
 6746: 	   *     7 i=4 1     2     2     1
 6747: 	   *     8     2     2     2     1
 6748: 	   *     9 i=5 1 i=3 1 i=2 1     1
 6749: 	   *    10     2     1     1     1
 6750: 	   *    11 i=6 1     2     1     1
 6751: 	   *    12     2     2     1     1
 6752: 	   *    13 i=7 1 i=4 1     2     1    
 6753: 	   *    14     2     1     2     1
 6754: 	   *    15 i=8 1     2     2     1
 6755: 	   *    16     2     2     2     1
 6756: 	   */
 6757: 	  codtab[h][k]=j;
 6758: 	  /* codtab[12][3]=1; */
 6759: 	  /*codtab[h][Tvar[k]]=j;*/
 6760: 	  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]]);
 6761: 	} 
 6762:       }
 6763:     }
 6764:   } 
 6765:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
 6766:      codtab[1][2]=1;codtab[2][2]=2; */
 6767:   /* for(i=1; i <=m ;i++){ 
 6768:      for(k=1; k <=cptcovn; k++){
 6769:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
 6770:      }
 6771:      printf("\n");
 6772:      }
 6773:      scanf("%d",i);*/
 6774: 
 6775:  free_ivector(Ndum,-1,NCOVMAX);
 6776: 
 6777: 
 6778:     
 6779:   /* Initialisation of ----------- gnuplot -------------*/
 6780:   strcpy(optionfilegnuplot,optionfilefiname);
 6781:   if(mle==-3)
 6782:     strcat(optionfilegnuplot,"-mort");
 6783:   strcat(optionfilegnuplot,".gp");
 6784: 
 6785:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
 6786:     printf("Problem with file %s",optionfilegnuplot);
 6787:   }
 6788:   else{
 6789:     fprintf(ficgp,"\n# %s\n", version); 
 6790:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
 6791:     //fprintf(ficgp,"set missing 'NaNq'\n");
 6792:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
 6793:   }
 6794:   /*  fclose(ficgp);*/
 6795: 
 6796: 
 6797:   /* Initialisation of --------- index.htm --------*/
 6798: 
 6799:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
 6800:   if(mle==-3)
 6801:     strcat(optionfilehtm,"-mort");
 6802:   strcat(optionfilehtm,".htm");
 6803:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
 6804:     printf("Problem with %s \n",optionfilehtm);
 6805:     exit(0);
 6806:   }
 6807: 
 6808:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
 6809:   strcat(optionfilehtmcov,"-cov.htm");
 6810:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
 6811:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
 6812:   }
 6813:   else{
 6814:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 6815: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 6816: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
 6817: 	  optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 6818:   }
 6819: 
 6820:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 6821: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 6822: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
 6823: \n\
 6824: <hr  size=\"2\" color=\"#EC5E5E\">\
 6825:  <ul><li><h4>Parameter files</h4>\n\
 6826:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
 6827:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
 6828:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
 6829:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
 6830:  - Date and time at start: %s</ul>\n",\
 6831: 	  optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
 6832: 	  optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
 6833: 	  fileres,fileres,\
 6834: 	  filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
 6835:   fflush(fichtm);
 6836: 
 6837:   strcpy(pathr,path);
 6838:   strcat(pathr,optionfilefiname);
 6839: #ifdef WIN32
 6840:   _chdir(optionfilefiname); /* Move to directory named optionfile */
 6841: #else
 6842:   chdir(optionfilefiname); /* Move to directory named optionfile */
 6843: #endif
 6844: 	  
 6845:   
 6846:   /* Calculates basic frequencies. Computes observed prevalence at single age
 6847:      and prints on file fileres'p'. */
 6848:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
 6849: 
 6850:   fprintf(fichtm,"\n");
 6851:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
 6852: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
 6853: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
 6854: 	  imx,agemin,agemax,jmin,jmax,jmean);
 6855:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6856:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6857:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6858:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6859:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
 6860:     
 6861:    
 6862:   /* For Powell, parameters are in a vector p[] starting at p[1]
 6863:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
 6864:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
 6865: 
 6866:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
 6867:   /* For mortality only */
 6868:   if (mle==-3){
 6869:     ximort=matrix(1,NDIM,1,NDIM); 
 6870:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
 6871:     cens=ivector(1,n);
 6872:     ageexmed=vector(1,n);
 6873:     agecens=vector(1,n);
 6874:     dcwave=ivector(1,n);
 6875:  
 6876:     for (i=1; i<=imx; i++){
 6877:       dcwave[i]=-1;
 6878:       for (m=firstpass; m<=lastpass; m++)
 6879: 	if (s[m][i]>nlstate) {
 6880: 	  dcwave[i]=m;
 6881: 	  /*	printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
 6882: 	  break;
 6883: 	}
 6884:     }
 6885: 
 6886:     for (i=1; i<=imx; i++) {
 6887:       if (wav[i]>0){
 6888: 	ageexmed[i]=agev[mw[1][i]][i];
 6889: 	j=wav[i];
 6890: 	agecens[i]=1.; 
 6891: 
 6892: 	if (ageexmed[i]> 1 && wav[i] > 0){
 6893: 	  agecens[i]=agev[mw[j][i]][i];
 6894: 	  cens[i]= 1;
 6895: 	}else if (ageexmed[i]< 1) 
 6896: 	  cens[i]= -1;
 6897: 	if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
 6898: 	  cens[i]=0 ;
 6899:       }
 6900:       else cens[i]=-1;
 6901:     }
 6902:     
 6903:     for (i=1;i<=NDIM;i++) {
 6904:       for (j=1;j<=NDIM;j++)
 6905: 	ximort[i][j]=(i == j ? 1.0 : 0.0);
 6906:     }
 6907:     
 6908:     /*p[1]=0.0268; p[NDIM]=0.083;*/
 6909:     /*printf("%lf %lf", p[1], p[2]);*/
 6910:     
 6911:     
 6912: #ifdef GSL
 6913:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
 6914: #else
 6915:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
 6916: #endif
 6917:     strcpy(filerespow,"pow-mort"); 
 6918:     strcat(filerespow,fileres);
 6919:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
 6920:       printf("Problem with resultfile: %s\n", filerespow);
 6921:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 6922:     }
 6923: #ifdef GSL
 6924:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
 6925: #else
 6926:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
 6927: #endif
 6928:     /*  for (i=1;i<=nlstate;i++)
 6929: 	for(j=1;j<=nlstate+ndeath;j++)
 6930: 	if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 6931:     */
 6932:     fprintf(ficrespow,"\n");
 6933: #ifdef GSL
 6934:     /* gsl starts here */ 
 6935:     T = gsl_multimin_fminimizer_nmsimplex;
 6936:     gsl_multimin_fminimizer *sfm = NULL;
 6937:     gsl_vector *ss, *x;
 6938:     gsl_multimin_function minex_func;
 6939: 
 6940:     /* Initial vertex size vector */
 6941:     ss = gsl_vector_alloc (NDIM);
 6942:     
 6943:     if (ss == NULL){
 6944:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
 6945:     }
 6946:     /* Set all step sizes to 1 */
 6947:     gsl_vector_set_all (ss, 0.001);
 6948: 
 6949:     /* Starting point */
 6950:     
 6951:     x = gsl_vector_alloc (NDIM);
 6952:     
 6953:     if (x == NULL){
 6954:       gsl_vector_free(ss);
 6955:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
 6956:     }
 6957:   
 6958:     /* Initialize method and iterate */
 6959:     /*     p[1]=0.0268; p[NDIM]=0.083; */
 6960:     /*     gsl_vector_set(x, 0, 0.0268); */
 6961:     /*     gsl_vector_set(x, 1, 0.083); */
 6962:     gsl_vector_set(x, 0, p[1]);
 6963:     gsl_vector_set(x, 1, p[2]);
 6964: 
 6965:     minex_func.f = &gompertz_f;
 6966:     minex_func.n = NDIM;
 6967:     minex_func.params = (void *)&p; /* ??? */
 6968:     
 6969:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
 6970:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
 6971:     
 6972:     printf("Iterations beginning .....\n\n");
 6973:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
 6974: 
 6975:     iteri=0;
 6976:     while (rval == GSL_CONTINUE){
 6977:       iteri++;
 6978:       status = gsl_multimin_fminimizer_iterate(sfm);
 6979:       
 6980:       if (status) printf("error: %s\n", gsl_strerror (status));
 6981:       fflush(0);
 6982:       
 6983:       if (status) 
 6984:         break;
 6985:       
 6986:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
 6987:       ssval = gsl_multimin_fminimizer_size (sfm);
 6988:       
 6989:       if (rval == GSL_SUCCESS)
 6990:         printf ("converged to a local maximum at\n");
 6991:       
 6992:       printf("%5d ", iteri);
 6993:       for (it = 0; it < NDIM; it++){
 6994: 	printf ("%10.5f ", gsl_vector_get (sfm->x, it));
 6995:       }
 6996:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
 6997:     }
 6998:     
 6999:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
 7000:     
 7001:     gsl_vector_free(x); /* initial values */
 7002:     gsl_vector_free(ss); /* inital step size */
 7003:     for (it=0; it<NDIM; it++){
 7004:       p[it+1]=gsl_vector_get(sfm->x,it);
 7005:       fprintf(ficrespow," %.12lf", p[it]);
 7006:     }
 7007:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
 7008: #endif
 7009: #ifdef POWELL
 7010:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
 7011: #endif  
 7012:     fclose(ficrespow);
 7013:     
 7014:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
 7015: 
 7016:     for(i=1; i <=NDIM; i++)
 7017:       for(j=i+1;j<=NDIM;j++)
 7018: 	matcov[i][j]=matcov[j][i];
 7019:     
 7020:     printf("\nCovariance matrix\n ");
 7021:     for(i=1; i <=NDIM; i++) {
 7022:       for(j=1;j<=NDIM;j++){ 
 7023: 	printf("%f ",matcov[i][j]);
 7024:       }
 7025:       printf("\n ");
 7026:     }
 7027:     
 7028:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
 7029:     for (i=1;i<=NDIM;i++) 
 7030:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
 7031: 
 7032:     lsurv=vector(1,AGESUP);
 7033:     lpop=vector(1,AGESUP);
 7034:     tpop=vector(1,AGESUP);
 7035:     lsurv[agegomp]=100000;
 7036:     
 7037:     for (k=agegomp;k<=AGESUP;k++) {
 7038:       agemortsup=k;
 7039:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
 7040:     }
 7041:     
 7042:     for (k=agegomp;k<agemortsup;k++)
 7043:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
 7044:     
 7045:     for (k=agegomp;k<agemortsup;k++){
 7046:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
 7047:       sumlpop=sumlpop+lpop[k];
 7048:     }
 7049:     
 7050:     tpop[agegomp]=sumlpop;
 7051:     for (k=agegomp;k<(agemortsup-3);k++){
 7052:       /*  tpop[k+1]=2;*/
 7053:       tpop[k+1]=tpop[k]-lpop[k];
 7054:     }
 7055:     
 7056:     
 7057:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
 7058:     for (k=agegomp;k<(agemortsup-2);k++) 
 7059:       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]);
 7060:     
 7061:     
 7062:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 7063:     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 7064:     
 7065:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
 7066: 		     stepm, weightopt,\
 7067: 		     model,imx,p,matcov,agemortsup);
 7068:     
 7069:     free_vector(lsurv,1,AGESUP);
 7070:     free_vector(lpop,1,AGESUP);
 7071:     free_vector(tpop,1,AGESUP);
 7072: #ifdef GSL
 7073:     free_ivector(cens,1,n);
 7074:     free_vector(agecens,1,n);
 7075:     free_ivector(dcwave,1,n);
 7076:     free_matrix(ximort,1,NDIM,1,NDIM);
 7077: #endif
 7078:   } /* Endof if mle==-3 mortality only */
 7079:   /* Standard maximisation */
 7080:   else{ /* For mle >=1 */
 7081:     globpr=0;/* debug */
 7082:     /* Computes likelihood for initial parameters */
 7083:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 7084:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 7085:     for (k=1; k<=npar;k++)
 7086:       printf(" %d %8.5f",k,p[k]);
 7087:     printf("\n");
 7088:     globpr=1; /* again, to print the contributions */
 7089:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 7090:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 7091:     for (k=1; k<=npar;k++)
 7092:       printf(" %d %8.5f",k,p[k]);
 7093:     printf("\n");
 7094:     if(mle>=1){ /* Could be 1 or 2, Real Maximisation */
 7095:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
 7096:     }
 7097:     
 7098:     /*--------- results files --------------*/
 7099:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle= 0 weight=%d\nmodel=1+age+%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate, ndeath, maxwav, weightopt,model);
 7100:     
 7101:     
 7102:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 7103:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 7104:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 7105:     for(i=1,jk=1; i <=nlstate; i++){
 7106:       for(k=1; k <=(nlstate+ndeath); k++){
 7107: 	if (k != i) {
 7108: 	  printf("%d%d ",i,k);
 7109: 	  fprintf(ficlog,"%d%d ",i,k);
 7110: 	  fprintf(ficres,"%1d%1d ",i,k);
 7111: 	  for(j=1; j <=ncovmodel; j++){
 7112: 	    printf("%lf ",p[jk]);
 7113: 	    fprintf(ficlog,"%lf ",p[jk]);
 7114: 	    fprintf(ficres,"%lf ",p[jk]);
 7115: 	    jk++; 
 7116: 	  }
 7117: 	  printf("\n");
 7118: 	  fprintf(ficlog,"\n");
 7119: 	  fprintf(ficres,"\n");
 7120: 	}
 7121:       }
 7122:     }
 7123:     if(mle!=0){
 7124:       /* Computing hessian and covariance matrix */
 7125:       ftolhess=ftol; /* Usually correct */
 7126:       hesscov(matcov, p, npar, delti, ftolhess, func);
 7127:     }
 7128:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
 7129:     printf("# Scales (for hessian or gradient estimation)\n");
 7130:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
 7131:     for(i=1,jk=1; i <=nlstate; i++){
 7132:       for(j=1; j <=nlstate+ndeath; j++){
 7133: 	if (j!=i) {
 7134: 	  fprintf(ficres,"%1d%1d",i,j);
 7135: 	  printf("%1d%1d",i,j);
 7136: 	  fprintf(ficlog,"%1d%1d",i,j);
 7137: 	  for(k=1; k<=ncovmodel;k++){
 7138: 	    printf(" %.5e",delti[jk]);
 7139: 	    fprintf(ficlog," %.5e",delti[jk]);
 7140: 	    fprintf(ficres," %.5e",delti[jk]);
 7141: 	    jk++;
 7142: 	  }
 7143: 	  printf("\n");
 7144: 	  fprintf(ficlog,"\n");
 7145: 	  fprintf(ficres,"\n");
 7146: 	}
 7147:       }
 7148:     }
 7149:     
 7150:     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");
 7151:     if(mle>=1)
 7152:       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");
 7153:     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");
 7154:     /* # 121 Var(a12)\n\ */
 7155:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
 7156:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 7157:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 7158:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 7159:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 7160:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 7161:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 7162:     
 7163:     
 7164:     /* Just to have a covariance matrix which will be more understandable
 7165:        even is we still don't want to manage dictionary of variables
 7166:     */
 7167:     for(itimes=1;itimes<=2;itimes++){
 7168:       jj=0;
 7169:       for(i=1; i <=nlstate; i++){
 7170: 	for(j=1; j <=nlstate+ndeath; j++){
 7171: 	  if(j==i) continue;
 7172: 	  for(k=1; k<=ncovmodel;k++){
 7173: 	    jj++;
 7174: 	    ca[0]= k+'a'-1;ca[1]='\0';
 7175: 	    if(itimes==1){
 7176: 	      if(mle>=1)
 7177: 		printf("#%1d%1d%d",i,j,k);
 7178: 	      fprintf(ficlog,"#%1d%1d%d",i,j,k);
 7179: 	      fprintf(ficres,"#%1d%1d%d",i,j,k);
 7180: 	    }else{
 7181: 	      if(mle>=1)
 7182: 		printf("%1d%1d%d",i,j,k);
 7183: 	      fprintf(ficlog,"%1d%1d%d",i,j,k);
 7184: 	      fprintf(ficres,"%1d%1d%d",i,j,k);
 7185: 	    }
 7186: 	    ll=0;
 7187: 	    for(li=1;li <=nlstate; li++){
 7188: 	      for(lj=1;lj <=nlstate+ndeath; lj++){
 7189: 		if(lj==li) continue;
 7190: 		for(lk=1;lk<=ncovmodel;lk++){
 7191: 		  ll++;
 7192: 		  if(ll<=jj){
 7193: 		    cb[0]= lk +'a'-1;cb[1]='\0';
 7194: 		    if(ll<jj){
 7195: 		      if(itimes==1){
 7196: 			if(mle>=1)
 7197: 			  printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 7198: 			fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 7199: 			fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 7200: 		      }else{
 7201: 			if(mle>=1)
 7202: 			  printf(" %.5e",matcov[jj][ll]); 
 7203: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 7204: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 7205: 		      }
 7206: 		    }else{
 7207: 		      if(itimes==1){
 7208: 			if(mle>=1)
 7209: 			  printf(" Var(%s%1d%1d)",ca,i,j);
 7210: 			fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
 7211: 			fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
 7212: 		      }else{
 7213: 			if(mle>=1)
 7214: 			  printf(" %.5e",matcov[jj][ll]); 
 7215: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 7216: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 7217: 		      }
 7218: 		    }
 7219: 		  }
 7220: 		} /* end lk */
 7221: 	      } /* end lj */
 7222: 	    } /* end li */
 7223: 	    if(mle>=1)
 7224: 	      printf("\n");
 7225: 	    fprintf(ficlog,"\n");
 7226: 	    fprintf(ficres,"\n");
 7227: 	    numlinepar++;
 7228: 	  } /* end k*/
 7229: 	} /*end j */
 7230:       } /* end i */
 7231:     } /* end itimes */
 7232:     
 7233:     fflush(ficlog);
 7234:     fflush(ficres);
 7235:     
 7236:     while((c=getc(ficpar))=='#' && c!= EOF){
 7237:       ungetc(c,ficpar);
 7238:       fgets(line, MAXLINE, ficpar);
 7239:       fputs(line,stdout);
 7240:       fputs(line,ficparo);
 7241:     }
 7242:     ungetc(c,ficpar);
 7243:     
 7244:     estepm=0;
 7245:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
 7246:     if (estepm==0 || estepm < stepm) estepm=stepm;
 7247:     if (fage <= 2) {
 7248:       bage = ageminpar;
 7249:       fage = agemaxpar;
 7250:     }
 7251:     
 7252:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
 7253:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 7254:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 7255: 
 7256:     /* Other stuffs, more or less useful */    
 7257:     while((c=getc(ficpar))=='#' && c!= EOF){
 7258:       ungetc(c,ficpar);
 7259:       fgets(line, MAXLINE, ficpar);
 7260:       fputs(line,stdout);
 7261:       fputs(line,ficparo);
 7262:     }
 7263:     ungetc(c,ficpar);
 7264:     
 7265:     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);
 7266:     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);
 7267:     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);
 7268:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
 7269:     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);
 7270:     
 7271:     while((c=getc(ficpar))=='#' && c!= EOF){
 7272:       ungetc(c,ficpar);
 7273:       fgets(line, MAXLINE, ficpar);
 7274:       fputs(line,stdout);
 7275:       fputs(line,ficparo);
 7276:     }
 7277:     ungetc(c,ficpar);
 7278:     
 7279:     
 7280:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
 7281:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
 7282:     
 7283:     fscanf(ficpar,"pop_based=%d\n",&popbased);
 7284:     fprintf(ficparo,"pop_based=%d\n",popbased);   
 7285:     fprintf(ficres,"pop_based=%d\n",popbased);   
 7286:     
 7287:     while((c=getc(ficpar))=='#' && c!= EOF){
 7288:       ungetc(c,ficpar);
 7289:       fgets(line, MAXLINE, ficpar);
 7290:       fputs(line,stdout);
 7291:       fputs(line,ficparo);
 7292:     }
 7293:     ungetc(c,ficpar);
 7294:     
 7295:     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);
 7296:     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);
 7297:     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);
 7298:     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);
 7299:     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);
 7300:     /* day and month of proj2 are not used but only year anproj2.*/
 7301:     
 7302:     
 7303:     
 7304:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
 7305:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
 7306:     
 7307:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 7308:     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 7309:     
 7310:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
 7311: 		 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
 7312: 		 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
 7313:       
 7314:    /*------------ free_vector  -------------*/
 7315:    /*  chdir(path); */
 7316:  
 7317:     free_ivector(wav,1,imx);
 7318:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
 7319:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
 7320:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
 7321:     free_lvector(num,1,n);
 7322:     free_vector(agedc,1,n);
 7323:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
 7324:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
 7325:     fclose(ficparo);
 7326:     fclose(ficres);
 7327: 
 7328: 
 7329:     /* Other results (useful)*/
 7330: 
 7331: 
 7332:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 7333:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
 7334:     prlim=matrix(1,nlstate,1,nlstate);
 7335:     prevalence_limit(p, prlim,  ageminpar, agemaxpar);
 7336:     fclose(ficrespl);
 7337: 
 7338: #ifdef FREEEXIT2
 7339: #include "freeexit2.h"
 7340: #endif
 7341: 
 7342:     /*------------- h Pij x at various ages ------------*/
 7343:     /*#include "hpijx.h"*/
 7344:     hPijx(p, bage, fage);
 7345:     fclose(ficrespij);
 7346: 
 7347:   /*-------------- Variance of one-step probabilities---*/
 7348:     k=1;
 7349:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
 7350: 
 7351: 
 7352:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 7353:     for(i=1;i<=AGESUP;i++)
 7354:       for(j=1;j<=NCOVMAX;j++)
 7355: 	for(k=1;k<=NCOVMAX;k++)
 7356: 	  probs[i][j][k]=0.;
 7357: 
 7358:     /*---------- Forecasting ------------------*/
 7359:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
 7360:     if(prevfcast==1){
 7361:       /*    if(stepm ==1){*/
 7362:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
 7363:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
 7364:       /*      }  */
 7365:       /*      else{ */
 7366:       /*        erreur=108; */
 7367:       /*        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); */
 7368:       /*        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); */
 7369:       /*      } */
 7370:     }
 7371:  
 7372:     /* ------ Other prevalence ratios------------ */
 7373: 
 7374:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
 7375: 
 7376:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 7377:     /*  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",\
 7378: 	ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
 7379:     */
 7380: 
 7381:     if (mobilav!=0) {
 7382:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 7383:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 7384: 	fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 7385: 	printf(" Error in movingaverage mobilav=%d\n",mobilav);
 7386:       }
 7387:     }
 7388: 
 7389: 
 7390:     /*---------- Health expectancies, no variances ------------*/
 7391: 
 7392:     strcpy(filerese,"e");
 7393:     strcat(filerese,fileres);
 7394:     if((ficreseij=fopen(filerese,"w"))==NULL) {
 7395:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 7396:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 7397:     }
 7398:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
 7399:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
 7400:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 7401:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 7402:           
 7403:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 7404: 	fprintf(ficreseij,"\n#****** ");
 7405: 	for(j=1;j<=cptcoveff;j++) {
 7406: 	  fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7407: 	}
 7408: 	fprintf(ficreseij,"******\n");
 7409: 
 7410: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 7411: 	oldm=oldms;savm=savms;
 7412: 	evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
 7413:       
 7414: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 7415:       /*}*/
 7416:     }
 7417:     fclose(ficreseij);
 7418: 
 7419: 
 7420:     /*---------- Health expectancies and variances ------------*/
 7421: 
 7422: 
 7423:     strcpy(filerest,"t");
 7424:     strcat(filerest,fileres);
 7425:     if((ficrest=fopen(filerest,"w"))==NULL) {
 7426:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
 7427:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
 7428:     }
 7429:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
 7430:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
 7431: 
 7432: 
 7433:     strcpy(fileresstde,"stde");
 7434:     strcat(fileresstde,fileres);
 7435:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
 7436:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 7437:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 7438:     }
 7439:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 7440:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 7441: 
 7442:     strcpy(filerescve,"cve");
 7443:     strcat(filerescve,fileres);
 7444:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
 7445:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 7446:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 7447:     }
 7448:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 7449:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 7450: 
 7451:     strcpy(fileresv,"v");
 7452:     strcat(fileresv,fileres);
 7453:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
 7454:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
 7455:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
 7456:     }
 7457:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 7458:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 7459: 
 7460:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 7461:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 7462:           
 7463:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 7464:     	fprintf(ficrest,"\n#****** ");
 7465: 	for(j=1;j<=cptcoveff;j++) 
 7466: 	  fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7467: 	fprintf(ficrest,"******\n");
 7468: 
 7469: 	fprintf(ficresstdeij,"\n#****** ");
 7470: 	fprintf(ficrescveij,"\n#****** ");
 7471: 	for(j=1;j<=cptcoveff;j++) {
 7472: 	  fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7473: 	  fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7474: 	}
 7475: 	fprintf(ficresstdeij,"******\n");
 7476: 	fprintf(ficrescveij,"******\n");
 7477: 
 7478: 	fprintf(ficresvij,"\n#****** ");
 7479: 	for(j=1;j<=cptcoveff;j++) 
 7480: 	  fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7481: 	fprintf(ficresvij,"******\n");
 7482: 
 7483: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 7484: 	oldm=oldms;savm=savms;
 7485: 	cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
 7486: 	/*
 7487: 	 */
 7488: 	/* goto endfree; */
 7489:  
 7490: 	vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 7491: 	pstamp(ficrest);
 7492: 
 7493: 
 7494: 	for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 7495: 	  oldm=oldms;savm=savms; /* Segmentation fault */
 7496: 	  cptcod= 0; /* To be deleted */
 7497: 	  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 */
 7498: 	  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 ");
 7499: 	  if(vpopbased==1)
 7500: 	    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);
 7501: 	  else
 7502: 	    fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
 7503: 	  fprintf(ficrest,"# Age e.. (std) ");
 7504: 	  for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
 7505: 	  fprintf(ficrest,"\n");
 7506: 
 7507: 	  epj=vector(1,nlstate+1);
 7508: 	  for(age=bage; age <=fage ;age++){
 7509: 	    prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
 7510: 	    if (vpopbased==1) {
 7511: 	      if(mobilav ==0){
 7512: 		for(i=1; i<=nlstate;i++)
 7513: 		  prlim[i][i]=probs[(int)age][i][k];
 7514: 	      }else{ /* mobilav */ 
 7515: 		for(i=1; i<=nlstate;i++)
 7516: 		  prlim[i][i]=mobaverage[(int)age][i][k];
 7517: 	      }
 7518: 	    }
 7519: 	
 7520: 	    fprintf(ficrest," %4.0f",age);
 7521: 	    for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
 7522: 	      for(i=1, epj[j]=0.;i <=nlstate;i++) {
 7523: 		epj[j] += prlim[i][i]*eij[i][j][(int)age];
 7524: 		/*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
 7525: 	      }
 7526: 	      epj[nlstate+1] +=epj[j];
 7527: 	    }
 7528: 
 7529: 	    for(i=1, vepp=0.;i <=nlstate;i++)
 7530: 	      for(j=1;j <=nlstate;j++)
 7531: 		vepp += vareij[i][j][(int)age];
 7532: 	    fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
 7533: 	    for(j=1;j <=nlstate;j++){
 7534: 	      fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
 7535: 	    }
 7536: 	    fprintf(ficrest,"\n");
 7537: 	  }
 7538: 	}
 7539: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 7540: 	free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 7541: 	free_vector(epj,1,nlstate+1);
 7542:       /*}*/
 7543:     }
 7544:     free_vector(weight,1,n);
 7545:     free_imatrix(Tvard,1,NCOVMAX,1,2);
 7546:     free_imatrix(s,1,maxwav+1,1,n);
 7547:     free_matrix(anint,1,maxwav,1,n); 
 7548:     free_matrix(mint,1,maxwav,1,n);
 7549:     free_ivector(cod,1,n);
 7550:     free_ivector(tab,1,NCOVMAX);
 7551:     fclose(ficresstdeij);
 7552:     fclose(ficrescveij);
 7553:     fclose(ficresvij);
 7554:     fclose(ficrest);
 7555:     fclose(ficpar);
 7556:   
 7557:     /*------- Variance of period (stable) prevalence------*/   
 7558: 
 7559:     strcpy(fileresvpl,"vpl");
 7560:     strcat(fileresvpl,fileres);
 7561:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
 7562:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
 7563:       exit(0);
 7564:     }
 7565:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
 7566: 
 7567:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 7568:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 7569:           
 7570:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 7571:     	fprintf(ficresvpl,"\n#****** ");
 7572: 	for(j=1;j<=cptcoveff;j++) 
 7573: 	  fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7574: 	fprintf(ficresvpl,"******\n");
 7575:       
 7576: 	varpl=matrix(1,nlstate,(int) bage, (int) fage);
 7577: 	oldm=oldms;savm=savms;
 7578: 	varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
 7579: 	free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
 7580:       /*}*/
 7581:     }
 7582: 
 7583:     fclose(ficresvpl);
 7584: 
 7585:     /*---------- End : free ----------------*/
 7586:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 7587:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 7588:   }  /* mle==-3 arrives here for freeing */
 7589:  /* endfree:*/
 7590:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
 7591:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
 7592:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
 7593:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
 7594:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
 7595:     free_matrix(covar,0,NCOVMAX,1,n);
 7596:     free_matrix(matcov,1,npar,1,npar);
 7597:     /*free_vector(delti,1,npar);*/
 7598:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 7599:     free_matrix(agev,1,maxwav,1,imx);
 7600:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
 7601: 
 7602:     free_ivector(ncodemax,1,NCOVMAX);
 7603:     free_ivector(Tvar,1,NCOVMAX);
 7604:     free_ivector(Tprod,1,NCOVMAX);
 7605:     free_ivector(Tvaraff,1,NCOVMAX);
 7606:     free_ivector(Tage,1,NCOVMAX);
 7607: 
 7608:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
 7609:     free_imatrix(codtab,1,100,1,10);
 7610:   fflush(fichtm);
 7611:   fflush(ficgp);
 7612:   
 7613: 
 7614:   if((nberr >0) || (nbwarn>0)){
 7615:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
 7616:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
 7617:   }else{
 7618:     printf("End of Imach\n");
 7619:     fprintf(ficlog,"End of Imach\n");
 7620:   }
 7621:   printf("See log file on %s\n",filelog);
 7622:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
 7623:   /*(void) gettimeofday(&end_time,&tzp);*/
 7624:   rend_time = time(NULL);  
 7625:   end_time = *localtime(&rend_time);
 7626:   /* tml = *localtime(&end_time.tm_sec); */
 7627:   strcpy(strtend,asctime(&end_time));
 7628:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
 7629:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
 7630:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 7631: 
 7632:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 7633:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 7634:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 7635:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
 7636: /*   if(fileappend(fichtm,optionfilehtm)){ */
 7637:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 7638:   fclose(fichtm);
 7639:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 7640:   fclose(fichtmcov);
 7641:   fclose(ficgp);
 7642:   fclose(ficlog);
 7643:   /*------ End -----------*/
 7644: 
 7645: 
 7646:    printf("Before Current directory %s!\n",pathcd);
 7647: #ifdef WIN32
 7648:    if (_chdir(pathcd) != 0)
 7649: 	   printf("Can't move to directory %s!\n",path);
 7650:    if(_getcwd(pathcd,MAXLINE) > 0)
 7651: #else
 7652:    if(chdir(pathcd) != 0)
 7653: 	   printf("Can't move to directory %s!\n", path);
 7654:    if (getcwd(pathcd, MAXLINE) > 0)
 7655: #endif 
 7656:     printf("Current directory %s!\n",pathcd);
 7657:   /*strcat(plotcmd,CHARSEPARATOR);*/
 7658:   sprintf(plotcmd,"gnuplot");
 7659: #ifdef _WIN32
 7660:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
 7661: #endif
 7662:   if(!stat(plotcmd,&info)){
 7663:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 7664:     if(!stat(getenv("GNUPLOTBIN"),&info)){
 7665:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
 7666:     }else
 7667:       strcpy(pplotcmd,plotcmd);
 7668: #ifdef __unix
 7669:     strcpy(plotcmd,GNUPLOTPROGRAM);
 7670:     if(!stat(plotcmd,&info)){
 7671:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 7672:     }else
 7673:       strcpy(pplotcmd,plotcmd);
 7674: #endif
 7675:   }else
 7676:     strcpy(pplotcmd,plotcmd);
 7677:   
 7678:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
 7679:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
 7680: 
 7681:   if((outcmd=system(plotcmd)) != 0){
 7682:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
 7683:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
 7684:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
 7685:     if((outcmd=system(plotcmd)) != 0)
 7686:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
 7687:   }
 7688:   printf(" Successful, please wait...");
 7689:   while (z[0] != 'q') {
 7690:     /* chdir(path); */
 7691:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
 7692:     scanf("%s",z);
 7693: /*     if (z[0] == 'c') system("./imach"); */
 7694:     if (z[0] == 'e') {
 7695: #ifdef __APPLE__
 7696:       sprintf(pplotcmd, "open %s", optionfilehtm);
 7697: #elif __linux
 7698:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
 7699: #else
 7700:       sprintf(pplotcmd, "%s", optionfilehtm);
 7701: #endif
 7702:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
 7703:       system(pplotcmd);
 7704:     }
 7705:     else if (z[0] == 'g') system(plotcmd);
 7706:     else if (z[0] == 'q') exit(0);
 7707:   }
 7708:   end:
 7709:   while (z[0] != 'q') {
 7710:     printf("\nType  q for exiting: ");
 7711:     scanf("%s",z);
 7712:   }
 7713: }

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