Annotation of imach/src/imach-nlopt.c, revision 1.1

1.1     ! brouard     1: /* $Id: imach.c,v 1.161 2014/09/15 20:41:41 brouard Exp $
        !             2:   $State: Exp $
        !             3:   $Log: imach.c,v $
        !             4:   Revision 1.161  2014/09/15 20:41:41  brouard
        !             5:   Summary: Problem with macro SQR on Intel compiler
        !             6: 
        !             7:   Revision 1.160  2014/09/02 09:24:05  brouard
        !             8:   *** empty log message ***
        !             9: 
        !            10:   Revision 1.159  2014/09/01 10:34:10  brouard
        !            11:   Summary: WIN32
        !            12:   Author: Brouard
        !            13: 
        !            14:   Revision 1.158  2014/08/27 17:11:51  brouard
        !            15:   *** empty log message ***
        !            16: 
        !            17:   Revision 1.157  2014/08/27 16:26:55  brouard
        !            18:   Summary: Preparing windows Visual studio version
        !            19:   Author: Brouard
        !            20: 
        !            21:   In order to compile on Visual studio, time.h is now correct and time_t
        !            22:   and tm struct should be used. difftime should be used but sometimes I
        !            23:   just make the differences in raw time format (time(&now).
        !            24:   Trying to suppress #ifdef LINUX
        !            25:   Add xdg-open for __linux in order to open default browser.
        !            26: 
        !            27:   Revision 1.156  2014/08/25 20:10:10  brouard
        !            28:   *** empty log message ***
        !            29: 
        !            30:   Revision 1.155  2014/08/25 18:32:34  brouard
        !            31:   Summary: New compile, minor changes
        !            32:   Author: Brouard
        !            33: 
        !            34:   Revision 1.154  2014/06/20 17:32:08  brouard
        !            35:   Summary: Outputs now all graphs of convergence to period prevalence
        !            36: 
        !            37:   Revision 1.153  2014/06/20 16:45:46  brouard
        !            38:   Summary: If 3 live state, convergence to period prevalence on same graph
        !            39:   Author: Brouard
        !            40: 
        !            41:   Revision 1.152  2014/06/18 17:54:09  brouard
        !            42:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
        !            43: 
        !            44:   Revision 1.151  2014/06/18 16:43:30  brouard
        !            45:   *** empty log message ***
        !            46: 
        !            47:   Revision 1.150  2014/06/18 16:42:35  brouard
        !            48:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
        !            49:   Author: brouard
        !            50: 
        !            51:   Revision 1.149  2014/06/18 15:51:14  brouard
        !            52:   Summary: Some fixes in parameter files errors
        !            53:   Author: Nicolas Brouard
        !            54: 
        !            55:   Revision 1.148  2014/06/17 17:38:48  brouard
        !            56:   Summary: Nothing new
        !            57:   Author: Brouard
        !            58: 
        !            59:   Just a new packaging for OS/X version 0.98nS
        !            60: 
        !            61:   Revision 1.147  2014/06/16 10:33:11  brouard
        !            62:   *** empty log message ***
        !            63: 
        !            64:   Revision 1.146  2014/06/16 10:20:28  brouard
        !            65:   Summary: Merge
        !            66:   Author: Brouard
        !            67: 
        !            68:   Merge, before building revised version.
        !            69: 
        !            70:   Revision 1.145  2014/06/10 21:23:15  brouard
        !            71:   Summary: Debugging with valgrind
        !            72:   Author: Nicolas Brouard
        !            73: 
        !            74:   Lot of changes in order to output the results with some covariates
        !            75:   After the Edimburgh REVES conference 2014, it seems mandatory to
        !            76:   improve the code.
        !            77:   No more memory valgrind error but a lot has to be done in order to
        !            78:   continue the work of splitting the code into subroutines.
        !            79:   Also, decodemodel has been improved. Tricode is still not
        !            80:   optimal. nbcode should be improved. Documentation has been added in
        !            81:   the source code.
        !            82: 
        !            83:   Revision 1.143  2014/01/26 09:45:38  brouard
        !            84:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
        !            85: 
        !            86:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
        !            87:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
        !            88: 
        !            89:   Revision 1.142  2014/01/26 03:57:36  brouard
        !            90:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
        !            91: 
        !            92:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
        !            93: 
        !            94:   Revision 1.141  2014/01/26 02:42:01  brouard
        !            95:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
        !            96: 
        !            97:   Revision 1.140  2011/09/02 10:37:54  brouard
        !            98:   Summary: times.h is ok with mingw32 now.
        !            99: 
        !           100:   Revision 1.139  2010/06/14 07:50:17  brouard
        !           101:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
        !           102:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
        !           103: 
        !           104:   Revision 1.138  2010/04/30 18:19:40  brouard
        !           105:   *** empty log message ***
        !           106: 
        !           107:   Revision 1.137  2010/04/29 18:11:38  brouard
        !           108:   (Module): Checking covariates for more complex models
        !           109:   than V1+V2. A lot of change to be done. Unstable.
        !           110: 
        !           111:   Revision 1.136  2010/04/26 20:30:53  brouard
        !           112:   (Module): merging some libgsl code. Fixing computation
        !           113:   of likelione (using inter/intrapolation if mle = 0) in order to
        !           114:   get same likelihood as if mle=1.
        !           115:   Some cleaning of code and comments added.
        !           116: 
        !           117:   Revision 1.135  2009/10/29 15:33:14  brouard
        !           118:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
        !           119: 
        !           120:   Revision 1.134  2009/10/29 13:18:53  brouard
        !           121:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
        !           122: 
        !           123:   Revision 1.133  2009/07/06 10:21:25  brouard
        !           124:   just nforces
        !           125: 
        !           126:   Revision 1.132  2009/07/06 08:22:05  brouard
        !           127:   Many tings
        !           128: 
        !           129:   Revision 1.131  2009/06/20 16:22:47  brouard
        !           130:   Some dimensions resccaled
        !           131: 
        !           132:   Revision 1.130  2009/05/26 06:44:34  brouard
        !           133:   (Module): Max Covariate is now set to 20 instead of 8. A
        !           134:   lot of cleaning with variables initialized to 0. Trying to make
        !           135:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
        !           136: 
        !           137:   Revision 1.129  2007/08/31 13:49:27  lievre
        !           138:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
        !           139: 
        !           140:   Revision 1.128  2006/06/30 13:02:05  brouard
        !           141:   (Module): Clarifications on computing e.j
        !           142: 
        !           143:   Revision 1.127  2006/04/28 18:11:50  brouard
        !           144:   (Module): Yes the sum of survivors was wrong since
        !           145:   imach-114 because nhstepm was no more computed in the age
        !           146:   loop. Now we define nhstepma in the age loop.
        !           147:   (Module): In order to speed up (in case of numerous covariates) we
        !           148:   compute health expectancies (without variances) in a first step
        !           149:   and then all the health expectancies with variances or standard
        !           150:   deviation (needs data from the Hessian matrices) which slows the
        !           151:   computation.
        !           152:   In the future we should be able to stop the program is only health
        !           153:   expectancies and graph are needed without standard deviations.
        !           154: 
        !           155:   Revision 1.126  2006/04/28 17:23:28  brouard
        !           156:   (Module): Yes the sum of survivors was wrong since
        !           157:   imach-114 because nhstepm was no more computed in the age
        !           158:   loop. Now we define nhstepma in the age loop.
        !           159:   Version 0.98h
        !           160: 
        !           161:   Revision 1.125  2006/04/04 15:20:31  lievre
        !           162:   Errors in calculation of health expectancies. Age was not initialized.
        !           163:   Forecasting file added.
        !           164: 
        !           165:   Revision 1.124  2006/03/22 17:13:53  lievre
        !           166:   Parameters are printed with %lf instead of %f (more numbers after the comma).
        !           167:   The log-likelihood is printed in the log file
        !           168: 
        !           169:   Revision 1.123  2006/03/20 10:52:43  brouard
        !           170:   * imach.c (Module): <title> changed, corresponds to .htm file
        !           171:   name. <head> headers where missing.
        !           172: 
        !           173:   * imach.c (Module): Weights can have a decimal point as for
        !           174:   English (a comma might work with a correct LC_NUMERIC environment,
        !           175:   otherwise the weight is truncated).
        !           176:   Modification of warning when the covariates values are not 0 or
        !           177:   1.
        !           178:   Version 0.98g
        !           179: 
        !           180:   Revision 1.122  2006/03/20 09:45:41  brouard
        !           181:   (Module): Weights can have a decimal point as for
        !           182:   English (a comma might work with a correct LC_NUMERIC environment,
        !           183:   otherwise the weight is truncated).
        !           184:   Modification of warning when the covariates values are not 0 or
        !           185:   1.
        !           186:   Version 0.98g
        !           187: 
        !           188:   Revision 1.121  2006/03/16 17:45:01  lievre
        !           189:   * imach.c (Module): Comments concerning covariates added
        !           190: 
        !           191:   * imach.c (Module): refinements in the computation of lli if
        !           192:   status=-2 in order to have more reliable computation if stepm is
        !           193:   not 1 month. Version 0.98f
        !           194: 
        !           195:   Revision 1.120  2006/03/16 15:10:38  lievre
        !           196:   (Module): refinements in the computation of lli if
        !           197:   status=-2 in order to have more reliable computation if stepm is
        !           198:   not 1 month. Version 0.98f
        !           199: 
        !           200:   Revision 1.119  2006/03/15 17:42:26  brouard
        !           201:   (Module): Bug if status = -2, the loglikelihood was
        !           202:   computed as likelihood omitting the logarithm. Version O.98e
        !           203: 
        !           204:   Revision 1.118  2006/03/14 18:20:07  brouard
        !           205:   (Module): varevsij Comments added explaining the second
        !           206:   table of variances if popbased=1 .
        !           207:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
        !           208:   (Module): Function pstamp added
        !           209:   (Module): Version 0.98d
        !           210: 
        !           211:   Revision 1.117  2006/03/14 17:16:22  brouard
        !           212:   (Module): varevsij Comments added explaining the second
        !           213:   table of variances if popbased=1 .
        !           214:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
        !           215:   (Module): Function pstamp added
        !           216:   (Module): Version 0.98d
        !           217: 
        !           218:   Revision 1.116  2006/03/06 10:29:27  brouard
        !           219:   (Module): Variance-covariance wrong links and
        !           220:   varian-covariance of ej. is needed (Saito).
        !           221: 
        !           222:   Revision 1.115  2006/02/27 12:17:45  brouard
        !           223:   (Module): One freematrix added in mlikeli! 0.98c
        !           224: 
        !           225:   Revision 1.114  2006/02/26 12:57:58  brouard
        !           226:   (Module): Some improvements in processing parameter
        !           227:   filename with strsep.
        !           228: 
        !           229:   Revision 1.113  2006/02/24 14:20:24  brouard
        !           230:   (Module): Memory leaks checks with valgrind and:
        !           231:   datafile was not closed, some imatrix were not freed and on matrix
        !           232:   allocation too.
        !           233: 
        !           234:   Revision 1.112  2006/01/30 09:55:26  brouard
        !           235:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
        !           236: 
        !           237:   Revision 1.111  2006/01/25 20:38:18  brouard
        !           238:   (Module): Lots of cleaning and bugs added (Gompertz)
        !           239:   (Module): Comments can be added in data file. Missing date values
        !           240:   can be a simple dot '.'.
        !           241: 
        !           242:   Revision 1.110  2006/01/25 00:51:50  brouard
        !           243:   (Module): Lots of cleaning and bugs added (Gompertz)
        !           244: 
        !           245:   Revision 1.109  2006/01/24 19:37:15  brouard
        !           246:   (Module): Comments (lines starting with a #) are allowed in data.
        !           247: 
        !           248:   Revision 1.108  2006/01/19 18:05:42  lievre
        !           249:   Gnuplot problem appeared...
        !           250:   To be fixed
        !           251: 
        !           252:   Revision 1.107  2006/01/19 16:20:37  brouard
        !           253:   Test existence of gnuplot in imach path
        !           254: 
        !           255:   Revision 1.106  2006/01/19 13:24:36  brouard
        !           256:   Some cleaning and links added in html output
        !           257: 
        !           258:   Revision 1.105  2006/01/05 20:23:19  lievre
        !           259:   *** empty log message ***
        !           260: 
        !           261:   Revision 1.104  2005/09/30 16:11:43  lievre
        !           262:   (Module): sump fixed, loop imx fixed, and simplifications.
        !           263:   (Module): If the status is missing at the last wave but we know
        !           264:   that the person is alive, then we can code his/her status as -2
        !           265:   (instead of missing=-1 in earlier versions) and his/her
        !           266:   contributions to the likelihood is 1 - Prob of dying from last
        !           267:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
        !           268:   the healthy state at last known wave). Version is 0.98
        !           269: 
        !           270:   Revision 1.103  2005/09/30 15:54:49  lievre
        !           271:   (Module): sump fixed, loop imx fixed, and simplifications.
        !           272: 
        !           273:   Revision 1.102  2004/09/15 17:31:30  brouard
        !           274:   Add the possibility to read data file including tab characters.
        !           275: 
        !           276:   Revision 1.101  2004/09/15 10:38:38  brouard
        !           277:   Fix on curr_time
        !           278: 
        !           279:   Revision 1.100  2004/07/12 18:29:06  brouard
        !           280:   Add version for Mac OS X. Just define UNIX in Makefile
        !           281: 
        !           282:   Revision 1.99  2004/06/05 08:57:40  brouard
        !           283:   *** empty log message ***
        !           284: 
        !           285:   Revision 1.98  2004/05/16 15:05:56  brouard
        !           286:   New version 0.97 . First attempt to estimate force of mortality
        !           287:   directly from the data i.e. without the need of knowing the health
        !           288:   state at each age, but using a Gompertz model: log u =a + b*age .
        !           289:   This is the basic analysis of mortality and should be done before any
        !           290:   other analysis, in order to test if the mortality estimated from the
        !           291:   cross-longitudinal survey is different from the mortality estimated
        !           292:   from other sources like vital statistic data.
        !           293: 
        !           294:   The same imach parameter file can be used but the option for mle should be -3.
        !           295: 
        !           296:   Agnès, who wrote this part of the code, tried to keep most of the
        !           297:   former routines in order to include the new code within the former code.
        !           298: 
        !           299:   The output is very simple: only an estimate of the intercept and of
        !           300:   the slope with 95% confident intervals.
        !           301: 
        !           302:   Current limitations:
        !           303:   A) Even if you enter covariates, i.e. with the
        !           304:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
        !           305:   B) There is no computation of Life Expectancy nor Life Table.
        !           306: 
        !           307:   Revision 1.97  2004/02/20 13:25:42  lievre
        !           308:   Version 0.96d. Population forecasting command line is (temporarily)
        !           309:   suppressed.
        !           310: 
        !           311:   Revision 1.96  2003/07/15 15:38:55  brouard
        !           312:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
        !           313:   rewritten within the same printf. Workaround: many printfs.
        !           314: 
        !           315:   Revision 1.95  2003/07/08 07:54:34  brouard
        !           316:   * imach.c (Repository):
        !           317:   (Repository): Using imachwizard code to output a more meaningful covariance
        !           318:   matrix (cov(a12,c31) instead of numbers.
        !           319: 
        !           320:   Revision 1.94  2003/06/27 13:00:02  brouard
        !           321:   Just cleaning
        !           322: 
        !           323:   Revision 1.93  2003/06/25 16:33:55  brouard
        !           324:   (Module): On windows (cygwin) function asctime_r doesn't
        !           325:   exist so I changed back to asctime which exists.
        !           326:   (Module): Version 0.96b
        !           327: 
        !           328:   Revision 1.92  2003/06/25 16:30:45  brouard
        !           329:   (Module): On windows (cygwin) function asctime_r doesn't
        !           330:   exist so I changed back to asctime which exists.
        !           331: 
        !           332:   Revision 1.91  2003/06/25 15:30:29  brouard
        !           333:   * imach.c (Repository): Duplicated warning errors corrected.
        !           334:   (Repository): Elapsed time after each iteration is now output. It
        !           335:   helps to forecast when convergence will be reached. Elapsed time
        !           336:   is stamped in powell.  We created a new html file for the graphs
        !           337:   concerning matrix of covariance. It has extension -cov.htm.
        !           338: 
        !           339:   Revision 1.90  2003/06/24 12:34:15  brouard
        !           340:   (Module): Some bugs corrected for windows. Also, when
        !           341:   mle=-1 a template is output in file "or"mypar.txt with the design
        !           342:   of the covariance matrix to be input.
        !           343: 
        !           344:   Revision 1.89  2003/06/24 12:30:52  brouard
        !           345:   (Module): Some bugs corrected for windows. Also, when
        !           346:   mle=-1 a template is output in file "or"mypar.txt with the design
        !           347:   of the covariance matrix to be input.
        !           348: 
        !           349:   Revision 1.88  2003/06/23 17:54:56  brouard
        !           350:   * 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.
        !           351: 
        !           352:   Revision 1.87  2003/06/18 12:26:01  brouard
        !           353:   Version 0.96
        !           354: 
        !           355:   Revision 1.86  2003/06/17 20:04:08  brouard
        !           356:   (Module): Change position of html and gnuplot routines and added
        !           357:   routine fileappend.
        !           358: 
        !           359:   Revision 1.85  2003/06/17 13:12:43  brouard
        !           360:   * imach.c (Repository): Check when date of death was earlier that
        !           361:   current date of interview. It may happen when the death was just
        !           362:   prior to the death. In this case, dh was negative and likelihood
        !           363:   was wrong (infinity). We still send an "Error" but patch by
        !           364:   assuming that the date of death was just one stepm after the
        !           365:   interview.
        !           366:   (Repository): Because some people have very long ID (first column)
        !           367:   we changed int to long in num[] and we added a new lvector for
        !           368:   memory allocation. But we also truncated to 8 characters (left
        !           369:   truncation)
        !           370:   (Repository): No more line truncation errors.
        !           371: 
        !           372:   Revision 1.84  2003/06/13 21:44:43  brouard
        !           373:   * imach.c (Repository): Replace "freqsummary" at a correct
        !           374:   place. It differs from routine "prevalence" which may be called
        !           375:   many times. Probs is memory consuming and must be used with
        !           376:   parcimony.
        !           377:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
        !           378: 
        !           379:   Revision 1.83  2003/06/10 13:39:11  lievre
        !           380:   *** empty log message ***
        !           381: 
        !           382:   Revision 1.82  2003/06/05 15:57:20  brouard
        !           383:   Add log in  imach.c and  fullversion number is now printed.
        !           384: 
        !           385: */
        !           386: /*
        !           387:    Interpolated Markov Chain
        !           388: 
        !           389:   Short summary of the programme:
        !           390:   
        !           391:   This program computes Healthy Life Expectancies from
        !           392:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
        !           393:   first survey ("cross") where individuals from different ages are
        !           394:   interviewed on their health status or degree of disability (in the
        !           395:   case of a health survey which is our main interest) -2- at least a
        !           396:   second wave of interviews ("longitudinal") which measure each change
        !           397:   (if any) in individual health status.  Health expectancies are
        !           398:   computed from the time spent in each health state according to a
        !           399:   model. More health states you consider, more time is necessary to reach the
        !           400:   Maximum Likelihood of the parameters involved in the model.  The
        !           401:   simplest model is the multinomial logistic model where pij is the
        !           402:   probability to be observed in state j at the second wave
        !           403:   conditional to be observed in state i at the first wave. Therefore
        !           404:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
        !           405:   'age' is age and 'sex' is a covariate. If you want to have a more
        !           406:   complex model than "constant and age", you should modify the program
        !           407:   where the markup *Covariates have to be included here again* invites
        !           408:   you to do it.  More covariates you add, slower the
        !           409:   convergence.
        !           410: 
        !           411:   The advantage of this computer programme, compared to a simple
        !           412:   multinomial logistic model, is clear when the delay between waves is not
        !           413:   identical for each individual. Also, if a individual missed an
        !           414:   intermediate interview, the information is lost, but taken into
        !           415:   account using an interpolation or extrapolation.  
        !           416: 
        !           417:   hPijx is the probability to be observed in state i at age x+h
        !           418:   conditional to the observed state i at age x. The delay 'h' can be
        !           419:   split into an exact number (nh*stepm) of unobserved intermediate
        !           420:   states. This elementary transition (by month, quarter,
        !           421:   semester or year) is modelled as a multinomial logistic.  The hPx
        !           422:   matrix is simply the matrix product of nh*stepm elementary matrices
        !           423:   and the contribution of each individual to the likelihood is simply
        !           424:   hPijx.
        !           425: 
        !           426:   Also this programme outputs the covariance matrix of the parameters but also
        !           427:   of the life expectancies. It also computes the period (stable) prevalence. 
        !           428:   
        !           429:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
        !           430:            Institut national d'études démographiques, Paris.
        !           431:   This software have been partly granted by Euro-REVES, a concerted action
        !           432:   from the European Union.
        !           433:   It is copyrighted identically to a GNU software product, ie programme and
        !           434:   software can be distributed freely for non commercial use. Latest version
        !           435:   can be accessed at http://euroreves.ined.fr/imach .
        !           436: 
        !           437:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
        !           438:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
        !           439:   
        !           440:   **********************************************************************/
        !           441: /*
        !           442:   main
        !           443:   read parameterfile
        !           444:   read datafile
        !           445:   concatwav
        !           446:   freqsummary
        !           447:   if (mle >= 1)
        !           448:     mlikeli
        !           449:   print results files
        !           450:   if mle==1 
        !           451:      computes hessian
        !           452:   read end of parameter file: agemin, agemax, bage, fage, estepm
        !           453:       begin-prev-date,...
        !           454:   open gnuplot file
        !           455:   open html file
        !           456:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
        !           457:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
        !           458:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
        !           459:     freexexit2 possible for memory heap.
        !           460: 
        !           461:   h Pij x                         | pij_nom  ficrestpij
        !           462:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
        !           463:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
        !           464:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
        !           465: 
        !           466:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
        !           467:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
        !           468:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
        !           469:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
        !           470:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
        !           471: 
        !           472:   forecasting if prevfcast==1 prevforecast call prevalence()
        !           473:   health expectancies
        !           474:   Variance-covariance of DFLE
        !           475:   prevalence()
        !           476:    movingaverage()
        !           477:   varevsij() 
        !           478:   if popbased==1 varevsij(,popbased)
        !           479:   total life expectancies
        !           480:   Variance of period (stable) prevalence
        !           481:  end
        !           482: */
        !           483: 
        !           484: 
        !           485: 
        !           486:  
        !           487: #include <math.h>
        !           488: #include <stdio.h>
        !           489: #include <stdlib.h>
        !           490: #include <string.h>
        !           491: 
        !           492: #ifdef _WIN32
        !           493: #include <io.h>
        !           494: #else
        !           495: #include <unistd.h>
        !           496: #endif
        !           497: 
        !           498: #include <limits.h>
        !           499: #include <sys/types.h>
        !           500: #include <sys/stat.h>
        !           501: #include <errno.h>
        !           502: /* extern int errno; */
        !           503: 
        !           504: /* #ifdef LINUX */
        !           505: /* #include <time.h> */
        !           506: /* #include "timeval.h" */
        !           507: /* #else */
        !           508: /* #include <sys/time.h> */
        !           509: /* #endif */
        !           510: 
        !           511: #include <time.h>
        !           512: 
        !           513: #ifdef GSL
        !           514: #include <gsl/gsl_errno.h>
        !           515: #include <gsl/gsl_multimin.h>
        !           516: #endif
        !           517: 
        !           518: #ifdef NLOPT
        !           519: #include <nlopt.h>
        !           520: #endif
        !           521: 
        !           522: /* #include <libintl.h> */
        !           523: /* #define _(String) gettext (String) */
        !           524: 
        !           525: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
        !           526: 
        !           527: #define GNUPLOTPROGRAM "gnuplot"
        !           528: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
        !           529: #define FILENAMELENGTH 132
        !           530: 
        !           531: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
        !           532: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
        !           533: 
        !           534: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
        !           535: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
        !           536: 
        !           537: #define NINTERVMAX 8
        !           538: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
        !           539: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
        !           540: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
        !           541: #define codtabm(h,k)  1 & (h-1) >> (k-1) ;
        !           542: #define MAXN 20000
        !           543: #define YEARM 12. /**< Number of months per year */
        !           544: #define AGESUP 130
        !           545: #define AGEBASE 40
        !           546: #define AGEGOMP 10. /**< Minimal age for Gompertz adjustment */
        !           547: #ifdef _WIN32
        !           548: #define DIRSEPARATOR '\\'
        !           549: #define CHARSEPARATOR "\\"
        !           550: #define ODIRSEPARATOR '/'
        !           551: #else
        !           552: #define DIRSEPARATOR '/'
        !           553: #define CHARSEPARATOR "/"
        !           554: #define ODIRSEPARATOR '\\'
        !           555: #endif
        !           556: 
        !           557: /* $Id: imach.c,v 1.161 2014/09/15 20:41:41 brouard Exp $ */
        !           558: /* $State: Exp $ */
        !           559: 
        !           560: char version[]="Imach version 0.98nX, August 2014,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121)";
        !           561: char fullversion[]="$Revision: 1.161 $ $Date: 2014/09/15 20:41:41 $"; 
        !           562: char strstart[80];
        !           563: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
        !           564: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
        !           565: int nvar=0, nforce=0; /* Number of variables, number of forces */
        !           566: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
        !           567: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
        !           568: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
        !           569: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
        !           570: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
        !           571: int cptcovprodnoage=0; /**< Number of covariate products without age */   
        !           572: int cptcoveff=0; /* Total number of covariates to vary for printing results */
        !           573: int cptcov=0; /* Working variable */
        !           574: int npar=NPARMAX;
        !           575: int nlstate=2; /* Number of live states */
        !           576: int ndeath=1; /* Number of dead states */
        !           577: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
        !           578: int popbased=0;
        !           579: 
        !           580: int *wav; /* Number of waves for this individuual 0 is possible */
        !           581: int maxwav=0; /* Maxim number of waves */
        !           582: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
        !           583: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
        !           584: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
        !           585:                   to the likelihood and the sum of weights (done by funcone)*/
        !           586: int mle=1, weightopt=0;
        !           587: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
        !           588: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
        !           589: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
        !           590:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
        !           591: int countcallfunc=0;  /* Count the number of calls to func */
        !           592: double jmean=1; /* Mean space between 2 waves */
        !           593: double **matprod2(); /* test */
        !           594: double **oldm, **newm, **savm; /* Working pointers to matrices */
        !           595: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
        !           596: /*FILE *fic ; */ /* Used in readdata only */
        !           597: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
        !           598: FILE *ficlog, *ficrespow;
        !           599: int globpr=0; /* Global variable for printing or not */
        !           600: double fretone; /* Only one call to likelihood */
        !           601: long ipmx=0; /* Number of contributions */
        !           602: double sw; /* Sum of weights */
        !           603: char filerespow[FILENAMELENGTH];
        !           604: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
        !           605: FILE *ficresilk;
        !           606: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
        !           607: FILE *ficresprobmorprev;
        !           608: FILE *fichtm, *fichtmcov; /* Html File */
        !           609: FILE *ficreseij;
        !           610: char filerese[FILENAMELENGTH];
        !           611: FILE *ficresstdeij;
        !           612: char fileresstde[FILENAMELENGTH];
        !           613: FILE *ficrescveij;
        !           614: char filerescve[FILENAMELENGTH];
        !           615: FILE  *ficresvij;
        !           616: char fileresv[FILENAMELENGTH];
        !           617: FILE  *ficresvpl;
        !           618: char fileresvpl[FILENAMELENGTH];
        !           619: char title[MAXLINE];
        !           620: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
        !           621: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
        !           622: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
        !           623: char command[FILENAMELENGTH];
        !           624: int  outcmd=0;
        !           625: 
        !           626: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
        !           627: 
        !           628: char filelog[FILENAMELENGTH]; /* Log file */
        !           629: char filerest[FILENAMELENGTH];
        !           630: char fileregp[FILENAMELENGTH];
        !           631: char popfile[FILENAMELENGTH];
        !           632: 
        !           633: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
        !           634: 
        !           635: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
        !           636: /* struct timezone tzp; */
        !           637: /* extern int gettimeofday(); */
        !           638: struct tm tml, *gmtime(), *localtime();
        !           639: 
        !           640: extern time_t time();
        !           641: 
        !           642: struct tm start_time, end_time, curr_time, last_time, forecast_time;
        !           643: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
        !           644: struct tm tm;
        !           645: 
        !           646: char strcurr[80], strfor[80];
        !           647: 
        !           648: char *endptr;
        !           649: long lval;
        !           650: double dval;
        !           651: 
        !           652: #define NR_END 1
        !           653: #define FREE_ARG char*
        !           654: #define FTOL 1.0e-10
        !           655: 
        !           656: #define NRANSI 
        !           657: #define ITMAX 200 
        !           658: 
        !           659: #define TOL 2.0e-4 
        !           660: 
        !           661: #define CGOLD 0.3819660 
        !           662: #define ZEPS 1.0e-10 
        !           663: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
        !           664: 
        !           665: #define GOLD 1.618034 
        !           666: #define GLIMIT 100.0 
        !           667: #define TINY 1.0e-20 
        !           668: 
        !           669: static double maxarg1,maxarg2;
        !           670: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
        !           671: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
        !           672:   
        !           673: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
        !           674: #define rint(a) floor(a+0.5)
        !           675: 
        !           676: static double sqrarg;
        !           677: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
        !           678: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
        !           679: int agegomp= AGEGOMP;
        !           680: 
        !           681: int imx; 
        !           682: int stepm=1;
        !           683: /* Stepm, step in month: minimum step interpolation*/
        !           684: 
        !           685: int estepm;
        !           686: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
        !           687: 
        !           688: int m,nb;
        !           689: long *num;
        !           690: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
        !           691: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
        !           692: double **pmmij, ***probs;
        !           693: double *ageexmed,*agecens;
        !           694: double dateintmean=0;
        !           695: 
        !           696: double *weight;
        !           697: int **s; /* Status */
        !           698: double *agedc;
        !           699: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
        !           700:                  * covar=matrix(0,NCOVMAX,1,n); 
        !           701:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
        !           702: double  idx; 
        !           703: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
        !           704: int *Ndum; /** Freq of modality (tricode */
        !           705: int **codtab; /**< codtab=imatrix(1,100,1,10); */
        !           706: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
        !           707: double *lsurv, *lpop, *tpop;
        !           708: 
        !           709: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
        !           710: double ftolhess; /**< Tolerance for computing hessian */
        !           711: 
        !           712: /**************** split *************************/
        !           713: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
        !           714: {
        !           715:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
        !           716:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
        !           717:   */ 
        !           718:   char *ss;                            /* pointer */
        !           719:   int  l1, l2;                         /* length counters */
        !           720: 
        !           721:   l1 = strlen(path );                  /* length of path */
        !           722:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
        !           723:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
        !           724:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
        !           725:     strcpy( name, path );              /* we got the fullname name because no directory */
        !           726:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
        !           727:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
        !           728:     /* get current working directory */
        !           729:     /*    extern  char* getcwd ( char *buf , int len);*/
        !           730:     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
        !           731:       return( GLOCK_ERROR_GETCWD );
        !           732:     }
        !           733:     /* got dirc from getcwd*/
        !           734:     printf(" DIRC = %s \n",dirc);
        !           735:   } else {                             /* strip direcotry from path */
        !           736:     ss++;                              /* after this, the filename */
        !           737:     l2 = strlen( ss );                 /* length of filename */
        !           738:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
        !           739:     strcpy( name, ss );                /* save file name */
        !           740:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
        !           741:     dirc[l1-l2] = 0;                   /* add zero */
        !           742:     printf(" DIRC2 = %s \n",dirc);
        !           743:   }
        !           744:   /* We add a separator at the end of dirc if not exists */
        !           745:   l1 = strlen( dirc );                 /* length of directory */
        !           746:   if( dirc[l1-1] != DIRSEPARATOR ){
        !           747:     dirc[l1] =  DIRSEPARATOR;
        !           748:     dirc[l1+1] = 0; 
        !           749:     printf(" DIRC3 = %s \n",dirc);
        !           750:   }
        !           751:   ss = strrchr( name, '.' );           /* find last / */
        !           752:   if (ss >0){
        !           753:     ss++;
        !           754:     strcpy(ext,ss);                    /* save extension */
        !           755:     l1= strlen( name);
        !           756:     l2= strlen(ss)+1;
        !           757:     strncpy( finame, name, l1-l2);
        !           758:     finame[l1-l2]= 0;
        !           759:   }
        !           760: 
        !           761:   return( 0 );                         /* we're done */
        !           762: }
        !           763: 
        !           764: 
        !           765: /******************************************/
        !           766: 
        !           767: void replace_back_to_slash(char *s, char*t)
        !           768: {
        !           769:   int i;
        !           770:   int lg=0;
        !           771:   i=0;
        !           772:   lg=strlen(t);
        !           773:   for(i=0; i<= lg; i++) {
        !           774:     (s[i] = t[i]);
        !           775:     if (t[i]== '\\') s[i]='/';
        !           776:   }
        !           777: }
        !           778: 
        !           779: char *trimbb(char *out, char *in)
        !           780: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
        !           781:   char *s;
        !           782:   s=out;
        !           783:   while (*in != '\0'){
        !           784:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
        !           785:       in++;
        !           786:     }
        !           787:     *out++ = *in++;
        !           788:   }
        !           789:   *out='\0';
        !           790:   return s;
        !           791: }
        !           792: 
        !           793: char *cutl(char *blocc, char *alocc, char *in, char occ)
        !           794: {
        !           795:   /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ' 
        !           796:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
        !           797:      gives blocc="abcdef2ghi" and alocc="j".
        !           798:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
        !           799:   */
        !           800:   char *s, *t;
        !           801:   t=in;s=in;
        !           802:   while ((*in != occ) && (*in != '\0')){
        !           803:     *alocc++ = *in++;
        !           804:   }
        !           805:   if( *in == occ){
        !           806:     *(alocc)='\0';
        !           807:     s=++in;
        !           808:   }
        !           809:  
        !           810:   if (s == t) {/* occ not found */
        !           811:     *(alocc-(in-s))='\0';
        !           812:     in=s;
        !           813:   }
        !           814:   while ( *in != '\0'){
        !           815:     *blocc++ = *in++;
        !           816:   }
        !           817: 
        !           818:   *blocc='\0';
        !           819:   return t;
        !           820: }
        !           821: char *cutv(char *blocc, char *alocc, char *in, char occ)
        !           822: {
        !           823:   /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ' 
        !           824:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
        !           825:      gives blocc="abcdef2ghi" and alocc="j".
        !           826:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
        !           827:   */
        !           828:   char *s, *t;
        !           829:   t=in;s=in;
        !           830:   while (*in != '\0'){
        !           831:     while( *in == occ){
        !           832:       *blocc++ = *in++;
        !           833:       s=in;
        !           834:     }
        !           835:     *blocc++ = *in++;
        !           836:   }
        !           837:   if (s == t) /* occ not found */
        !           838:     *(blocc-(in-s))='\0';
        !           839:   else
        !           840:     *(blocc-(in-s)-1)='\0';
        !           841:   in=s;
        !           842:   while ( *in != '\0'){
        !           843:     *alocc++ = *in++;
        !           844:   }
        !           845: 
        !           846:   *alocc='\0';
        !           847:   return s;
        !           848: }
        !           849: 
        !           850: int nbocc(char *s, char occ)
        !           851: {
        !           852:   int i,j=0;
        !           853:   int lg=20;
        !           854:   i=0;
        !           855:   lg=strlen(s);
        !           856:   for(i=0; i<= lg; i++) {
        !           857:   if  (s[i] == occ ) j++;
        !           858:   }
        !           859:   return j;
        !           860: }
        !           861: 
        !           862: /* void cutv(char *u,char *v, char*t, char occ) */
        !           863: /* { */
        !           864: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
        !           865: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
        !           866: /*      gives u="abcdef2ghi" and v="j" *\/ */
        !           867: /*   int i,lg,j,p=0; */
        !           868: /*   i=0; */
        !           869: /*   lg=strlen(t); */
        !           870: /*   for(j=0; j<=lg-1; j++) { */
        !           871: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
        !           872: /*   } */
        !           873: 
        !           874: /*   for(j=0; j<p; j++) { */
        !           875: /*     (u[j] = t[j]); */
        !           876: /*   } */
        !           877: /*      u[p]='\0'; */
        !           878: 
        !           879: /*    for(j=0; j<= lg; j++) { */
        !           880: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
        !           881: /*   } */
        !           882: /* } */
        !           883: 
        !           884: #ifdef _WIN32
        !           885: char * strsep(char **pp, const char *delim)
        !           886: {
        !           887:   char *p, *q;
        !           888:          
        !           889:   if ((p = *pp) == NULL)
        !           890:     return 0;
        !           891:   if ((q = strpbrk (p, delim)) != NULL)
        !           892:   {
        !           893:     *pp = q + 1;
        !           894:     *q = '\0';
        !           895:   }
        !           896:   else
        !           897:     *pp = 0;
        !           898:   return p;
        !           899: }
        !           900: #endif
        !           901: 
        !           902: /********************** nrerror ********************/
        !           903: 
        !           904: void nrerror(char error_text[])
        !           905: {
        !           906:   fprintf(stderr,"ERREUR ...\n");
        !           907:   fprintf(stderr,"%s\n",error_text);
        !           908:   exit(EXIT_FAILURE);
        !           909: }
        !           910: /*********************** vector *******************/
        !           911: double *vector(int nl, int nh)
        !           912: {
        !           913:   double *v;
        !           914:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
        !           915:   if (!v) nrerror("allocation failure in vector");
        !           916:   return v-nl+NR_END;
        !           917: }
        !           918: 
        !           919: /************************ free vector ******************/
        !           920: void free_vector(double*v, int nl, int nh)
        !           921: {
        !           922:   free((FREE_ARG)(v+nl-NR_END));
        !           923: }
        !           924: 
        !           925: /************************ivector *******************************/
        !           926: int *ivector(long nl,long nh)
        !           927: {
        !           928:   int *v;
        !           929:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
        !           930:   if (!v) nrerror("allocation failure in ivector");
        !           931:   return v-nl+NR_END;
        !           932: }
        !           933: 
        !           934: /******************free ivector **************************/
        !           935: void free_ivector(int *v, long nl, long nh)
        !           936: {
        !           937:   free((FREE_ARG)(v+nl-NR_END));
        !           938: }
        !           939: 
        !           940: /************************lvector *******************************/
        !           941: long *lvector(long nl,long nh)
        !           942: {
        !           943:   long *v;
        !           944:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
        !           945:   if (!v) nrerror("allocation failure in ivector");
        !           946:   return v-nl+NR_END;
        !           947: }
        !           948: 
        !           949: /******************free lvector **************************/
        !           950: void free_lvector(long *v, long nl, long nh)
        !           951: {
        !           952:   free((FREE_ARG)(v+nl-NR_END));
        !           953: }
        !           954: 
        !           955: /******************* imatrix *******************************/
        !           956: int **imatrix(long nrl, long nrh, long ncl, long nch) 
        !           957:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
        !           958: { 
        !           959:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
        !           960:   int **m; 
        !           961:   
        !           962:   /* allocate pointers to rows */ 
        !           963:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
        !           964:   if (!m) nrerror("allocation failure 1 in matrix()"); 
        !           965:   m += NR_END; 
        !           966:   m -= nrl; 
        !           967:   
        !           968:   
        !           969:   /* allocate rows and set pointers to them */ 
        !           970:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
        !           971:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
        !           972:   m[nrl] += NR_END; 
        !           973:   m[nrl] -= ncl; 
        !           974:   
        !           975:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
        !           976:   
        !           977:   /* return pointer to array of pointers to rows */ 
        !           978:   return m; 
        !           979: } 
        !           980: 
        !           981: /****************** free_imatrix *************************/
        !           982: void free_imatrix(m,nrl,nrh,ncl,nch)
        !           983:       int **m;
        !           984:       long nch,ncl,nrh,nrl; 
        !           985:      /* free an int matrix allocated by imatrix() */ 
        !           986: { 
        !           987:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
        !           988:   free((FREE_ARG) (m+nrl-NR_END)); 
        !           989: } 
        !           990: 
        !           991: /******************* matrix *******************************/
        !           992: double **matrix(long nrl, long nrh, long ncl, long nch)
        !           993: {
        !           994:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
        !           995:   double **m;
        !           996: 
        !           997:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
        !           998:   if (!m) nrerror("allocation failure 1 in matrix()");
        !           999:   m += NR_END;
        !          1000:   m -= nrl;
        !          1001: 
        !          1002:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
        !          1003:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
        !          1004:   m[nrl] += NR_END;
        !          1005:   m[nrl] -= ncl;
        !          1006: 
        !          1007:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
        !          1008:   return m;
        !          1009:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
        !          1010: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
        !          1011: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
        !          1012:    */
        !          1013: }
        !          1014: 
        !          1015: /*************************free matrix ************************/
        !          1016: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
        !          1017: {
        !          1018:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
        !          1019:   free((FREE_ARG)(m+nrl-NR_END));
        !          1020: }
        !          1021: 
        !          1022: /******************* ma3x *******************************/
        !          1023: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
        !          1024: {
        !          1025:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
        !          1026:   double ***m;
        !          1027: 
        !          1028:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
        !          1029:   if (!m) nrerror("allocation failure 1 in matrix()");
        !          1030:   m += NR_END;
        !          1031:   m -= nrl;
        !          1032: 
        !          1033:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
        !          1034:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
        !          1035:   m[nrl] += NR_END;
        !          1036:   m[nrl] -= ncl;
        !          1037: 
        !          1038:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
        !          1039: 
        !          1040:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
        !          1041:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
        !          1042:   m[nrl][ncl] += NR_END;
        !          1043:   m[nrl][ncl] -= nll;
        !          1044:   for (j=ncl+1; j<=nch; j++) 
        !          1045:     m[nrl][j]=m[nrl][j-1]+nlay;
        !          1046:   
        !          1047:   for (i=nrl+1; i<=nrh; i++) {
        !          1048:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
        !          1049:     for (j=ncl+1; j<=nch; j++) 
        !          1050:       m[i][j]=m[i][j-1]+nlay;
        !          1051:   }
        !          1052:   return m; 
        !          1053:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
        !          1054:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
        !          1055:   */
        !          1056: }
        !          1057: 
        !          1058: /*************************free ma3x ************************/
        !          1059: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
        !          1060: {
        !          1061:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
        !          1062:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
        !          1063:   free((FREE_ARG)(m+nrl-NR_END));
        !          1064: }
        !          1065: 
        !          1066: /*************** function subdirf ***********/
        !          1067: char *subdirf(char fileres[])
        !          1068: {
        !          1069:   /* Caution optionfilefiname is hidden */
        !          1070:   strcpy(tmpout,optionfilefiname);
        !          1071:   strcat(tmpout,"/"); /* Add to the right */
        !          1072:   strcat(tmpout,fileres);
        !          1073:   return tmpout;
        !          1074: }
        !          1075: 
        !          1076: /*************** function subdirf2 ***********/
        !          1077: char *subdirf2(char fileres[], char *preop)
        !          1078: {
        !          1079:   
        !          1080:   /* Caution optionfilefiname is hidden */
        !          1081:   strcpy(tmpout,optionfilefiname);
        !          1082:   strcat(tmpout,"/");
        !          1083:   strcat(tmpout,preop);
        !          1084:   strcat(tmpout,fileres);
        !          1085:   return tmpout;
        !          1086: }
        !          1087: 
        !          1088: /*************** function subdirf3 ***********/
        !          1089: char *subdirf3(char fileres[], char *preop, char *preop2)
        !          1090: {
        !          1091:   
        !          1092:   /* Caution optionfilefiname is hidden */
        !          1093:   strcpy(tmpout,optionfilefiname);
        !          1094:   strcat(tmpout,"/");
        !          1095:   strcat(tmpout,preop);
        !          1096:   strcat(tmpout,preop2);
        !          1097:   strcat(tmpout,fileres);
        !          1098:   return tmpout;
        !          1099: }
        !          1100: 
        !          1101: /***************** f1dim *************************/
        !          1102: extern int ncom; 
        !          1103: extern double *pcom,*xicom;
        !          1104: extern double (*nrfunc)(double []); 
        !          1105:  
        !          1106: double f1dim(double x) 
        !          1107: { 
        !          1108:   int j; 
        !          1109:   double f;
        !          1110:   double *xt; 
        !          1111:  
        !          1112:   xt=vector(1,ncom); 
        !          1113:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
        !          1114:   f=(*nrfunc)(xt); 
        !          1115:   free_vector(xt,1,ncom); 
        !          1116:   return f; 
        !          1117: } 
        !          1118: 
        !          1119: /*****************brent *************************/
        !          1120: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
        !          1121: { 
        !          1122:   int iter; 
        !          1123:   double a,b,d,etemp;
        !          1124:   double fu=0,fv,fw,fx;
        !          1125:   double ftemp;
        !          1126:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
        !          1127:   double e=0.0; 
        !          1128:  
        !          1129:   a=(ax < cx ? ax : cx); 
        !          1130:   b=(ax > cx ? ax : cx); 
        !          1131:   x=w=v=bx; 
        !          1132:   fw=fv=fx=(*f)(x); 
        !          1133:   for (iter=1;iter<=ITMAX;iter++) { 
        !          1134:     xm=0.5*(a+b); 
        !          1135:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
        !          1136:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
        !          1137:     printf(".");fflush(stdout);
        !          1138:     fprintf(ficlog,".");fflush(ficlog);
        !          1139: #ifdef DEBUG
        !          1140:     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);
        !          1141:     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);
        !          1142:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
        !          1143: #endif
        !          1144:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
        !          1145:       *xmin=x; 
        !          1146:       return fx; 
        !          1147:     } 
        !          1148:     ftemp=fu;
        !          1149:     if (fabs(e) > tol1) { 
        !          1150:       r=(x-w)*(fx-fv); 
        !          1151:       q=(x-v)*(fx-fw); 
        !          1152:       p=(x-v)*q-(x-w)*r; 
        !          1153:       q=2.0*(q-r); 
        !          1154:       if (q > 0.0) p = -p; 
        !          1155:       q=fabs(q); 
        !          1156:       etemp=e; 
        !          1157:       e=d; 
        !          1158:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
        !          1159:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
        !          1160:       else { 
        !          1161:        d=p/q; 
        !          1162:        u=x+d; 
        !          1163:        if (u-a < tol2 || b-u < tol2) 
        !          1164:          d=SIGN(tol1,xm-x); 
        !          1165:       } 
        !          1166:     } else { 
        !          1167:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
        !          1168:     } 
        !          1169:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
        !          1170:     fu=(*f)(u); 
        !          1171:     if (fu <= fx) { 
        !          1172:       if (u >= x) a=x; else b=x; 
        !          1173:       SHFT(v,w,x,u) 
        !          1174:        SHFT(fv,fw,fx,fu) 
        !          1175:        } else { 
        !          1176:          if (u < x) a=u; else b=u; 
        !          1177:          if (fu <= fw || w == x) { 
        !          1178:            v=w; 
        !          1179:            w=u; 
        !          1180:            fv=fw; 
        !          1181:            fw=fu; 
        !          1182:          } else if (fu <= fv || v == x || v == w) { 
        !          1183:            v=u; 
        !          1184:            fv=fu; 
        !          1185:          } 
        !          1186:        } 
        !          1187:   } 
        !          1188:   nrerror("Too many iterations in brent"); 
        !          1189:   *xmin=x; 
        !          1190:   return fx; 
        !          1191: } 
        !          1192: 
        !          1193: /****************** mnbrak ***********************/
        !          1194: 
        !          1195: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
        !          1196:            double (*func)(double)) 
        !          1197: { 
        !          1198:   double ulim,u,r,q, dum;
        !          1199:   double fu; 
        !          1200:  
        !          1201:   *fa=(*func)(*ax); 
        !          1202:   *fb=(*func)(*bx); 
        !          1203:   if (*fb > *fa) { 
        !          1204:     SHFT(dum,*ax,*bx,dum) 
        !          1205:       SHFT(dum,*fb,*fa,dum) 
        !          1206:       } 
        !          1207:   *cx=(*bx)+GOLD*(*bx-*ax); 
        !          1208:   *fc=(*func)(*cx); 
        !          1209:   while (*fb > *fc) { 
        !          1210:     r=(*bx-*ax)*(*fb-*fc); 
        !          1211:     q=(*bx-*cx)*(*fb-*fa); 
        !          1212:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
        !          1213:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); 
        !          1214:     ulim=(*bx)+GLIMIT*(*cx-*bx); 
        !          1215:     if ((*bx-u)*(u-*cx) > 0.0) { 
        !          1216:       fu=(*func)(u); 
        !          1217:     } else if ((*cx-u)*(u-ulim) > 0.0) { 
        !          1218:       fu=(*func)(u); 
        !          1219:       if (fu < *fc) { 
        !          1220:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
        !          1221:          SHFT(*fb,*fc,fu,(*func)(u)) 
        !          1222:          } 
        !          1223:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { 
        !          1224:       u=ulim; 
        !          1225:       fu=(*func)(u); 
        !          1226:     } else { 
        !          1227:       u=(*cx)+GOLD*(*cx-*bx); 
        !          1228:       fu=(*func)(u); 
        !          1229:     } 
        !          1230:     SHFT(*ax,*bx,*cx,u) 
        !          1231:       SHFT(*fa,*fb,*fc,fu) 
        !          1232:       } 
        !          1233: } 
        !          1234: 
        !          1235: /*************** linmin ************************/
        !          1236: 
        !          1237: int ncom; 
        !          1238: double *pcom,*xicom;
        !          1239: double (*nrfunc)(double []); 
        !          1240:  
        !          1241: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
        !          1242: { 
        !          1243:   double brent(double ax, double bx, double cx, 
        !          1244:               double (*f)(double), double tol, double *xmin); 
        !          1245:   double f1dim(double x); 
        !          1246:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
        !          1247:              double *fc, double (*func)(double)); 
        !          1248:   int j; 
        !          1249:   double xx,xmin,bx,ax; 
        !          1250:   double fx,fb,fa;
        !          1251:  
        !          1252:   ncom=n; 
        !          1253:   pcom=vector(1,n); 
        !          1254:   xicom=vector(1,n); 
        !          1255:   nrfunc=func; 
        !          1256:   for (j=1;j<=n;j++) { 
        !          1257:     pcom[j]=p[j]; 
        !          1258:     xicom[j]=xi[j]; 
        !          1259:   } 
        !          1260:   ax=0.0; 
        !          1261:   xx=1.0; 
        !          1262:   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); 
        !          1263:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); 
        !          1264: #ifdef DEBUG
        !          1265:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
        !          1266:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
        !          1267: #endif
        !          1268:   for (j=1;j<=n;j++) { 
        !          1269:     xi[j] *= xmin; 
        !          1270:     p[j] += xi[j]; 
        !          1271:   } 
        !          1272:   free_vector(xicom,1,n); 
        !          1273:   free_vector(pcom,1,n); 
        !          1274: } 
        !          1275: 
        !          1276: char *asc_diff_time(long time_sec, char ascdiff[])
        !          1277: {
        !          1278:   long sec_left, days, hours, minutes;
        !          1279:   days = (time_sec) / (60*60*24);
        !          1280:   sec_left = (time_sec) % (60*60*24);
        !          1281:   hours = (sec_left) / (60*60) ;
        !          1282:   sec_left = (sec_left) %(60*60);
        !          1283:   minutes = (sec_left) /60;
        !          1284:   sec_left = (sec_left) % (60);
        !          1285:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
        !          1286:   return ascdiff;
        !          1287: }
        !          1288: 
        !          1289: /*************** powell ************************/
        !          1290: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
        !          1291:            double (*func)(double [])) 
        !          1292: { 
        !          1293:   void linmin(double p[], double xi[], int n, double *fret, 
        !          1294:              double (*func)(double [])); 
        !          1295:   int i,ibig,j; 
        !          1296:   double del,t,*pt,*ptt,*xit;
        !          1297:   double fp,fptt;
        !          1298:   double *xits;
        !          1299:   int niterf, itmp;
        !          1300: 
        !          1301:   pt=vector(1,n); 
        !          1302:   ptt=vector(1,n); 
        !          1303:   xit=vector(1,n); 
        !          1304:   xits=vector(1,n); 
        !          1305:   *fret=(*func)(p); 
        !          1306:   for (j=1;j<=n;j++) pt[j]=p[j]; 
        !          1307:     rcurr_time = time(NULL);  
        !          1308:   for (*iter=1;;++(*iter)) { 
        !          1309:     fp=(*fret); 
        !          1310:     ibig=0; 
        !          1311:     del=0.0; 
        !          1312:     rlast_time=rcurr_time;
        !          1313:     /* (void) gettimeofday(&curr_time,&tzp); */
        !          1314:     rcurr_time = time(NULL);  
        !          1315:     curr_time = *localtime(&rcurr_time);
        !          1316:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
        !          1317:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
        !          1318: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
        !          1319:    for (i=1;i<=n;i++) {
        !          1320:       printf(" %d %.12f",i, p[i]);
        !          1321:       fprintf(ficlog," %d %.12lf",i, p[i]);
        !          1322:       fprintf(ficrespow," %.12lf", p[i]);
        !          1323:     }
        !          1324:     printf("\n");
        !          1325:     fprintf(ficlog,"\n");
        !          1326:     fprintf(ficrespow,"\n");fflush(ficrespow);
        !          1327:     if(*iter <=3){
        !          1328:       tml = *localtime(&rcurr_time);
        !          1329:       strcpy(strcurr,asctime(&tml));
        !          1330: /*       asctime_r(&tm,strcurr); */
        !          1331:       rforecast_time=rcurr_time; 
        !          1332:       itmp = strlen(strcurr);
        !          1333:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
        !          1334:        strcurr[itmp-1]='\0';
        !          1335:       printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
        !          1336:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
        !          1337:       for(niterf=10;niterf<=30;niterf+=10){
        !          1338:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
        !          1339:        forecast_time = *localtime(&rforecast_time);
        !          1340: /*     asctime_r(&tmf,strfor); */
        !          1341:        strcpy(strfor,asctime(&forecast_time));
        !          1342:        itmp = strlen(strfor);
        !          1343:        if(strfor[itmp-1]=='\n')
        !          1344:        strfor[itmp-1]='\0';
        !          1345:        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);
        !          1346:        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);
        !          1347:       }
        !          1348:     }
        !          1349:     for (i=1;i<=n;i++) { 
        !          1350:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; 
        !          1351:       fptt=(*fret); 
        !          1352: #ifdef DEBUG
        !          1353:       printf("fret=%lf \n",*fret);
        !          1354:       fprintf(ficlog,"fret=%lf \n",*fret);
        !          1355: #endif
        !          1356:       printf("%d",i);fflush(stdout);
        !          1357:       fprintf(ficlog,"%d",i);fflush(ficlog);
        !          1358:       linmin(p,xit,n,fret,func); 
        !          1359:       if (fabs(fptt-(*fret)) > del) { 
        !          1360:        del=fabs(fptt-(*fret)); 
        !          1361:        ibig=i; 
        !          1362:       } 
        !          1363: #ifdef DEBUG
        !          1364:       printf("%d %.12e",i,(*fret));
        !          1365:       fprintf(ficlog,"%d %.12e",i,(*fret));
        !          1366:       for (j=1;j<=n;j++) {
        !          1367:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
        !          1368:        printf(" x(%d)=%.12e",j,xit[j]);
        !          1369:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
        !          1370:       }
        !          1371:       for(j=1;j<=n;j++) {
        !          1372:        printf(" p=%.12e",p[j]);
        !          1373:        fprintf(ficlog," p=%.12e",p[j]);
        !          1374:       }
        !          1375:       printf("\n");
        !          1376:       fprintf(ficlog,"\n");
        !          1377: #endif
        !          1378:     } 
        !          1379:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
        !          1380: #ifdef DEBUG
        !          1381:       int k[2],l;
        !          1382:       k[0]=1;
        !          1383:       k[1]=-1;
        !          1384:       printf("Max: %.12e",(*func)(p));
        !          1385:       fprintf(ficlog,"Max: %.12e",(*func)(p));
        !          1386:       for (j=1;j<=n;j++) {
        !          1387:        printf(" %.12e",p[j]);
        !          1388:        fprintf(ficlog," %.12e",p[j]);
        !          1389:       }
        !          1390:       printf("\n");
        !          1391:       fprintf(ficlog,"\n");
        !          1392:       for(l=0;l<=1;l++) {
        !          1393:        for (j=1;j<=n;j++) {
        !          1394:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
        !          1395:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
        !          1396:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
        !          1397:        }
        !          1398:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
        !          1399:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
        !          1400:       }
        !          1401: #endif
        !          1402: 
        !          1403: 
        !          1404:       free_vector(xit,1,n); 
        !          1405:       free_vector(xits,1,n); 
        !          1406:       free_vector(ptt,1,n); 
        !          1407:       free_vector(pt,1,n); 
        !          1408:       return; 
        !          1409:     } 
        !          1410:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
        !          1411:     for (j=1;j<=n;j++) { /* Computes an extrapolated point */
        !          1412:       ptt[j]=2.0*p[j]-pt[j]; 
        !          1413:       xit[j]=p[j]-pt[j]; 
        !          1414:       pt[j]=p[j]; 
        !          1415:     } 
        !          1416:     fptt=(*func)(ptt); 
        !          1417:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
        !          1418:       /* x1 f1=fp x2 f2=*fret x3 f3=fptt, xm fm */
        !          1419:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
        !          1420:       /* Let f"(x2) be the 2nd derivative equal everywhere. Then the parabolic through (x1,f1), (x2,f2) and (x3,f3)
        !          1421:         will reach at f3 = fm + h^2/2 f''m  ; f" = (f1 -2f2 +f3 ) / h**2 */
        !          1422:       /* f1-f3 = delta(2h) = 2 h**2 f'' = 2(f1- 2f2 +f3) */
        !          1423:       /* Thus we compare delta(2h) with observed f1-f3 */
        !          1424:       /* or best gain on one ancient line 'del' with total gain f1-f2 = f1 - f2 - 'del' with del */ 
        !          1425:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
        !          1426:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del);
        !          1427:       t= t- del*SQR(fp-fptt);
        !          1428:       printf("t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
        !          1429:       fprintf(ficlog,"t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
        !          1430: #ifdef DEBUG
        !          1431:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
        !          1432:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
        !          1433:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
        !          1434:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
        !          1435:       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);
        !          1436:       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);
        !          1437: #endif
        !          1438:       if (t < 0.0) { /* Then we use it for last direction */
        !          1439:        linmin(p,xit,n,fret,func); /* computes mean on the extrapolated direction.*/
        !          1440:        for (j=1;j<=n;j++) { 
        !          1441:          xi[j][ibig]=xi[j][n]; /* Replace the direction with biggest decrease by n */
        !          1442:          xi[j][n]=xit[j];      /* and nth direction by the extrapolated */
        !          1443:        }
        !          1444:        printf("Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
        !          1445:        fprintf(ficlog,"Gaining to use average direction of P0 P%d instead of biggest increase direction :\n",n,ibig);
        !          1446: 
        !          1447: #ifdef DEBUG
        !          1448:        for(j=1;j<=n;j++){
        !          1449:          printf(" %.12e",xit[j]);
        !          1450:          fprintf(ficlog," %.12e",xit[j]);
        !          1451:        }
        !          1452:        printf("\n");
        !          1453:        fprintf(ficlog,"\n");
        !          1454: #endif
        !          1455:       }
        !          1456:     } 
        !          1457:   } 
        !          1458: } 
        !          1459: 
        !          1460: /**** Prevalence limit (stable or period prevalence)  ****************/
        !          1461: 
        !          1462: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
        !          1463: {
        !          1464:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
        !          1465:      matrix by transitions matrix until convergence is reached */
        !          1466: 
        !          1467:   int i, ii,j,k;
        !          1468:   double min, max, maxmin, maxmax,sumnew=0.;
        !          1469:   /* double **matprod2(); */ /* test */
        !          1470:   double **out, cov[NCOVMAX+1], **pmij();
        !          1471:   double **newm;
        !          1472:   double agefin, delaymax=50 ; /* Max number of years to converge */
        !          1473: 
        !          1474:   for (ii=1;ii<=nlstate+ndeath;ii++)
        !          1475:     for (j=1;j<=nlstate+ndeath;j++){
        !          1476:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          1477:     }
        !          1478: 
        !          1479:    cov[1]=1.;
        !          1480:  
        !          1481:  /* Even if hstepm = 1, at least one multiplication by the unit matrix */
        !          1482:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
        !          1483:     newm=savm;
        !          1484:     /* Covariates have to be included here again */
        !          1485:     cov[2]=agefin;
        !          1486:     
        !          1487:     for (k=1; k<=cptcovn;k++) {
        !          1488:       cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
        !          1489:       /*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]]);*/
        !          1490:     }
        !          1491:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
        !          1492:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
        !          1493:     /*   cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]]; */
        !          1494:     
        !          1495:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
        !          1496:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
        !          1497:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
        !          1498:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
        !          1499:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
        !          1500:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
        !          1501:     
        !          1502:     savm=oldm;
        !          1503:     oldm=newm;
        !          1504:     maxmax=0.;
        !          1505:     for(j=1;j<=nlstate;j++){
        !          1506:       min=1.;
        !          1507:       max=0.;
        !          1508:       for(i=1; i<=nlstate; i++) {
        !          1509:        sumnew=0;
        !          1510:        for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
        !          1511:        prlim[i][j]= newm[i][j]/(1-sumnew);
        !          1512:         /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
        !          1513:        max=FMAX(max,prlim[i][j]);
        !          1514:        min=FMIN(min,prlim[i][j]);
        !          1515:       }
        !          1516:       maxmin=max-min;
        !          1517:       maxmax=FMAX(maxmax,maxmin);
        !          1518:     }
        !          1519:     if(maxmax < ftolpl){
        !          1520:       return prlim;
        !          1521:     }
        !          1522:   }
        !          1523: }
        !          1524: 
        !          1525: /*************** transition probabilities ***************/ 
        !          1526: 
        !          1527: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
        !          1528: {
        !          1529:   /* According to parameters values stored in x and the covariate's values stored in cov,
        !          1530:      computes the probability to be observed in state j being in state i by appying the
        !          1531:      model to the ncovmodel covariates (including constant and age).
        !          1532:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
        !          1533:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
        !          1534:      ncth covariate in the global vector x is given by the formula:
        !          1535:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
        !          1536:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
        !          1537:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
        !          1538:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
        !          1539:      Outputs ps[i][j] the probability to be observed in j being in j according to
        !          1540:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
        !          1541:   */
        !          1542:   double s1, lnpijopii;
        !          1543:   /*double t34;*/
        !          1544:   int i,j,j1, nc, ii, jj;
        !          1545: 
        !          1546:     for(i=1; i<= nlstate; i++){
        !          1547:       for(j=1; j<i;j++){
        !          1548:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
        !          1549:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
        !          1550:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
        !          1551: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
        !          1552:        }
        !          1553:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
        !          1554: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
        !          1555:       }
        !          1556:       for(j=i+1; j<=nlstate+ndeath;j++){
        !          1557:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
        !          1558:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
        !          1559:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
        !          1560: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
        !          1561:        }
        !          1562:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
        !          1563:       }
        !          1564:     }
        !          1565:     
        !          1566:     for(i=1; i<= nlstate; i++){
        !          1567:       s1=0;
        !          1568:       for(j=1; j<i; j++){
        !          1569:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
        !          1570:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
        !          1571:       }
        !          1572:       for(j=i+1; j<=nlstate+ndeath; j++){
        !          1573:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
        !          1574:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
        !          1575:       }
        !          1576:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
        !          1577:       ps[i][i]=1./(s1+1.);
        !          1578:       /* Computing other pijs */
        !          1579:       for(j=1; j<i; j++)
        !          1580:        ps[i][j]= exp(ps[i][j])*ps[i][i];
        !          1581:       for(j=i+1; j<=nlstate+ndeath; j++)
        !          1582:        ps[i][j]= exp(ps[i][j])*ps[i][i];
        !          1583:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
        !          1584:     } /* end i */
        !          1585:     
        !          1586:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
        !          1587:       for(jj=1; jj<= nlstate+ndeath; jj++){
        !          1588:        ps[ii][jj]=0;
        !          1589:        ps[ii][ii]=1;
        !          1590:       }
        !          1591:     }
        !          1592:     
        !          1593:     
        !          1594:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
        !          1595:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
        !          1596:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
        !          1597:     /*   } */
        !          1598:     /*   printf("\n "); */
        !          1599:     /* } */
        !          1600:     /* printf("\n ");printf("%lf ",cov[2]);*/
        !          1601:     /*
        !          1602:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
        !          1603:       goto end;*/
        !          1604:     return ps;
        !          1605: }
        !          1606: 
        !          1607: /**************** Product of 2 matrices ******************/
        !          1608: 
        !          1609: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
        !          1610: {
        !          1611:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
        !          1612:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
        !          1613:   /* in, b, out are matrice of pointers which should have been initialized 
        !          1614:      before: only the contents of out is modified. The function returns
        !          1615:      a pointer to pointers identical to out */
        !          1616:   int i, j, k;
        !          1617:   for(i=nrl; i<= nrh; i++)
        !          1618:     for(k=ncolol; k<=ncoloh; k++){
        !          1619:       out[i][k]=0.;
        !          1620:       for(j=ncl; j<=nch; j++)
        !          1621:        out[i][k] +=in[i][j]*b[j][k];
        !          1622:     }
        !          1623:   return out;
        !          1624: }
        !          1625: 
        !          1626: 
        !          1627: /************* Higher Matrix Product ***************/
        !          1628: 
        !          1629: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
        !          1630: {
        !          1631:   /* Computes the transition matrix starting at age 'age' over 
        !          1632:      'nhstepm*hstepm*stepm' months (i.e. until
        !          1633:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
        !          1634:      nhstepm*hstepm matrices. 
        !          1635:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
        !          1636:      (typically every 2 years instead of every month which is too big 
        !          1637:      for the memory).
        !          1638:      Model is determined by parameters x and covariates have to be 
        !          1639:      included manually here. 
        !          1640: 
        !          1641:      */
        !          1642: 
        !          1643:   int i, j, d, h, k;
        !          1644:   double **out, cov[NCOVMAX+1];
        !          1645:   double **newm;
        !          1646: 
        !          1647:   /* Hstepm could be zero and should return the unit matrix */
        !          1648:   for (i=1;i<=nlstate+ndeath;i++)
        !          1649:     for (j=1;j<=nlstate+ndeath;j++){
        !          1650:       oldm[i][j]=(i==j ? 1.0 : 0.0);
        !          1651:       po[i][j][0]=(i==j ? 1.0 : 0.0);
        !          1652:     }
        !          1653:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
        !          1654:   for(h=1; h <=nhstepm; h++){
        !          1655:     for(d=1; d <=hstepm; d++){
        !          1656:       newm=savm;
        !          1657:       /* Covariates have to be included here again */
        !          1658:       cov[1]=1.;
        !          1659:       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
        !          1660:       for (k=1; k<=cptcovn;k++) 
        !          1661:        cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
        !          1662:       for (k=1; k<=cptcovage;k++)
        !          1663:        cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
        !          1664:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
        !          1665:        cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
        !          1666: 
        !          1667: 
        !          1668:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
        !          1669:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
        !          1670:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
        !          1671:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
        !          1672:       savm=oldm;
        !          1673:       oldm=newm;
        !          1674:     }
        !          1675:     for(i=1; i<=nlstate+ndeath; i++)
        !          1676:       for(j=1;j<=nlstate+ndeath;j++) {
        !          1677:        po[i][j][h]=newm[i][j];
        !          1678:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
        !          1679:       }
        !          1680:     /*printf("h=%d ",h);*/
        !          1681:   } /* end h */
        !          1682: /*     printf("\n H=%d \n",h); */
        !          1683:   return po;
        !          1684: }
        !          1685: 
        !          1686: double myfunc(unsigned n, const double *p, double *grad, double (*func) (double [])){
        !          1687:   /* double (*nrfunc)(double []);  */
        !          1688:   /* double myfunc(unsigned n, const double *p, double *grad, void *my_func_data){ */
        !          1689:   double fret;
        !          1690:   double *xt;
        !          1691:   int j;
        !          1692: 
        !          1693:   xt=vector(1,n); 
        !          1694:  for (j=1;j<=n;j++)
        !          1695:    xt[j]=p[j]; 
        !          1696:   ++countcallfunc;
        !          1697: 
        !          1698:   fret=(*func)(xt); 
        !          1699:   printf("Function = %.12lf ",fret);
        !          1700:   for (j=1;j<=n;j++)
        !          1701:     printf(" %d %.8lf", j, p[j]); 
        !          1702:   printf("\n");
        !          1703:  free_vector(xt,1,n);
        !          1704:   return fret;
        !          1705: }
        !          1706: /*************** log-likelihood *************/
        !          1707: double func( double *x)
        !          1708: {
        !          1709:   int i, ii, j, k, mi, d, kk;
        !          1710:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
        !          1711:   double **out;
        !          1712:   double sw; /* Sum of weights */
        !          1713:   double lli; /* Individual log likelihood */
        !          1714:   int s1, s2;
        !          1715:   double bbh, survp;
        !          1716:   long ipmx;
        !          1717:   /*extern weight */
        !          1718:   /* We are differentiating ll according to initial status */
        !          1719:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
        !          1720:   /*for(i=1;i<imx;i++) 
        !          1721:     printf(" %d\n",s[4][i]);
        !          1722:   */
        !          1723:   cov[1]=1.;
        !          1724: 
        !          1725:   for(k=1; k<=nlstate; k++) ll[k]=0.;
        !          1726: 
        !          1727:   if(mle==1){
        !          1728:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
        !          1729:       /* Computes the values of the ncovmodel covariates of the model
        !          1730:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
        !          1731:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
        !          1732:         to be observed in j being in i according to the model.
        !          1733:        */
        !          1734:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
        !          1735:        cov[2+k]=covar[Tvar[k]][i];
        !          1736:       }
        !          1737:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
        !          1738:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
        !          1739:         has been calculated etc */
        !          1740:       for(mi=1; mi<= wav[i]-1; mi++){
        !          1741:        for (ii=1;ii<=nlstate+ndeath;ii++)
        !          1742:          for (j=1;j<=nlstate+ndeath;j++){
        !          1743:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          1744:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          1745:          }
        !          1746:        for(d=0; d<dh[mi][i]; d++){
        !          1747:          newm=savm;
        !          1748:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          1749:          for (kk=1; kk<=cptcovage;kk++) {
        !          1750:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
        !          1751:          }
        !          1752:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
        !          1753:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
        !          1754:          savm=oldm;
        !          1755:          oldm=newm;
        !          1756:        } /* end mult */
        !          1757:       
        !          1758:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
        !          1759:        /* But now since version 0.9 we anticipate for bias at large stepm.
        !          1760:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
        !          1761:         * (in months) between two waves is not a multiple of stepm, we rounded to 
        !          1762:         * the nearest (and in case of equal distance, to the lowest) interval but now
        !          1763:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
        !          1764:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
        !          1765:         * probability in order to take into account the bias as a fraction of the way
        !          1766:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
        !          1767:         * -stepm/2 to stepm/2 .
        !          1768:         * For stepm=1 the results are the same as for previous versions of Imach.
        !          1769:         * For stepm > 1 the results are less biased than in previous versions. 
        !          1770:         */
        !          1771:        s1=s[mw[mi][i]][i];
        !          1772:        s2=s[mw[mi+1][i]][i];
        !          1773:        bbh=(double)bh[mi][i]/(double)stepm; 
        !          1774:        /* bias bh is positive if real duration
        !          1775:         * is higher than the multiple of stepm and negative otherwise.
        !          1776:         */
        !          1777:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
        !          1778:        if( s2 > nlstate){ 
        !          1779:          /* i.e. if s2 is a death state and if the date of death is known 
        !          1780:             then the contribution to the likelihood is the probability to 
        !          1781:             die between last step unit time and current  step unit time, 
        !          1782:             which is also equal to probability to die before dh 
        !          1783:             minus probability to die before dh-stepm . 
        !          1784:             In version up to 0.92 likelihood was computed
        !          1785:        as if date of death was unknown. Death was treated as any other
        !          1786:        health state: the date of the interview describes the actual state
        !          1787:        and not the date of a change in health state. The former idea was
        !          1788:        to consider that at each interview the state was recorded
        !          1789:        (healthy, disable or death) and IMaCh was corrected; but when we
        !          1790:        introduced the exact date of death then we should have modified
        !          1791:        the contribution of an exact death to the likelihood. This new
        !          1792:        contribution is smaller and very dependent of the step unit
        !          1793:        stepm. It is no more the probability to die between last interview
        !          1794:        and month of death but the probability to survive from last
        !          1795:        interview up to one month before death multiplied by the
        !          1796:        probability to die within a month. Thanks to Chris
        !          1797:        Jackson for correcting this bug.  Former versions increased
        !          1798:        mortality artificially. The bad side is that we add another loop
        !          1799:        which slows down the processing. The difference can be up to 10%
        !          1800:        lower mortality.
        !          1801:          */
        !          1802:          lli=log(out[s1][s2] - savm[s1][s2]);
        !          1803: 
        !          1804: 
        !          1805:        } else if  (s2==-2) {
        !          1806:          for (j=1,survp=0. ; j<=nlstate; j++) 
        !          1807:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
        !          1808:          /*survp += out[s1][j]; */
        !          1809:          lli= log(survp);
        !          1810:        }
        !          1811:        
        !          1812:        else if  (s2==-4) { 
        !          1813:          for (j=3,survp=0. ; j<=nlstate; j++)  
        !          1814:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
        !          1815:          lli= log(survp); 
        !          1816:        } 
        !          1817: 
        !          1818:        else if  (s2==-5) { 
        !          1819:          for (j=1,survp=0. ; j<=2; j++)  
        !          1820:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
        !          1821:          lli= log(survp); 
        !          1822:        } 
        !          1823:        
        !          1824:        else{
        !          1825:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
        !          1826:          /*  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 */
        !          1827:        } 
        !          1828:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
        !          1829:        /*if(lli ==000.0)*/
        !          1830:        /*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); */
        !          1831:        ipmx +=1;
        !          1832:        sw += weight[i];
        !          1833:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
        !          1834:       } /* end of wave */
        !          1835:     } /* end of individual */
        !          1836:   }  else if(mle==2){
        !          1837:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
        !          1838:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
        !          1839:       for(mi=1; mi<= wav[i]-1; mi++){
        !          1840:        for (ii=1;ii<=nlstate+ndeath;ii++)
        !          1841:          for (j=1;j<=nlstate+ndeath;j++){
        !          1842:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          1843:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          1844:          }
        !          1845:        for(d=0; d<=dh[mi][i]; d++){
        !          1846:          newm=savm;
        !          1847:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          1848:          for (kk=1; kk<=cptcovage;kk++) {
        !          1849:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
        !          1850:          }
        !          1851:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
        !          1852:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
        !          1853:          savm=oldm;
        !          1854:          oldm=newm;
        !          1855:        } /* end mult */
        !          1856:       
        !          1857:        s1=s[mw[mi][i]][i];
        !          1858:        s2=s[mw[mi+1][i]][i];
        !          1859:        bbh=(double)bh[mi][i]/(double)stepm; 
        !          1860:        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 */
        !          1861:        ipmx +=1;
        !          1862:        sw += weight[i];
        !          1863:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
        !          1864:       } /* end of wave */
        !          1865:     } /* end of individual */
        !          1866:   }  else if(mle==3){  /* exponential inter-extrapolation */
        !          1867:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
        !          1868:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
        !          1869:       for(mi=1; mi<= wav[i]-1; mi++){
        !          1870:        for (ii=1;ii<=nlstate+ndeath;ii++)
        !          1871:          for (j=1;j<=nlstate+ndeath;j++){
        !          1872:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          1873:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          1874:          }
        !          1875:        for(d=0; d<dh[mi][i]; d++){
        !          1876:          newm=savm;
        !          1877:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          1878:          for (kk=1; kk<=cptcovage;kk++) {
        !          1879:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
        !          1880:          }
        !          1881:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
        !          1882:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
        !          1883:          savm=oldm;
        !          1884:          oldm=newm;
        !          1885:        } /* end mult */
        !          1886:       
        !          1887:        s1=s[mw[mi][i]][i];
        !          1888:        s2=s[mw[mi+1][i]][i];
        !          1889:        bbh=(double)bh[mi][i]/(double)stepm; 
        !          1890:        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 */
        !          1891:        ipmx +=1;
        !          1892:        sw += weight[i];
        !          1893:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
        !          1894:       } /* end of wave */
        !          1895:     } /* end of individual */
        !          1896:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
        !          1897:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
        !          1898:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
        !          1899:       for(mi=1; mi<= wav[i]-1; mi++){
        !          1900:        for (ii=1;ii<=nlstate+ndeath;ii++)
        !          1901:          for (j=1;j<=nlstate+ndeath;j++){
        !          1902:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          1903:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          1904:          }
        !          1905:        for(d=0; d<dh[mi][i]; d++){
        !          1906:          newm=savm;
        !          1907:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          1908:          for (kk=1; kk<=cptcovage;kk++) {
        !          1909:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
        !          1910:          }
        !          1911:        
        !          1912:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
        !          1913:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
        !          1914:          savm=oldm;
        !          1915:          oldm=newm;
        !          1916:        } /* end mult */
        !          1917:       
        !          1918:        s1=s[mw[mi][i]][i];
        !          1919:        s2=s[mw[mi+1][i]][i];
        !          1920:        if( s2 > nlstate){ 
        !          1921:          lli=log(out[s1][s2] - savm[s1][s2]);
        !          1922:        }else{
        !          1923:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
        !          1924:        }
        !          1925:        ipmx +=1;
        !          1926:        sw += weight[i];
        !          1927:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
        !          1928: /*     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]); */
        !          1929:       } /* end of wave */
        !          1930:     } /* end of individual */
        !          1931:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
        !          1932:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
        !          1933:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
        !          1934:       for(mi=1; mi<= wav[i]-1; mi++){
        !          1935:        for (ii=1;ii<=nlstate+ndeath;ii++)
        !          1936:          for (j=1;j<=nlstate+ndeath;j++){
        !          1937:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          1938:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          1939:          }
        !          1940:        for(d=0; d<dh[mi][i]; d++){
        !          1941:          newm=savm;
        !          1942:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          1943:          for (kk=1; kk<=cptcovage;kk++) {
        !          1944:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
        !          1945:          }
        !          1946:        
        !          1947:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
        !          1948:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
        !          1949:          savm=oldm;
        !          1950:          oldm=newm;
        !          1951:        } /* end mult */
        !          1952:       
        !          1953:        s1=s[mw[mi][i]][i];
        !          1954:        s2=s[mw[mi+1][i]][i];
        !          1955:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
        !          1956:        ipmx +=1;
        !          1957:        sw += weight[i];
        !          1958:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
        !          1959:        /*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]);*/
        !          1960:       } /* end of wave */
        !          1961:     } /* end of individual */
        !          1962:   } /* End of if */
        !          1963:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
        !          1964:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
        !          1965:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
        !          1966:   return -l;
        !          1967: }
        !          1968: 
        !          1969: /*************** log-likelihood *************/
        !          1970: double funcone( double *x)
        !          1971: {
        !          1972:   /* Same as likeli but slower because of a lot of printf and if */
        !          1973:   int i, ii, j, k, mi, d, kk;
        !          1974:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
        !          1975:   double **out;
        !          1976:   double lli; /* Individual log likelihood */
        !          1977:   double llt;
        !          1978:   int s1, s2;
        !          1979:   double bbh, survp;
        !          1980:   /*extern weight */
        !          1981:   /* We are differentiating ll according to initial status */
        !          1982:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
        !          1983:   /*for(i=1;i<imx;i++) 
        !          1984:     printf(" %d\n",s[4][i]);
        !          1985:   */
        !          1986:   cov[1]=1.;
        !          1987: 
        !          1988:   for(k=1; k<=nlstate; k++) ll[k]=0.;
        !          1989: 
        !          1990:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
        !          1991:     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
        !          1992:     for(mi=1; mi<= wav[i]-1; mi++){
        !          1993:       for (ii=1;ii<=nlstate+ndeath;ii++)
        !          1994:        for (j=1;j<=nlstate+ndeath;j++){
        !          1995:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          1996:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          1997:        }
        !          1998:       for(d=0; d<dh[mi][i]; d++){
        !          1999:        newm=savm;
        !          2000:        cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          2001:        for (kk=1; kk<=cptcovage;kk++) {
        !          2002:          cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
        !          2003:        }
        !          2004:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
        !          2005:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
        !          2006:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
        !          2007:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
        !          2008:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
        !          2009:        savm=oldm;
        !          2010:        oldm=newm;
        !          2011:       } /* end mult */
        !          2012:       
        !          2013:       s1=s[mw[mi][i]][i];
        !          2014:       s2=s[mw[mi+1][i]][i];
        !          2015:       bbh=(double)bh[mi][i]/(double)stepm; 
        !          2016:       /* bias is positive if real duration
        !          2017:        * is higher than the multiple of stepm and negative otherwise.
        !          2018:        */
        !          2019:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
        !          2020:        lli=log(out[s1][s2] - savm[s1][s2]);
        !          2021:       } else if  (s2==-2) {
        !          2022:        for (j=1,survp=0. ; j<=nlstate; j++) 
        !          2023:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
        !          2024:        lli= log(survp);
        !          2025:       }else if (mle==1){
        !          2026:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
        !          2027:       } else if(mle==2){
        !          2028:        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 */
        !          2029:       } else if(mle==3){  /* exponential inter-extrapolation */
        !          2030:        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 */
        !          2031:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
        !          2032:        lli=log(out[s1][s2]); /* Original formula */
        !          2033:       } else{  /* mle=0 back to 1 */
        !          2034:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
        !          2035:        /*lli=log(out[s1][s2]); */ /* Original formula */
        !          2036:       } /* End of if */
        !          2037:       ipmx +=1;
        !          2038:       sw += weight[i];
        !          2039:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
        !          2040:       /*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]); */
        !          2041:       if(globpr){
        !          2042:        fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
        !          2043:  %11.6f %11.6f %11.6f ", \
        !          2044:                num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
        !          2045:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
        !          2046:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
        !          2047:          llt +=ll[k]*gipmx/gsw;
        !          2048:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
        !          2049:        }
        !          2050:        fprintf(ficresilk," %10.6f\n", -llt);
        !          2051:       }
        !          2052:     } /* end of wave */
        !          2053:   } /* end of individual */
        !          2054:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
        !          2055:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
        !          2056:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
        !          2057:   if(globpr==0){ /* First time we count the contributions and weights */
        !          2058:     gipmx=ipmx;
        !          2059:     gsw=sw;
        !          2060:   }
        !          2061:   return -l;
        !          2062: }
        !          2063: 
        !          2064: 
        !          2065: /*************** function likelione ***********/
        !          2066: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
        !          2067: {
        !          2068:   /* This routine should help understanding what is done with 
        !          2069:      the selection of individuals/waves and
        !          2070:      to check the exact contribution to the likelihood.
        !          2071:      Plotting could be done.
        !          2072:    */
        !          2073:   int k;
        !          2074: 
        !          2075:   if(*globpri !=0){ /* Just counts and sums, no printings */
        !          2076:     strcpy(fileresilk,"ilk"); 
        !          2077:     strcat(fileresilk,fileres);
        !          2078:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
        !          2079:       printf("Problem with resultfile: %s\n", fileresilk);
        !          2080:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
        !          2081:     }
        !          2082:     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");
        !          2083:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
        !          2084:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
        !          2085:     for(k=1; k<=nlstate; k++) 
        !          2086:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
        !          2087:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
        !          2088:   }
        !          2089: 
        !          2090:   *fretone=(*funcone)(p);
        !          2091:   if(*globpri !=0){
        !          2092:     fclose(ficresilk);
        !          2093:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
        !          2094:     fflush(fichtm); 
        !          2095:   } 
        !          2096:   return;
        !          2097: }
        !          2098: 
        !          2099: 
        !          2100: /*********** Maximum Likelihood Estimation ***************/
        !          2101: 
        !          2102: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
        !          2103: {
        !          2104:   int i,j, iter;
        !          2105:   double **xi;
        !          2106:   double fret;
        !          2107:   double fretone; /* Only one call to likelihood */
        !          2108:   /*  char filerespow[FILENAMELENGTH];*/
        !          2109:   xi=matrix(1,npar,1,npar);
        !          2110:   for (i=1;i<=npar;i++)
        !          2111:     for (j=1;j<=npar;j++)
        !          2112:       xi[i][j]=(i==j ? 1.0 : 0.0);
        !          2113:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
        !          2114:   strcpy(filerespow,"pow"); 
        !          2115:   strcat(filerespow,fileres);
        !          2116:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
        !          2117:     printf("Problem with resultfile: %s\n", filerespow);
        !          2118:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
        !          2119:   }
        !          2120:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
        !          2121:   for (i=1;i<=nlstate;i++)
        !          2122:     for(j=1;j<=nlstate+ndeath;j++)
        !          2123:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
        !          2124:   fprintf(ficrespow,"\n");
        !          2125: #ifdef POWELL
        !          2126:   powell(p,xi,npar,ftol,&iter,&fret,func);
        !          2127: #endif
        !          2128: #ifdef NLOPT
        !          2129:   int creturn;
        !          2130:   nlopt_opt opt;
        !          2131:   double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /* lower bounds */
        !          2132:   double minf; /* the minimum objective value, upon return */
        !          2133:  /* opt = nlopt_create(NLOPT_LN_NEWUOA,npar); */
        !          2134:  opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
        !          2135:   nlopt_set_lower_bounds(opt, lb);
        !          2136:   printf(" Func %.12lf \n",myfunc(npar,*(&p),NULL,func));
        !          2137:   /* printf(" Func %.12lf /n",myfunc(npar,p,NULL,NULL)); */
        !          2138:   /* nlopt_set_min_objective(opt, myfunc, NULL); */
        !          2139:   nlopt_set_min_objective(opt, myfunc, func);
        !          2140:   nlopt_set_xtol_rel(opt, ftol);
        !          2141:   /* printf(" Func %.12lf /n",myfunc(npar,p,NULL,func)); */
        !          2142:  if ((creturn=nlopt_optimize(opt, p, &minf)) < 0) {
        !          2143:     printf("nlopt failed! %d\n",creturn); 
        !          2144:   }
        !          2145:   else {
        !          2146:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
        !          2147:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
        !          2148:     iter=countcallfunc; /* not equal */
        !          2149:   }
        !          2150:   nlopt_destroy(opt);
        !          2151: #endif
        !          2152:   free_matrix(xi,1,npar,1,npar);
        !          2153:   fclose(ficrespow);
        !          2154:   printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
        !          2155:   fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
        !          2156:   fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
        !          2157: 
        !          2158: }
        !          2159: 
        !          2160: /**** Computes Hessian and covariance matrix ***/
        !          2161: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
        !          2162: {
        !          2163:   double  **a,**y,*x,pd;
        !          2164:   double **hess;
        !          2165:   int i, j,jk;
        !          2166:   int *indx;
        !          2167: 
        !          2168:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
        !          2169:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
        !          2170:   void lubksb(double **a, int npar, int *indx, double b[]) ;
        !          2171:   void ludcmp(double **a, int npar, int *indx, double *d) ;
        !          2172:   double gompertz(double p[]);
        !          2173:   hess=matrix(1,npar,1,npar);
        !          2174: 
        !          2175:   printf("\nCalculation of the hessian matrix. Wait...\n");
        !          2176:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
        !          2177:   for (i=1;i<=npar;i++){
        !          2178:     printf("%d",i);fflush(stdout);
        !          2179:     fprintf(ficlog,"%d",i);fflush(ficlog);
        !          2180:    
        !          2181:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
        !          2182:     
        !          2183:     /*  printf(" %f ",p[i]);
        !          2184:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
        !          2185:   }
        !          2186:   
        !          2187:   for (i=1;i<=npar;i++) {
        !          2188:     for (j=1;j<=npar;j++)  {
        !          2189:       if (j>i) { 
        !          2190:        printf(".%d%d",i,j);fflush(stdout);
        !          2191:        fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
        !          2192:        hess[i][j]=hessij(p,delti,i,j,func,npar);
        !          2193:        
        !          2194:        hess[j][i]=hess[i][j];    
        !          2195:        /*printf(" %lf ",hess[i][j]);*/
        !          2196:       }
        !          2197:     }
        !          2198:   }
        !          2199:   printf("\n");
        !          2200:   fprintf(ficlog,"\n");
        !          2201: 
        !          2202:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
        !          2203:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
        !          2204:   
        !          2205:   a=matrix(1,npar,1,npar);
        !          2206:   y=matrix(1,npar,1,npar);
        !          2207:   x=vector(1,npar);
        !          2208:   indx=ivector(1,npar);
        !          2209:   for (i=1;i<=npar;i++)
        !          2210:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
        !          2211:   ludcmp(a,npar,indx,&pd);
        !          2212: 
        !          2213:   for (j=1;j<=npar;j++) {
        !          2214:     for (i=1;i<=npar;i++) x[i]=0;
        !          2215:     x[j]=1;
        !          2216:     lubksb(a,npar,indx,x);
        !          2217:     for (i=1;i<=npar;i++){ 
        !          2218:       matcov[i][j]=x[i];
        !          2219:     }
        !          2220:   }
        !          2221: 
        !          2222:   printf("\n#Hessian matrix#\n");
        !          2223:   fprintf(ficlog,"\n#Hessian matrix#\n");
        !          2224:   for (i=1;i<=npar;i++) { 
        !          2225:     for (j=1;j<=npar;j++) { 
        !          2226:       printf("%.3e ",hess[i][j]);
        !          2227:       fprintf(ficlog,"%.3e ",hess[i][j]);
        !          2228:     }
        !          2229:     printf("\n");
        !          2230:     fprintf(ficlog,"\n");
        !          2231:   }
        !          2232: 
        !          2233:   /* Recompute Inverse */
        !          2234:   for (i=1;i<=npar;i++)
        !          2235:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
        !          2236:   ludcmp(a,npar,indx,&pd);
        !          2237: 
        !          2238:   /*  printf("\n#Hessian matrix recomputed#\n");
        !          2239: 
        !          2240:   for (j=1;j<=npar;j++) {
        !          2241:     for (i=1;i<=npar;i++) x[i]=0;
        !          2242:     x[j]=1;
        !          2243:     lubksb(a,npar,indx,x);
        !          2244:     for (i=1;i<=npar;i++){ 
        !          2245:       y[i][j]=x[i];
        !          2246:       printf("%.3e ",y[i][j]);
        !          2247:       fprintf(ficlog,"%.3e ",y[i][j]);
        !          2248:     }
        !          2249:     printf("\n");
        !          2250:     fprintf(ficlog,"\n");
        !          2251:   }
        !          2252:   */
        !          2253: 
        !          2254:   free_matrix(a,1,npar,1,npar);
        !          2255:   free_matrix(y,1,npar,1,npar);
        !          2256:   free_vector(x,1,npar);
        !          2257:   free_ivector(indx,1,npar);
        !          2258:   free_matrix(hess,1,npar,1,npar);
        !          2259: 
        !          2260: 
        !          2261: }
        !          2262: 
        !          2263: /*************** hessian matrix ****************/
        !          2264: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
        !          2265: {
        !          2266:   int i;
        !          2267:   int l=1, lmax=20;
        !          2268:   double k1,k2;
        !          2269:   double p2[MAXPARM+1]; /* identical to x */
        !          2270:   double res;
        !          2271:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
        !          2272:   double fx;
        !          2273:   int k=0,kmax=10;
        !          2274:   double l1;
        !          2275: 
        !          2276:   fx=func(x);
        !          2277:   for (i=1;i<=npar;i++) p2[i]=x[i];
        !          2278:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
        !          2279:     l1=pow(10,l);
        !          2280:     delts=delt;
        !          2281:     for(k=1 ; k <kmax; k=k+1){
        !          2282:       delt = delta*(l1*k);
        !          2283:       p2[theta]=x[theta] +delt;
        !          2284:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
        !          2285:       p2[theta]=x[theta]-delt;
        !          2286:       k2=func(p2)-fx;
        !          2287:       /*res= (k1-2.0*fx+k2)/delt/delt; */
        !          2288:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
        !          2289:       
        !          2290: #ifdef DEBUGHESS
        !          2291:       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);
        !          2292:       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);
        !          2293: #endif
        !          2294:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
        !          2295:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
        !          2296:        k=kmax;
        !          2297:       }
        !          2298:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
        !          2299:        k=kmax; l=lmax*10.;
        !          2300:       }
        !          2301:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
        !          2302:        delts=delt;
        !          2303:       }
        !          2304:     }
        !          2305:   }
        !          2306:   delti[theta]=delts;
        !          2307:   return res; 
        !          2308:   
        !          2309: }
        !          2310: 
        !          2311: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
        !          2312: {
        !          2313:   int i;
        !          2314:   int l=1, l1, lmax=20;
        !          2315:   double k1,k2,k3,k4,res,fx;
        !          2316:   double p2[MAXPARM+1];
        !          2317:   int k;
        !          2318: 
        !          2319:   fx=func(x);
        !          2320:   for (k=1; k<=2; k++) {
        !          2321:     for (i=1;i<=npar;i++) p2[i]=x[i];
        !          2322:     p2[thetai]=x[thetai]+delti[thetai]/k;
        !          2323:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
        !          2324:     k1=func(p2)-fx;
        !          2325:   
        !          2326:     p2[thetai]=x[thetai]+delti[thetai]/k;
        !          2327:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
        !          2328:     k2=func(p2)-fx;
        !          2329:   
        !          2330:     p2[thetai]=x[thetai]-delti[thetai]/k;
        !          2331:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
        !          2332:     k3=func(p2)-fx;
        !          2333:   
        !          2334:     p2[thetai]=x[thetai]-delti[thetai]/k;
        !          2335:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
        !          2336:     k4=func(p2)-fx;
        !          2337:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
        !          2338: #ifdef DEBUG
        !          2339:     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);
        !          2340:     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);
        !          2341: #endif
        !          2342:   }
        !          2343:   return res;
        !          2344: }
        !          2345: 
        !          2346: /************** Inverse of matrix **************/
        !          2347: void ludcmp(double **a, int n, int *indx, double *d) 
        !          2348: { 
        !          2349:   int i,imax,j,k; 
        !          2350:   double big,dum,sum,temp; 
        !          2351:   double *vv; 
        !          2352:  
        !          2353:   vv=vector(1,n); 
        !          2354:   *d=1.0; 
        !          2355:   for (i=1;i<=n;i++) { 
        !          2356:     big=0.0; 
        !          2357:     for (j=1;j<=n;j++) 
        !          2358:       if ((temp=fabs(a[i][j])) > big) big=temp; 
        !          2359:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
        !          2360:     vv[i]=1.0/big; 
        !          2361:   } 
        !          2362:   for (j=1;j<=n;j++) { 
        !          2363:     for (i=1;i<j;i++) { 
        !          2364:       sum=a[i][j]; 
        !          2365:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
        !          2366:       a[i][j]=sum; 
        !          2367:     } 
        !          2368:     big=0.0; 
        !          2369:     for (i=j;i<=n;i++) { 
        !          2370:       sum=a[i][j]; 
        !          2371:       for (k=1;k<j;k++) 
        !          2372:        sum -= a[i][k]*a[k][j]; 
        !          2373:       a[i][j]=sum; 
        !          2374:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
        !          2375:        big=dum; 
        !          2376:        imax=i; 
        !          2377:       } 
        !          2378:     } 
        !          2379:     if (j != imax) { 
        !          2380:       for (k=1;k<=n;k++) { 
        !          2381:        dum=a[imax][k]; 
        !          2382:        a[imax][k]=a[j][k]; 
        !          2383:        a[j][k]=dum; 
        !          2384:       } 
        !          2385:       *d = -(*d); 
        !          2386:       vv[imax]=vv[j]; 
        !          2387:     } 
        !          2388:     indx[j]=imax; 
        !          2389:     if (a[j][j] == 0.0) a[j][j]=TINY; 
        !          2390:     if (j != n) { 
        !          2391:       dum=1.0/(a[j][j]); 
        !          2392:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
        !          2393:     } 
        !          2394:   } 
        !          2395:   free_vector(vv,1,n);  /* Doesn't work */
        !          2396: ;
        !          2397: } 
        !          2398: 
        !          2399: void lubksb(double **a, int n, int *indx, double b[]) 
        !          2400: { 
        !          2401:   int i,ii=0,ip,j; 
        !          2402:   double sum; 
        !          2403:  
        !          2404:   for (i=1;i<=n;i++) { 
        !          2405:     ip=indx[i]; 
        !          2406:     sum=b[ip]; 
        !          2407:     b[ip]=b[i]; 
        !          2408:     if (ii) 
        !          2409:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
        !          2410:     else if (sum) ii=i; 
        !          2411:     b[i]=sum; 
        !          2412:   } 
        !          2413:   for (i=n;i>=1;i--) { 
        !          2414:     sum=b[i]; 
        !          2415:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
        !          2416:     b[i]=sum/a[i][i]; 
        !          2417:   } 
        !          2418: } 
        !          2419: 
        !          2420: void pstamp(FILE *fichier)
        !          2421: {
        !          2422:   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
        !          2423: }
        !          2424: 
        !          2425: /************ Frequencies ********************/
        !          2426: 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[])
        !          2427: {  /* Some frequencies */
        !          2428:   
        !          2429:   int i, m, jk, k1,i1, j1, bool, z1,j;
        !          2430:   int first;
        !          2431:   double ***freq; /* Frequencies */
        !          2432:   double *pp, **prop;
        !          2433:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
        !          2434:   char fileresp[FILENAMELENGTH];
        !          2435:   
        !          2436:   pp=vector(1,nlstate);
        !          2437:   prop=matrix(1,nlstate,iagemin,iagemax+3);
        !          2438:   strcpy(fileresp,"p");
        !          2439:   strcat(fileresp,fileres);
        !          2440:   if((ficresp=fopen(fileresp,"w"))==NULL) {
        !          2441:     printf("Problem with prevalence resultfile: %s\n", fileresp);
        !          2442:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
        !          2443:     exit(0);
        !          2444:   }
        !          2445:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
        !          2446:   j1=0;
        !          2447:   
        !          2448:   j=cptcoveff;
        !          2449:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
        !          2450: 
        !          2451:   first=1;
        !          2452: 
        !          2453:   /* for(k1=1; k1<=j ; k1++){   /* Loop on covariates */
        !          2454:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ /* Now it is 2 */
        !          2455:   /*    j1++;
        !          2456: */
        !          2457:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
        !          2458:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
        !          2459:        scanf("%d", i);*/
        !          2460:       for (i=-5; i<=nlstate+ndeath; i++)  
        !          2461:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
        !          2462:          for(m=iagemin; m <= iagemax+3; m++)
        !          2463:            freq[i][jk][m]=0;
        !          2464:       
        !          2465:       for (i=1; i<=nlstate; i++)  
        !          2466:        for(m=iagemin; m <= iagemax+3; m++)
        !          2467:          prop[i][m]=0;
        !          2468:       
        !          2469:       dateintsum=0;
        !          2470:       k2cpt=0;
        !          2471:       for (i=1; i<=imx; i++) {
        !          2472:        bool=1;
        !          2473:        if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
        !          2474:          for (z1=1; z1<=cptcoveff; z1++)       
        !          2475:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
        !          2476:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
        !          2477:               bool=0;
        !          2478:               /* 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", 
        !          2479:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
        !          2480:                 j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
        !          2481:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
        !          2482:             } 
        !          2483:        }
        !          2484:  
        !          2485:        if (bool==1){
        !          2486:          for(m=firstpass; m<=lastpass; m++){
        !          2487:            k2=anint[m][i]+(mint[m][i]/12.);
        !          2488:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
        !          2489:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
        !          2490:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
        !          2491:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
        !          2492:              if (m<lastpass) {
        !          2493:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
        !          2494:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
        !          2495:              }
        !          2496:              
        !          2497:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
        !          2498:                dateintsum=dateintsum+k2;
        !          2499:                k2cpt++;
        !          2500:              }
        !          2501:              /*}*/
        !          2502:          }
        !          2503:        }
        !          2504:       } /* end i */
        !          2505:        
        !          2506:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
        !          2507:       pstamp(ficresp);
        !          2508:       if  (cptcovn>0) {
        !          2509:        fprintf(ficresp, "\n#********** Variable "); 
        !          2510:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
        !          2511:        fprintf(ficresp, "**********\n#");
        !          2512:        fprintf(ficlog, "\n#********** Variable "); 
        !          2513:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
        !          2514:        fprintf(ficlog, "**********\n#");
        !          2515:       }
        !          2516:       for(i=1; i<=nlstate;i++) 
        !          2517:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
        !          2518:       fprintf(ficresp, "\n");
        !          2519:       
        !          2520:       for(i=iagemin; i <= iagemax+3; i++){
        !          2521:        if(i==iagemax+3){
        !          2522:          fprintf(ficlog,"Total");
        !          2523:        }else{
        !          2524:          if(first==1){
        !          2525:            first=0;
        !          2526:            printf("See log file for details...\n");
        !          2527:          }
        !          2528:          fprintf(ficlog,"Age %d", i);
        !          2529:        }
        !          2530:        for(jk=1; jk <=nlstate ; jk++){
        !          2531:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
        !          2532:            pp[jk] += freq[jk][m][i]; 
        !          2533:        }
        !          2534:        for(jk=1; jk <=nlstate ; jk++){
        !          2535:          for(m=-1, pos=0; m <=0 ; m++)
        !          2536:            pos += freq[jk][m][i];
        !          2537:          if(pp[jk]>=1.e-10){
        !          2538:            if(first==1){
        !          2539:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
        !          2540:            }
        !          2541:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
        !          2542:          }else{
        !          2543:            if(first==1)
        !          2544:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
        !          2545:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
        !          2546:          }
        !          2547:        }
        !          2548: 
        !          2549:        for(jk=1; jk <=nlstate ; jk++){
        !          2550:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
        !          2551:            pp[jk] += freq[jk][m][i];
        !          2552:        }       
        !          2553:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
        !          2554:          pos += pp[jk];
        !          2555:          posprop += prop[jk][i];
        !          2556:        }
        !          2557:        for(jk=1; jk <=nlstate ; jk++){
        !          2558:          if(pos>=1.e-5){
        !          2559:            if(first==1)
        !          2560:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
        !          2561:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
        !          2562:          }else{
        !          2563:            if(first==1)
        !          2564:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
        !          2565:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
        !          2566:          }
        !          2567:          if( i <= iagemax){
        !          2568:            if(pos>=1.e-5){
        !          2569:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
        !          2570:              /*probs[i][jk][j1]= pp[jk]/pos;*/
        !          2571:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
        !          2572:            }
        !          2573:            else
        !          2574:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
        !          2575:          }
        !          2576:        }
        !          2577:        
        !          2578:        for(jk=-1; jk <=nlstate+ndeath; jk++)
        !          2579:          for(m=-1; m <=nlstate+ndeath; m++)
        !          2580:            if(freq[jk][m][i] !=0 ) {
        !          2581:            if(first==1)
        !          2582:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
        !          2583:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
        !          2584:            }
        !          2585:        if(i <= iagemax)
        !          2586:          fprintf(ficresp,"\n");
        !          2587:        if(first==1)
        !          2588:          printf("Others in log...\n");
        !          2589:        fprintf(ficlog,"\n");
        !          2590:       }
        !          2591:       /*}*/
        !          2592:   }
        !          2593:   dateintmean=dateintsum/k2cpt; 
        !          2594:  
        !          2595:   fclose(ficresp);
        !          2596:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
        !          2597:   free_vector(pp,1,nlstate);
        !          2598:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
        !          2599:   /* End of Freq */
        !          2600: }
        !          2601: 
        !          2602: /************ Prevalence ********************/
        !          2603: 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)
        !          2604: {  
        !          2605:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
        !          2606:      in each health status at the date of interview (if between dateprev1 and dateprev2).
        !          2607:      We still use firstpass and lastpass as another selection.
        !          2608:   */
        !          2609:  
        !          2610:   int i, m, jk, k1, i1, j1, bool, z1,j;
        !          2611:   double ***freq; /* Frequencies */
        !          2612:   double *pp, **prop;
        !          2613:   double pos,posprop; 
        !          2614:   double  y2; /* in fractional years */
        !          2615:   int iagemin, iagemax;
        !          2616:   int first; /** to stop verbosity which is redirected to log file */
        !          2617: 
        !          2618:   iagemin= (int) agemin;
        !          2619:   iagemax= (int) agemax;
        !          2620:   /*pp=vector(1,nlstate);*/
        !          2621:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
        !          2622:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
        !          2623:   j1=0;
        !          2624:   
        !          2625:   /*j=cptcoveff;*/
        !          2626:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
        !          2627:   
        !          2628:   first=1;
        !          2629:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
        !          2630:     /*for(i1=1; i1<=ncodemax[k1];i1++){
        !          2631:       j1++;*/
        !          2632:       
        !          2633:       for (i=1; i<=nlstate; i++)  
        !          2634:        for(m=iagemin; m <= iagemax+3; m++)
        !          2635:          prop[i][m]=0.0;
        !          2636:      
        !          2637:       for (i=1; i<=imx; i++) { /* Each individual */
        !          2638:        bool=1;
        !          2639:        if  (cptcovn>0) {
        !          2640:          for (z1=1; z1<=cptcoveff; z1++) 
        !          2641:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
        !          2642:              bool=0;
        !          2643:        } 
        !          2644:        if (bool==1) { 
        !          2645:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
        !          2646:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
        !          2647:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
        !          2648:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
        !          2649:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
        !          2650:              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); 
        !          2651:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
        !          2652:                /*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]]);*/
        !          2653:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
        !          2654:                prop[s[m][i]][iagemax+3] += weight[i]; 
        !          2655:              } 
        !          2656:            }
        !          2657:          } /* end selection of waves */
        !          2658:        }
        !          2659:       }
        !          2660:       for(i=iagemin; i <= iagemax+3; i++){  
        !          2661:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
        !          2662:          posprop += prop[jk][i]; 
        !          2663:        } 
        !          2664:        
        !          2665:        for(jk=1; jk <=nlstate ; jk++){     
        !          2666:          if( i <=  iagemax){ 
        !          2667:            if(posprop>=1.e-5){ 
        !          2668:              probs[i][jk][j1]= prop[jk][i]/posprop;
        !          2669:            } else{
        !          2670:              if(first==1){
        !          2671:                first=0;
        !          2672:                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]);
        !          2673:              }
        !          2674:            }
        !          2675:          } 
        !          2676:        }/* end jk */ 
        !          2677:       }/* end i */ 
        !          2678:     /*} *//* end i1 */
        !          2679:   } /* end j1 */
        !          2680:   
        !          2681:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
        !          2682:   /*free_vector(pp,1,nlstate);*/
        !          2683:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
        !          2684: }  /* End of prevalence */
        !          2685: 
        !          2686: /************* Waves Concatenation ***************/
        !          2687: 
        !          2688: 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)
        !          2689: {
        !          2690:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
        !          2691:      Death is a valid wave (if date is known).
        !          2692:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
        !          2693:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
        !          2694:      and mw[mi+1][i]. dh depends on stepm.
        !          2695:      */
        !          2696: 
        !          2697:   int i, mi, m;
        !          2698:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
        !          2699:      double sum=0., jmean=0.;*/
        !          2700:   int first;
        !          2701:   int j, k=0,jk, ju, jl;
        !          2702:   double sum=0.;
        !          2703:   first=0;
        !          2704:   jmin=1e+5;
        !          2705:   jmax=-1;
        !          2706:   jmean=0.;
        !          2707:   for(i=1; i<=imx; i++){
        !          2708:     mi=0;
        !          2709:     m=firstpass;
        !          2710:     while(s[m][i] <= nlstate){
        !          2711:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
        !          2712:        mw[++mi][i]=m;
        !          2713:       if(m >=lastpass)
        !          2714:        break;
        !          2715:       else
        !          2716:        m++;
        !          2717:     }/* end while */
        !          2718:     if (s[m][i] > nlstate){
        !          2719:       mi++;    /* Death is another wave */
        !          2720:       /* if(mi==0)  never been interviewed correctly before death */
        !          2721:         /* Only death is a correct wave */
        !          2722:       mw[mi][i]=m;
        !          2723:     }
        !          2724: 
        !          2725:     wav[i]=mi;
        !          2726:     if(mi==0){
        !          2727:       nbwarn++;
        !          2728:       if(first==0){
        !          2729:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
        !          2730:        first=1;
        !          2731:       }
        !          2732:       if(first==1){
        !          2733:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
        !          2734:       }
        !          2735:     } /* end mi==0 */
        !          2736:   } /* End individuals */
        !          2737: 
        !          2738:   for(i=1; i<=imx; i++){
        !          2739:     for(mi=1; mi<wav[i];mi++){
        !          2740:       if (stepm <=0)
        !          2741:        dh[mi][i]=1;
        !          2742:       else{
        !          2743:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
        !          2744:          if (agedc[i] < 2*AGESUP) {
        !          2745:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
        !          2746:            if(j==0) j=1;  /* Survives at least one month after exam */
        !          2747:            else if(j<0){
        !          2748:              nberr++;
        !          2749:              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]);
        !          2750:              j=1; /* Temporary Dangerous patch */
        !          2751:              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);
        !          2752:              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]);
        !          2753:              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);
        !          2754:            }
        !          2755:            k=k+1;
        !          2756:            if (j >= jmax){
        !          2757:              jmax=j;
        !          2758:              ijmax=i;
        !          2759:            }
        !          2760:            if (j <= jmin){
        !          2761:              jmin=j;
        !          2762:              ijmin=i;
        !          2763:            }
        !          2764:            sum=sum+j;
        !          2765:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
        !          2766:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
        !          2767:          }
        !          2768:        }
        !          2769:        else{
        !          2770:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
        !          2771: /*       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]); */
        !          2772: 
        !          2773:          k=k+1;
        !          2774:          if (j >= jmax) {
        !          2775:            jmax=j;
        !          2776:            ijmax=i;
        !          2777:          }
        !          2778:          else if (j <= jmin){
        !          2779:            jmin=j;
        !          2780:            ijmin=i;
        !          2781:          }
        !          2782:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
        !          2783:          /*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]);*/
        !          2784:          if(j<0){
        !          2785:            nberr++;
        !          2786:            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]);
        !          2787:            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]);
        !          2788:          }
        !          2789:          sum=sum+j;
        !          2790:        }
        !          2791:        jk= j/stepm;
        !          2792:        jl= j -jk*stepm;
        !          2793:        ju= j -(jk+1)*stepm;
        !          2794:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
        !          2795:          if(jl==0){
        !          2796:            dh[mi][i]=jk;
        !          2797:            bh[mi][i]=0;
        !          2798:          }else{ /* We want a negative bias in order to only have interpolation ie
        !          2799:                  * to avoid the price of an extra matrix product in likelihood */
        !          2800:            dh[mi][i]=jk+1;
        !          2801:            bh[mi][i]=ju;
        !          2802:          }
        !          2803:        }else{
        !          2804:          if(jl <= -ju){
        !          2805:            dh[mi][i]=jk;
        !          2806:            bh[mi][i]=jl;       /* bias is positive if real duration
        !          2807:                                 * is higher than the multiple of stepm and negative otherwise.
        !          2808:                                 */
        !          2809:          }
        !          2810:          else{
        !          2811:            dh[mi][i]=jk+1;
        !          2812:            bh[mi][i]=ju;
        !          2813:          }
        !          2814:          if(dh[mi][i]==0){
        !          2815:            dh[mi][i]=1; /* At least one step */
        !          2816:            bh[mi][i]=ju; /* At least one step */
        !          2817:            /*  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);*/
        !          2818:          }
        !          2819:        } /* end if mle */
        !          2820:       }
        !          2821:     } /* end wave */
        !          2822:   }
        !          2823:   jmean=sum/k;
        !          2824:   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);
        !          2825:   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);
        !          2826:  }
        !          2827: 
        !          2828: /*********** Tricode ****************************/
        !          2829: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
        !          2830: {
        !          2831:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
        !          2832:   /*     Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
        !          2833:   /* Boring subroutine which should only output nbcode[Tvar[j]][k]
        !          2834:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
        !          2835:   /* nbcode[Tvar[j]][1]= 
        !          2836:   */
        !          2837: 
        !          2838:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
        !          2839:   int modmaxcovj=0; /* Modality max of covariates j */
        !          2840:   int cptcode=0; /* Modality max of covariates j */
        !          2841:   int modmincovj=0; /* Modality min of covariates j */
        !          2842: 
        !          2843: 
        !          2844:   cptcoveff=0; 
        !          2845:  
        !          2846:   for (k=-1; k < maxncov; k++) Ndum[k]=0;
        !          2847:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
        !          2848: 
        !          2849:   /* Loop on covariates without age and products */
        !          2850:   for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
        !          2851:     for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the 
        !          2852:                               modality of this covariate Vj*/ 
        !          2853:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
        !          2854:                                    * If product of Vn*Vm, still boolean *:
        !          2855:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
        !          2856:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
        !          2857:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
        !          2858:                                      modality of the nth covariate of individual i. */
        !          2859:       if (ij > modmaxcovj)
        !          2860:         modmaxcovj=ij; 
        !          2861:       else if (ij < modmincovj) 
        !          2862:        modmincovj=ij; 
        !          2863:       if ((ij < -1) && (ij > NCOVMAX)){
        !          2864:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
        !          2865:        exit(1);
        !          2866:       }else
        !          2867:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
        !          2868:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
        !          2869:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
        !          2870:       /* getting the maximum value of the modality of the covariate
        !          2871:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
        !          2872:         female is 1, then modmaxcovj=1.*/
        !          2873:     }
        !          2874:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
        !          2875:     cptcode=modmaxcovj;
        !          2876:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
        !          2877:    /*for (i=0; i<=cptcode; i++) {*/
        !          2878:     for (i=modmincovj;  i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
        !          2879:       printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
        !          2880:       if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
        !          2881:        ncodemax[j]++;  /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
        !          2882:       }
        !          2883:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
        !          2884:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
        !          2885:     } /* Ndum[-1] number of undefined modalities */
        !          2886: 
        !          2887:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
        !          2888:     /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
        !          2889:     /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
        !          2890:        modmincovj=3; modmaxcovj = 7;
        !          2891:        There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
        !          2892:        which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy 
        !          2893:        variables V1_1 and V1_2.
        !          2894:        nbcode[Tvar[j]][ij]=k;
        !          2895:        nbcode[Tvar[j]][1]=0;
        !          2896:        nbcode[Tvar[j]][2]=1;
        !          2897:        nbcode[Tvar[j]][3]=2;
        !          2898:     */
        !          2899:     ij=1; /* ij is similar to i but can jumps over null modalities */
        !          2900:     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
        !          2901:       for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
        !          2902:        /*recode from 0 */
        !          2903:        if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
        !          2904:          nbcode[Tvar[j]][ij]=k;  /* stores the modality in an array nbcode. 
        !          2905:                                     k is a modality. If we have model=V1+V1*sex 
        !          2906:                                     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
        !          2907:          ij++;
        !          2908:        }
        !          2909:        if (ij > ncodemax[j]) break; 
        !          2910:       }  /* end of loop on */
        !          2911:     } /* end of loop on modality */ 
        !          2912:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
        !          2913:   
        !          2914:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
        !          2915:   
        !          2916:   for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */ 
        !          2917:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
        !          2918:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
        !          2919:    Ndum[ij]++; 
        !          2920:  } 
        !          2921: 
        !          2922:  ij=1;
        !          2923:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
        !          2924:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
        !          2925:    if((Ndum[i]!=0) && (i<=ncovcol)){
        !          2926:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
        !          2927:      Tvaraff[ij]=i; /*For printing (unclear) */
        !          2928:      ij++;
        !          2929:    }else
        !          2930:        Tvaraff[ij]=0;
        !          2931:  }
        !          2932:  ij--;
        !          2933:  cptcoveff=ij; /*Number of total covariates*/
        !          2934: 
        !          2935: }
        !          2936: 
        !          2937: 
        !          2938: /*********** Health Expectancies ****************/
        !          2939: 
        !          2940: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
        !          2941: 
        !          2942: {
        !          2943:   /* Health expectancies, no variances */
        !          2944:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
        !          2945:   int nhstepma, nstepma; /* Decreasing with age */
        !          2946:   double age, agelim, hf;
        !          2947:   double ***p3mat;
        !          2948:   double eip;
        !          2949: 
        !          2950:   pstamp(ficreseij);
        !          2951:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
        !          2952:   fprintf(ficreseij,"# Age");
        !          2953:   for(i=1; i<=nlstate;i++){
        !          2954:     for(j=1; j<=nlstate;j++){
        !          2955:       fprintf(ficreseij," e%1d%1d ",i,j);
        !          2956:     }
        !          2957:     fprintf(ficreseij," e%1d. ",i);
        !          2958:   }
        !          2959:   fprintf(ficreseij,"\n");
        !          2960: 
        !          2961:   
        !          2962:   if(estepm < stepm){
        !          2963:     printf ("Problem %d lower than %d\n",estepm, stepm);
        !          2964:   }
        !          2965:   else  hstepm=estepm;   
        !          2966:   /* We compute the life expectancy from trapezoids spaced every estepm months
        !          2967:    * This is mainly to measure the difference between two models: for example
        !          2968:    * if stepm=24 months pijx are given only every 2 years and by summing them
        !          2969:    * we are calculating an estimate of the Life Expectancy assuming a linear 
        !          2970:    * progression in between and thus overestimating or underestimating according
        !          2971:    * to the curvature of the survival function. If, for the same date, we 
        !          2972:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
        !          2973:    * to compare the new estimate of Life expectancy with the same linear 
        !          2974:    * hypothesis. A more precise result, taking into account a more precise
        !          2975:    * curvature will be obtained if estepm is as small as stepm. */
        !          2976: 
        !          2977:   /* For example we decided to compute the life expectancy with the smallest unit */
        !          2978:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
        !          2979:      nhstepm is the number of hstepm from age to agelim 
        !          2980:      nstepm is the number of stepm from age to agelin. 
        !          2981:      Look at hpijx to understand the reason of that which relies in memory size
        !          2982:      and note for a fixed period like estepm months */
        !          2983:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
        !          2984:      survival function given by stepm (the optimization length). Unfortunately it
        !          2985:      means that if the survival funtion is printed only each two years of age and if
        !          2986:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
        !          2987:      results. So we changed our mind and took the option of the best precision.
        !          2988:   */
        !          2989:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
        !          2990: 
        !          2991:   agelim=AGESUP;
        !          2992:   /* If stepm=6 months */
        !          2993:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
        !          2994:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
        !          2995:     
        !          2996: /* nhstepm age range expressed in number of stepm */
        !          2997:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
        !          2998:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
        !          2999:   /* if (stepm >= YEARM) hstepm=1;*/
        !          3000:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
        !          3001:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          3002: 
        !          3003:   for (age=bage; age<=fage; age ++){ 
        !          3004:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
        !          3005:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
        !          3006:     /* if (stepm >= YEARM) hstepm=1;*/
        !          3007:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
        !          3008: 
        !          3009:     /* If stepm=6 months */
        !          3010:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
        !          3011:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
        !          3012:     
        !          3013:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
        !          3014:     
        !          3015:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
        !          3016:     
        !          3017:     printf("%d|",(int)age);fflush(stdout);
        !          3018:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
        !          3019:     
        !          3020:     /* Computing expectancies */
        !          3021:     for(i=1; i<=nlstate;i++)
        !          3022:       for(j=1; j<=nlstate;j++)
        !          3023:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
        !          3024:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
        !          3025:          
        !          3026:          /* 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]);*/
        !          3027: 
        !          3028:        }
        !          3029: 
        !          3030:     fprintf(ficreseij,"%3.0f",age );
        !          3031:     for(i=1; i<=nlstate;i++){
        !          3032:       eip=0;
        !          3033:       for(j=1; j<=nlstate;j++){
        !          3034:        eip +=eij[i][j][(int)age];
        !          3035:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
        !          3036:       }
        !          3037:       fprintf(ficreseij,"%9.4f", eip );
        !          3038:     }
        !          3039:     fprintf(ficreseij,"\n");
        !          3040:     
        !          3041:   }
        !          3042:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          3043:   printf("\n");
        !          3044:   fprintf(ficlog,"\n");
        !          3045:   
        !          3046: }
        !          3047: 
        !          3048: 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[] )
        !          3049: 
        !          3050: {
        !          3051:   /* Covariances of health expectancies eij and of total life expectancies according
        !          3052:    to initial status i, ei. .
        !          3053:   */
        !          3054:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
        !          3055:   int nhstepma, nstepma; /* Decreasing with age */
        !          3056:   double age, agelim, hf;
        !          3057:   double ***p3matp, ***p3matm, ***varhe;
        !          3058:   double **dnewm,**doldm;
        !          3059:   double *xp, *xm;
        !          3060:   double **gp, **gm;
        !          3061:   double ***gradg, ***trgradg;
        !          3062:   int theta;
        !          3063: 
        !          3064:   double eip, vip;
        !          3065: 
        !          3066:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
        !          3067:   xp=vector(1,npar);
        !          3068:   xm=vector(1,npar);
        !          3069:   dnewm=matrix(1,nlstate*nlstate,1,npar);
        !          3070:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
        !          3071:   
        !          3072:   pstamp(ficresstdeij);
        !          3073:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
        !          3074:   fprintf(ficresstdeij,"# Age");
        !          3075:   for(i=1; i<=nlstate;i++){
        !          3076:     for(j=1; j<=nlstate;j++)
        !          3077:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
        !          3078:     fprintf(ficresstdeij," e%1d. ",i);
        !          3079:   }
        !          3080:   fprintf(ficresstdeij,"\n");
        !          3081: 
        !          3082:   pstamp(ficrescveij);
        !          3083:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
        !          3084:   fprintf(ficrescveij,"# Age");
        !          3085:   for(i=1; i<=nlstate;i++)
        !          3086:     for(j=1; j<=nlstate;j++){
        !          3087:       cptj= (j-1)*nlstate+i;
        !          3088:       for(i2=1; i2<=nlstate;i2++)
        !          3089:        for(j2=1; j2<=nlstate;j2++){
        !          3090:          cptj2= (j2-1)*nlstate+i2;
        !          3091:          if(cptj2 <= cptj)
        !          3092:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
        !          3093:        }
        !          3094:     }
        !          3095:   fprintf(ficrescveij,"\n");
        !          3096:   
        !          3097:   if(estepm < stepm){
        !          3098:     printf ("Problem %d lower than %d\n",estepm, stepm);
        !          3099:   }
        !          3100:   else  hstepm=estepm;   
        !          3101:   /* We compute the life expectancy from trapezoids spaced every estepm months
        !          3102:    * This is mainly to measure the difference between two models: for example
        !          3103:    * if stepm=24 months pijx are given only every 2 years and by summing them
        !          3104:    * we are calculating an estimate of the Life Expectancy assuming a linear 
        !          3105:    * progression in between and thus overestimating or underestimating according
        !          3106:    * to the curvature of the survival function. If, for the same date, we 
        !          3107:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
        !          3108:    * to compare the new estimate of Life expectancy with the same linear 
        !          3109:    * hypothesis. A more precise result, taking into account a more precise
        !          3110:    * curvature will be obtained if estepm is as small as stepm. */
        !          3111: 
        !          3112:   /* For example we decided to compute the life expectancy with the smallest unit */
        !          3113:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
        !          3114:      nhstepm is the number of hstepm from age to agelim 
        !          3115:      nstepm is the number of stepm from age to agelin. 
        !          3116:      Look at hpijx to understand the reason of that which relies in memory size
        !          3117:      and note for a fixed period like estepm months */
        !          3118:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
        !          3119:      survival function given by stepm (the optimization length). Unfortunately it
        !          3120:      means that if the survival funtion is printed only each two years of age and if
        !          3121:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
        !          3122:      results. So we changed our mind and took the option of the best precision.
        !          3123:   */
        !          3124:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
        !          3125: 
        !          3126:   /* If stepm=6 months */
        !          3127:   /* nhstepm age range expressed in number of stepm */
        !          3128:   agelim=AGESUP;
        !          3129:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
        !          3130:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
        !          3131:   /* if (stepm >= YEARM) hstepm=1;*/
        !          3132:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
        !          3133:   
        !          3134:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          3135:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          3136:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
        !          3137:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
        !          3138:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
        !          3139:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
        !          3140: 
        !          3141:   for (age=bage; age<=fage; age ++){ 
        !          3142:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
        !          3143:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
        !          3144:     /* if (stepm >= YEARM) hstepm=1;*/
        !          3145:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
        !          3146: 
        !          3147:     /* If stepm=6 months */
        !          3148:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
        !          3149:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
        !          3150:     
        !          3151:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
        !          3152: 
        !          3153:     /* Computing  Variances of health expectancies */
        !          3154:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
        !          3155:        decrease memory allocation */
        !          3156:     for(theta=1; theta <=npar; theta++){
        !          3157:       for(i=1; i<=npar; i++){ 
        !          3158:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
        !          3159:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
        !          3160:       }
        !          3161:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
        !          3162:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
        !          3163:   
        !          3164:       for(j=1; j<= nlstate; j++){
        !          3165:        for(i=1; i<=nlstate; i++){
        !          3166:          for(h=0; h<=nhstepm-1; h++){
        !          3167:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
        !          3168:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
        !          3169:          }
        !          3170:        }
        !          3171:       }
        !          3172:      
        !          3173:       for(ij=1; ij<= nlstate*nlstate; ij++)
        !          3174:        for(h=0; h<=nhstepm-1; h++){
        !          3175:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
        !          3176:        }
        !          3177:     }/* End theta */
        !          3178:     
        !          3179:     
        !          3180:     for(h=0; h<=nhstepm-1; h++)
        !          3181:       for(j=1; j<=nlstate*nlstate;j++)
        !          3182:        for(theta=1; theta <=npar; theta++)
        !          3183:          trgradg[h][j][theta]=gradg[h][theta][j];
        !          3184:     
        !          3185: 
        !          3186:      for(ij=1;ij<=nlstate*nlstate;ij++)
        !          3187:       for(ji=1;ji<=nlstate*nlstate;ji++)
        !          3188:        varhe[ij][ji][(int)age] =0.;
        !          3189: 
        !          3190:      printf("%d|",(int)age);fflush(stdout);
        !          3191:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
        !          3192:      for(h=0;h<=nhstepm-1;h++){
        !          3193:       for(k=0;k<=nhstepm-1;k++){
        !          3194:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
        !          3195:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
        !          3196:        for(ij=1;ij<=nlstate*nlstate;ij++)
        !          3197:          for(ji=1;ji<=nlstate*nlstate;ji++)
        !          3198:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
        !          3199:       }
        !          3200:     }
        !          3201: 
        !          3202:     /* Computing expectancies */
        !          3203:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
        !          3204:     for(i=1; i<=nlstate;i++)
        !          3205:       for(j=1; j<=nlstate;j++)
        !          3206:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
        !          3207:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
        !          3208:          
        !          3209:          /* 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]);*/
        !          3210: 
        !          3211:        }
        !          3212: 
        !          3213:     fprintf(ficresstdeij,"%3.0f",age );
        !          3214:     for(i=1; i<=nlstate;i++){
        !          3215:       eip=0.;
        !          3216:       vip=0.;
        !          3217:       for(j=1; j<=nlstate;j++){
        !          3218:        eip += eij[i][j][(int)age];
        !          3219:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
        !          3220:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
        !          3221:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
        !          3222:       }
        !          3223:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
        !          3224:     }
        !          3225:     fprintf(ficresstdeij,"\n");
        !          3226: 
        !          3227:     fprintf(ficrescveij,"%3.0f",age );
        !          3228:     for(i=1; i<=nlstate;i++)
        !          3229:       for(j=1; j<=nlstate;j++){
        !          3230:        cptj= (j-1)*nlstate+i;
        !          3231:        for(i2=1; i2<=nlstate;i2++)
        !          3232:          for(j2=1; j2<=nlstate;j2++){
        !          3233:            cptj2= (j2-1)*nlstate+i2;
        !          3234:            if(cptj2 <= cptj)
        !          3235:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
        !          3236:          }
        !          3237:       }
        !          3238:     fprintf(ficrescveij,"\n");
        !          3239:    
        !          3240:   }
        !          3241:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
        !          3242:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
        !          3243:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
        !          3244:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
        !          3245:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          3246:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          3247:   printf("\n");
        !          3248:   fprintf(ficlog,"\n");
        !          3249: 
        !          3250:   free_vector(xm,1,npar);
        !          3251:   free_vector(xp,1,npar);
        !          3252:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
        !          3253:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
        !          3254:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
        !          3255: }
        !          3256: 
        !          3257: /************ Variance ******************/
        !          3258: 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[])
        !          3259: {
        !          3260:   /* Variance of health expectancies */
        !          3261:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
        !          3262:   /* double **newm;*/
        !          3263:   double **dnewm,**doldm;
        !          3264:   double **dnewmp,**doldmp;
        !          3265:   int i, j, nhstepm, hstepm, h, nstepm ;
        !          3266:   int k, cptcode;
        !          3267:   double *xp;
        !          3268:   double **gp, **gm;  /* for var eij */
        !          3269:   double ***gradg, ***trgradg; /*for var eij */
        !          3270:   double **gradgp, **trgradgp; /* for var p point j */
        !          3271:   double *gpp, *gmp; /* for var p point j */
        !          3272:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
        !          3273:   double ***p3mat;
        !          3274:   double age,agelim, hf;
        !          3275:   double ***mobaverage;
        !          3276:   int theta;
        !          3277:   char digit[4];
        !          3278:   char digitp[25];
        !          3279: 
        !          3280:   char fileresprobmorprev[FILENAMELENGTH];
        !          3281: 
        !          3282:   if(popbased==1){
        !          3283:     if(mobilav!=0)
        !          3284:       strcpy(digitp,"-populbased-mobilav-");
        !          3285:     else strcpy(digitp,"-populbased-nomobil-");
        !          3286:   }
        !          3287:   else 
        !          3288:     strcpy(digitp,"-stablbased-");
        !          3289: 
        !          3290:   if (mobilav!=0) {
        !          3291:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
        !          3292:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
        !          3293:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
        !          3294:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
        !          3295:     }
        !          3296:   }
        !          3297: 
        !          3298:   strcpy(fileresprobmorprev,"prmorprev"); 
        !          3299:   sprintf(digit,"%-d",ij);
        !          3300:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
        !          3301:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
        !          3302:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
        !          3303:   strcat(fileresprobmorprev,fileres);
        !          3304:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
        !          3305:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
        !          3306:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
        !          3307:   }
        !          3308:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
        !          3309:  
        !          3310:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
        !          3311:   pstamp(ficresprobmorprev);
        !          3312:   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);
        !          3313:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
        !          3314:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
        !          3315:     fprintf(ficresprobmorprev," p.%-d SE",j);
        !          3316:     for(i=1; i<=nlstate;i++)
        !          3317:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
        !          3318:   }  
        !          3319:   fprintf(ficresprobmorprev,"\n");
        !          3320:   fprintf(ficgp,"\n# Routine varevsij");
        !          3321:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
        !          3322:   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");
        !          3323:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
        !          3324: /*   } */
        !          3325:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
        !          3326:   pstamp(ficresvij);
        !          3327:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
        !          3328:   if(popbased==1)
        !          3329:     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);
        !          3330:   else
        !          3331:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
        !          3332:   fprintf(ficresvij,"# Age");
        !          3333:   for(i=1; i<=nlstate;i++)
        !          3334:     for(j=1; j<=nlstate;j++)
        !          3335:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
        !          3336:   fprintf(ficresvij,"\n");
        !          3337: 
        !          3338:   xp=vector(1,npar);
        !          3339:   dnewm=matrix(1,nlstate,1,npar);
        !          3340:   doldm=matrix(1,nlstate,1,nlstate);
        !          3341:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
        !          3342:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
        !          3343: 
        !          3344:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
        !          3345:   gpp=vector(nlstate+1,nlstate+ndeath);
        !          3346:   gmp=vector(nlstate+1,nlstate+ndeath);
        !          3347:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
        !          3348:   
        !          3349:   if(estepm < stepm){
        !          3350:     printf ("Problem %d lower than %d\n",estepm, stepm);
        !          3351:   }
        !          3352:   else  hstepm=estepm;   
        !          3353:   /* For example we decided to compute the life expectancy with the smallest unit */
        !          3354:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
        !          3355:      nhstepm is the number of hstepm from age to agelim 
        !          3356:      nstepm is the number of stepm from age to agelin. 
        !          3357:      Look at function hpijx to understand why (it is linked to memory size questions) */
        !          3358:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
        !          3359:      survival function given by stepm (the optimization length). Unfortunately it
        !          3360:      means that if the survival funtion is printed every two years of age and if
        !          3361:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
        !          3362:      results. So we changed our mind and took the option of the best precision.
        !          3363:   */
        !          3364:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
        !          3365:   agelim = AGESUP;
        !          3366:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
        !          3367:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
        !          3368:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
        !          3369:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          3370:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
        !          3371:     gp=matrix(0,nhstepm,1,nlstate);
        !          3372:     gm=matrix(0,nhstepm,1,nlstate);
        !          3373: 
        !          3374: 
        !          3375:     for(theta=1; theta <=npar; theta++){
        !          3376:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
        !          3377:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
        !          3378:       }
        !          3379:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
        !          3380:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
        !          3381: 
        !          3382:       if (popbased==1) {
        !          3383:        if(mobilav ==0){
        !          3384:          for(i=1; i<=nlstate;i++)
        !          3385:            prlim[i][i]=probs[(int)age][i][ij];
        !          3386:        }else{ /* mobilav */ 
        !          3387:          for(i=1; i<=nlstate;i++)
        !          3388:            prlim[i][i]=mobaverage[(int)age][i][ij];
        !          3389:        }
        !          3390:       }
        !          3391:   
        !          3392:       for(j=1; j<= nlstate; j++){
        !          3393:        for(h=0; h<=nhstepm; h++){
        !          3394:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
        !          3395:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
        !          3396:        }
        !          3397:       }
        !          3398:       /* This for computing probability of death (h=1 means
        !          3399:          computed over hstepm matrices product = hstepm*stepm months) 
        !          3400:          as a weighted average of prlim.
        !          3401:       */
        !          3402:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
        !          3403:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
        !          3404:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
        !          3405:       }    
        !          3406:       /* end probability of death */
        !          3407: 
        !          3408:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
        !          3409:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
        !          3410:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
        !          3411:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
        !          3412:  
        !          3413:       if (popbased==1) {
        !          3414:        if(mobilav ==0){
        !          3415:          for(i=1; i<=nlstate;i++)
        !          3416:            prlim[i][i]=probs[(int)age][i][ij];
        !          3417:        }else{ /* mobilav */ 
        !          3418:          for(i=1; i<=nlstate;i++)
        !          3419:            prlim[i][i]=mobaverage[(int)age][i][ij];
        !          3420:        }
        !          3421:       }
        !          3422: 
        !          3423:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
        !          3424:        for(h=0; h<=nhstepm; h++){
        !          3425:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
        !          3426:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
        !          3427:        }
        !          3428:       }
        !          3429:       /* This for computing probability of death (h=1 means
        !          3430:          computed over hstepm matrices product = hstepm*stepm months) 
        !          3431:          as a weighted average of prlim.
        !          3432:       */
        !          3433:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
        !          3434:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
        !          3435:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
        !          3436:       }    
        !          3437:       /* end probability of death */
        !          3438: 
        !          3439:       for(j=1; j<= nlstate; j++) /* vareij */
        !          3440:        for(h=0; h<=nhstepm; h++){
        !          3441:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
        !          3442:        }
        !          3443: 
        !          3444:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
        !          3445:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
        !          3446:       }
        !          3447: 
        !          3448:     } /* End theta */
        !          3449: 
        !          3450:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
        !          3451: 
        !          3452:     for(h=0; h<=nhstepm; h++) /* veij */
        !          3453:       for(j=1; j<=nlstate;j++)
        !          3454:        for(theta=1; theta <=npar; theta++)
        !          3455:          trgradg[h][j][theta]=gradg[h][theta][j];
        !          3456: 
        !          3457:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
        !          3458:       for(theta=1; theta <=npar; theta++)
        !          3459:        trgradgp[j][theta]=gradgp[theta][j];
        !          3460:   
        !          3461: 
        !          3462:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
        !          3463:     for(i=1;i<=nlstate;i++)
        !          3464:       for(j=1;j<=nlstate;j++)
        !          3465:        vareij[i][j][(int)age] =0.;
        !          3466: 
        !          3467:     for(h=0;h<=nhstepm;h++){
        !          3468:       for(k=0;k<=nhstepm;k++){
        !          3469:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
        !          3470:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
        !          3471:        for(i=1;i<=nlstate;i++)
        !          3472:          for(j=1;j<=nlstate;j++)
        !          3473:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
        !          3474:       }
        !          3475:     }
        !          3476:   
        !          3477:     /* pptj */
        !          3478:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
        !          3479:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
        !          3480:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
        !          3481:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
        !          3482:        varppt[j][i]=doldmp[j][i];
        !          3483:     /* end ppptj */
        !          3484:     /*  x centered again */
        !          3485:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
        !          3486:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
        !          3487:  
        !          3488:     if (popbased==1) {
        !          3489:       if(mobilav ==0){
        !          3490:        for(i=1; i<=nlstate;i++)
        !          3491:          prlim[i][i]=probs[(int)age][i][ij];
        !          3492:       }else{ /* mobilav */ 
        !          3493:        for(i=1; i<=nlstate;i++)
        !          3494:          prlim[i][i]=mobaverage[(int)age][i][ij];
        !          3495:       }
        !          3496:     }
        !          3497:              
        !          3498:     /* This for computing probability of death (h=1 means
        !          3499:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
        !          3500:        as a weighted average of prlim.
        !          3501:     */
        !          3502:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
        !          3503:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
        !          3504:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
        !          3505:     }    
        !          3506:     /* end probability of death */
        !          3507: 
        !          3508:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
        !          3509:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
        !          3510:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
        !          3511:       for(i=1; i<=nlstate;i++){
        !          3512:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
        !          3513:       }
        !          3514:     } 
        !          3515:     fprintf(ficresprobmorprev,"\n");
        !          3516: 
        !          3517:     fprintf(ficresvij,"%.0f ",age );
        !          3518:     for(i=1; i<=nlstate;i++)
        !          3519:       for(j=1; j<=nlstate;j++){
        !          3520:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
        !          3521:       }
        !          3522:     fprintf(ficresvij,"\n");
        !          3523:     free_matrix(gp,0,nhstepm,1,nlstate);
        !          3524:     free_matrix(gm,0,nhstepm,1,nlstate);
        !          3525:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
        !          3526:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
        !          3527:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          3528:   } /* End age */
        !          3529:   free_vector(gpp,nlstate+1,nlstate+ndeath);
        !          3530:   free_vector(gmp,nlstate+1,nlstate+ndeath);
        !          3531:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
        !          3532:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
        !          3533:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
        !          3534:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
        !          3535:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
        !          3536: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
        !          3537: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
        !          3538: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
        !          3539:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
        !          3540:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
        !          3541:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
        !          3542:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
        !          3543:   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);
        !          3544:   /*  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);
        !          3545: */
        !          3546: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
        !          3547:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
        !          3548: 
        !          3549:   free_vector(xp,1,npar);
        !          3550:   free_matrix(doldm,1,nlstate,1,nlstate);
        !          3551:   free_matrix(dnewm,1,nlstate,1,npar);
        !          3552:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
        !          3553:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
        !          3554:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
        !          3555:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
        !          3556:   fclose(ficresprobmorprev);
        !          3557:   fflush(ficgp);
        !          3558:   fflush(fichtm); 
        !          3559: }  /* end varevsij */
        !          3560: 
        !          3561: /************ Variance of prevlim ******************/
        !          3562: 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[])
        !          3563: {
        !          3564:   /* Variance of prevalence limit */
        !          3565:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
        !          3566:   double **newm;
        !          3567:   double **dnewm,**doldm;
        !          3568:   int i, j, nhstepm, hstepm;
        !          3569:   int k, cptcode;
        !          3570:   double *xp;
        !          3571:   double *gp, *gm;
        !          3572:   double **gradg, **trgradg;
        !          3573:   double age,agelim;
        !          3574:   int theta;
        !          3575:   
        !          3576:   pstamp(ficresvpl);
        !          3577:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
        !          3578:   fprintf(ficresvpl,"# Age");
        !          3579:   for(i=1; i<=nlstate;i++)
        !          3580:       fprintf(ficresvpl," %1d-%1d",i,i);
        !          3581:   fprintf(ficresvpl,"\n");
        !          3582: 
        !          3583:   xp=vector(1,npar);
        !          3584:   dnewm=matrix(1,nlstate,1,npar);
        !          3585:   doldm=matrix(1,nlstate,1,nlstate);
        !          3586:   
        !          3587:   hstepm=1*YEARM; /* Every year of age */
        !          3588:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
        !          3589:   agelim = AGESUP;
        !          3590:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
        !          3591:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
        !          3592:     if (stepm >= YEARM) hstepm=1;
        !          3593:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
        !          3594:     gradg=matrix(1,npar,1,nlstate);
        !          3595:     gp=vector(1,nlstate);
        !          3596:     gm=vector(1,nlstate);
        !          3597: 
        !          3598:     for(theta=1; theta <=npar; theta++){
        !          3599:       for(i=1; i<=npar; i++){ /* Computes gradient */
        !          3600:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
        !          3601:       }
        !          3602:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
        !          3603:       for(i=1;i<=nlstate;i++)
        !          3604:        gp[i] = prlim[i][i];
        !          3605:     
        !          3606:       for(i=1; i<=npar; i++) /* Computes gradient */
        !          3607:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
        !          3608:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
        !          3609:       for(i=1;i<=nlstate;i++)
        !          3610:        gm[i] = prlim[i][i];
        !          3611: 
        !          3612:       for(i=1;i<=nlstate;i++)
        !          3613:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
        !          3614:     } /* End theta */
        !          3615: 
        !          3616:     trgradg =matrix(1,nlstate,1,npar);
        !          3617: 
        !          3618:     for(j=1; j<=nlstate;j++)
        !          3619:       for(theta=1; theta <=npar; theta++)
        !          3620:        trgradg[j][theta]=gradg[theta][j];
        !          3621: 
        !          3622:     for(i=1;i<=nlstate;i++)
        !          3623:       varpl[i][(int)age] =0.;
        !          3624:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
        !          3625:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
        !          3626:     for(i=1;i<=nlstate;i++)
        !          3627:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
        !          3628: 
        !          3629:     fprintf(ficresvpl,"%.0f ",age );
        !          3630:     for(i=1; i<=nlstate;i++)
        !          3631:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
        !          3632:     fprintf(ficresvpl,"\n");
        !          3633:     free_vector(gp,1,nlstate);
        !          3634:     free_vector(gm,1,nlstate);
        !          3635:     free_matrix(gradg,1,npar,1,nlstate);
        !          3636:     free_matrix(trgradg,1,nlstate,1,npar);
        !          3637:   } /* End age */
        !          3638: 
        !          3639:   free_vector(xp,1,npar);
        !          3640:   free_matrix(doldm,1,nlstate,1,npar);
        !          3641:   free_matrix(dnewm,1,nlstate,1,nlstate);
        !          3642: 
        !          3643: }
        !          3644: 
        !          3645: /************ Variance of one-step probabilities  ******************/
        !          3646: 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[])
        !          3647: {
        !          3648:   int i, j=0,  i1, k1, l1, t, tj;
        !          3649:   int k2, l2, j1,  z1;
        !          3650:   int k=0,l, cptcode;
        !          3651:   int first=1, first1, first2;
        !          3652:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
        !          3653:   double **dnewm,**doldm;
        !          3654:   double *xp;
        !          3655:   double *gp, *gm;
        !          3656:   double **gradg, **trgradg;
        !          3657:   double **mu;
        !          3658:   double age,agelim, cov[NCOVMAX+1];
        !          3659:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
        !          3660:   int theta;
        !          3661:   char fileresprob[FILENAMELENGTH];
        !          3662:   char fileresprobcov[FILENAMELENGTH];
        !          3663:   char fileresprobcor[FILENAMELENGTH];
        !          3664:   double ***varpij;
        !          3665: 
        !          3666:   strcpy(fileresprob,"prob"); 
        !          3667:   strcat(fileresprob,fileres);
        !          3668:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
        !          3669:     printf("Problem with resultfile: %s\n", fileresprob);
        !          3670:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
        !          3671:   }
        !          3672:   strcpy(fileresprobcov,"probcov"); 
        !          3673:   strcat(fileresprobcov,fileres);
        !          3674:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
        !          3675:     printf("Problem with resultfile: %s\n", fileresprobcov);
        !          3676:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
        !          3677:   }
        !          3678:   strcpy(fileresprobcor,"probcor"); 
        !          3679:   strcat(fileresprobcor,fileres);
        !          3680:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
        !          3681:     printf("Problem with resultfile: %s\n", fileresprobcor);
        !          3682:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
        !          3683:   }
        !          3684:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
        !          3685:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
        !          3686:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
        !          3687:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
        !          3688:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
        !          3689:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
        !          3690:   pstamp(ficresprob);
        !          3691:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
        !          3692:   fprintf(ficresprob,"# Age");
        !          3693:   pstamp(ficresprobcov);
        !          3694:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
        !          3695:   fprintf(ficresprobcov,"# Age");
        !          3696:   pstamp(ficresprobcor);
        !          3697:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
        !          3698:   fprintf(ficresprobcor,"# Age");
        !          3699: 
        !          3700: 
        !          3701:   for(i=1; i<=nlstate;i++)
        !          3702:     for(j=1; j<=(nlstate+ndeath);j++){
        !          3703:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
        !          3704:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
        !          3705:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
        !          3706:     }  
        !          3707:  /* fprintf(ficresprob,"\n");
        !          3708:   fprintf(ficresprobcov,"\n");
        !          3709:   fprintf(ficresprobcor,"\n");
        !          3710:  */
        !          3711:   xp=vector(1,npar);
        !          3712:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
        !          3713:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
        !          3714:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
        !          3715:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
        !          3716:   first=1;
        !          3717:   fprintf(ficgp,"\n# Routine varprob");
        !          3718:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
        !          3719:   fprintf(fichtm,"\n");
        !          3720: 
        !          3721:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
        !          3722:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
        !          3723:   file %s<br>\n",optionfilehtmcov);
        !          3724:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
        !          3725: and drawn. It helps understanding how is the covariance between two incidences.\
        !          3726:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
        !          3727:   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. \
        !          3728: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
        !          3729: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
        !          3730: standard deviations wide on each axis. <br>\
        !          3731:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
        !          3732:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
        !          3733: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
        !          3734: 
        !          3735:   cov[1]=1;
        !          3736:   /* tj=cptcoveff; */
        !          3737:   tj = (int) pow(2,cptcoveff);
        !          3738:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
        !          3739:   j1=0;
        !          3740:   for(j1=1; j1<=tj;j1++){
        !          3741:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
        !          3742:     /*j1++;*/
        !          3743:       if  (cptcovn>0) {
        !          3744:        fprintf(ficresprob, "\n#********** Variable "); 
        !          3745:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
        !          3746:        fprintf(ficresprob, "**********\n#\n");
        !          3747:        fprintf(ficresprobcov, "\n#********** Variable "); 
        !          3748:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
        !          3749:        fprintf(ficresprobcov, "**********\n#\n");
        !          3750:        
        !          3751:        fprintf(ficgp, "\n#********** Variable "); 
        !          3752:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
        !          3753:        fprintf(ficgp, "**********\n#\n");
        !          3754:        
        !          3755:        
        !          3756:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
        !          3757:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
        !          3758:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
        !          3759:        
        !          3760:        fprintf(ficresprobcor, "\n#********** Variable ");    
        !          3761:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
        !          3762:        fprintf(ficresprobcor, "**********\n#");    
        !          3763:       }
        !          3764:       
        !          3765:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
        !          3766:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
        !          3767:       gp=vector(1,(nlstate)*(nlstate+ndeath));
        !          3768:       gm=vector(1,(nlstate)*(nlstate+ndeath));
        !          3769:       for (age=bage; age<=fage; age ++){ 
        !          3770:        cov[2]=age;
        !          3771:        for (k=1; k<=cptcovn;k++) {
        !          3772:          cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
        !          3773:                                                         * 1  1 1 1 1
        !          3774:                                                         * 2  2 1 1 1
        !          3775:                                                         * 3  1 2 1 1
        !          3776:                                                         */
        !          3777:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
        !          3778:        }
        !          3779:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
        !          3780:        for (k=1; k<=cptcovprod;k++)
        !          3781:          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
        !          3782:        
        !          3783:     
        !          3784:        for(theta=1; theta <=npar; theta++){
        !          3785:          for(i=1; i<=npar; i++)
        !          3786:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
        !          3787:          
        !          3788:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
        !          3789:          
        !          3790:          k=0;
        !          3791:          for(i=1; i<= (nlstate); i++){
        !          3792:            for(j=1; j<=(nlstate+ndeath);j++){
        !          3793:              k=k+1;
        !          3794:              gp[k]=pmmij[i][j];
        !          3795:            }
        !          3796:          }
        !          3797:          
        !          3798:          for(i=1; i<=npar; i++)
        !          3799:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
        !          3800:     
        !          3801:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
        !          3802:          k=0;
        !          3803:          for(i=1; i<=(nlstate); i++){
        !          3804:            for(j=1; j<=(nlstate+ndeath);j++){
        !          3805:              k=k+1;
        !          3806:              gm[k]=pmmij[i][j];
        !          3807:            }
        !          3808:          }
        !          3809:      
        !          3810:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
        !          3811:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
        !          3812:        }
        !          3813: 
        !          3814:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
        !          3815:          for(theta=1; theta <=npar; theta++)
        !          3816:            trgradg[j][theta]=gradg[theta][j];
        !          3817:        
        !          3818:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
        !          3819:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
        !          3820: 
        !          3821:        pmij(pmmij,cov,ncovmodel,x,nlstate);
        !          3822:        
        !          3823:        k=0;
        !          3824:        for(i=1; i<=(nlstate); i++){
        !          3825:          for(j=1; j<=(nlstate+ndeath);j++){
        !          3826:            k=k+1;
        !          3827:            mu[k][(int) age]=pmmij[i][j];
        !          3828:          }
        !          3829:        }
        !          3830:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
        !          3831:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
        !          3832:            varpij[i][j][(int)age] = doldm[i][j];
        !          3833: 
        !          3834:        /*printf("\n%d ",(int)age);
        !          3835:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
        !          3836:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
        !          3837:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
        !          3838:          }*/
        !          3839: 
        !          3840:        fprintf(ficresprob,"\n%d ",(int)age);
        !          3841:        fprintf(ficresprobcov,"\n%d ",(int)age);
        !          3842:        fprintf(ficresprobcor,"\n%d ",(int)age);
        !          3843: 
        !          3844:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
        !          3845:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
        !          3846:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
        !          3847:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
        !          3848:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
        !          3849:        }
        !          3850:        i=0;
        !          3851:        for (k=1; k<=(nlstate);k++){
        !          3852:          for (l=1; l<=(nlstate+ndeath);l++){ 
        !          3853:            i++;
        !          3854:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
        !          3855:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
        !          3856:            for (j=1; j<=i;j++){
        !          3857:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
        !          3858:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
        !          3859:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
        !          3860:            }
        !          3861:          }
        !          3862:        }/* end of loop for state */
        !          3863:       } /* end of loop for age */
        !          3864:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
        !          3865:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
        !          3866:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
        !          3867:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
        !          3868:       
        !          3869:       /* Confidence intervalle of pij  */
        !          3870:       /*
        !          3871:        fprintf(ficgp,"\nunset parametric;unset label");
        !          3872:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
        !          3873:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
        !          3874:        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);
        !          3875:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
        !          3876:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
        !          3877:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
        !          3878:       */
        !          3879: 
        !          3880:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
        !          3881:       first1=1;first2=2;
        !          3882:       for (k2=1; k2<=(nlstate);k2++){
        !          3883:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
        !          3884:          if(l2==k2) continue;
        !          3885:          j=(k2-1)*(nlstate+ndeath)+l2;
        !          3886:          for (k1=1; k1<=(nlstate);k1++){
        !          3887:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
        !          3888:              if(l1==k1) continue;
        !          3889:              i=(k1-1)*(nlstate+ndeath)+l1;
        !          3890:              if(i<=j) continue;
        !          3891:              for (age=bage; age<=fage; age ++){ 
        !          3892:                if ((int)age %5==0){
        !          3893:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
        !          3894:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
        !          3895:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
        !          3896:                  mu1=mu[i][(int) age]/stepm*YEARM ;
        !          3897:                  mu2=mu[j][(int) age]/stepm*YEARM;
        !          3898:                  c12=cv12/sqrt(v1*v2);
        !          3899:                  /* Computing eigen value of matrix of covariance */
        !          3900:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
        !          3901:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
        !          3902:                  if ((lc2 <0) || (lc1 <0) ){
        !          3903:                    if(first2==1){
        !          3904:                      first1=0;
        !          3905:                    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);
        !          3906:                    }
        !          3907:                    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);
        !          3908:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
        !          3909:                    /* lc2=fabs(lc2); */
        !          3910:                  }
        !          3911: 
        !          3912:                  /* Eigen vectors */
        !          3913:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
        !          3914:                  /*v21=sqrt(1.-v11*v11); *//* error */
        !          3915:                  v21=(lc1-v1)/cv12*v11;
        !          3916:                  v12=-v21;
        !          3917:                  v22=v11;
        !          3918:                  tnalp=v21/v11;
        !          3919:                  if(first1==1){
        !          3920:                    first1=0;
        !          3921:                    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);
        !          3922:                  }
        !          3923:                  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);
        !          3924:                  /*printf(fignu*/
        !          3925:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
        !          3926:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
        !          3927:                  if(first==1){
        !          3928:                    first=0;
        !          3929:                    fprintf(ficgp,"\nset parametric;unset label");
        !          3930:                    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);
        !          3931:                    fprintf(ficgp,"\nset ter png small size 320, 240");
        !          3932:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
        !          3933:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
        !          3934: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
        !          3935:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
        !          3936:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
        !          3937:                    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
        !          3938:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
        !          3939:                    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
        !          3940:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
        !          3941:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
        !          3942:                    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",\
        !          3943:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
        !          3944:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
        !          3945:                  }else{
        !          3946:                    first=0;
        !          3947:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
        !          3948:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
        !          3949:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
        !          3950:                    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",\
        !          3951:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
        !          3952:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
        !          3953:                  }/* if first */
        !          3954:                } /* age mod 5 */
        !          3955:              } /* end loop age */
        !          3956:              fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
        !          3957:              first=1;
        !          3958:            } /*l12 */
        !          3959:          } /* k12 */
        !          3960:        } /*l1 */
        !          3961:       }/* k1 */
        !          3962:       /* } /* loop covariates */
        !          3963:   }
        !          3964:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
        !          3965:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
        !          3966:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
        !          3967:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
        !          3968:   free_vector(xp,1,npar);
        !          3969:   fclose(ficresprob);
        !          3970:   fclose(ficresprobcov);
        !          3971:   fclose(ficresprobcor);
        !          3972:   fflush(ficgp);
        !          3973:   fflush(fichtmcov);
        !          3974: }
        !          3975: 
        !          3976: 
        !          3977: /******************* Printing html file ***********/
        !          3978: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
        !          3979:                  int lastpass, int stepm, int weightopt, char model[],\
        !          3980:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
        !          3981:                  int popforecast, int estepm ,\
        !          3982:                  double jprev1, double mprev1,double anprev1, \
        !          3983:                  double jprev2, double mprev2,double anprev2){
        !          3984:   int jj1, k1, i1, cpt;
        !          3985: 
        !          3986:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
        !          3987:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
        !          3988: </ul>");
        !          3989:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
        !          3990:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
        !          3991:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
        !          3992:    fprintf(fichtm,"\
        !          3993:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
        !          3994:           stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
        !          3995:    fprintf(fichtm,"\
        !          3996:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
        !          3997:           subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
        !          3998:    fprintf(fichtm,"\
        !          3999:  - (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): \
        !          4000:    <a href=\"%s\">%s</a> <br>\n",
        !          4001:           estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
        !          4002:    fprintf(fichtm,"\
        !          4003:  - Population projections by age and states: \
        !          4004:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
        !          4005: 
        !          4006: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
        !          4007: 
        !          4008:  m=pow(2,cptcoveff);
        !          4009:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
        !          4010: 
        !          4011:  jj1=0;
        !          4012:  for(k1=1; k1<=m;k1++){
        !          4013:    for(i1=1; i1<=ncodemax[k1];i1++){
        !          4014:      jj1++;
        !          4015:      if (cptcovn > 0) {
        !          4016:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
        !          4017:        for (cpt=1; cpt<=cptcoveff;cpt++) 
        !          4018:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
        !          4019:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
        !          4020:      }
        !          4021:      /* Pij */
        !          4022:      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> \
        !          4023: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
        !          4024:      /* Quasi-incidences */
        !          4025:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
        !          4026:  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> \
        !          4027: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
        !          4028:        /* Period (stable) prevalence in each health state */
        !          4029:        for(cpt=1; cpt<=nlstate;cpt++){
        !          4030:         fprintf(fichtm,"<br>- Convergence from each state (1 to %d) to period (stable) prevalence in state %d <a href=\"%s%d_%d.png\">%s%d_%d.png</a><br> \
        !          4031: <img src=\"%s%d_%d.png\">",nlstate, cpt, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
        !          4032:        }
        !          4033:      for(cpt=1; cpt<=nlstate;cpt++) {
        !          4034:         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> \
        !          4035: <img src=\"%s%d%d.png\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
        !          4036:      }
        !          4037:    } /* end i1 */
        !          4038:  }/* End k1 */
        !          4039:  fprintf(fichtm,"</ul>");
        !          4040: 
        !          4041: 
        !          4042:  fprintf(fichtm,"\
        !          4043: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
        !          4044:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
        !          4045: 
        !          4046:  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
        !          4047:         subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
        !          4048:  fprintf(fichtm,"\
        !          4049:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
        !          4050:         subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
        !          4051: 
        !          4052:  fprintf(fichtm,"\
        !          4053:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
        !          4054:         subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
        !          4055:  fprintf(fichtm,"\
        !          4056:  - 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): \
        !          4057:    <a href=\"%s\">%s</a> <br>\n</li>",
        !          4058:           estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
        !          4059:  fprintf(fichtm,"\
        !          4060:  - (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): \
        !          4061:    <a href=\"%s\">%s</a> <br>\n</li>",
        !          4062:           estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
        !          4063:  fprintf(fichtm,"\
        !          4064:  - 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",
        !          4065:         estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
        !          4066:  fprintf(fichtm,"\
        !          4067:  - 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",
        !          4068:         estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
        !          4069:  fprintf(fichtm,"\
        !          4070:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
        !          4071:         subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
        !          4072: 
        !          4073: /*  if(popforecast==1) fprintf(fichtm,"\n */
        !          4074: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
        !          4075: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
        !          4076: /*     <br>",fileres,fileres,fileres,fileres); */
        !          4077: /*  else  */
        !          4078: /*    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); */
        !          4079:  fflush(fichtm);
        !          4080:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
        !          4081: 
        !          4082:  m=pow(2,cptcoveff);
        !          4083:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
        !          4084: 
        !          4085:  jj1=0;
        !          4086:  for(k1=1; k1<=m;k1++){
        !          4087:    for(i1=1; i1<=ncodemax[k1];i1++){
        !          4088:      jj1++;
        !          4089:      if (cptcovn > 0) {
        !          4090:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
        !          4091:        for (cpt=1; cpt<=cptcoveff;cpt++) 
        !          4092:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
        !          4093:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
        !          4094:      }
        !          4095:      for(cpt=1; cpt<=nlstate;cpt++) {
        !          4096:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
        !          4097: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
        !          4098: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
        !          4099:      }
        !          4100:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
        !          4101: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
        !          4102: true period expectancies (those weighted with period prevalences are also\
        !          4103:  drawn in addition to the population based expectancies computed using\
        !          4104:  observed and cahotic prevalences: %s%d.png<br>\
        !          4105: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
        !          4106:    } /* end i1 */
        !          4107:  }/* End k1 */
        !          4108:  fprintf(fichtm,"</ul>");
        !          4109:  fflush(fichtm);
        !          4110: }
        !          4111: 
        !          4112: /******************* Gnuplot file **************/
        !          4113: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
        !          4114: 
        !          4115:   char dirfileres[132],optfileres[132];
        !          4116:   int m0,cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
        !          4117:   int ng=0;
        !          4118: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
        !          4119: /*     printf("Problem with file %s",optionfilegnuplot); */
        !          4120: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
        !          4121: /*   } */
        !          4122: 
        !          4123:   /*#ifdef windows */
        !          4124:   fprintf(ficgp,"cd \"%s\" \n",pathc);
        !          4125:     /*#endif */
        !          4126:   m=pow(2,cptcoveff);
        !          4127: 
        !          4128:   strcpy(dirfileres,optionfilefiname);
        !          4129:   strcpy(optfileres,"vpl");
        !          4130:  /* 1eme*/
        !          4131:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
        !          4132:   for (cpt=1; cpt<= nlstate ; cpt ++) {
        !          4133:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
        !          4134:      fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
        !          4135:      fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
        !          4136:      fprintf(ficgp,"set xlabel \"Age\" \n\
        !          4137: set ylabel \"Probability\" \n\
        !          4138: set ter png small size 320, 240\n\
        !          4139: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
        !          4140: 
        !          4141:      for (i=1; i<= nlstate ; i ++) {
        !          4142:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
        !          4143:        else        fprintf(ficgp," \%%*lf (\%%*lf)");
        !          4144:      }
        !          4145:      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);
        !          4146:      for (i=1; i<= nlstate ; i ++) {
        !          4147:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
        !          4148:        else fprintf(ficgp," \%%*lf (\%%*lf)");
        !          4149:      } 
        !          4150:      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); 
        !          4151:      for (i=1; i<= nlstate ; i ++) {
        !          4152:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
        !          4153:        else fprintf(ficgp," \%%*lf (\%%*lf)");
        !          4154:      }  
        !          4155:      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));
        !          4156:    }
        !          4157:   }
        !          4158:   /*2 eme*/
        !          4159:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
        !          4160:   for (k1=1; k1<= m ; k1 ++) { 
        !          4161:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
        !          4162:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
        !          4163:     
        !          4164:     for (i=1; i<= nlstate+1 ; i ++) {
        !          4165:       k=2*i;
        !          4166:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
        !          4167:       for (j=1; j<= nlstate+1 ; j ++) {
        !          4168:        if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
        !          4169:        else fprintf(ficgp," \%%*lf (\%%*lf)");
        !          4170:       }   
        !          4171:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
        !          4172:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
        !          4173:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
        !          4174:       for (j=1; j<= nlstate+1 ; j ++) {
        !          4175:        if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
        !          4176:        else fprintf(ficgp," \%%*lf (\%%*lf)");
        !          4177:       }   
        !          4178:       fprintf(ficgp,"\" t\"\" w l lt 0,");
        !          4179:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
        !          4180:       for (j=1; j<= nlstate+1 ; j ++) {
        !          4181:        if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
        !          4182:        else fprintf(ficgp," \%%*lf (\%%*lf)");
        !          4183:       }   
        !          4184:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
        !          4185:       else fprintf(ficgp,"\" t\"\" w l lt 0,");
        !          4186:     }
        !          4187:   }
        !          4188:   
        !          4189:   /*3eme*/
        !          4190:   
        !          4191:   for (k1=1; k1<= m ; k1 ++) { 
        !          4192:     for (cpt=1; cpt<= nlstate ; cpt ++) {
        !          4193:       /*       k=2+nlstate*(2*cpt-2); */
        !          4194:       k=2+(nlstate+1)*(cpt-1);
        !          4195:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
        !          4196:       fprintf(ficgp,"set ter png small size 320, 240\n\
        !          4197: 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);
        !          4198:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
        !          4199:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
        !          4200:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
        !          4201:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
        !          4202:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
        !          4203:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
        !          4204:        
        !          4205:       */
        !          4206:       for (i=1; i< nlstate ; i ++) {
        !          4207:        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);
        !          4208:        /*      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);*/
        !          4209:        
        !          4210:       } 
        !          4211:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
        !          4212:     }
        !          4213:   }
        !          4214:   
        !          4215:   /* CV preval stable (period) */
        !          4216:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
        !          4217:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
        !          4218:       k=3;
        !          4219:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
        !          4220:       fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
        !          4221:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
        !          4222: set ter png small size 320, 240\n\
        !          4223: unset log y\n\
        !          4224: plot [%.f:%.f]  ", ageminpar, agemaxpar);
        !          4225:       for (i=1; i<= nlstate ; i ++){
        !          4226:        if(i==1)
        !          4227:          fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
        !          4228:        else
        !          4229:          fprintf(ficgp,", '' ");
        !          4230:        l=(nlstate+ndeath)*(i-1)+1;
        !          4231:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
        !          4232:        for (j=1; j<= (nlstate-1) ; j ++)
        !          4233:          fprintf(ficgp,"+$%d",k+l+j);
        !          4234:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
        !          4235:       } /* nlstate */
        !          4236:       fprintf(ficgp,"\n");
        !          4237:     } /* end cpt state*/ 
        !          4238:   } /* end covariate */  
        !          4239:   
        !          4240:   /* proba elementaires */
        !          4241:   for(i=1,jk=1; i <=nlstate; i++){
        !          4242:     for(k=1; k <=(nlstate+ndeath); k++){
        !          4243:       if (k != i) {
        !          4244:        for(j=1; j <=ncovmodel; j++){
        !          4245:          fprintf(ficgp,"p%d=%f ",jk,p[jk]);
        !          4246:          jk++; 
        !          4247:          fprintf(ficgp,"\n");
        !          4248:        }
        !          4249:       }
        !          4250:     }
        !          4251:    }
        !          4252:   /*goto avoid;*/
        !          4253:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
        !          4254:      for(jk=1; jk <=m; jk++) {
        !          4255:        fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
        !          4256:        if (ng==2)
        !          4257:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
        !          4258:        else
        !          4259:         fprintf(ficgp,"\nset title \"Probability\"\n");
        !          4260:        fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
        !          4261:        i=1;
        !          4262:        for(k2=1; k2<=nlstate; k2++) {
        !          4263:         k3=i;
        !          4264:         for(k=1; k<=(nlstate+ndeath); k++) {
        !          4265:           if (k != k2){
        !          4266:             if(ng==2)
        !          4267:               fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
        !          4268:             else
        !          4269:               fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
        !          4270:             ij=1;/* To be checked else nbcode[0][0] wrong */
        !          4271:             for(j=3; j <=ncovmodel; j++) {
        !          4272:               /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
        !          4273:               /*        /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
        !          4274:               /*        ij++; */
        !          4275:               /* } */
        !          4276:               /* else */
        !          4277:                 fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
        !          4278:             }
        !          4279:             fprintf(ficgp,")/(1");
        !          4280:             
        !          4281:             for(k1=1; k1 <=nlstate; k1++){   
        !          4282:               fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
        !          4283:               ij=1;
        !          4284:               for(j=3; j <=ncovmodel; j++){
        !          4285:                 /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
        !          4286:                 /*   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
        !          4287:                 /*   ij++; */
        !          4288:                 /* } */
        !          4289:                 /* else */
        !          4290:                   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
        !          4291:               }
        !          4292:               fprintf(ficgp,")");
        !          4293:             }
        !          4294:             fprintf(ficgp,") t \"p%d%d\" ", k2,k);
        !          4295:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
        !          4296:             i=i+ncovmodel;
        !          4297:           }
        !          4298:         } /* end k */
        !          4299:        } /* end k2 */
        !          4300:      } /* end jk */
        !          4301:    } /* end ng */
        !          4302:  avoid:
        !          4303:    fflush(ficgp); 
        !          4304: }  /* end gnuplot */
        !          4305: 
        !          4306: 
        !          4307: /*************** Moving average **************/
        !          4308: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
        !          4309: 
        !          4310:   int i, cpt, cptcod;
        !          4311:   int modcovmax =1;
        !          4312:   int mobilavrange, mob;
        !          4313:   double age;
        !          4314: 
        !          4315:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
        !          4316:                           a covariate has 2 modalities */
        !          4317:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
        !          4318: 
        !          4319:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
        !          4320:     if(mobilav==1) mobilavrange=5; /* default */
        !          4321:     else mobilavrange=mobilav;
        !          4322:     for (age=bage; age<=fage; age++)
        !          4323:       for (i=1; i<=nlstate;i++)
        !          4324:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
        !          4325:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
        !          4326:     /* We keep the original values on the extreme ages bage, fage and for 
        !          4327:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
        !          4328:        we use a 5 terms etc. until the borders are no more concerned. 
        !          4329:     */ 
        !          4330:     for (mob=3;mob <=mobilavrange;mob=mob+2){
        !          4331:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
        !          4332:        for (i=1; i<=nlstate;i++){
        !          4333:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
        !          4334:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
        !          4335:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
        !          4336:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
        !          4337:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
        !          4338:              }
        !          4339:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
        !          4340:          }
        !          4341:        }
        !          4342:       }/* end age */
        !          4343:     }/* end mob */
        !          4344:   }else return -1;
        !          4345:   return 0;
        !          4346: }/* End movingaverage */
        !          4347: 
        !          4348: 
        !          4349: /************** Forecasting ******************/
        !          4350: 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){
        !          4351:   /* proj1, year, month, day of starting projection 
        !          4352:      agemin, agemax range of age
        !          4353:      dateprev1 dateprev2 range of dates during which prevalence is computed
        !          4354:      anproj2 year of en of projection (same day and month as proj1).
        !          4355:   */
        !          4356:   int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
        !          4357:   int *popage;
        !          4358:   double agec; /* generic age */
        !          4359:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
        !          4360:   double *popeffectif,*popcount;
        !          4361:   double ***p3mat;
        !          4362:   double ***mobaverage;
        !          4363:   char fileresf[FILENAMELENGTH];
        !          4364: 
        !          4365:   agelim=AGESUP;
        !          4366:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
        !          4367:  
        !          4368:   strcpy(fileresf,"f"); 
        !          4369:   strcat(fileresf,fileres);
        !          4370:   if((ficresf=fopen(fileresf,"w"))==NULL) {
        !          4371:     printf("Problem with forecast resultfile: %s\n", fileresf);
        !          4372:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
        !          4373:   }
        !          4374:   printf("Computing forecasting: result on file '%s' \n", fileresf);
        !          4375:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
        !          4376: 
        !          4377:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
        !          4378: 
        !          4379:   if (mobilav!=0) {
        !          4380:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
        !          4381:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
        !          4382:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
        !          4383:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
        !          4384:     }
        !          4385:   }
        !          4386: 
        !          4387:   stepsize=(int) (stepm+YEARM-1)/YEARM;
        !          4388:   if (stepm<=12) stepsize=1;
        !          4389:   if(estepm < stepm){
        !          4390:     printf ("Problem %d lower than %d\n",estepm, stepm);
        !          4391:   }
        !          4392:   else  hstepm=estepm;   
        !          4393: 
        !          4394:   hstepm=hstepm/stepm; 
        !          4395:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
        !          4396:                                fractional in yp1 */
        !          4397:   anprojmean=yp;
        !          4398:   yp2=modf((yp1*12),&yp);
        !          4399:   mprojmean=yp;
        !          4400:   yp1=modf((yp2*30.5),&yp);
        !          4401:   jprojmean=yp;
        !          4402:   if(jprojmean==0) jprojmean=1;
        !          4403:   if(mprojmean==0) jprojmean=1;
        !          4404: 
        !          4405:   i1=cptcoveff;
        !          4406:   if (cptcovn < 1){i1=1;}
        !          4407:   
        !          4408:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
        !          4409:   
        !          4410:   fprintf(ficresf,"#****** Routine prevforecast **\n");
        !          4411: 
        !          4412: /*           if (h==(int)(YEARM*yearp)){ */
        !          4413:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
        !          4414:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
        !          4415:       k=k+1;
        !          4416:       fprintf(ficresf,"\n#******");
        !          4417:       for(j=1;j<=cptcoveff;j++) {
        !          4418:        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]]);
        !          4419:       }
        !          4420:       fprintf(ficresf,"******\n");
        !          4421:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
        !          4422:       for(j=1; j<=nlstate+ndeath;j++){ 
        !          4423:        for(i=1; i<=nlstate;i++)              
        !          4424:           fprintf(ficresf," p%d%d",i,j);
        !          4425:        fprintf(ficresf," p.%d",j);
        !          4426:       }
        !          4427:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
        !          4428:        fprintf(ficresf,"\n");
        !          4429:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
        !          4430: 
        !          4431:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
        !          4432:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
        !          4433:          nhstepm = nhstepm/hstepm; 
        !          4434:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          4435:          oldm=oldms;savm=savms;
        !          4436:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
        !          4437:        
        !          4438:          for (h=0; h<=nhstepm; h++){
        !          4439:            if (h*hstepm/YEARM*stepm ==yearp) {
        !          4440:               fprintf(ficresf,"\n");
        !          4441:               for(j=1;j<=cptcoveff;j++) 
        !          4442:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
        !          4443:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
        !          4444:            } 
        !          4445:            for(j=1; j<=nlstate+ndeath;j++) {
        !          4446:              ppij=0.;
        !          4447:              for(i=1; i<=nlstate;i++) {
        !          4448:                if (mobilav==1) 
        !          4449:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
        !          4450:                else {
        !          4451:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
        !          4452:                }
        !          4453:                if (h*hstepm/YEARM*stepm== yearp) {
        !          4454:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
        !          4455:                }
        !          4456:              } /* end i */
        !          4457:              if (h*hstepm/YEARM*stepm==yearp) {
        !          4458:                fprintf(ficresf," %.3f", ppij);
        !          4459:              }
        !          4460:            }/* end j */
        !          4461:          } /* end h */
        !          4462:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          4463:        } /* end agec */
        !          4464:       } /* end yearp */
        !          4465:     } /* end cptcod */
        !          4466:   } /* end  cptcov */
        !          4467:        
        !          4468:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
        !          4469: 
        !          4470:   fclose(ficresf);
        !          4471: }
        !          4472: 
        !          4473: /************** Forecasting *****not tested NB*************/
        !          4474: 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){
        !          4475:   
        !          4476:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
        !          4477:   int *popage;
        !          4478:   double calagedatem, agelim, kk1, kk2;
        !          4479:   double *popeffectif,*popcount;
        !          4480:   double ***p3mat,***tabpop,***tabpopprev;
        !          4481:   double ***mobaverage;
        !          4482:   char filerespop[FILENAMELENGTH];
        !          4483: 
        !          4484:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
        !          4485:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
        !          4486:   agelim=AGESUP;
        !          4487:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
        !          4488:   
        !          4489:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
        !          4490:   
        !          4491:   
        !          4492:   strcpy(filerespop,"pop"); 
        !          4493:   strcat(filerespop,fileres);
        !          4494:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
        !          4495:     printf("Problem with forecast resultfile: %s\n", filerespop);
        !          4496:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
        !          4497:   }
        !          4498:   printf("Computing forecasting: result on file '%s' \n", filerespop);
        !          4499:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
        !          4500: 
        !          4501:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
        !          4502: 
        !          4503:   if (mobilav!=0) {
        !          4504:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
        !          4505:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
        !          4506:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
        !          4507:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
        !          4508:     }
        !          4509:   }
        !          4510: 
        !          4511:   stepsize=(int) (stepm+YEARM-1)/YEARM;
        !          4512:   if (stepm<=12) stepsize=1;
        !          4513:   
        !          4514:   agelim=AGESUP;
        !          4515:   
        !          4516:   hstepm=1;
        !          4517:   hstepm=hstepm/stepm; 
        !          4518:   
        !          4519:   if (popforecast==1) {
        !          4520:     if((ficpop=fopen(popfile,"r"))==NULL) {
        !          4521:       printf("Problem with population file : %s\n",popfile);exit(0);
        !          4522:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
        !          4523:     } 
        !          4524:     popage=ivector(0,AGESUP);
        !          4525:     popeffectif=vector(0,AGESUP);
        !          4526:     popcount=vector(0,AGESUP);
        !          4527:     
        !          4528:     i=1;   
        !          4529:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
        !          4530:    
        !          4531:     imx=i;
        !          4532:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
        !          4533:   }
        !          4534: 
        !          4535:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
        !          4536:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
        !          4537:       k=k+1;
        !          4538:       fprintf(ficrespop,"\n#******");
        !          4539:       for(j=1;j<=cptcoveff;j++) {
        !          4540:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
        !          4541:       }
        !          4542:       fprintf(ficrespop,"******\n");
        !          4543:       fprintf(ficrespop,"# Age");
        !          4544:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
        !          4545:       if (popforecast==1)  fprintf(ficrespop," [Population]");
        !          4546:       
        !          4547:       for (cpt=0; cpt<=0;cpt++) { 
        !          4548:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
        !          4549:        
        !          4550:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
        !          4551:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
        !          4552:          nhstepm = nhstepm/hstepm; 
        !          4553:          
        !          4554:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          4555:          oldm=oldms;savm=savms;
        !          4556:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
        !          4557:        
        !          4558:          for (h=0; h<=nhstepm; h++){
        !          4559:            if (h==(int) (calagedatem+YEARM*cpt)) {
        !          4560:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
        !          4561:            } 
        !          4562:            for(j=1; j<=nlstate+ndeath;j++) {
        !          4563:              kk1=0.;kk2=0;
        !          4564:              for(i=1; i<=nlstate;i++) {              
        !          4565:                if (mobilav==1) 
        !          4566:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
        !          4567:                else {
        !          4568:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
        !          4569:                }
        !          4570:              }
        !          4571:              if (h==(int)(calagedatem+12*cpt)){
        !          4572:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
        !          4573:                  /*fprintf(ficrespop," %.3f", kk1);
        !          4574:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
        !          4575:              }
        !          4576:            }
        !          4577:            for(i=1; i<=nlstate;i++){
        !          4578:              kk1=0.;
        !          4579:                for(j=1; j<=nlstate;j++){
        !          4580:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
        !          4581:                }
        !          4582:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
        !          4583:            }
        !          4584: 
        !          4585:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
        !          4586:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
        !          4587:          }
        !          4588:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          4589:        }
        !          4590:       }
        !          4591:  
        !          4592:   /******/
        !          4593: 
        !          4594:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
        !          4595:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
        !          4596:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
        !          4597:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
        !          4598:          nhstepm = nhstepm/hstepm; 
        !          4599:          
        !          4600:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          4601:          oldm=oldms;savm=savms;
        !          4602:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
        !          4603:          for (h=0; h<=nhstepm; h++){
        !          4604:            if (h==(int) (calagedatem+YEARM*cpt)) {
        !          4605:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
        !          4606:            } 
        !          4607:            for(j=1; j<=nlstate+ndeath;j++) {
        !          4608:              kk1=0.;kk2=0;
        !          4609:              for(i=1; i<=nlstate;i++) {              
        !          4610:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
        !          4611:              }
        !          4612:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
        !          4613:            }
        !          4614:          }
        !          4615:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          4616:        }
        !          4617:       }
        !          4618:    } 
        !          4619:   }
        !          4620:  
        !          4621:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
        !          4622: 
        !          4623:   if (popforecast==1) {
        !          4624:     free_ivector(popage,0,AGESUP);
        !          4625:     free_vector(popeffectif,0,AGESUP);
        !          4626:     free_vector(popcount,0,AGESUP);
        !          4627:   }
        !          4628:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
        !          4629:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
        !          4630:   fclose(ficrespop);
        !          4631: } /* End of popforecast */
        !          4632: 
        !          4633: int fileappend(FILE *fichier, char *optionfich)
        !          4634: {
        !          4635:   if((fichier=fopen(optionfich,"a"))==NULL) {
        !          4636:     printf("Problem with file: %s\n", optionfich);
        !          4637:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
        !          4638:     return (0);
        !          4639:   }
        !          4640:   fflush(fichier);
        !          4641:   return (1);
        !          4642: }
        !          4643: 
        !          4644: 
        !          4645: /**************** function prwizard **********************/
        !          4646: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
        !          4647: {
        !          4648: 
        !          4649:   /* Wizard to print covariance matrix template */
        !          4650: 
        !          4651:   char ca[32], cb[32], cc[32];
        !          4652:   int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
        !          4653:   int numlinepar;
        !          4654: 
        !          4655:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
        !          4656:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
        !          4657:   for(i=1; i <=nlstate; i++){
        !          4658:     jj=0;
        !          4659:     for(j=1; j <=nlstate+ndeath; j++){
        !          4660:       if(j==i) continue;
        !          4661:       jj++;
        !          4662:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
        !          4663:       printf("%1d%1d",i,j);
        !          4664:       fprintf(ficparo,"%1d%1d",i,j);
        !          4665:       for(k=1; k<=ncovmodel;k++){
        !          4666:        /*        printf(" %lf",param[i][j][k]); */
        !          4667:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
        !          4668:        printf(" 0.");
        !          4669:        fprintf(ficparo," 0.");
        !          4670:       }
        !          4671:       printf("\n");
        !          4672:       fprintf(ficparo,"\n");
        !          4673:     }
        !          4674:   }
        !          4675:   printf("# Scales (for hessian or gradient estimation)\n");
        !          4676:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
        !          4677:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
        !          4678:   for(i=1; i <=nlstate; i++){
        !          4679:     jj=0;
        !          4680:     for(j=1; j <=nlstate+ndeath; j++){
        !          4681:       if(j==i) continue;
        !          4682:       jj++;
        !          4683:       fprintf(ficparo,"%1d%1d",i,j);
        !          4684:       printf("%1d%1d",i,j);
        !          4685:       fflush(stdout);
        !          4686:       for(k=1; k<=ncovmodel;k++){
        !          4687:        /*      printf(" %le",delti3[i][j][k]); */
        !          4688:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
        !          4689:        printf(" 0.");
        !          4690:        fprintf(ficparo," 0.");
        !          4691:       }
        !          4692:       numlinepar++;
        !          4693:       printf("\n");
        !          4694:       fprintf(ficparo,"\n");
        !          4695:     }
        !          4696:   }
        !          4697:   printf("# Covariance matrix\n");
        !          4698: /* # 121 Var(a12)\n\ */
        !          4699: /* # 122 Cov(b12,a12) Var(b12)\n\ */
        !          4700: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
        !          4701: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
        !          4702: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
        !          4703: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
        !          4704: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
        !          4705: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
        !          4706:   fflush(stdout);
        !          4707:   fprintf(ficparo,"# Covariance matrix\n");
        !          4708:   /* # 121 Var(a12)\n\ */
        !          4709:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
        !          4710:   /* #   ...\n\ */
        !          4711:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
        !          4712:   
        !          4713:   for(itimes=1;itimes<=2;itimes++){
        !          4714:     jj=0;
        !          4715:     for(i=1; i <=nlstate; i++){
        !          4716:       for(j=1; j <=nlstate+ndeath; j++){
        !          4717:        if(j==i) continue;
        !          4718:        for(k=1; k<=ncovmodel;k++){
        !          4719:          jj++;
        !          4720:          ca[0]= k+'a'-1;ca[1]='\0';
        !          4721:          if(itimes==1){
        !          4722:            printf("#%1d%1d%d",i,j,k);
        !          4723:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
        !          4724:          }else{
        !          4725:            printf("%1d%1d%d",i,j,k);
        !          4726:            fprintf(ficparo,"%1d%1d%d",i,j,k);
        !          4727:            /*  printf(" %.5le",matcov[i][j]); */
        !          4728:          }
        !          4729:          ll=0;
        !          4730:          for(li=1;li <=nlstate; li++){
        !          4731:            for(lj=1;lj <=nlstate+ndeath; lj++){
        !          4732:              if(lj==li) continue;
        !          4733:              for(lk=1;lk<=ncovmodel;lk++){
        !          4734:                ll++;
        !          4735:                if(ll<=jj){
        !          4736:                  cb[0]= lk +'a'-1;cb[1]='\0';
        !          4737:                  if(ll<jj){
        !          4738:                    if(itimes==1){
        !          4739:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
        !          4740:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
        !          4741:                    }else{
        !          4742:                      printf(" 0.");
        !          4743:                      fprintf(ficparo," 0.");
        !          4744:                    }
        !          4745:                  }else{
        !          4746:                    if(itimes==1){
        !          4747:                      printf(" Var(%s%1d%1d)",ca,i,j);
        !          4748:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
        !          4749:                    }else{
        !          4750:                      printf(" 0.");
        !          4751:                      fprintf(ficparo," 0.");
        !          4752:                    }
        !          4753:                  }
        !          4754:                }
        !          4755:              } /* end lk */
        !          4756:            } /* end lj */
        !          4757:          } /* end li */
        !          4758:          printf("\n");
        !          4759:          fprintf(ficparo,"\n");
        !          4760:          numlinepar++;
        !          4761:        } /* end k*/
        !          4762:       } /*end j */
        !          4763:     } /* end i */
        !          4764:   } /* end itimes */
        !          4765: 
        !          4766: } /* end of prwizard */
        !          4767: /******************* Gompertz Likelihood ******************************/
        !          4768: double gompertz(double x[])
        !          4769: { 
        !          4770:   double A,B,L=0.0,sump=0.,num=0.;
        !          4771:   int i,n=0; /* n is the size of the sample */
        !          4772: 
        !          4773:   for (i=0;i<=imx-1 ; i++) {
        !          4774:     sump=sump+weight[i];
        !          4775:     /*    sump=sump+1;*/
        !          4776:     num=num+1;
        !          4777:   }
        !          4778:  
        !          4779:  
        !          4780:   /* for (i=0; i<=imx; i++) 
        !          4781:      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]);*/
        !          4782: 
        !          4783:   for (i=1;i<=imx ; i++)
        !          4784:     {
        !          4785:       if (cens[i] == 1 && wav[i]>1)
        !          4786:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
        !          4787:       
        !          4788:       if (cens[i] == 0 && wav[i]>1)
        !          4789:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
        !          4790:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
        !          4791:       
        !          4792:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
        !          4793:       if (wav[i] > 1 ) { /* ??? */
        !          4794:        L=L+A*weight[i];
        !          4795:        /*      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]);*/
        !          4796:       }
        !          4797:     }
        !          4798: 
        !          4799:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
        !          4800:  
        !          4801:   return -2*L*num/sump;
        !          4802: }
        !          4803: 
        !          4804: #ifdef GSL
        !          4805: /******************* Gompertz_f Likelihood ******************************/
        !          4806: double gompertz_f(const gsl_vector *v, void *params)
        !          4807: { 
        !          4808:   double A,B,LL=0.0,sump=0.,num=0.;
        !          4809:   double *x= (double *) v->data;
        !          4810:   int i,n=0; /* n is the size of the sample */
        !          4811: 
        !          4812:   for (i=0;i<=imx-1 ; i++) {
        !          4813:     sump=sump+weight[i];
        !          4814:     /*    sump=sump+1;*/
        !          4815:     num=num+1;
        !          4816:   }
        !          4817:  
        !          4818:  
        !          4819:   /* for (i=0; i<=imx; i++) 
        !          4820:      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]);*/
        !          4821:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
        !          4822:   for (i=1;i<=imx ; i++)
        !          4823:     {
        !          4824:       if (cens[i] == 1 && wav[i]>1)
        !          4825:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
        !          4826:       
        !          4827:       if (cens[i] == 0 && wav[i]>1)
        !          4828:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
        !          4829:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
        !          4830:       
        !          4831:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
        !          4832:       if (wav[i] > 1 ) { /* ??? */
        !          4833:        LL=LL+A*weight[i];
        !          4834:        /*      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]);*/
        !          4835:       }
        !          4836:     }
        !          4837: 
        !          4838:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
        !          4839:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
        !          4840:  
        !          4841:   return -2*LL*num/sump;
        !          4842: }
        !          4843: #endif
        !          4844: 
        !          4845: /******************* Printing html file ***********/
        !          4846: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
        !          4847:                  int lastpass, int stepm, int weightopt, char model[],\
        !          4848:                  int imx,  double p[],double **matcov,double agemortsup){
        !          4849:   int i,k;
        !          4850: 
        !          4851:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
        !          4852:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
        !          4853:   for (i=1;i<=2;i++) 
        !          4854:     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]));
        !          4855:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
        !          4856:   fprintf(fichtm,"</ul>");
        !          4857: 
        !          4858: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
        !          4859: 
        !          4860:  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>");
        !          4861: 
        !          4862:  for (k=agegomp;k<(agemortsup-2);k++) 
        !          4863:    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]);
        !          4864: 
        !          4865:  
        !          4866:   fflush(fichtm);
        !          4867: }
        !          4868: 
        !          4869: /******************* Gnuplot file **************/
        !          4870: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
        !          4871: 
        !          4872:   char dirfileres[132],optfileres[132];
        !          4873:   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
        !          4874:   int ng;
        !          4875: 
        !          4876: 
        !          4877:   /*#ifdef windows */
        !          4878:   fprintf(ficgp,"cd \"%s\" \n",pathc);
        !          4879:     /*#endif */
        !          4880: 
        !          4881: 
        !          4882:   strcpy(dirfileres,optionfilefiname);
        !          4883:   strcpy(optfileres,"vpl");
        !          4884:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
        !          4885:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
        !          4886:   fprintf(ficgp, "set ter png small size 320, 240\n set log y\n"); 
        !          4887:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
        !          4888:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
        !          4889: 
        !          4890: } 
        !          4891: 
        !          4892: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
        !          4893: {
        !          4894: 
        !          4895:   /*-------- data file ----------*/
        !          4896:   FILE *fic;
        !          4897:   char dummy[]="                         ";
        !          4898:   int i, j, n;
        !          4899:   int linei, month, year,iout;
        !          4900:   char line[MAXLINE], linetmp[MAXLINE];
        !          4901:   char stra[80], strb[80];
        !          4902:   char *stratrunc;
        !          4903:   int lstra;
        !          4904: 
        !          4905: 
        !          4906:   if((fic=fopen(datafile,"r"))==NULL)    {
        !          4907:     printf("Problem while opening datafile: %s\n", datafile);return 1;
        !          4908:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
        !          4909:   }
        !          4910: 
        !          4911:   i=1;
        !          4912:   linei=0;
        !          4913:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
        !          4914:     linei=linei+1;
        !          4915:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
        !          4916:       if(line[j] == '\t')
        !          4917:        line[j] = ' ';
        !          4918:     }
        !          4919:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
        !          4920:       ;
        !          4921:     };
        !          4922:     line[j+1]=0;  /* Trims blanks at end of line */
        !          4923:     if(line[0]=='#'){
        !          4924:       fprintf(ficlog,"Comment line\n%s\n",line);
        !          4925:       printf("Comment line\n%s\n",line);
        !          4926:       continue;
        !          4927:     }
        !          4928:     trimbb(linetmp,line); /* Trims multiple blanks in line */
        !          4929:     for (j=0; line[j]!='\0';j++){
        !          4930:       line[j]=linetmp[j];
        !          4931:     }
        !          4932:   
        !          4933: 
        !          4934:     for (j=maxwav;j>=1;j--){
        !          4935:       cutv(stra, strb, line, ' '); 
        !          4936:       if(strb[0]=='.') { /* Missing status */
        !          4937:        lval=-1;
        !          4938:       }else{
        !          4939:        errno=0;
        !          4940:        lval=strtol(strb,&endptr,10); 
        !          4941:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
        !          4942:        if( strb[0]=='\0' || (*endptr != '\0')){
        !          4943:          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);
        !          4944:          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);
        !          4945:          return 1;
        !          4946:        }
        !          4947:       }
        !          4948:       s[j][i]=lval;
        !          4949:       
        !          4950:       strcpy(line,stra);
        !          4951:       cutv(stra, strb,line,' ');
        !          4952:       if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
        !          4953:       }
        !          4954:       else  if(iout=sscanf(strb,"%s.",dummy) != 0){
        !          4955:        month=99;
        !          4956:        year=9999;
        !          4957:       }else{
        !          4958:        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);
        !          4959:        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);
        !          4960:        return 1;
        !          4961:       }
        !          4962:       anint[j][i]= (double) year; 
        !          4963:       mint[j][i]= (double)month; 
        !          4964:       strcpy(line,stra);
        !          4965:     } /* ENd Waves */
        !          4966:     
        !          4967:     cutv(stra, strb,line,' '); 
        !          4968:     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
        !          4969:     }
        !          4970:     else  if(iout=sscanf(strb,"%s.",dummy) != 0){
        !          4971:       month=99;
        !          4972:       year=9999;
        !          4973:     }else{
        !          4974:       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);
        !          4975:        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);
        !          4976:        return 1;
        !          4977:     }
        !          4978:     andc[i]=(double) year; 
        !          4979:     moisdc[i]=(double) month; 
        !          4980:     strcpy(line,stra);
        !          4981:     
        !          4982:     cutv(stra, strb,line,' '); 
        !          4983:     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
        !          4984:     }
        !          4985:     else  if(iout=sscanf(strb,"%s.", dummy) != 0){
        !          4986:       month=99;
        !          4987:       year=9999;
        !          4988:     }else{
        !          4989:       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);
        !          4990:       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);
        !          4991:        return 1;
        !          4992:     }
        !          4993:     if (year==9999) {
        !          4994:       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);
        !          4995:       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);
        !          4996:        return 1;
        !          4997: 
        !          4998:     }
        !          4999:     annais[i]=(double)(year);
        !          5000:     moisnais[i]=(double)(month); 
        !          5001:     strcpy(line,stra);
        !          5002:     
        !          5003:     cutv(stra, strb,line,' '); 
        !          5004:     errno=0;
        !          5005:     dval=strtod(strb,&endptr); 
        !          5006:     if( strb[0]=='\0' || (*endptr != '\0')){
        !          5007:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
        !          5008:       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);
        !          5009:       fflush(ficlog);
        !          5010:       return 1;
        !          5011:     }
        !          5012:     weight[i]=dval; 
        !          5013:     strcpy(line,stra);
        !          5014:     
        !          5015:     for (j=ncovcol;j>=1;j--){
        !          5016:       cutv(stra, strb,line,' '); 
        !          5017:       if(strb[0]=='.') { /* Missing status */
        !          5018:        lval=-1;
        !          5019:       }else{
        !          5020:        errno=0;
        !          5021:        lval=strtol(strb,&endptr,10); 
        !          5022:        if( strb[0]=='\0' || (*endptr != '\0')){
        !          5023:          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);
        !          5024:          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);
        !          5025:          return 1;
        !          5026:        }
        !          5027:       }
        !          5028:       if(lval <-1 || lval >1){
        !          5029:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
        !          5030:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
        !          5031:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
        !          5032:  For example, for multinomial values like 1, 2 and 3,\n \
        !          5033:  build V1=0 V2=0 for the reference value (1),\n \
        !          5034:         V1=1 V2=0 for (2) \n \
        !          5035:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
        !          5036:  output of IMaCh is often meaningless.\n \
        !          5037:  Exiting.\n",lval,linei, i,line,j);
        !          5038:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
        !          5039:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
        !          5040:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
        !          5041:  For example, for multinomial values like 1, 2 and 3,\n \
        !          5042:  build V1=0 V2=0 for the reference value (1),\n \
        !          5043:         V1=1 V2=0 for (2) \n \
        !          5044:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
        !          5045:  output of IMaCh is often meaningless.\n \
        !          5046:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
        !          5047:        return 1;
        !          5048:       }
        !          5049:       covar[j][i]=(double)(lval);
        !          5050:       strcpy(line,stra);
        !          5051:     }  
        !          5052:     lstra=strlen(stra);
        !          5053:      
        !          5054:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
        !          5055:       stratrunc = &(stra[lstra-9]);
        !          5056:       num[i]=atol(stratrunc);
        !          5057:     }
        !          5058:     else
        !          5059:       num[i]=atol(stra);
        !          5060:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
        !          5061:       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;}*/
        !          5062:     
        !          5063:     i=i+1;
        !          5064:   } /* End loop reading  data */
        !          5065: 
        !          5066:   *imax=i-1; /* Number of individuals */
        !          5067:   fclose(fic);
        !          5068:  
        !          5069:   return (0);
        !          5070:   endread:
        !          5071:     printf("Exiting readdata: ");
        !          5072:     fclose(fic);
        !          5073:     return (1);
        !          5074: 
        !          5075: 
        !          5076: 
        !          5077: }
        !          5078: void removespace(char *str) {
        !          5079:   char *p1 = str, *p2 = str;
        !          5080:   do
        !          5081:     while (*p2 == ' ')
        !          5082:       p2++;
        !          5083:   while (*p1++ = *p2++);
        !          5084: }
        !          5085: 
        !          5086: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
        !          5087:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
        !          5088:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
        !          5089:    * - cptcovn or number of covariates k of the models excluding age*products =6
        !          5090:    * - cptcovage number of covariates with age*products =2
        !          5091:    * - cptcovs number of simple covariates
        !          5092:    * - 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
        !          5093:    *     which is a new column after the 9 (ncovcol) variables. 
        !          5094:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
        !          5095:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
        !          5096:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
        !          5097:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
        !          5098:  */
        !          5099: {
        !          5100:   int i, j, k, ks;
        !          5101:   int i1, j1, k1, k2;
        !          5102:   char modelsav[80];
        !          5103:   char stra[80], strb[80], strc[80], strd[80],stre[80];
        !          5104: 
        !          5105:   /*removespace(model);*/
        !          5106:   if (strlen(model) >1){ /* If there is at least 1 covariate */
        !          5107:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
        !          5108:     j=nbocc(model,'+'); /**< j=Number of '+' */
        !          5109:     j1=nbocc(model,'*'); /**< j1=Number of '*' */
        !          5110:     cptcovs=j+1-j1; /**<  Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2  */
        !          5111:     cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
        !          5112:                   /* including age products which are counted in cptcovage.
        !          5113:                  /* but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
        !          5114:     cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
        !          5115:     cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
        !          5116:     strcpy(modelsav,model); 
        !          5117:     if (strstr(model,"AGE") !=0){
        !          5118:       printf("Error. AGE must be in lower case 'age' model=%s ",model);
        !          5119:       fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
        !          5120:       return 1;
        !          5121:     }
        !          5122:     if (strstr(model,"v") !=0){
        !          5123:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
        !          5124:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
        !          5125:       return 1;
        !          5126:     }
        !          5127:     
        !          5128:     /*   Design
        !          5129:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
        !          5130:      *  <          ncovcol=8                >
        !          5131:      * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
        !          5132:      *   k=  1    2      3       4     5       6      7        8
        !          5133:      *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
        !          5134:      *  covar[k,i], value of kth covariate if not including age for individual i:
        !          5135:      *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
        !          5136:      *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
        !          5137:      *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
        !          5138:      *  Tage[++cptcovage]=k
        !          5139:      *       if products, new covar are created after ncovcol with k1
        !          5140:      *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
        !          5141:      *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
        !          5142:      *  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
        !          5143:      *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
        !          5144:      *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
        !          5145:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
        !          5146:      *  <          ncovcol=8                >
        !          5147:      *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
        !          5148:      *          k=  1    2      3       4     5       6      7        8    9   10   11  12
        !          5149:      *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
        !          5150:      * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
        !          5151:      * p Tprod[1]@2={                         6, 5}
        !          5152:      *p Tvard[1][1]@4= {7, 8, 5, 6}
        !          5153:      * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
        !          5154:      *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
        !          5155:      *How to reorganize?
        !          5156:      * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
        !          5157:      * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
        !          5158:      *       {2,   1,     4,      8,    5,      6,     3,       7}
        !          5159:      * Struct []
        !          5160:      */
        !          5161: 
        !          5162:     /* This loop fills the array Tvar from the string 'model'.*/
        !          5163:     /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
        !          5164:     /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
        !          5165:     /*         k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
        !          5166:     /*         k=3 V4 Tvar[k=3]= 4 (from V4) */
        !          5167:     /*         k=2 V1 Tvar[k=2]= 1 (from V1) */
        !          5168:     /*         k=1 Tvar[1]=2 (from V2) */
        !          5169:     /*         k=5 Tvar[5] */
        !          5170:     /* for (k=1; k<=cptcovn;k++) { */
        !          5171:     /*         cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
        !          5172:     /*         } */
        !          5173:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
        !          5174:     /*
        !          5175:      * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
        !          5176:     for(k=cptcovt; k>=1;k--) /**< Number of covariates */
        !          5177:         Tvar[k]=0;
        !          5178:     cptcovage=0;
        !          5179:     for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
        !          5180:       cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
        !          5181:                                     modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
        !          5182:       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
        !          5183:       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
        !          5184:       /*scanf("%d",i);*/
        !          5185:       if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
        !          5186:        cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
        !          5187:        if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
        !          5188:          /* covar is not filled and then is empty */
        !          5189:          cptcovprod--;
        !          5190:          cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
        !          5191:          Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
        !          5192:          cptcovage++; /* Sums the number of covariates which include age as a product */
        !          5193:          Tage[cptcovage]=k;  /* Tage[1] = 4 */
        !          5194:          /*printf("stre=%s ", stre);*/
        !          5195:        } else if (strcmp(strd,"age")==0) { /* or age*Vn */
        !          5196:          cptcovprod--;
        !          5197:          cutl(stre,strb,strc,'V');
        !          5198:          Tvar[k]=atoi(stre);
        !          5199:          cptcovage++;
        !          5200:          Tage[cptcovage]=k;
        !          5201:        } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
        !          5202:          /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
        !          5203:          cptcovn++;
        !          5204:          cptcovprodnoage++;k1++;
        !          5205:          cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
        !          5206:          Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
        !          5207:                                  because this model-covariate is a construction we invent a new column
        !          5208:                                  ncovcol + k1
        !          5209:                                  If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
        !          5210:                                  Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
        !          5211:          cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
        !          5212:          Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
        !          5213:          Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
        !          5214:          Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
        !          5215:          k2=k2+2;
        !          5216:          Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
        !          5217:          Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
        !          5218:          for (i=1; i<=lastobs;i++){
        !          5219:            /* Computes the new covariate which is a product of
        !          5220:               covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
        !          5221:            covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
        !          5222:          }
        !          5223:        } /* End age is not in the model */
        !          5224:       } /* End if model includes a product */
        !          5225:       else { /* no more sum */
        !          5226:        /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
        !          5227:        /*  scanf("%d",i);*/
        !          5228:        cutl(strd,strc,strb,'V');
        !          5229:        ks++; /**< Number of simple covariates */
        !          5230:        cptcovn++;
        !          5231:        Tvar[k]=atoi(strd);
        !          5232:       }
        !          5233:       strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
        !          5234:       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
        !          5235:        scanf("%d",i);*/
        !          5236:     } /* end of loop + */
        !          5237:   } /* end model */
        !          5238:   
        !          5239:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
        !          5240:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
        !          5241: 
        !          5242:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
        !          5243:   printf("cptcovprod=%d ", cptcovprod);
        !          5244:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
        !          5245: 
        !          5246:   scanf("%d ",i);*/
        !          5247: 
        !          5248: 
        !          5249:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
        !          5250:   endread:
        !          5251:     printf("Exiting decodemodel: ");
        !          5252:     return (1);
        !          5253: }
        !          5254: 
        !          5255: calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
        !          5256: {
        !          5257:   int i, m;
        !          5258: 
        !          5259:   for (i=1; i<=imx; i++) {
        !          5260:     for(m=2; (m<= maxwav); m++) {
        !          5261:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
        !          5262:        anint[m][i]=9999;
        !          5263:        s[m][i]=-1;
        !          5264:       }
        !          5265:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
        !          5266:        *nberr++;
        !          5267:        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\n",(int)moisdc[i],(int)andc[i],num[i],i);
        !          5268:        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\n",(int)moisdc[i],(int)andc[i],num[i],i);
        !          5269:        s[m][i]=-1;
        !          5270:       }
        !          5271:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
        !          5272:        *nberr++;
        !          5273:        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]); 
        !          5274:        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]); 
        !          5275:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
        !          5276:       }
        !          5277:     }
        !          5278:   }
        !          5279: 
        !          5280:   for (i=1; i<=imx; i++)  {
        !          5281:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
        !          5282:     for(m=firstpass; (m<= lastpass); m++){
        !          5283:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
        !          5284:        if (s[m][i] >= nlstate+1) {
        !          5285:          if(agedc[i]>0)
        !          5286:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
        !          5287:              agev[m][i]=agedc[i];
        !          5288:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
        !          5289:            else {
        !          5290:              if ((int)andc[i]!=9999){
        !          5291:                nbwarn++;
        !          5292:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
        !          5293:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
        !          5294:                agev[m][i]=-1;
        !          5295:              }
        !          5296:            }
        !          5297:        }
        !          5298:        else if(s[m][i] !=9){ /* Standard case, age in fractional
        !          5299:                                 years but with the precision of a month */
        !          5300:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
        !          5301:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
        !          5302:            agev[m][i]=1;
        !          5303:          else if(agev[m][i] < *agemin){ 
        !          5304:            *agemin=agev[m][i];
        !          5305:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
        !          5306:          }
        !          5307:          else if(agev[m][i] >*agemax){
        !          5308:            *agemax=agev[m][i];
        !          5309:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
        !          5310:          }
        !          5311:          /*agev[m][i]=anint[m][i]-annais[i];*/
        !          5312:          /*     agev[m][i] = age[i]+2*m;*/
        !          5313:        }
        !          5314:        else { /* =9 */
        !          5315:          agev[m][i]=1;
        !          5316:          s[m][i]=-1;
        !          5317:        }
        !          5318:       }
        !          5319:       else /*= 0 Unknown */
        !          5320:        agev[m][i]=1;
        !          5321:     }
        !          5322:     
        !          5323:   }
        !          5324:   for (i=1; i<=imx; i++)  {
        !          5325:     for(m=firstpass; (m<=lastpass); m++){
        !          5326:       if (s[m][i] > (nlstate+ndeath)) {
        !          5327:        *nberr++;
        !          5328:        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);     
        !          5329:        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);     
        !          5330:        return 1;
        !          5331:       }
        !          5332:     }
        !          5333:   }
        !          5334: 
        !          5335:   /*for (i=1; i<=imx; i++){
        !          5336:   for (m=firstpass; (m<lastpass); m++){
        !          5337:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
        !          5338: }
        !          5339: 
        !          5340: }*/
        !          5341: 
        !          5342: 
        !          5343:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
        !          5344:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
        !          5345: 
        !          5346:   return (0);
        !          5347:   endread:
        !          5348:     printf("Exiting calandcheckages: ");
        !          5349:     return (1);
        !          5350: }
        !          5351: 
        !          5352: 
        !          5353: /***********************************************/
        !          5354: /**************** Main Program *****************/
        !          5355: /***********************************************/
        !          5356: 
        !          5357: int main(int argc, char *argv[])
        !          5358: {
        !          5359: #ifdef GSL
        !          5360:   const gsl_multimin_fminimizer_type *T;
        !          5361:   size_t iteri = 0, it;
        !          5362:   int rval = GSL_CONTINUE;
        !          5363:   int status = GSL_SUCCESS;
        !          5364:   double ssval;
        !          5365: #endif
        !          5366:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
        !          5367:   int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
        !          5368:   int linei, month, year,iout;
        !          5369:   int jj, ll, li, lj, lk, imk;
        !          5370:   int numlinepar=0; /* Current linenumber of parameter file */
        !          5371:   int itimes;
        !          5372:   int NDIM=2;
        !          5373:   int vpopbased=0;
        !          5374: 
        !          5375:   char ca[32], cb[32], cc[32];
        !          5376:   /*  FILE *fichtm; *//* Html File */
        !          5377:   /* FILE *ficgp;*/ /*Gnuplot File */
        !          5378:   struct stat info;
        !          5379:   double agedeb, agefin,hf;
        !          5380:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
        !          5381: 
        !          5382:   double fret;
        !          5383:   double **xi,tmp,delta;
        !          5384: 
        !          5385:   double dum; /* Dummy variable */
        !          5386:   double ***p3mat;
        !          5387:   double ***mobaverage;
        !          5388:   int *indx;
        !          5389:   char line[MAXLINE], linepar[MAXLINE];
        !          5390:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
        !          5391:   char pathr[MAXLINE], pathimach[MAXLINE]; 
        !          5392:   char **bp, *tok, *val; /* pathtot */
        !          5393:   int firstobs=1, lastobs=10;
        !          5394:   int sdeb, sfin; /* Status at beginning and end */
        !          5395:   int c,  h , cpt,l;
        !          5396:   int ju,jl, mi;
        !          5397:   int i1,j1, jk,aa,bb, stepsize, ij;
        !          5398:   int jnais,jdc,jint4,jint1,jint2,jint3,*tab; 
        !          5399:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
        !          5400:   int mobilav=0,popforecast=0;
        !          5401:   int hstepm, nhstepm;
        !          5402:   int agemortsup;
        !          5403:   float  sumlpop=0.;
        !          5404:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
        !          5405:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
        !          5406: 
        !          5407:   double bage, fage, age, agelim, agebase;
        !          5408:   double ftolpl=FTOL;
        !          5409:   double **prlim;
        !          5410:   double ***param; /* Matrix of parameters */
        !          5411:   double  *p;
        !          5412:   double **matcov; /* Matrix of covariance */
        !          5413:   double ***delti3; /* Scale */
        !          5414:   double *delti; /* Scale */
        !          5415:   double ***eij, ***vareij;
        !          5416:   double **varpl; /* Variances of prevalence limits by age */
        !          5417:   double *epj, vepp;
        !          5418:   double kk1, kk2;
        !          5419:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
        !          5420:   double **ximort;
        !          5421:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
        !          5422:   int *dcwave;
        !          5423: 
        !          5424:   char z[1]="c", occ;
        !          5425: 
        !          5426:   /*char  *strt;*/
        !          5427:   char strtend[80];
        !          5428: 
        !          5429:   long total_usecs;
        !          5430:  
        !          5431: /*   setlocale (LC_ALL, ""); */
        !          5432: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
        !          5433: /*   textdomain (PACKAGE); */
        !          5434: /*   setlocale (LC_CTYPE, ""); */
        !          5435: /*   setlocale (LC_MESSAGES, ""); */
        !          5436: 
        !          5437:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
        !          5438:   rstart_time = time(NULL);  
        !          5439:   /*  (void) gettimeofday(&start_time,&tzp);*/
        !          5440:   start_time = *localtime(&rstart_time);
        !          5441:   curr_time=start_time;
        !          5442:   /*tml = *localtime(&start_time.tm_sec);*/
        !          5443:   /* strcpy(strstart,asctime(&tml)); */
        !          5444:   strcpy(strstart,asctime(&start_time));
        !          5445: 
        !          5446: /*  printf("Localtime (at start)=%s",strstart); */
        !          5447: /*  tp.tm_sec = tp.tm_sec +86400; */
        !          5448: /*  tm = *localtime(&start_time.tm_sec); */
        !          5449: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
        !          5450: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
        !          5451: /*   tmg.tm_hour=tmg.tm_hour + 1; */
        !          5452: /*   tp.tm_sec = mktime(&tmg); */
        !          5453: /*   strt=asctime(&tmg); */
        !          5454: /*   printf("Time(after) =%s",strstart);  */
        !          5455: /*  (void) time (&time_value);
        !          5456: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
        !          5457: *  tm = *localtime(&time_value);
        !          5458: *  strstart=asctime(&tm);
        !          5459: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
        !          5460: */
        !          5461: 
        !          5462:   nberr=0; /* Number of errors and warnings */
        !          5463:   nbwarn=0;
        !          5464:   getcwd(pathcd, size);
        !          5465: 
        !          5466:   printf("\n%s\n%s",version,fullversion);
        !          5467:   if(argc <=1){
        !          5468:     printf("\nEnter the parameter file name: ");
        !          5469:     fgets(pathr,FILENAMELENGTH,stdin);
        !          5470:     i=strlen(pathr);
        !          5471:     if(pathr[i-1]=='\n')
        !          5472:       pathr[i-1]='\0';
        !          5473:     i=strlen(pathr);
        !          5474:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
        !          5475:       pathr[i-1]='\0';
        !          5476:    for (tok = pathr; tok != NULL; ){
        !          5477:       printf("Pathr |%s|\n",pathr);
        !          5478:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
        !          5479:       printf("val= |%s| pathr=%s\n",val,pathr);
        !          5480:       strcpy (pathtot, val);
        !          5481:       if(pathr[0] == '\0') break; /* Dirty */
        !          5482:     }
        !          5483:   }
        !          5484:   else{
        !          5485:     strcpy(pathtot,argv[1]);
        !          5486:   }
        !          5487:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
        !          5488:   /*cygwin_split_path(pathtot,path,optionfile);
        !          5489:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
        !          5490:   /* cutv(path,optionfile,pathtot,'\\');*/
        !          5491: 
        !          5492:   /* Split argv[0], imach program to get pathimach */
        !          5493:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
        !          5494:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
        !          5495:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
        !          5496:  /*   strcpy(pathimach,argv[0]); */
        !          5497:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
        !          5498:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
        !          5499:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
        !          5500:   chdir(path); /* Can be a relative path */
        !          5501:   if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
        !          5502:     printf("Current directory %s!\n",pathcd);
        !          5503:   strcpy(command,"mkdir ");
        !          5504:   strcat(command,optionfilefiname);
        !          5505:   if((outcmd=system(command)) != 0){
        !          5506:     printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
        !          5507:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
        !          5508:     /* fclose(ficlog); */
        !          5509: /*     exit(1); */
        !          5510:   }
        !          5511: /*   if((imk=mkdir(optionfilefiname))<0){ */
        !          5512: /*     perror("mkdir"); */
        !          5513: /*   } */
        !          5514: 
        !          5515:   /*-------- arguments in the command line --------*/
        !          5516: 
        !          5517:   /* Log file */
        !          5518:   strcat(filelog, optionfilefiname);
        !          5519:   strcat(filelog,".log");    /* */
        !          5520:   if((ficlog=fopen(filelog,"w"))==NULL)    {
        !          5521:     printf("Problem with logfile %s\n",filelog);
        !          5522:     goto end;
        !          5523:   }
        !          5524:   fprintf(ficlog,"Log filename:%s\n",filelog);
        !          5525:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
        !          5526:   fprintf(ficlog,"\nEnter the parameter file name: \n");
        !          5527:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
        !          5528:  path=%s \n\
        !          5529:  optionfile=%s\n\
        !          5530:  optionfilext=%s\n\
        !          5531:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
        !          5532: 
        !          5533:   printf("Local time (at start):%s",strstart);
        !          5534:   fprintf(ficlog,"Local time (at start): %s",strstart);
        !          5535:   fflush(ficlog);
        !          5536: /*   (void) gettimeofday(&curr_time,&tzp); */
        !          5537: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
        !          5538: 
        !          5539:   /* */
        !          5540:   strcpy(fileres,"r");
        !          5541:   strcat(fileres, optionfilefiname);
        !          5542:   strcat(fileres,".txt");    /* Other files have txt extension */
        !          5543: 
        !          5544:   /*---------arguments file --------*/
        !          5545: 
        !          5546:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
        !          5547:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
        !          5548:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
        !          5549:     fflush(ficlog);
        !          5550:     /* goto end; */
        !          5551:     exit(70); 
        !          5552:   }
        !          5553: 
        !          5554: 
        !          5555: 
        !          5556:   strcpy(filereso,"o");
        !          5557:   strcat(filereso,fileres);
        !          5558:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
        !          5559:     printf("Problem with Output resultfile: %s\n", filereso);
        !          5560:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
        !          5561:     fflush(ficlog);
        !          5562:     goto end;
        !          5563:   }
        !          5564: 
        !          5565:   /* Reads comments: lines beginning with '#' */
        !          5566:   numlinepar=0;
        !          5567:   while((c=getc(ficpar))=='#' && c!= EOF){
        !          5568:     ungetc(c,ficpar);
        !          5569:     fgets(line, MAXLINE, ficpar);
        !          5570:     numlinepar++;
        !          5571:     fputs(line,stdout);
        !          5572:     fputs(line,ficparo);
        !          5573:     fputs(line,ficlog);
        !          5574:   }
        !          5575:   ungetc(c,ficpar);
        !          5576: 
        !          5577:   fscanf(ficpar,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d model=%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model);
        !          5578:   numlinepar++;
        !          5579:   printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model);
        !          5580:   fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
        !          5581:   fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
        !          5582:   fflush(ficlog);
        !          5583:   while((c=getc(ficpar))=='#' && c!= EOF){
        !          5584:     ungetc(c,ficpar);
        !          5585:     fgets(line, MAXLINE, ficpar);
        !          5586:     numlinepar++;
        !          5587:     fputs(line, stdout);
        !          5588:     //puts(line);
        !          5589:     fputs(line,ficparo);
        !          5590:     fputs(line,ficlog);
        !          5591:   }
        !          5592:   ungetc(c,ficpar);
        !          5593: 
        !          5594:    
        !          5595:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
        !          5596:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
        !          5597:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
        !          5598:      v1+v2*age+v2*v3 makes cptcovn = 3
        !          5599:   */
        !          5600:   if (strlen(model)>1) 
        !          5601:     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*/
        !          5602:   else
        !          5603:     ncovmodel=2;
        !          5604:   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
        !          5605:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
        !          5606:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
        !          5607:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
        !          5608:     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);
        !          5609:     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);
        !          5610:     fflush(stdout);
        !          5611:     fclose (ficlog);
        !          5612:     goto end;
        !          5613:   }
        !          5614:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
        !          5615:   delti=delti3[1][1];
        !          5616:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
        !          5617:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
        !          5618:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
        !          5619:     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
        !          5620:     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
        !          5621:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
        !          5622:     fclose (ficparo);
        !          5623:     fclose (ficlog);
        !          5624:     goto end;
        !          5625:     exit(0);
        !          5626:   }
        !          5627:   else if(mle==-3) {
        !          5628:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
        !          5629:     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
        !          5630:     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
        !          5631:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
        !          5632:     matcov=matrix(1,npar,1,npar);
        !          5633:   }
        !          5634:   else{
        !          5635:     /* Read guessed parameters */
        !          5636:     /* Reads comments: lines beginning with '#' */
        !          5637:     while((c=getc(ficpar))=='#' && c!= EOF){
        !          5638:       ungetc(c,ficpar);
        !          5639:       fgets(line, MAXLINE, ficpar);
        !          5640:       numlinepar++;
        !          5641:       fputs(line,stdout);
        !          5642:       fputs(line,ficparo);
        !          5643:       fputs(line,ficlog);
        !          5644:     }
        !          5645:     ungetc(c,ficpar);
        !          5646:     
        !          5647:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
        !          5648:     for(i=1; i <=nlstate; i++){
        !          5649:       j=0;
        !          5650:       for(jj=1; jj <=nlstate+ndeath; jj++){
        !          5651:        if(jj==i) continue;
        !          5652:        j++;
        !          5653:        fscanf(ficpar,"%1d%1d",&i1,&j1);
        !          5654:        if ((i1 != i) && (j1 != j)){
        !          5655:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
        !          5656: It might be a problem of design; if ncovcol and the model are correct\n \
        !          5657: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
        !          5658:          exit(1);
        !          5659:        }
        !          5660:        fprintf(ficparo,"%1d%1d",i1,j1);
        !          5661:        if(mle==1)
        !          5662:          printf("%1d%1d",i,j);
        !          5663:        fprintf(ficlog,"%1d%1d",i,j);
        !          5664:        for(k=1; k<=ncovmodel;k++){
        !          5665:          fscanf(ficpar," %lf",&param[i][j][k]);
        !          5666:          if(mle==1){
        !          5667:            printf(" %lf",param[i][j][k]);
        !          5668:            fprintf(ficlog," %lf",param[i][j][k]);
        !          5669:          }
        !          5670:          else
        !          5671:            fprintf(ficlog," %lf",param[i][j][k]);
        !          5672:          fprintf(ficparo," %lf",param[i][j][k]);
        !          5673:        }
        !          5674:        fscanf(ficpar,"\n");
        !          5675:        numlinepar++;
        !          5676:        if(mle==1)
        !          5677:          printf("\n");
        !          5678:        fprintf(ficlog,"\n");
        !          5679:        fprintf(ficparo,"\n");
        !          5680:       }
        !          5681:     }  
        !          5682:     fflush(ficlog);
        !          5683: 
        !          5684:     /* Reads scales values */
        !          5685:     p=param[1][1];
        !          5686:     
        !          5687:     /* Reads comments: lines beginning with '#' */
        !          5688:     while((c=getc(ficpar))=='#' && c!= EOF){
        !          5689:       ungetc(c,ficpar);
        !          5690:       fgets(line, MAXLINE, ficpar);
        !          5691:       numlinepar++;
        !          5692:       fputs(line,stdout);
        !          5693:       fputs(line,ficparo);
        !          5694:       fputs(line,ficlog);
        !          5695:     }
        !          5696:     ungetc(c,ficpar);
        !          5697: 
        !          5698:     for(i=1; i <=nlstate; i++){
        !          5699:       for(j=1; j <=nlstate+ndeath-1; j++){
        !          5700:        fscanf(ficpar,"%1d%1d",&i1,&j1);
        !          5701:        if ((i1-i)*(j1-j)!=0){
        !          5702:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
        !          5703:          exit(1);
        !          5704:        }
        !          5705:        printf("%1d%1d",i,j);
        !          5706:        fprintf(ficparo,"%1d%1d",i1,j1);
        !          5707:        fprintf(ficlog,"%1d%1d",i1,j1);
        !          5708:        for(k=1; k<=ncovmodel;k++){
        !          5709:          fscanf(ficpar,"%le",&delti3[i][j][k]);
        !          5710:          printf(" %le",delti3[i][j][k]);
        !          5711:          fprintf(ficparo," %le",delti3[i][j][k]);
        !          5712:          fprintf(ficlog," %le",delti3[i][j][k]);
        !          5713:        }
        !          5714:        fscanf(ficpar,"\n");
        !          5715:        numlinepar++;
        !          5716:        printf("\n");
        !          5717:        fprintf(ficparo,"\n");
        !          5718:        fprintf(ficlog,"\n");
        !          5719:       }
        !          5720:     }
        !          5721:     fflush(ficlog);
        !          5722: 
        !          5723:     /* Reads covariance matrix */
        !          5724:     delti=delti3[1][1];
        !          5725: 
        !          5726: 
        !          5727:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
        !          5728:   
        !          5729:     /* Reads comments: lines beginning with '#' */
        !          5730:     while((c=getc(ficpar))=='#' && c!= EOF){
        !          5731:       ungetc(c,ficpar);
        !          5732:       fgets(line, MAXLINE, ficpar);
        !          5733:       numlinepar++;
        !          5734:       fputs(line,stdout);
        !          5735:       fputs(line,ficparo);
        !          5736:       fputs(line,ficlog);
        !          5737:     }
        !          5738:     ungetc(c,ficpar);
        !          5739:   
        !          5740:     matcov=matrix(1,npar,1,npar);
        !          5741:     for(i=1; i <=npar; i++)
        !          5742:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
        !          5743:       
        !          5744:     for(i=1; i <=npar; i++){
        !          5745:       fscanf(ficpar,"%s",str);
        !          5746:       if(mle==1)
        !          5747:        printf("%s",str);
        !          5748:       fprintf(ficlog,"%s",str);
        !          5749:       fprintf(ficparo,"%s",str);
        !          5750:       for(j=1; j <=i; j++){
        !          5751:        fscanf(ficpar," %le",&matcov[i][j]);
        !          5752:        if(mle==1){
        !          5753:          printf(" %.5le",matcov[i][j]);
        !          5754:        }
        !          5755:        fprintf(ficlog," %.5le",matcov[i][j]);
        !          5756:        fprintf(ficparo," %.5le",matcov[i][j]);
        !          5757:       }
        !          5758:       fscanf(ficpar,"\n");
        !          5759:       numlinepar++;
        !          5760:       if(mle==1)
        !          5761:        printf("\n");
        !          5762:       fprintf(ficlog,"\n");
        !          5763:       fprintf(ficparo,"\n");
        !          5764:     }
        !          5765:     for(i=1; i <=npar; i++)
        !          5766:       for(j=i+1;j<=npar;j++)
        !          5767:        matcov[i][j]=matcov[j][i];
        !          5768:     
        !          5769:     if(mle==1)
        !          5770:       printf("\n");
        !          5771:     fprintf(ficlog,"\n");
        !          5772:     
        !          5773:     fflush(ficlog);
        !          5774:     
        !          5775:     /*-------- Rewriting parameter file ----------*/
        !          5776:     strcpy(rfileres,"r");    /* "Rparameterfile */
        !          5777:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
        !          5778:     strcat(rfileres,".");    /* */
        !          5779:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
        !          5780:     if((ficres =fopen(rfileres,"w"))==NULL) {
        !          5781:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
        !          5782:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
        !          5783:     }
        !          5784:     fprintf(ficres,"#%s\n",version);
        !          5785:   }    /* End of mle != -3 */
        !          5786: 
        !          5787: 
        !          5788:   n= lastobs;
        !          5789:   num=lvector(1,n);
        !          5790:   moisnais=vector(1,n);
        !          5791:   annais=vector(1,n);
        !          5792:   moisdc=vector(1,n);
        !          5793:   andc=vector(1,n);
        !          5794:   agedc=vector(1,n);
        !          5795:   cod=ivector(1,n);
        !          5796:   weight=vector(1,n);
        !          5797:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
        !          5798:   mint=matrix(1,maxwav,1,n);
        !          5799:   anint=matrix(1,maxwav,1,n);
        !          5800:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
        !          5801:   tab=ivector(1,NCOVMAX);
        !          5802:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
        !          5803: 
        !          5804:   /* Reads data from file datafile */
        !          5805:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
        !          5806:     goto end;
        !          5807: 
        !          5808:   /* Calculation of the number of parameters from char model */
        !          5809:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
        !          5810:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
        !          5811:        k=3 V4 Tvar[k=3]= 4 (from V4)
        !          5812:        k=2 V1 Tvar[k=2]= 1 (from V1)
        !          5813:        k=1 Tvar[1]=2 (from V2)
        !          5814:     */
        !          5815:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
        !          5816:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
        !          5817:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
        !          5818:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
        !          5819:   */
        !          5820:   /* For model-covariate k tells which data-covariate to use but
        !          5821:     because this model-covariate is a construction we invent a new column
        !          5822:     ncovcol + k1
        !          5823:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
        !          5824:     Tvar[3=V1*V4]=4+1 etc */
        !          5825:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
        !          5826:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
        !          5827:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
        !          5828:   */
        !          5829:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
        !          5830:   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
        !          5831:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
        !          5832:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
        !          5833:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
        !          5834:                         4 covariates (3 plus signs)
        !          5835:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
        !          5836:                      */  
        !          5837: 
        !          5838:   if(decodemodel(model, lastobs) == 1)
        !          5839:     goto end;
        !          5840: 
        !          5841:   if((double)(lastobs-imx)/(double)imx > 1.10){
        !          5842:     nbwarn++;
        !          5843:     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); 
        !          5844:     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); 
        !          5845:   }
        !          5846:     /*  if(mle==1){*/
        !          5847:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
        !          5848:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
        !          5849:   }
        !          5850: 
        !          5851:     /*-calculation of age at interview from date of interview and age at death -*/
        !          5852:   agev=matrix(1,maxwav,1,imx);
        !          5853: 
        !          5854:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
        !          5855:     goto end;
        !          5856: 
        !          5857: 
        !          5858:   agegomp=(int)agemin;
        !          5859:   free_vector(moisnais,1,n);
        !          5860:   free_vector(annais,1,n);
        !          5861:   /* free_matrix(mint,1,maxwav,1,n);
        !          5862:      free_matrix(anint,1,maxwav,1,n);*/
        !          5863:   free_vector(moisdc,1,n);
        !          5864:   free_vector(andc,1,n);
        !          5865:   /* */
        !          5866:   
        !          5867:   wav=ivector(1,imx);
        !          5868:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
        !          5869:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
        !          5870:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
        !          5871:    
        !          5872:   /* Concatenates waves */
        !          5873:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
        !          5874:   /* */
        !          5875:  
        !          5876:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
        !          5877: 
        !          5878:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
        !          5879:   ncodemax[1]=1;
        !          5880:   Ndum =ivector(-1,NCOVMAX);  
        !          5881:   if (ncovmodel > 2)
        !          5882:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
        !          5883: 
        !          5884:   codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
        !          5885:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
        !          5886:   h=0;
        !          5887: 
        !          5888: 
        !          5889:   /*if (cptcovn > 0) */
        !          5890:       
        !          5891:  
        !          5892:   m=pow(2,cptcoveff);
        !          5893:  
        !          5894:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
        !          5895:     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 */ 
        !          5896:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
        !          5897:        for(cpt=1; cpt <=pow(2,k-1); cpt++){  /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */ 
        !          5898:          h++;
        !          5899:          if (h>m) 
        !          5900:            h=1;
        !          5901:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
        !          5902:           *     h     1     2     3     4
        !          5903:           *______________________________  
        !          5904:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
        !          5905:           *     2     2     1     1     1
        !          5906:           *     3 i=2 1     2     1     1
        !          5907:           *     4     2     2     1     1
        !          5908:           *     5 i=3 1 i=2 1     2     1
        !          5909:           *     6     2     1     2     1
        !          5910:           *     7 i=4 1     2     2     1
        !          5911:           *     8     2     2     2     1
        !          5912:           *     9 i=5 1 i=3 1 i=2 1     1
        !          5913:           *    10     2     1     1     1
        !          5914:           *    11 i=6 1     2     1     1
        !          5915:           *    12     2     2     1     1
        !          5916:           *    13 i=7 1 i=4 1     2     1    
        !          5917:           *    14     2     1     2     1
        !          5918:           *    15 i=8 1     2     2     1
        !          5919:           *    16     2     2     2     1
        !          5920:           */
        !          5921:          codtab[h][k]=j;
        !          5922:          /*codtab[h][Tvar[k]]=j;*/
        !          5923:          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]]);
        !          5924:        } 
        !          5925:       }
        !          5926:     }
        !          5927:   } 
        !          5928:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
        !          5929:      codtab[1][2]=1;codtab[2][2]=2; */
        !          5930:   /* for(i=1; i <=m ;i++){ 
        !          5931:      for(k=1; k <=cptcovn; k++){
        !          5932:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
        !          5933:      }
        !          5934:      printf("\n");
        !          5935:      }
        !          5936:      scanf("%d",i);*/
        !          5937: 
        !          5938:  free_ivector(Ndum,-1,NCOVMAX);
        !          5939: 
        !          5940: 
        !          5941:     
        !          5942:   /*------------ gnuplot -------------*/
        !          5943:   strcpy(optionfilegnuplot,optionfilefiname);
        !          5944:   if(mle==-3)
        !          5945:     strcat(optionfilegnuplot,"-mort");
        !          5946:   strcat(optionfilegnuplot,".gp");
        !          5947: 
        !          5948:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
        !          5949:     printf("Problem with file %s",optionfilegnuplot);
        !          5950:   }
        !          5951:   else{
        !          5952:     fprintf(ficgp,"\n# %s\n", version); 
        !          5953:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
        !          5954:     //fprintf(ficgp,"set missing 'NaNq'\n");
        !          5955:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
        !          5956:   }
        !          5957:   /*  fclose(ficgp);*/
        !          5958:   /*--------- index.htm --------*/
        !          5959: 
        !          5960:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
        !          5961:   if(mle==-3)
        !          5962:     strcat(optionfilehtm,"-mort");
        !          5963:   strcat(optionfilehtm,".htm");
        !          5964:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
        !          5965:     printf("Problem with %s \n",optionfilehtm);
        !          5966:     exit(0);
        !          5967:   }
        !          5968: 
        !          5969:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
        !          5970:   strcat(optionfilehtmcov,"-cov.htm");
        !          5971:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
        !          5972:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
        !          5973:   }
        !          5974:   else{
        !          5975:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
        !          5976: <hr size=\"2\" color=\"#EC5E5E\"> \n\
        !          5977: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
        !          5978:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
        !          5979:   }
        !          5980: 
        !          5981:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
        !          5982: <hr size=\"2\" color=\"#EC5E5E\"> \n\
        !          5983: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
        !          5984: \n\
        !          5985: <hr  size=\"2\" color=\"#EC5E5E\">\
        !          5986:  <ul><li><h4>Parameter files</h4>\n\
        !          5987:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
        !          5988:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
        !          5989:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
        !          5990:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
        !          5991:  - Date and time at start: %s</ul>\n",\
        !          5992:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
        !          5993:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
        !          5994:          fileres,fileres,\
        !          5995:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
        !          5996:   fflush(fichtm);
        !          5997: 
        !          5998:   strcpy(pathr,path);
        !          5999:   strcat(pathr,optionfilefiname);
        !          6000:   chdir(optionfilefiname); /* Move to directory named optionfile */
        !          6001:   
        !          6002:   /* Calculates basic frequencies. Computes observed prevalence at single age
        !          6003:      and prints on file fileres'p'. */
        !          6004:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
        !          6005: 
        !          6006:   fprintf(fichtm,"\n");
        !          6007:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
        !          6008: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
        !          6009: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
        !          6010:          imx,agemin,agemax,jmin,jmax,jmean);
        !          6011:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
        !          6012:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
        !          6013:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
        !          6014:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
        !          6015:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
        !          6016:     
        !          6017:    
        !          6018:   /* For Powell, parameters are in a vector p[] starting at p[1]
        !          6019:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
        !          6020:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
        !          6021: 
        !          6022:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
        !          6023: 
        !          6024:   if (mle==-3){
        !          6025:     ximort=matrix(1,NDIM,1,NDIM); 
        !          6026: /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
        !          6027:     cens=ivector(1,n);
        !          6028:     ageexmed=vector(1,n);
        !          6029:     agecens=vector(1,n);
        !          6030:     dcwave=ivector(1,n);
        !          6031:  
        !          6032:     for (i=1; i<=imx; i++){
        !          6033:       dcwave[i]=-1;
        !          6034:       for (m=firstpass; m<=lastpass; m++)
        !          6035:        if (s[m][i]>nlstate) {
        !          6036:          dcwave[i]=m;
        !          6037:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
        !          6038:          break;
        !          6039:        }
        !          6040:     }
        !          6041: 
        !          6042:     for (i=1; i<=imx; i++) {
        !          6043:       if (wav[i]>0){
        !          6044:        ageexmed[i]=agev[mw[1][i]][i];
        !          6045:        j=wav[i];
        !          6046:        agecens[i]=1.; 
        !          6047: 
        !          6048:        if (ageexmed[i]> 1 && wav[i] > 0){
        !          6049:          agecens[i]=agev[mw[j][i]][i];
        !          6050:          cens[i]= 1;
        !          6051:        }else if (ageexmed[i]< 1) 
        !          6052:          cens[i]= -1;
        !          6053:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
        !          6054:          cens[i]=0 ;
        !          6055:       }
        !          6056:       else cens[i]=-1;
        !          6057:     }
        !          6058:     
        !          6059:     for (i=1;i<=NDIM;i++) {
        !          6060:       for (j=1;j<=NDIM;j++)
        !          6061:        ximort[i][j]=(i == j ? 1.0 : 0.0);
        !          6062:     }
        !          6063:     
        !          6064:     /*p[1]=0.0268; p[NDIM]=0.083;*/
        !          6065:     /*printf("%lf %lf", p[1], p[2]);*/
        !          6066:     
        !          6067:     
        !          6068: #ifdef GSL
        !          6069:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
        !          6070: #else
        !          6071:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
        !          6072: #endif
        !          6073:     strcpy(filerespow,"pow-mort"); 
        !          6074:     strcat(filerespow,fileres);
        !          6075:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
        !          6076:       printf("Problem with resultfile: %s\n", filerespow);
        !          6077:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
        !          6078:     }
        !          6079: #ifdef GSL
        !          6080:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
        !          6081: #else
        !          6082:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
        !          6083: #endif
        !          6084:     /*  for (i=1;i<=nlstate;i++)
        !          6085:        for(j=1;j<=nlstate+ndeath;j++)
        !          6086:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
        !          6087:     */
        !          6088:     fprintf(ficrespow,"\n");
        !          6089: #ifdef GSL
        !          6090:     /* gsl starts here */ 
        !          6091:     T = gsl_multimin_fminimizer_nmsimplex;
        !          6092:     gsl_multimin_fminimizer *sfm = NULL;
        !          6093:     gsl_vector *ss, *x;
        !          6094:     gsl_multimin_function minex_func;
        !          6095: 
        !          6096:     /* Initial vertex size vector */
        !          6097:     ss = gsl_vector_alloc (NDIM);
        !          6098:     
        !          6099:     if (ss == NULL){
        !          6100:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
        !          6101:     }
        !          6102:     /* Set all step sizes to 1 */
        !          6103:     gsl_vector_set_all (ss, 0.001);
        !          6104: 
        !          6105:     /* Starting point */
        !          6106:     
        !          6107:     x = gsl_vector_alloc (NDIM);
        !          6108:     
        !          6109:     if (x == NULL){
        !          6110:       gsl_vector_free(ss);
        !          6111:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
        !          6112:     }
        !          6113:   
        !          6114:     /* Initialize method and iterate */
        !          6115:     /*     p[1]=0.0268; p[NDIM]=0.083; */
        !          6116: /*     gsl_vector_set(x, 0, 0.0268); */
        !          6117: /*     gsl_vector_set(x, 1, 0.083); */
        !          6118:     gsl_vector_set(x, 0, p[1]);
        !          6119:     gsl_vector_set(x, 1, p[2]);
        !          6120: 
        !          6121:     minex_func.f = &gompertz_f;
        !          6122:     minex_func.n = NDIM;
        !          6123:     minex_func.params = (void *)&p; /* ??? */
        !          6124:     
        !          6125:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
        !          6126:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
        !          6127:     
        !          6128:     printf("Iterations beginning .....\n\n");
        !          6129:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
        !          6130: 
        !          6131:     iteri=0;
        !          6132:     while (rval == GSL_CONTINUE){
        !          6133:       iteri++;
        !          6134:       status = gsl_multimin_fminimizer_iterate(sfm);
        !          6135:       
        !          6136:       if (status) printf("error: %s\n", gsl_strerror (status));
        !          6137:       fflush(0);
        !          6138:       
        !          6139:       if (status) 
        !          6140:         break;
        !          6141:       
        !          6142:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
        !          6143:       ssval = gsl_multimin_fminimizer_size (sfm);
        !          6144:       
        !          6145:       if (rval == GSL_SUCCESS)
        !          6146:         printf ("converged to a local maximum at\n");
        !          6147:       
        !          6148:       printf("%5d ", iteri);
        !          6149:       for (it = 0; it < NDIM; it++){
        !          6150:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
        !          6151:       }
        !          6152:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
        !          6153:     }
        !          6154:     
        !          6155:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
        !          6156:     
        !          6157:     gsl_vector_free(x); /* initial values */
        !          6158:     gsl_vector_free(ss); /* inital step size */
        !          6159:     for (it=0; it<NDIM; it++){
        !          6160:       p[it+1]=gsl_vector_get(sfm->x,it);
        !          6161:       fprintf(ficrespow," %.12lf", p[it]);
        !          6162:     }
        !          6163:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
        !          6164: #endif
        !          6165: #ifdef POWELL
        !          6166:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
        !          6167: #endif  
        !          6168:     fclose(ficrespow);
        !          6169:     
        !          6170:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
        !          6171: 
        !          6172:     for(i=1; i <=NDIM; i++)
        !          6173:       for(j=i+1;j<=NDIM;j++)
        !          6174:        matcov[i][j]=matcov[j][i];
        !          6175:     
        !          6176:     printf("\nCovariance matrix\n ");
        !          6177:     for(i=1; i <=NDIM; i++) {
        !          6178:       for(j=1;j<=NDIM;j++){ 
        !          6179:        printf("%f ",matcov[i][j]);
        !          6180:       }
        !          6181:       printf("\n ");
        !          6182:     }
        !          6183:     
        !          6184:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
        !          6185:     for (i=1;i<=NDIM;i++) 
        !          6186:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
        !          6187: 
        !          6188:     lsurv=vector(1,AGESUP);
        !          6189:     lpop=vector(1,AGESUP);
        !          6190:     tpop=vector(1,AGESUP);
        !          6191:     lsurv[agegomp]=100000;
        !          6192:     
        !          6193:     for (k=agegomp;k<=AGESUP;k++) {
        !          6194:       agemortsup=k;
        !          6195:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
        !          6196:     }
        !          6197:     
        !          6198:     for (k=agegomp;k<agemortsup;k++)
        !          6199:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
        !          6200:     
        !          6201:     for (k=agegomp;k<agemortsup;k++){
        !          6202:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
        !          6203:       sumlpop=sumlpop+lpop[k];
        !          6204:     }
        !          6205:     
        !          6206:     tpop[agegomp]=sumlpop;
        !          6207:     for (k=agegomp;k<(agemortsup-3);k++){
        !          6208:       /*  tpop[k+1]=2;*/
        !          6209:       tpop[k+1]=tpop[k]-lpop[k];
        !          6210:     }
        !          6211:     
        !          6212:     
        !          6213:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
        !          6214:     for (k=agegomp;k<(agemortsup-2);k++) 
        !          6215:       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]);
        !          6216:     
        !          6217:     
        !          6218:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
        !          6219:     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
        !          6220:     
        !          6221:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
        !          6222:                     stepm, weightopt,\
        !          6223:                     model,imx,p,matcov,agemortsup);
        !          6224:     
        !          6225:     free_vector(lsurv,1,AGESUP);
        !          6226:     free_vector(lpop,1,AGESUP);
        !          6227:     free_vector(tpop,1,AGESUP);
        !          6228: #ifdef GSL
        !          6229:     free_ivector(cens,1,n);
        !          6230:     free_vector(agecens,1,n);
        !          6231:     free_ivector(dcwave,1,n);
        !          6232:     free_matrix(ximort,1,NDIM,1,NDIM);
        !          6233: #endif
        !          6234:   } /* Endof if mle==-3 */
        !          6235:   
        !          6236:   else{ /* For mle >=1 */
        !          6237:     globpr=0;/* debug */
        !          6238:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
        !          6239:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
        !          6240:     for (k=1; k<=npar;k++)
        !          6241:       printf(" %d %8.5f",k,p[k]);
        !          6242:     printf("\n");
        !          6243:     globpr=1; /* to print the contributions */
        !          6244:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
        !          6245:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
        !          6246:     for (k=1; k<=npar;k++)
        !          6247:       printf(" %d %8.5f",k,p[k]);
        !          6248:     printf("\n");
        !          6249:     if(mle>=1){ /* Could be 1 or 2 */
        !          6250:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
        !          6251:     }
        !          6252:     
        !          6253:     /*--------- results files --------------*/
        !          6254:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle= 0 weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate, ndeath, maxwav, weightopt,model);
        !          6255:     
        !          6256:     
        !          6257:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
        !          6258:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
        !          6259:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
        !          6260:     for(i=1,jk=1; i <=nlstate; i++){
        !          6261:       for(k=1; k <=(nlstate+ndeath); k++){
        !          6262:        if (k != i) {
        !          6263:          printf("%d%d ",i,k);
        !          6264:          fprintf(ficlog,"%d%d ",i,k);
        !          6265:          fprintf(ficres,"%1d%1d ",i,k);
        !          6266:          for(j=1; j <=ncovmodel; j++){
        !          6267:            printf("%lf ",p[jk]);
        !          6268:            fprintf(ficlog,"%lf ",p[jk]);
        !          6269:            fprintf(ficres,"%lf ",p[jk]);
        !          6270:            jk++; 
        !          6271:          }
        !          6272:          printf("\n");
        !          6273:          fprintf(ficlog,"\n");
        !          6274:          fprintf(ficres,"\n");
        !          6275:        }
        !          6276:       }
        !          6277:     }
        !          6278:     if(mle!=0){
        !          6279:       /* Computing hessian and covariance matrix */
        !          6280:       ftolhess=ftol; /* Usually correct */
        !          6281:       hesscov(matcov, p, npar, delti, ftolhess, func);
        !          6282:     }
        !          6283:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
        !          6284:     printf("# Scales (for hessian or gradient estimation)\n");
        !          6285:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
        !          6286:     for(i=1,jk=1; i <=nlstate; i++){
        !          6287:       for(j=1; j <=nlstate+ndeath; j++){
        !          6288:        if (j!=i) {
        !          6289:          fprintf(ficres,"%1d%1d",i,j);
        !          6290:          printf("%1d%1d",i,j);
        !          6291:          fprintf(ficlog,"%1d%1d",i,j);
        !          6292:          for(k=1; k<=ncovmodel;k++){
        !          6293:            printf(" %.5e",delti[jk]);
        !          6294:            fprintf(ficlog," %.5e",delti[jk]);
        !          6295:            fprintf(ficres," %.5e",delti[jk]);
        !          6296:            jk++;
        !          6297:          }
        !          6298:          printf("\n");
        !          6299:          fprintf(ficlog,"\n");
        !          6300:          fprintf(ficres,"\n");
        !          6301:        }
        !          6302:       }
        !          6303:     }
        !          6304:     
        !          6305:     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");
        !          6306:     if(mle>=1)
        !          6307:       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");
        !          6308:     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");
        !          6309:     /* # 121 Var(a12)\n\ */
        !          6310:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
        !          6311:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
        !          6312:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
        !          6313:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
        !          6314:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
        !          6315:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
        !          6316:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
        !          6317:     
        !          6318:     
        !          6319:     /* Just to have a covariance matrix which will be more understandable
        !          6320:        even is we still don't want to manage dictionary of variables
        !          6321:     */
        !          6322:     for(itimes=1;itimes<=2;itimes++){
        !          6323:       jj=0;
        !          6324:       for(i=1; i <=nlstate; i++){
        !          6325:        for(j=1; j <=nlstate+ndeath; j++){
        !          6326:          if(j==i) continue;
        !          6327:          for(k=1; k<=ncovmodel;k++){
        !          6328:            jj++;
        !          6329:            ca[0]= k+'a'-1;ca[1]='\0';
        !          6330:            if(itimes==1){
        !          6331:              if(mle>=1)
        !          6332:                printf("#%1d%1d%d",i,j,k);
        !          6333:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
        !          6334:              fprintf(ficres,"#%1d%1d%d",i,j,k);
        !          6335:            }else{
        !          6336:              if(mle>=1)
        !          6337:                printf("%1d%1d%d",i,j,k);
        !          6338:              fprintf(ficlog,"%1d%1d%d",i,j,k);
        !          6339:              fprintf(ficres,"%1d%1d%d",i,j,k);
        !          6340:            }
        !          6341:            ll=0;
        !          6342:            for(li=1;li <=nlstate; li++){
        !          6343:              for(lj=1;lj <=nlstate+ndeath; lj++){
        !          6344:                if(lj==li) continue;
        !          6345:                for(lk=1;lk<=ncovmodel;lk++){
        !          6346:                  ll++;
        !          6347:                  if(ll<=jj){
        !          6348:                    cb[0]= lk +'a'-1;cb[1]='\0';
        !          6349:                    if(ll<jj){
        !          6350:                      if(itimes==1){
        !          6351:                        if(mle>=1)
        !          6352:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
        !          6353:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
        !          6354:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
        !          6355:                      }else{
        !          6356:                        if(mle>=1)
        !          6357:                          printf(" %.5e",matcov[jj][ll]); 
        !          6358:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
        !          6359:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
        !          6360:                      }
        !          6361:                    }else{
        !          6362:                      if(itimes==1){
        !          6363:                        if(mle>=1)
        !          6364:                          printf(" Var(%s%1d%1d)",ca,i,j);
        !          6365:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
        !          6366:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
        !          6367:                      }else{
        !          6368:                        if(mle>=1)
        !          6369:                          printf(" %.5e",matcov[jj][ll]); 
        !          6370:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
        !          6371:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
        !          6372:                      }
        !          6373:                    }
        !          6374:                  }
        !          6375:                } /* end lk */
        !          6376:              } /* end lj */
        !          6377:            } /* end li */
        !          6378:            if(mle>=1)
        !          6379:              printf("\n");
        !          6380:            fprintf(ficlog,"\n");
        !          6381:            fprintf(ficres,"\n");
        !          6382:            numlinepar++;
        !          6383:          } /* end k*/
        !          6384:        } /*end j */
        !          6385:       } /* end i */
        !          6386:     } /* end itimes */
        !          6387:     
        !          6388:     fflush(ficlog);
        !          6389:     fflush(ficres);
        !          6390:     
        !          6391:     while((c=getc(ficpar))=='#' && c!= EOF){
        !          6392:       ungetc(c,ficpar);
        !          6393:       fgets(line, MAXLINE, ficpar);
        !          6394:       fputs(line,stdout);
        !          6395:       fputs(line,ficparo);
        !          6396:     }
        !          6397:     ungetc(c,ficpar);
        !          6398:     
        !          6399:     estepm=0;
        !          6400:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
        !          6401:     if (estepm==0 || estepm < stepm) estepm=stepm;
        !          6402:     if (fage <= 2) {
        !          6403:       bage = ageminpar;
        !          6404:       fage = agemaxpar;
        !          6405:     }
        !          6406:     
        !          6407:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
        !          6408:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
        !          6409:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
        !          6410:     
        !          6411:     while((c=getc(ficpar))=='#' && c!= EOF){
        !          6412:       ungetc(c,ficpar);
        !          6413:       fgets(line, MAXLINE, ficpar);
        !          6414:       fputs(line,stdout);
        !          6415:       fputs(line,ficparo);
        !          6416:     }
        !          6417:     ungetc(c,ficpar);
        !          6418:     
        !          6419:     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);
        !          6420:     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);
        !          6421:     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);
        !          6422:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
        !          6423:     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);
        !          6424:     
        !          6425:     while((c=getc(ficpar))=='#' && c!= EOF){
        !          6426:       ungetc(c,ficpar);
        !          6427:       fgets(line, MAXLINE, ficpar);
        !          6428:       fputs(line,stdout);
        !          6429:       fputs(line,ficparo);
        !          6430:     }
        !          6431:     ungetc(c,ficpar);
        !          6432:     
        !          6433:     
        !          6434:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
        !          6435:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
        !          6436:     
        !          6437:     fscanf(ficpar,"pop_based=%d\n",&popbased);
        !          6438:     fprintf(ficparo,"pop_based=%d\n",popbased);   
        !          6439:     fprintf(ficres,"pop_based=%d\n",popbased);   
        !          6440:     
        !          6441:     while((c=getc(ficpar))=='#' && c!= EOF){
        !          6442:       ungetc(c,ficpar);
        !          6443:       fgets(line, MAXLINE, ficpar);
        !          6444:       fputs(line,stdout);
        !          6445:       fputs(line,ficparo);
        !          6446:     }
        !          6447:     ungetc(c,ficpar);
        !          6448:     
        !          6449:     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);
        !          6450:     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);
        !          6451:     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);
        !          6452:     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);
        !          6453:     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);
        !          6454:     /* day and month of proj2 are not used but only year anproj2.*/
        !          6455:     
        !          6456:     
        !          6457:     
        !          6458:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
        !          6459:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
        !          6460:     
        !          6461:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
        !          6462:     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
        !          6463:     
        !          6464:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
        !          6465:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
        !          6466:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
        !          6467:       
        !          6468:    /*------------ free_vector  -------------*/
        !          6469:    /*  chdir(path); */
        !          6470:  
        !          6471:     free_ivector(wav,1,imx);
        !          6472:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
        !          6473:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
        !          6474:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
        !          6475:     free_lvector(num,1,n);
        !          6476:     free_vector(agedc,1,n);
        !          6477:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
        !          6478:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
        !          6479:     fclose(ficparo);
        !          6480:     fclose(ficres);
        !          6481: 
        !          6482: 
        !          6483:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
        !          6484: #include "prevlim.h"  /* Use ficrespl, ficlog */
        !          6485:     fclose(ficrespl);
        !          6486: 
        !          6487: #ifdef FREEEXIT2
        !          6488: #include "freeexit2.h"
        !          6489: #endif
        !          6490: 
        !          6491:     /*------------- h Pij x at various ages ------------*/
        !          6492: #include "hpijx.h"
        !          6493:     fclose(ficrespij);
        !          6494: 
        !          6495:   /*-------------- Variance of one-step probabilities---*/
        !          6496:     k=1;
        !          6497:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
        !          6498: 
        !          6499: 
        !          6500:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
        !          6501:     for(i=1;i<=AGESUP;i++)
        !          6502:       for(j=1;j<=NCOVMAX;j++)
        !          6503:        for(k=1;k<=NCOVMAX;k++)
        !          6504:          probs[i][j][k]=0.;
        !          6505: 
        !          6506:     /*---------- Forecasting ------------------*/
        !          6507:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
        !          6508:     if(prevfcast==1){
        !          6509:       /*    if(stepm ==1){*/
        !          6510:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
        !          6511:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
        !          6512:       /*      }  */
        !          6513:       /*      else{ */
        !          6514:       /*        erreur=108; */
        !          6515:       /*        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); */
        !          6516:       /*        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); */
        !          6517:       /*      } */
        !          6518:     }
        !          6519:   
        !          6520: 
        !          6521:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
        !          6522: 
        !          6523:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
        !          6524:     /*  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",\
        !          6525:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
        !          6526:     */
        !          6527: 
        !          6528:     if (mobilav!=0) {
        !          6529:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
        !          6530:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
        !          6531:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
        !          6532:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
        !          6533:       }
        !          6534:     }
        !          6535: 
        !          6536: 
        !          6537:     /*---------- Health expectancies, no variances ------------*/
        !          6538: 
        !          6539:     strcpy(filerese,"e");
        !          6540:     strcat(filerese,fileres);
        !          6541:     if((ficreseij=fopen(filerese,"w"))==NULL) {
        !          6542:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
        !          6543:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
        !          6544:     }
        !          6545:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
        !          6546:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
        !          6547:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
        !          6548:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
        !          6549:           
        !          6550:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
        !          6551:        fprintf(ficreseij,"\n#****** ");
        !          6552:        for(j=1;j<=cptcoveff;j++) {
        !          6553:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
        !          6554:        }
        !          6555:        fprintf(ficreseij,"******\n");
        !          6556: 
        !          6557:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
        !          6558:        oldm=oldms;savm=savms;
        !          6559:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
        !          6560:       
        !          6561:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
        !          6562:       /*}*/
        !          6563:     }
        !          6564:     fclose(ficreseij);
        !          6565: 
        !          6566: 
        !          6567:     /*---------- Health expectancies and variances ------------*/
        !          6568: 
        !          6569: 
        !          6570:     strcpy(filerest,"t");
        !          6571:     strcat(filerest,fileres);
        !          6572:     if((ficrest=fopen(filerest,"w"))==NULL) {
        !          6573:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
        !          6574:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
        !          6575:     }
        !          6576:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
        !          6577:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
        !          6578: 
        !          6579: 
        !          6580:     strcpy(fileresstde,"stde");
        !          6581:     strcat(fileresstde,fileres);
        !          6582:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
        !          6583:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
        !          6584:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
        !          6585:     }
        !          6586:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
        !          6587:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
        !          6588: 
        !          6589:     strcpy(filerescve,"cve");
        !          6590:     strcat(filerescve,fileres);
        !          6591:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
        !          6592:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
        !          6593:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
        !          6594:     }
        !          6595:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
        !          6596:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
        !          6597: 
        !          6598:     strcpy(fileresv,"v");
        !          6599:     strcat(fileresv,fileres);
        !          6600:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
        !          6601:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
        !          6602:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
        !          6603:     }
        !          6604:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
        !          6605:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
        !          6606: 
        !          6607:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
        !          6608:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
        !          6609:           
        !          6610:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
        !          6611:        fprintf(ficrest,"\n#****** ");
        !          6612:        for(j=1;j<=cptcoveff;j++) 
        !          6613:          fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
        !          6614:        fprintf(ficrest,"******\n");
        !          6615: 
        !          6616:        fprintf(ficresstdeij,"\n#****** ");
        !          6617:        fprintf(ficrescveij,"\n#****** ");
        !          6618:        for(j=1;j<=cptcoveff;j++) {
        !          6619:          fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
        !          6620:          fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
        !          6621:        }
        !          6622:        fprintf(ficresstdeij,"******\n");
        !          6623:        fprintf(ficrescveij,"******\n");
        !          6624: 
        !          6625:        fprintf(ficresvij,"\n#****** ");
        !          6626:        for(j=1;j<=cptcoveff;j++) 
        !          6627:          fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
        !          6628:        fprintf(ficresvij,"******\n");
        !          6629: 
        !          6630:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
        !          6631:        oldm=oldms;savm=savms;
        !          6632:        cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
        !          6633:        /*
        !          6634:         */
        !          6635:        /* goto endfree; */
        !          6636:  
        !          6637:        vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
        !          6638:        pstamp(ficrest);
        !          6639: 
        !          6640: 
        !          6641:        for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
        !          6642:          oldm=oldms;savm=savms; /* Segmentation fault */
        !          6643:          cptcod= 0; /* To be deleted */
        !          6644:          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 */
        !          6645:          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 ");
        !          6646:          if(vpopbased==1)
        !          6647:            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);
        !          6648:          else
        !          6649:            fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
        !          6650:          fprintf(ficrest,"# Age e.. (std) ");
        !          6651:          for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
        !          6652:          fprintf(ficrest,"\n");
        !          6653: 
        !          6654:          epj=vector(1,nlstate+1);
        !          6655:          for(age=bage; age <=fage ;age++){
        !          6656:            prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
        !          6657:            if (vpopbased==1) {
        !          6658:              if(mobilav ==0){
        !          6659:                for(i=1; i<=nlstate;i++)
        !          6660:                  prlim[i][i]=probs[(int)age][i][k];
        !          6661:              }else{ /* mobilav */ 
        !          6662:                for(i=1; i<=nlstate;i++)
        !          6663:                  prlim[i][i]=mobaverage[(int)age][i][k];
        !          6664:              }
        !          6665:            }
        !          6666:        
        !          6667:            fprintf(ficrest," %4.0f",age);
        !          6668:            for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
        !          6669:              for(i=1, epj[j]=0.;i <=nlstate;i++) {
        !          6670:                epj[j] += prlim[i][i]*eij[i][j][(int)age];
        !          6671:                /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
        !          6672:              }
        !          6673:              epj[nlstate+1] +=epj[j];
        !          6674:            }
        !          6675: 
        !          6676:            for(i=1, vepp=0.;i <=nlstate;i++)
        !          6677:              for(j=1;j <=nlstate;j++)
        !          6678:                vepp += vareij[i][j][(int)age];
        !          6679:            fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
        !          6680:            for(j=1;j <=nlstate;j++){
        !          6681:              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
        !          6682:            }
        !          6683:            fprintf(ficrest,"\n");
        !          6684:          }
        !          6685:        }
        !          6686:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
        !          6687:        free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
        !          6688:        free_vector(epj,1,nlstate+1);
        !          6689:       /*}*/
        !          6690:     }
        !          6691:     free_vector(weight,1,n);
        !          6692:     free_imatrix(Tvard,1,NCOVMAX,1,2);
        !          6693:     free_imatrix(s,1,maxwav+1,1,n);
        !          6694:     free_matrix(anint,1,maxwav,1,n); 
        !          6695:     free_matrix(mint,1,maxwav,1,n);
        !          6696:     free_ivector(cod,1,n);
        !          6697:     free_ivector(tab,1,NCOVMAX);
        !          6698:     fclose(ficresstdeij);
        !          6699:     fclose(ficrescveij);
        !          6700:     fclose(ficresvij);
        !          6701:     fclose(ficrest);
        !          6702:     fclose(ficpar);
        !          6703:   
        !          6704:     /*------- Variance of period (stable) prevalence------*/   
        !          6705: 
        !          6706:     strcpy(fileresvpl,"vpl");
        !          6707:     strcat(fileresvpl,fileres);
        !          6708:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
        !          6709:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
        !          6710:       exit(0);
        !          6711:     }
        !          6712:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
        !          6713: 
        !          6714:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
        !          6715:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
        !          6716:           
        !          6717:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
        !          6718:        fprintf(ficresvpl,"\n#****** ");
        !          6719:        for(j=1;j<=cptcoveff;j++) 
        !          6720:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
        !          6721:        fprintf(ficresvpl,"******\n");
        !          6722:       
        !          6723:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
        !          6724:        oldm=oldms;savm=savms;
        !          6725:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
        !          6726:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
        !          6727:       /*}*/
        !          6728:     }
        !          6729: 
        !          6730:     fclose(ficresvpl);
        !          6731: 
        !          6732:     /*---------- End : free ----------------*/
        !          6733:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
        !          6734:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
        !          6735:   }  /* mle==-3 arrives here for freeing */
        !          6736:  endfree:
        !          6737:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
        !          6738:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
        !          6739:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
        !          6740:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
        !          6741:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
        !          6742:     free_matrix(covar,0,NCOVMAX,1,n);
        !          6743:     free_matrix(matcov,1,npar,1,npar);
        !          6744:     /*free_vector(delti,1,npar);*/
        !          6745:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
        !          6746:     free_matrix(agev,1,maxwav,1,imx);
        !          6747:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
        !          6748: 
        !          6749:     free_ivector(ncodemax,1,NCOVMAX);
        !          6750:     free_ivector(Tvar,1,NCOVMAX);
        !          6751:     free_ivector(Tprod,1,NCOVMAX);
        !          6752:     free_ivector(Tvaraff,1,NCOVMAX);
        !          6753:     free_ivector(Tage,1,NCOVMAX);
        !          6754: 
        !          6755:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
        !          6756:     free_imatrix(codtab,1,100,1,10);
        !          6757:   fflush(fichtm);
        !          6758:   fflush(ficgp);
        !          6759:   
        !          6760: 
        !          6761:   if((nberr >0) || (nbwarn>0)){
        !          6762:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
        !          6763:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
        !          6764:   }else{
        !          6765:     printf("End of Imach\n");
        !          6766:     fprintf(ficlog,"End of Imach\n");
        !          6767:   }
        !          6768:   printf("See log file on %s\n",filelog);
        !          6769:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
        !          6770:   /*(void) gettimeofday(&end_time,&tzp);*/
        !          6771:   rend_time = time(NULL);  
        !          6772:   end_time = *localtime(&rend_time);
        !          6773:   /* tml = *localtime(&end_time.tm_sec); */
        !          6774:   strcpy(strtend,asctime(&end_time));
        !          6775:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
        !          6776:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
        !          6777:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
        !          6778: 
        !          6779:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
        !          6780:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
        !          6781:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
        !          6782:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
        !          6783: /*   if(fileappend(fichtm,optionfilehtm)){ */
        !          6784:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
        !          6785:   fclose(fichtm);
        !          6786:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
        !          6787:   fclose(fichtmcov);
        !          6788:   fclose(ficgp);
        !          6789:   fclose(ficlog);
        !          6790:   /*------ End -----------*/
        !          6791: 
        !          6792: 
        !          6793:    printf("Before Current directory %s!\n",pathcd);
        !          6794:    if(chdir(pathcd) != 0)
        !          6795:     printf("Can't move to directory %s!\n",path);
        !          6796:   if(getcwd(pathcd,MAXLINE) > 0)
        !          6797:     printf("Current directory %s!\n",pathcd);
        !          6798:   /*strcat(plotcmd,CHARSEPARATOR);*/
        !          6799:   sprintf(plotcmd,"gnuplot");
        !          6800: #ifdef _WIN32
        !          6801:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
        !          6802: #endif
        !          6803:   if(!stat(plotcmd,&info)){
        !          6804:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
        !          6805:     if(!stat(getenv("GNUPLOTBIN"),&info)){
        !          6806:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
        !          6807:     }else
        !          6808:       strcpy(pplotcmd,plotcmd);
        !          6809: #ifdef __unix
        !          6810:     strcpy(plotcmd,GNUPLOTPROGRAM);
        !          6811:     if(!stat(plotcmd,&info)){
        !          6812:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
        !          6813:     }else
        !          6814:       strcpy(pplotcmd,plotcmd);
        !          6815: #endif
        !          6816:   }else
        !          6817:     strcpy(pplotcmd,plotcmd);
        !          6818:   
        !          6819:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
        !          6820:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
        !          6821: 
        !          6822:   if((outcmd=system(plotcmd)) != 0){
        !          6823:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
        !          6824:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
        !          6825:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
        !          6826:     if((outcmd=system(plotcmd)) != 0)
        !          6827:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
        !          6828:   }
        !          6829:   printf(" Successful, please wait...");
        !          6830:   while (z[0] != 'q') {
        !          6831:     /* chdir(path); */
        !          6832:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
        !          6833:     scanf("%s",z);
        !          6834: /*     if (z[0] == 'c') system("./imach"); */
        !          6835:     if (z[0] == 'e') {
        !          6836: #ifdef __APPLE__
        !          6837:       sprintf(pplotcmd, "open %s", optionfilehtm);
        !          6838: #elif __linux
        !          6839:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
        !          6840: #else
        !          6841:       sprintf(pplotcmd, "%s", optionfilehtm);
        !          6842: #endif
        !          6843:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
        !          6844:       system(pplotcmd);
        !          6845:     }
        !          6846:     else if (z[0] == 'g') system(plotcmd);
        !          6847:     else if (z[0] == 'q') exit(0);
        !          6848:   }
        !          6849:   end:
        !          6850:   while (z[0] != 'q') {
        !          6851:     printf("\nType  q for exiting: ");
        !          6852:     scanf("%s",z);
        !          6853:   }
        !          6854: }

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